diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..10926e8 --- /dev/null +++ b/COPYING @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..5fd2ad5 --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ + + +# Gyre + +A downloader for videos (called coubs) from [Coub](https://coub.com). + +![](/data/screenshots/desktop_light.png) + +## What you can download + +* Single coubs +* Stories +* Channels +* Tags +* Search results +* Communities (incl. Featured and Coub of the Day) +* Hot coubs +* Random coubs + +## Installation + +There are several ways to install Gyre. + +### Download from Flathub + +Coming soon! + +### Build with GNOME Builder + +First clone this repository with GNOME Builder. Then hit the play button and it will automatically install and compile all dependencies for you. Afterwards you can export a Flatpak bundle to install Gyre on your machine. + +### Build with Meson + +The following commands will clone this repository and install Gyre (system-wide by default). Please note that there's currently no automatic way to uninstall the program. You can run `ninja uninstall` within the build directory, but some files won't be removed, because they were generated by external commands (e.g. glib-compile-schemas). These files have to be deleted manually. + +``` +git clone https://github.com/HelpSeeker/Gyre.git +cd Gyre +meson . _build +meson configure -Dprefix= # optional step +cd _build +ninja install +``` + +The 4th step is optional and allows you to specify a custom install location. Depending on the location GLib might not be able to find the GSettings schema, which is required to run Gyre. If that is the case, you have to manually point it to the schema + +``` +GSETTINGS_SCHEMA_DIR=/share/glib-2.0/schemas /bin/gyre +``` + +## Dependencies + +* meson >= 0.50 +* GTK >= 3.24 +* libhandy >= 1.0.0 +* Python >= 3.7 +* aiohttp +* FFmpeg + +## Troubleshooting + +#### (Flatpak only) Gyre prompts me for a new output location every time I load a profile, even though the directory exists. + +Most likely you deleted the directory at one point and created a new one with the same name. With normal file system access this wouldn't be a problem, but the Flatpak version requests access via XDG Portal and in that case the new directory is different from the old one, even if they share the same name. + +Choose the directory when prompted and export the profile again to update the output location to the new version. + +#### (Flatpak only) Gyre is unable to open its error log. + +Gyre tries to open the log with the default text editor. That doesn't work when running inside the Flatpak sandbox, so the error log will always be displayed by the internal viewer. + +#### (Flatpak only) Dialogs exceed the boundaries of my phone display. + +Gyre is mobile-ready thanks to libhandy, but there are issues with GTK 3, which require [additional patches](https://gitlab.gnome.org/GNOME/gtk/-/issues/3411) to make it work correctly on mobile. Mobile distros apply these patches, but they don't affect Flatpaks. I'm still looking for a solution to this problem (maybe an additional Flatpak with the patches applied?), but until then you are better off running Gyre locally. diff --git a/build-aux/flatpak/flatpak-pip-generator.py b/build-aux/flatpak/flatpak-pip-generator.py new file mode 100644 index 0000000..4e33c72 --- /dev/null +++ b/build-aux/flatpak/flatpak-pip-generator.py @@ -0,0 +1,407 @@ +#!/usr/bin/env python3 + +__license__ = 'MIT' + +import argparse +import json +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile +import urllib.request + +from collections import OrderedDict + +try: + import requirements +except ImportError: + exit('Requirements modules is not installed. Run "pip install requirements-parser"') + +parser = argparse.ArgumentParser() +parser.add_argument('packages', nargs='*') +parser.add_argument('--python2', action='store_true', + help='Look for a Python 2 package') +parser.add_argument('--cleanup', choices=['scripts', 'all'], + help='Select what to clean up after build') +parser.add_argument('--requirements-file', '-r', + help='Specify requirements.txt file') +parser.add_argument('--build-only', action='store_const', + dest='cleanup', const='all', + help='Clean up all files after build') +parser.add_argument('--no-build-isolation', action='store_true', default=False, + help='https://pip.pypa.io/en/stable/reference/pip/#pep-517-and-518-support') +parser.add_argument('--output', '-o', + help='Specify output file name') +parser.add_argument('--runtime', + help='Specify a flatpak to run pip inside of a sandbox, ensures python version compatibility') +opts = parser.parse_args() + + +def get_pypi_url(name: str, filename: str) -> str: + url = 'https://pypi.org/pypi/{}/json'.format(name) + print('Extracting download url for', name) + with urllib.request.urlopen(url) as response: + body = json.loads(response.read().decode('utf-8')) + for release in body['releases'].values(): + for source in release: + if source['filename'] == filename: + return source['url'] + raise Exception('Failed to extract url from {}'.format(url)) + + +def get_tar_package_url_pypi(name: str, version: str) -> str: + url = 'https://pypi.org/pypi/{}/{}/json'.format(name, version) + with urllib.request.urlopen(url) as response: + body = json.loads(response.read().decode('utf-8')) + for ext in ['bz2', 'gz', 'xz', 'zip']: + for source in body['urls']: + if source['url'].endswith(ext): + return source['url'] + err = 'Failed to get {}-{} source from {}'.format(name, version, url) + raise Exception(err) + + +def get_package_name(filename: str) -> str: + if filename.endswith(('bz2', 'gz', 'xz', 'zip')): + segments = filename.split('-') + if len(segments) == 2: + return segments[0] + return '-'.join(segments[:len(segments) - 1]) + elif filename.endswith('whl'): + segments = filename.split('-') + if len(segments) == 5: + return segments[0] + candidate = segments[:len(segments) - 4] + # Some packages list the version number twice + # e.g. PyQt5-5.15.0-5.15.0-cp35.cp36.cp37.cp38-abi3-manylinux2014_x86_64.whl + if candidate[-1] == segments[len(segments) - 4]: + return '-'.join(candidate[:-1]) + return '-'.join(candidate) + else: + raise Exception( + 'Downloaded filename: {} does not end with bz2, gz, xz, zip, or whl'.format(filename) + ) + + +def get_file_version(filename: str) -> str: + name = get_package_name(filename) + segments = filename.split(name + '-') + version = segments[1].split('-')[0] + for ext in ['tar.gz', 'whl', 'tar.xz', 'tar.gz', 'tar.bz2', 'zip']: + version = version.replace('.' + ext, '') + return version + + +def get_file_hash(filename: str) -> str: + sha = hashlib.sha256() + print('Generating hash for', filename.split('/')[-1]) + with open(filename, 'rb') as f: + while True: + data = f.read(1024 * 1024 * 32) + if not data: + break + sha.update(data) + return sha.hexdigest() + + +def download_tar_pypi(url: str, tempdir: str) -> None: + with urllib.request.urlopen(url) as response: + file_path = os.path.join(tempdir, url.split('/')[-1]) + with open(file_path, 'x+b') as tar_file: + shutil.copyfileobj(response, tar_file) + + +def parse_continuation_lines(fin): + for line in fin: + line = line.rstrip('\n') + while line.endswith('\\'): + try: + line = line[:-1] + next(fin).rstrip('\n') + except StopIteration: + exit('Requirements have a wrong number of line continuation characters "\\"') + yield line + + +def fprint(string: str) -> None: + separator = '=' * 72 # Same as `flatpak-builder` + print(separator) + print(string) + print(separator) + + +packages = [] +if opts.requirements_file and os.path.exists(opts.requirements_file): + with open(opts.requirements_file, 'r') as req_file: + reqs = parse_continuation_lines(req_file) + reqs_as_str = '\n'.join([r.split('--hash')[0] for r in reqs]) + packages = list(requirements.parse(reqs_as_str)) + requirements_file = opts.requirements_file +elif opts.packages: + packages = list(requirements.parse('\n'.join(opts.packages))) + with tempfile.NamedTemporaryFile('w', delete=False, prefix='requirements.') as req_file: + req_file.write('\n'.join(opts.packages)) + requirements_file = req_file.name +else: + exit('Please specifiy either packages or requirements file argument') + +with open(requirements_file, 'r') as req_file: + use_hash = '--hash=' in req_file.read() + +python_version = '2' if opts.python2 else '3' +if opts.python2: + pip_executable = 'pip2' +else: + pip_executable = 'pip3' + +if opts.runtime: + flatpak_cmd = [ + 'flatpak', + '--devel', + '--share=network', + '--filesystem=/tmp', + '--command={}'.format(pip_executable), + 'run', + opts.runtime + ] + if opts.requirements_file and os.path.exists(opts.requirements_file): + prefix = os.path.realpath(opts.requirements_file) + flag = '--filesystem={}'.format(prefix) + flatpak_cmd.insert(1,flag) +else: + flatpak_cmd = [pip_executable] + +if opts.output: + output_package = opts.output +elif opts.requirements_file: + output_package = 'python{}-{}'.format( + python_version, opts.requirements_file.replace('.txt', ''), + ) +elif len(packages) == 1: + output_package = 'python{}-{}'.format( + python_version, packages[0].name, + ) +else: + output_package = 'python{}-modules'.format(python_version) +output_filename = output_package + '.json' + +modules = [] +vcs_modules = [] +sources = {} + +tempdir_prefix = 'pip-generator-{}'.format(output_filename.replace('.json', '')) +with tempfile.TemporaryDirectory(prefix=tempdir_prefix) as tempdir: + pip_download = flatpak_cmd + [ + 'download', + '--exists-action=i', + '--dest', + tempdir, + '-r', + requirements_file + ] + if use_hash: + pip_download.append('--require-hashes') + + fprint('Downloading sources') + cmd = ' '.join(pip_download) + print('Running: "{}"'.format(cmd)) + try: + subprocess.run(pip_download, check=True) + except subprocess.CalledProcessError: + print('Failed to download') + print('Please fix the module manually in the generated file') + + if not opts.requirements_file: + try: + os.remove(requirements_file) + except FileNotFoundError: + pass + + fprint('Downloading arch independent packages') + for filename in os.listdir(tempdir): + if not filename.endswith(('bz2', 'gz', 'xz', 'zip')): + version = get_file_version(filename) + name = get_package_name(filename) + url = get_tar_package_url_pypi(name, version) + print('Deleting', filename) + try: + os.remove(os.path.join(tempdir, filename)) + except FileNotFoundError: + pass + print('Downloading {}'.format(url)) + download_tar_pypi(url, tempdir) + + files = {get_package_name(f): [] for f in os.listdir(tempdir)} + + for filename in os.listdir(tempdir): + name = get_package_name(filename) + files[name].append(filename) + + # Delete redundant sources, for vcs sources + for name in files: + if len(files[name]) > 1: + zip_source = False + for f in files[name]: + if f.endswith('.zip'): + zip_source = True + if zip_source: + for f in files[name]: + if not f.endswith('.zip'): + try: + os.remove(os.path.join(tempdir, f)) + except FileNotFoundError: + pass + + vcs_packages = { + x.name: {'vcs': x.vcs, 'revision': x.revision, 'uri': x.uri} + for x in packages + if x.vcs + } + + fprint('Obtaining hashes and urls') + for filename in os.listdir(tempdir): + name = get_package_name(filename) + sha256 = get_file_hash(os.path.join(tempdir, filename)) + + if name in vcs_packages: + uri = vcs_packages[name]['uri'] + revision = vcs_packages[name]['revision'] + vcs = vcs_packages[name]['vcs'] + url = 'https://' + uri.split('://', 1)[1] + s = 'commit' + if vcs == 'svn': + s = 'revision' + source = OrderedDict([ + ('type', vcs), + ('url', url), + (s, revision), + ]) + is_vcs = True + else: + url = get_pypi_url(name, filename) + source = OrderedDict([ + ('type', 'file'), + ('url', url), + ('sha256', sha256)]) + is_vcs = False + sources[name] = {'source': source, 'vcs': is_vcs} + +# Python3 packages that come as part of org.freedesktop.Sdk. +system_packages = ['cython', 'easy_install', 'mako', 'markdown', 'meson', 'pip', 'pygments', 'setuptools', 'six', 'wheel'] + +fprint('Generating dependencies') +for package in packages: + + if package.name is None: + print('Warning: skipping invalid requirement specification {} because it is missing a name'.format(package.line), file=sys.stderr) + print('Append #egg= to the end of the requirement line to fix', file=sys.stderr) + continue + elif package.name.casefold() in system_packages: + continue + + if len(package.extras) > 0: + extras = '[' + ','.join(extra for extra in package.extras) + ']' + else: + extras = '' + + version_list = [x[0] + x[1] for x in package.specs] + version = ','.join(version_list) + + if package.vcs: + revision = '' + if package.revision: + revision = '@' + package.revision + pkg = package.uri + revision + '#egg=' + package.name + else: + pkg = package.name + extras + version + + dependencies = [] + # Downloads the package again to list dependencies + + tempdir_prefix = 'pip-generator-{}'.format(package.name) + with tempfile.TemporaryDirectory(prefix='{}-{}'.format(tempdir_prefix, package.name)) as tempdir: + pip_download = flatpak_cmd + [ + 'download', + '--exists-action=i', + '--dest', + tempdir, + ] + try: + print('Generating dependencies for {}'.format(package.name)) + subprocess.run(pip_download + [pkg], check=True, stdout=subprocess.DEVNULL) + for filename in os.listdir(tempdir): + dep_name = get_package_name(filename) + if dep_name.casefold() in system_packages: + continue + dependencies.append(dep_name) + + except subprocess.CalledProcessError: + print('Failed to download {}'.format(package.name)) + + is_vcs = True if package.vcs else False + package_sources = [] + for dependency in dependencies: + if dependency in sources: + source = sources[dependency] + elif dependency.replace('_', '-') in sources: + source = sources[dependency.replace('_', '-')] + else: + continue + + if not (not source['vcs'] or is_vcs): + continue + + package_sources.append(source['source']) + + if package.vcs: + name_for_pip = '.' + else: + name_for_pip = pkg + + module_name = 'python{}-{}'.format(python_version, package.name) + + pip_command = [ + pip_executable, + 'install', + '--exists-action=i', + '--no-index', + '--find-links="file://${PWD}"', + '--prefix=${FLATPAK_DEST}', + '"{}"'.format(name_for_pip) + ] + if opts.no_build_isolation: + pip_command.append('--no-build-isolation') + + module = OrderedDict([ + ('name', module_name), + ('buildsystem', 'simple'), + ('build-commands', [' '.join(pip_command)]), + ('sources', package_sources), + ]) + if opts.cleanup == 'all': + module['cleanup'] = ['*'] + elif opts.cleanup == 'scripts': + module['cleanup'] = ['/bin', '/share/man/man1'] + + if package.vcs: + vcs_modules.append(module) + else: + modules.append(module) + +modules = vcs_modules + modules +if len(modules) == 1: + pypi_module = modules[0] +else: + pypi_module = { + 'name': output_package, + 'buildsystem': 'simple', + 'build-commands': [], + 'modules': modules, + } + +print() +with open(output_filename, 'w') as output: + output.write(json.dumps(pypi_module, indent=4)) + print('Output saved to {}'.format(output_filename)) + diff --git a/build-aux/flatpak/io.github.helpseeker.Gyre.json b/build-aux/flatpak/io.github.helpseeker.Gyre.json new file mode 100644 index 0000000..243cb02 --- /dev/null +++ b/build-aux/flatpak/io.github.helpseeker.Gyre.json @@ -0,0 +1,80 @@ +{ + "app-id" : "io.github.helpseeker.Gyre", + "runtime" : "org.gnome.Platform", + "runtime-version" : "3.38", + "sdk" : "org.gnome.Sdk", + "command" : "gyre", + "finish-args" : [ + "--share=network", + "--share=ipc", + "--socket=fallback-x11", + "--socket=wayland" + ], + "cleanup" : [ + "/include", + "/lib/pkgconfig", + "/man", + "/share/doc", + "/share/gtk-doc", + "/share/man", + "/share/pkgconfig", + "*.la", + "*.a" + ], + "modules" : [ + "python3-aiohttp.json", + { + "name" : "ffmpeg", + "config-opts" : [ + "--disable-all", + "--enable-avcodec", + "--enable-avformat", + "--enable-avfilter", + "--enable-ffmpeg", + "--enable-protocol=file", + "--enable-demuxer=concat,mov,mp3", + "--enable-muxer=matroska,mp4,asf,avi,flv,f4v,mov", + "--enable-bsf=h264_mp4toannexb" + ], + "sources" : [ + { + "type" : "git", + "url" : "https://git.ffmpeg.org/ffmpeg.git", + "tag" : "n4.3.1" + } + ] + }, + { + "name" : "libhandy", + "buildsystem" : "meson", + "config-opts" : [ + "-Dprofiling=false", + "-Dintrospection=enabled", + "-Dgtk_doc=false", + "-Dtests=false", + "-Dexamples=false", + "-Dvapi=false", + "-Dglade_catalog=disabled" + ], + "sources" : [ + { + "type" : "git", + "url" : "https://gitlab.gnome.org/GNOME/libhandy", + "tag" : "1.0.2" + } + ] + }, + { + "name" : "gyre", + "builddir" : true, + "buildsystem" : "meson", + "sources" : [ + { + "type" : "git", + "url" : "https://github.com/HelpSeeker/Gyre.git", + "tag" : "v0.1.0" + } + ] + } + ] +} diff --git a/build-aux/flatpak/python3-aiohttp.json b/build-aux/flatpak/python3-aiohttp.json new file mode 100644 index 0000000..97cb68e --- /dev/null +++ b/build-aux/flatpak/python3-aiohttp.json @@ -0,0 +1,49 @@ +{ + "name": "python3-aiohttp", + "buildsystem": "simple", + "build-commands": [ + "pip3 install --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"aiohttp\" --no-build-isolation" + ], + "sources": [ + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/ea/b7/e0e3c1c467636186c39925827be42f16fee389dc404ac29e930e9136be70/idna-2.10.tar.gz", + "sha256": "b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/97/e7/af7219a0fe240e8ef6bb555341a63c43045c21ab0392b4435e754b716fa1/yarl-1.6.3.tar.gz", + "sha256": "8a9066529240171b68893d60dca86a763eae2139dd42f42106b03cf4b426bf10" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz", + "sha256": "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/f0/cb/80a4a274df7da7b8baf083249b0890a0579374c3d74b5ac0ee9291f912dc/attrs-20.3.0.tar.gz", + "sha256": "832aa3cde19744e49938b91fea06d69ecb9e649c93ba974535d08ad92164f700" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/16/06/0f7367eafb692f73158e5c5cbca1aec798cdf78be5167f6415dd4205fa32/typing_extensions-3.7.4.3.tar.gz", + "sha256": "99d4073b617d30288f569d3f13d2bd7548c3a7e4c8de87db09a9d29bb3a4a60c" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/a1/78/aae1545aba6e87e23ecab8d212b58bb70e72164b67eb090b81bb17ad38e3/async-timeout-3.0.1.tar.gz", + "sha256": "0c3c816a028d47f659d6ff5c745cb2acf1f966da1fe5c19c77a70282b25f4c5f" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/1c/74/e8b46156f37ca56d10d895d4e8595aa2b344cff3c1fb3629ec97a8656ccb/multidict-5.1.0.tar.gz", + "sha256": "25b4e5f22d3a37ddf3effc0710ba692cfc792c2b9edfb9c05aefe823256e84d5" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/68/96/40a765d7d68028c5a6d169b2747ea3f4828ec91a358a63818d468380521c/aiohttp-3.7.3.tar.gz", + "sha256": "9c1a81af067e72261c9cbe33ea792893e83bc6aa987bfbd6fdc1e5e7b22777c4" + } + ] +} \ No newline at end of file diff --git a/build-aux/meson/postinstall.py b/build-aux/meson/postinstall.py new file mode 100755 index 0000000..6a3ea97 --- /dev/null +++ b/build-aux/meson/postinstall.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +from os import environ, path +from subprocess import call + +prefix = environ.get('MESON_INSTALL_PREFIX', '/usr/local') +datadir = path.join(prefix, 'share') +destdir = environ.get('DESTDIR', '') + +# Package managers set this so we don't need to run +if not destdir: + print('Updating icon cache...') + call(['gtk-update-icon-cache', '-qtf', path.join(datadir, 'icons', 'hicolor')]) + + print('Updating desktop database...') + call(['update-desktop-database', '-q', path.join(datadir, 'applications')]) + + print('Compiling GSettings schemas...') + call(['glib-compile-schemas', path.join(datadir, 'glib-2.0', 'schemas')]) + + diff --git a/data/gyre.gresource.xml b/data/gyre.gresource.xml new file mode 100644 index 0000000..1592dd7 --- /dev/null +++ b/data/gyre.gresource.xml @@ -0,0 +1,13 @@ + + + + ui/about.ui + ui/add_url.ui + ui/add_item.ui + ui/preferences.ui + ui/window.ui + ui/row.ui + menu/menu.xml + menu/add.xml + + diff --git a/data/icons/io.github.helpseeker.Gyre-symbolic.svg b/data/icons/io.github.helpseeker.Gyre-symbolic.svg new file mode 100644 index 0000000..9bda259 --- /dev/null +++ b/data/icons/io.github.helpseeker.Gyre-symbolic.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/data/icons/io.github.helpseeker.Gyre.Source.svg b/data/icons/io.github.helpseeker.Gyre.Source.svg new file mode 100644 index 0000000..a391710 --- /dev/null +++ b/data/icons/io.github.helpseeker.Gyre.Source.svg @@ -0,0 +1,3048 @@ + + + Adwaita Icon Template + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + GNOME Design Team + + + + + Adwaita Icon Template + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hicolor + Symbolic + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + battery is full and there is no a/c connected. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/icons/io.github.helpseeker.Gyre.svg b/data/icons/io.github.helpseeker.Gyre.svg new file mode 100644 index 0000000..b1b5bd4 --- /dev/null +++ b/data/icons/io.github.helpseeker.Gyre.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/data/io.github.helpseeker.Gyre.desktop b/data/io.github.helpseeker.Gyre.desktop new file mode 100644 index 0000000..d4eaace --- /dev/null +++ b/data/io.github.helpseeker.Gyre.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Name=Gyre +Comment=Download videos from Coub +Exec=gyre +Icon=io.github.helpseeker.Gyre +Terminal=false +Type=Application +StartupNotify=true +Categories=Network;GTK;GNOME; +Keywords=coub;download; + diff --git a/data/io.github.helpseeker.Gyre.gschema.xml b/data/io.github.helpseeker.Gyre.gschema.xml new file mode 100644 index 0000000..018eff9 --- /dev/null +++ b/data/io.github.helpseeker.Gyre.gschema.xml @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + '' + Output directory + + Directory to save downloaded coubs in + + + + 'mkv' + Output Extension + + What media container to use to combine separate video/audio streams + + + + '%id%' + Name Template + + Template to name downloaded coubs + Accepts a series of replacement strings: + + %id% - coub ID (identifier in the URL) + %title% - coub title + %creation% - creation date/time + %community% - coub community + %channel% - channel title + %tags% - all tags (separated by _) + + Other strings will be interpreted literally + + + + false + Overwrite Existing Files + + Wheter to overwrite existing files or skip them + + + + 1000 + Limit Loops + + Max. number of video loops per coub + In any case the amount is limited by the audio duration + + + + '' + Limit Duration + + Max. duration per coub (FFmpeg syntax) + Can be used together with a loop limit (the shorter option will be used) + + + + false + Keep Streams + + Keep audio/video streams instead of deleting them after merge + + + + true + Download Video + + Whether to download video streams + + + + 'Highest' + Video Resolution + + Whether to prefer the highest or lowest available video resolution + + + + '1600x1200' + Max. video resolution + + The highest video resolution considered for download + + + + '640x480' + Min. video resolution + + The lowest video resolution considered for download + + + + true + Download Audio + + Whether to download audio streams + + + + 'Best' + Audio quality + + Whether to prefer the best or worst available audio quality + + + + false + Download 'share' version + + Download the version as provided by Coub's own download button + + + + 25 + Connections + + How many connections aiohttp is allowed to use + Excessive values will lead to Coub disconnecting you + + + + 5 + Retries + + How often to reconnect after connection loss + -1 for infinite retries + + + + 0 + Limit Quantity + + Max. number of coubs to download during a single session + 0 for infinite coubs + + + + 'With Recoubs' + Download Recoubs + + How to treat recoubs during channel downloads + + + + false + Use Archive + + Whether to keep track of downloaded coubs + + + + '' + Archive Path + + Path to archive file + + + + false + Output Link List + + Output parsed coub links instead of downloading them + + + + '' + Link List Path + + Path to link list file + + + + false + Info JSON + + Output additional infos for downloaded coubs + + + + '' + Info JSON Path + + Path to info JSON file + + + + '_' + Tag Separator + + Character or string to separate tags in the output filename + + + + 1024 + Download chunk size + + Testing feature - not intended for normal users + + + + true + Allow Unicode Filenames + + Whether to allow unicode filenames or force ASCII + + + + diff --git a/data/io.github.helpseeker.Gyre.metainfo.xml b/data/io.github.helpseeker.Gyre.metainfo.xml new file mode 100644 index 0000000..281f099 --- /dev/null +++ b/data/io.github.helpseeker.Gyre.metainfo.xml @@ -0,0 +1,49 @@ + + + + io.github.helpseeker.Gyre + CC0-1.0 + GPL-3.0-or-later + Gyre + + Download videos from Coub + +

Gyre is a GTK3 downloader for videos from Coub.

+

What you can download with Gyre:

+
    +
  • Single coubs
  • +
  • Stories
  • +
  • Channels
  • +
  • Tags
  • +
  • Search results
  • +
  • Communities (incl. Featured and Coub of the Day)
  • +
  • Hot coubs
  • +
  • Random coubs
  • +
+

Ready to use on desktop and mobile.

+
+ + io.github.helpseeker.Gyre.desktop + + + + https://raw.githubusercontent.com/HelpSeeker/Gyre/master/data/screenshots/desktop_light_16x9.png + + + https://raw.githubusercontent.com/HelpSeeker/Gyre/master/data/screenshots/desktop_dark_16x9.png + + + + https://github.com/HelpSeeker/Gyre + https://github.com/HelpSeeker/Gyre/issues + HelpSeeker + AlmostSerious_AT_protonmail.ch + + + + +

First Release

+
+
+
+
diff --git a/data/menu/add.xml b/data/menu/add.xml new file mode 100644 index 0000000..5bf4a9b --- /dev/null +++ b/data/menu/add.xml @@ -0,0 +1,16 @@ + + + + +
+ + Add URL + app.add_url + + + Add Item + app.add_item + +
+
+
diff --git a/data/menu/menu.xml b/data/menu/menu.xml new file mode 100644 index 0000000..92d223e --- /dev/null +++ b/data/menu/menu.xml @@ -0,0 +1,32 @@ + + + + +
+ + Import Profile + app.import + + + Export Profile + app.export + +
+
+ + Error logs + app.log + +
+
+ + Preferences + app.prefs + + + About Gyre + app.about + +
+
+
diff --git a/data/meson.build b/data/meson.build new file mode 100644 index 0000000..16664e2 --- /dev/null +++ b/data/meson.build @@ -0,0 +1,55 @@ +pkgdatadir = get_option('prefix') / get_option('datadir') / meson.project_name() +desktopfiledir = get_option('datadir') / 'applications' +appdatadir = get_option('datadir') / 'metainfo' +schemadir = get_option('datadir') / 'glib-2.0' / 'schemas' +icondir = get_option('datadir') / 'icons' / 'hicolor' + +desktopfile = 'io.github.helpseeker.Gyre.desktop' +appdata = 'io.github.helpseeker.Gyre.metainfo.xml' +schema = 'io.github.helpseeker.Gyre.gschema.xml' +appicon = 'icons' / 'io.github.helpseeker.Gyre.svg' +symbolicicon = 'icons' / 'io.github.helpseeker.Gyre-symbolic.svg' + +gnome = import('gnome') + +# Gresources +gnome.compile_resources('gyre', + 'gyre.gresource.xml', + gresource_bundle: true, + install: true, + install_dir: pkgdatadir, +) + +# Desktop file +install_data(desktopfile, install_dir: desktopfiledir) + +desktop_utils = find_program('desktop-file-validate', required: false) +if desktop_utils.found() + test('Validate desktop file', desktop_utils, + args: [desktopfiledir / desktopfile] + ) +endif + +# Appdata +install_data(appdata, install_dir: appdatadir) + +appstream_util = find_program('appstream-util', required: false) +if appstream_util.found() + test('Validate appstream file', appstream_util, + args: ['validate-relax', appdatadir / appdata] + ) +endif + +# GSettings schema +install_data(schema, install_dir: schemadir) + +compile_schemas = find_program('glib-compile-schemas', required: false) +if compile_schemas.found() + test('Validate schema file', compile_schemas, + args: ['--strict', '--dry-run', meson.current_source_dir()] + ) +endif + +# Icons +install_data(appicon, install_dir: icondir / 'scalable' / 'apps') +install_data(symbolicicon, install_dir: icondir / 'symbolic' / 'apps') diff --git a/data/screenshots/desktop_dark.png b/data/screenshots/desktop_dark.png new file mode 100644 index 0000000..2e44965 Binary files /dev/null and b/data/screenshots/desktop_dark.png differ diff --git a/data/screenshots/desktop_dark_16x9.png b/data/screenshots/desktop_dark_16x9.png new file mode 100644 index 0000000..2c719a8 Binary files /dev/null and b/data/screenshots/desktop_dark_16x9.png differ diff --git a/data/screenshots/desktop_light.png b/data/screenshots/desktop_light.png new file mode 100644 index 0000000..387cbdc Binary files /dev/null and b/data/screenshots/desktop_light.png differ diff --git a/data/screenshots/desktop_light_16x9.png b/data/screenshots/desktop_light_16x9.png new file mode 100644 index 0000000..f883f8f Binary files /dev/null and b/data/screenshots/desktop_light_16x9.png differ diff --git a/data/screenshots/mobile.png b/data/screenshots/mobile.png new file mode 100755 index 0000000..57d043a Binary files /dev/null and b/data/screenshots/mobile.png differ diff --git a/data/ui/about.ui b/data/ui/about.ui new file mode 100644 index 0000000..77d50ee --- /dev/null +++ b/data/ui/about.ui @@ -0,0 +1,46 @@ + + + + + + diff --git a/data/ui/add_item.ui b/data/ui/add_item.ui new file mode 100644 index 0000000..ebdde7c --- /dev/null +++ b/data/ui/add_item.ui @@ -0,0 +1,202 @@ + + + + + + + True + False + go-previous-symbolic + + + diff --git a/data/ui/add_url.ui b/data/ui/add_url.ui new file mode 100644 index 0000000..7748dcd --- /dev/null +++ b/data/ui/add_url.ui @@ -0,0 +1,138 @@ + + + + + + + True + False + go-previous-symbolic + + + diff --git a/data/ui/preferences.ui b/data/ui/preferences.ui new file mode 100644 index 0000000..c65825a --- /dev/null +++ b/data/ui/preferences.ui @@ -0,0 +1,478 @@ + + + + + + + + True + False + document-open-symbolic + + + True + False + document-open-symbolic + + + True + False + document-open-symbolic + + + diff --git a/data/ui/row.ui b/data/ui/row.ui new file mode 100644 index 0000000..617c02e --- /dev/null +++ b/data/ui/row.ui @@ -0,0 +1,104 @@ + + + + + + True + False + edit-delete-symbolic + + + True + False + document-edit-symbolic + + + diff --git a/data/ui/window.ui b/data/ui/window.ui new file mode 100644 index 0000000..103957f --- /dev/null +++ b/data/ui/window.ui @@ -0,0 +1,226 @@ + + + + + + + diff --git a/gyre/__init__.py b/gyre/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/gyre/application.py b/gyre/application.py new file mode 100644 index 0000000..9f8246a --- /dev/null +++ b/gyre/application.py @@ -0,0 +1,328 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import asyncio +import pathlib +import time +import urllib + +import aiohttp +import gi + +gi.require_version("Gtk", "3.0") +gi.require_version("Handy", "1") + +from gi.repository import Gtk, Gio, Handy, GLib, GObject + +from gyre import utils +from gyre.core.container import cancel_containers, uncancel_containers +from gyre.core.coub import Coub, cancel_coubs, uncancel_coubs +from gyre.core.settings import Settings +from gyre.interface.about import AboutWindow +from gyre.interface.add import AddURLWindow, AddWindow +from gyre.interface.window import GyreWindow +from gyre.interface.preferences import PreferenceWindow +from gyre.interface import dialogs + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Global variables +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# A hard limit on how many Coubs to process at once +# Prevents excessive RAM usage for very large downloads +COUB_LIMIT = 1000 + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class Application(Gtk.Application): + + idle = GObject.Property(type=bool, default=True) + + def __init__(self): + super().__init__(application_id='io.github.helpseeker.Gyre', + flags=Gio.ApplicationFlags.FLAGS_NONE) + + self.window = None + self.connect("notify::idle", self._on_idle_changed) + + def add_actions(self): + add_url_clicked = Gio.SimpleAction.new("add_url", None) + add_url_clicked.connect("activate", self.do_add_url) + self.add_action(add_url_clicked) + + add_item_clicked = Gio.SimpleAction.new("add_item", None) + add_item_clicked.connect("activate", self.do_add_item) + self.add_action(add_item_clicked) + + clean_clicked = Gio.SimpleAction.new("clean", None) + clean_clicked.connect("activate", self.do_clean_list) + self.add_action(clean_clicked) + + import_clicked = Gio.SimpleAction.new("import", None) + import_clicked.connect("activate", self.do_import_profile) + self.add_action(import_clicked) + + export_clicked = Gio.SimpleAction.new("export", None) + export_clicked.connect("activate", self.do_export_profile) + self.add_action(export_clicked) + + error_log_clicked = Gio.SimpleAction.new("log", None) + error_log_clicked.connect("activate", self.do_open_error_log) + self.add_action(error_log_clicked) + + about_clicked = Gio.SimpleAction.new("about", None) + about_clicked.connect("activate", self.do_open_about) + self.add_action(about_clicked) + + prefs_clicked = Gio.SimpleAction.new("prefs", None) + prefs_clicked.connect("activate", self.do_open_prefs) + self.add_action(prefs_clicked) + + start_clicked = Gio.SimpleAction.new("start", None) + start_clicked.connect("activate", self.do_start_download) + self.add_action(start_clicked) + + stop_clicked = Gio.SimpleAction.new("stop", None) + stop_clicked.connect("activate", self.do_stop_download) + self.add_action(stop_clicked) + + def do_startup(self): + Gtk.Application.do_startup(self) + Handy.init() + + def do_activate(self): + if not self.window: + self.window = GyreWindow( + application=self, + title="Gyre", + icon_name="io.github.helpseeker.Gyre" + ) + self.add_actions() + + self.window.clean_button.set_action_name("app.clean") + self.window.start_button.set_action_name("app.start") + self.window.stop_button.set_action_name("app.stop") + # for some reason binding the action makes the start button sensitive again + self.window.update_widgets() + + self.window.connect("delete-event", self._on_delete_event) + self.window.show_all() + + self.window.present() + + def _on_delete_event(self, *args): + if self.idle: + return False + + dialog = dialogs.CloseConfirmation(self.window) + if dialog.run() == Gtk.ResponseType.YES: + self.quit() + dialog.destroy() + + return True + + def do_shutdown(self): + Gtk.Application.do_shutdown(self) + self._clean_up() + + def do_add_url(self, *args): + add_window = AddURLWindow(self.window.list) + add_window.set_transient_for(self.window) + add_window.show_all() + + def do_add_item(self, *args): + add_window = AddWindow(self.window.list) + add_window.set_transient_for(self.window) + add_window.show_all() + + def do_clean_list(self, *args): + # Temp list necessary as removing directly would mess up the order + to_remove = [] + for item in self.window.list: + if item.status in ["Finished", "No new coubs"]: + to_remove.append(item) + for item in to_remove: + self.window.list.remove(self.window.list.find(item)[1]) + + def do_import_profile(self, *args): + if not self.idle: + dialog = dialogs.ImportDisabledInfo(self.window) + dialog.run() + dialog.destroy() + return + + dialog = dialogs.ProfileImporter(self.window) + # FileChooserNative doesn't have any signals to connect + if dialog.run() == Gtk.ResponseType.ACCEPT: + profile = pathlib.Path(dialog.get_filename()) + utils.import_profile(profile, self.window.list) + dialog.destroy() + + def do_export_profile(self, *args): + dialog = dialogs.ProfileExporter(self.window) + # FileChooserNative doesn't have any signals to connect + if dialog.run() == Gtk.ResponseType.ACCEPT: + profile = pathlib.Path(dialog.get_filename()) + utils.export_profile(profile, self.window.list) + dialog.destroy() + + def do_open_error_log(self, *args): + error_log = Gio.File.new_for_path(str(utils.get_error_log())) + + try: + app = error_log.query_default_handler() + if not app.launch([error_log]): + raise GLib.Error + except GLib.Error: + # Provide an internal viewer, in case we're unable to launch a handler + # This is the norm for Flatpak + dialog = dialogs.ErrorLogViewer(self.window) + dialog.run() + dialog.destroy() + + def do_open_about(self, *args): + about_dialog = AboutWindow() + about_dialog.set_transient_for(self.window) + if about_dialog.run() == Gtk.ResponseType.DELETE_EVENT: + about_dialog.destroy() + + def do_open_prefs(self, *args): + prefs_window = PreferenceWindow() + prefs_window.set_transient_for(self.window) + prefs_window.show_all() + + def do_start_download(self, *args): + if not self.idle: + return + + uncancel_containers() + uncancel_coubs() + + # Prompt user, if no existing output folder is selected + # This can happen if no folder was chosen yet or if the chosen one was deleted + while not pathlib.Path(Settings.get_default().output_path).exists(): + dialog = dialogs.MissingPathWarning(self.window) + dialog.run() + dialog.destroy() + + try: + urllib.request.urlopen("https://coub.com") + except urllib.error.URLError: + dialog = dialogs.NoConnectionError(self.window) + dialog.run() + dialog.destroy() + return + + if not Settings.get_default().valid(): + dialog = dialogs.InvalidSettingsError(self.window) + dialog.run() + dialog.destroy() + return + + # Thread changes self.idle internally + thread = utils.WorkThread( + target=asyncio.run, + args=(process(self.window.list),), + daemon=True, + parent=self, + ) + thread.start() + + def do_stop_download(self, *args): + cancel_containers() + cancel_coubs() + # Stall until the work thread finished + while not self.idle: + time.sleep(0.1) + self._clean_up() + + def _on_idle_changed(self, *args): + for row in self.window.listbox: + row.set_editable(self.idle) + + @staticmethod + def _clean_up(): + for p in pathlib.Path(Settings.get_default().output_path).glob("*.gyre"): + p.unlink() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Functions +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +async def process(model): + ids = set() + coubs = [] + + quantity = None + if Settings.get_default().quantity_limit: + quantity = Settings.get_default().quantity_limit + + archive_content = set() + if Settings.get_default().archive: + archive = pathlib.Path(Settings.get_default().archive_path) + if archive.exists(): + archive_content = set(archive.read_text().splitlines()) + + tout = aiohttp.ClientTimeout(total=None) + conn = aiohttp.TCPConnector(limit=Settings.get_default().connections) + async with aiohttp.ClientSession(timeout=tout, connector=conn) as session: + for item in model: + item.status = "Started" + item.reset() + + try: + for item in model: + item.status = "Parsing" + temp = await item.get_ids(session, quantity) + # Weed out duplicates and already downloaded IDs + temp = [i for i in temp if not (i in ids or i in archive_content)] + # Adjust container count based on filtered ID list + item.count = len(temp) + if temp: + coubs.extend([Coub(i, item, session) for i in temp]) + # Ugly, but we want to keep it a set for faster lookup + ids = list(ids) + ids.extend(temp) + ids = set(ids) + if quantity is not None: + quantity -= len(temp) + item.status = "Waiting" + + # Marking containers as finished while parsing is problematic + # Users could clean them up (i.e. remove them) and mess up the list order + for item in model: + if Settings.get_default().output_list: + item.status = "Finished" + elif not item.count: + item.status = "No new coubs" + else: + item.status = "Downloading" + + if Settings.get_default().output_list: + links = [f"https://coub.com/view/{coub.id}" for coub in coubs] + pathlib.Path(Settings.get_default().output_list_path).write_text("\n".join(links)) + return + + while coubs: + tasks = [c.process() for c in coubs[:COUB_LIMIT]] + await asyncio.gather(*tasks) + coubs = coubs[COUB_LIMIT:] + except utils.CancelledError: + for item in model: + item.status = "Cancelled" diff --git a/gyre/core/container.py b/gyre/core/container.py new file mode 100644 index 0000000..c4d3970 --- /dev/null +++ b/gyre/core/container.py @@ -0,0 +1,499 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import asyncio +import json +import math +import pathlib +import re +from urllib.error import HTTPError +from urllib.parse import quote as urlquote +from urllib.parse import unquote as urlunquote +from urllib.request import urlopen + +from aiohttp import ClientError +from gi.repository import GObject + +from gyre.utils import CancelledError, write_error_log +from gyre.core.settings import Settings + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Global variables +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +CANCELLED = False + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class ContainerUnavailableError(Exception): + pass + + +class InsufficientRetriesError(Exception): + pass + + +class BaseContainer(GObject.GObject): + type = "" + id = "" + sort = "" + quantity = 0 + template = "" + + # Attempts are done on a per-page level, but the attempt limit is for all pages + attempt = 0 + + status = GObject.Property(type=str, default="") + page_progress = GObject.Property(type=int, default=0) + done = GObject.Property(type=int, default=0) + + pages = 0 + count = 0 + invalid = 0 + exist = 0 + + PER_PAGE = 25 + + def __init__(self, id, sort, quantity): + super().__init__() + # Links copied from the browser already have special characters escaped + # Using urlquote again leads to invalid templates + self.id = urlunquote(id) + self.sort = sort + self.quantity = quantity + + def _assemble_template(self): + pass + + def _fetch_page_count(self): + if CANCELLED: + raise CancelledError + + try: + with urlopen(self.template) as resp: + self.pages = json.loads(resp.read())["total_pages"] + except HTTPError: + raise ContainerUnavailableError + + async def _fetch_page_ids(self, request, session): + api_json = None + retries = Settings.get_default().retry_attempts + while retries < 0 or self.attempt <= retries: + if CANCELLED: + raise CancelledError + + try: + async with session.get(request) as response: + api_json = await response.read() + api_json = json.loads(api_json) + break + except ClientError: + self.attempt += 1 + + if api_json is None: + raise InsufficientRetriesError + + ids = [] + for coub in api_json["coubs"]: + if coub["recoub_to"]: + ids.append(coub["recoub_to"]["permalink"]) + else: + ids.append(coub["permalink"]) + + self.page_progress += 1 + return ids + + async def get_ids(self, session, quantity): + self._assemble_template() + + try: + self._fetch_page_count() + + if quantity is None and self.quantity: + quantity = self.quantity + elif quantity is not None and self.quantity: + quantity = self.quantity if self.quantity < quantity else quantity + + if quantity is not None: + max_pages = math.ceil(quantity/self.PER_PAGE) + if self.pages > max_pages: + self.pages = max_pages + + requests = [f"{self.template}&page={p}" for p in range(1, self.pages+1)] + tasks = [self._fetch_page_ids(r, session) for r in requests] + ids = await asyncio.gather(*tasks) + ids = [i for page in ids for i in page] + except ContainerUnavailableError: + self.status = f"Error: Invalid {self.type}" + write_error_log(f"Invalid {self.type}: {self.id}") + ids = [] + except InsufficientRetriesError: + # Be strict about not handling only partially parsed containers + self.status = "Error: No retry attempts left!" + write_error_log("No retry attempts left for {self.type} {self.id}!") + ids = [] + + if quantity is not None: + return ids[:quantity] + return ids + + def reset(self): + self.page_progress = 0 + self.pages = 0 + self.count = 0 + self.done = 0 + self.invalid = 0 + self.exist = 0 + + +class SingleCoub(BaseContainer): + type = "Coub" + + def __init__(self, id, sort="", quantity=0): + super().__init__(id, sort, quantity) + + # async is unnecessary here, but avoids the need for special treatment + async def get_ids(self, session, quantity): + # To trigger status change + self.pages = 1 + self.page_progress = 1 + + # Single coubs don't support per-container quantities + if quantity is not None: + return [self.id][:quantity] + return [self.id] + + +class LinkList(BaseContainer): + type = "List" + + def __init__(self, id, sort="", quantity=0): + super().__init__(id, sort, quantity) + self.list = pathlib.Path(id) + + def _valid_list_file(self): + try: + # Avoid using path object methods as they always read the whole file + with self.list.open("r") as f: + _ = f.read(1) + except FileNotFoundError: + self.status = "Error: List doesn't exist!" + return False + except (OSError, UnicodeError): + self.status = "Error: Invalid list file!" + return False + + return True + + async def get_ids(self, session, quantity): + # To trigger status change + self.pages = 1 + self.page_progress = 1 + + if not self._valid_list_file(): + return [] + + if quantity is None and self.quantity: + quantity = self.quantity + elif quantity is not None and self.quantity: + quantity = self.quantity if self.quantity < quantity else quantity + + ids = self.list.read_text().strip() + ids = re.split(r"\s+", ids) + ids = [i for i in ids if i.startswith("https://coub.com/view/")] + ids = [i.replace("https://coub.com/view/", "") for i in ids] + + if quantity is not None: + return ids[:quantity] + return ids + + +class Channel(BaseContainer): + type = "Channel" + + def __init__(self, id, sort="Most Recent", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Most Recent": "newest", + "Most Liked": "likes_count", + "Most Viewed": "views_count", + "Oldest": "oldest", + "Random": "random", + } + + template = f"https://coub.com/api/v2/timeline/channel/{urlquote(self.id)}" + template = f"{template}?per_page={self.PER_PAGE}" + + if not Settings.get_default().download_recoubs: + template = f"{template}&type=simples" + elif Settings.get_default().download_recoubs == 2: + template = f"{template}&type=recoubs" + + template = f"{template}&order_by={sort_map[self.sort]}" + + self.template = template + + +class Tag(BaseContainer): + type = "Tag" + + def __init__(self, id, sort="Popular", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Popular": "newest_popular", + "Top": "likes_count", + "Views Count": "views_count", + "Fresh": "newest" + } + + template = f"https://coub.com/api/v2/timeline/tag/{urlquote(self.id)}" + template = f"{template}?per_page={self.PER_PAGE}" + template = f"{template}&order_by={sort_map[self.sort]}" + + self.template = template + + def _fetch_page_count(self): + super()._fetch_page_count() + # API limits tags to 99 pages + if self.pages > 99: + self.pages = 99 + + +class Search(BaseContainer): + type = "Search" + + def __init__(self, id, sort="Relevance", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Relevance": None, + "Top": "likes_count", + "Views Count": "views_count", + "Most Recent": "newest" + } + + template = f"https://coub.com/api/v2/search/coubs?q={urlquote(self.id)}" + template = f"{template}&per_page={self.PER_PAGE}" + + if sort_map[self.sort]: + template = f"{template}&order_by={sort_map[self.sort]}" + + self.template = template + + +class Community(BaseContainer): + type = "Community" + + def __init__(self, id, sort="Hot (Monthly)", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Hot (Daily)": "daily", + "Hot (Weekly)": "weekly", + "Hot (Monthly)": "monthly", + "Hot (Quarterly)": "quarter", + "Hot (Six Months)": "half", + "Rising": "rising", + "Fresh": "fresh", + "Top": "likes_count", + "Views Count": "views_count", + "Random": "random", + } + + template = f"https://coub.com/api/v2/timeline/community/{urlquote(self.id)}" + + if self.sort in ("Top", "Views Count"): + template = f"{template}/fresh?order_by={sort_map[self.sort]}&" + elif self.sort == "Random": + template = f"https://coub.com/api/v2/timeline/random/{self.id}?" + else: + template = f"{template}/{sort_map[self.sort]}?" + + template = f"{template}per_page={self.PER_PAGE}" + + self.template = template + + def _fetch_page_count(self): + super()._fetch_page_count() + # API limits communities to 99 pages + if self.pages > 99: + self.pages = 99 + + +class Featured(Community): + type = "Featured" + + def __init__(self, id="", sort="Recent", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Recent": None, + "Top of the Month": "top_of_the_month", + "Undervalued": "undervalued", + } + template = "https://coub.com/api/v2/timeline/explore?" + + if sort_map[self.sort]: + template = f"{template}order_by={sort_map[self.sort]}&" + + template = f"{template}per_page={self.PER_PAGE}" + + self.template = template + + +class CoubOfTheDay(Community): + type = "Coub of the Day" + + def __init__(self, id="", sort="Recent", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Recent": None, + "Top": "top", + "Views Count": "views_count", + } + template = "https://coub.com/api/v2/timeline/explore/coub_of_the_day?" + + if sort_map[self.sort]: + template = f"{template}order_by={sort_map[self.sort]}&" + + template = f"{template}per_page={self.PER_PAGE}" + + self.template = template + + +class Story(BaseContainer): + type = "Story" + PER_PAGE = 20 + + def __init__(self, id, sort="", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + # Story URL contains ID + title separated by a dash + template = f"https://coub.com/api/v2/stories/{self.id.split('-')[0]}/coubs" + template = f"{template}?per_page={self.PER_PAGE}" + + self.template = template + + +class HotSection(BaseContainer): + type = "Hot Section" + + def __init__(self, id="", sort="Hot (Monthly)", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Hot (Daily)": "daily", + "Hot (Weekly)": "weekly", + "Hot (Monthly)": "monthly", + "Hot (Quarterly)": "quarter", + "Hot (Six Months)": "half", + "Rising": "rising", + "Fresh": "fresh", + } + + template = "https://coub.com/api/v2/timeline/subscriptions" + template = f"{template}/{sort_map[self.sort]}" + template = f"{template}?per_page={self.PER_PAGE}" + + self.template = template + + def _fetch_page_count(self): + super()._fetch_page_count() + # API limits hot section to 99 pages + if self.pages > 99: + self.pages = 99 + + +class Random(BaseContainer): + type = "Random" + + def __init__(self, id="", sort="Popular", quantity=0): + super().__init__(id, sort, quantity) + + def _assemble_template(self): + sort_map = { + "Popular": None, + "Top": "top", + } + + template = "https://coub.com/api/v2/timeline/explore/random?" + + if sort_map[self.sort]: + template = f"{template}order_by={sort_map[self.sort]}&" + + template = f"{template}per_page={self.PER_PAGE}" + + self.template = template + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Functions +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +def uncancel_containers(): + global CANCELLED + CANCELLED = False + + +def cancel_containers(): + global CANCELLED + CANCELLED = True + + +def create_container(type, id, sort, quantity): + args = {} + if id: + args["id"] = id + if sort: + args["sort"] = sort + if quantity: + args["quantity"] = quantity + + if type == "Coub": + return SingleCoub(**args) + if type == "List": + return LinkList(**args) + if type == "Channel": + return Channel(**args) + if type == "Tag": + return Tag(**args) + if type == "Search": + return Search(**args) + if type == "Community": + return Community(**args) + if type == "Featured": + return Featured(**args) + if type == "Coub of the Day": + return CoubOfTheDay(**args) + if type == "Story": + return Story(**args) + if type == "Hot Section": + return HotSection(**args) + if type == "Random": + return Random(**args) diff --git a/gyre/core/coub.py b/gyre/core/coub.py new file mode 100644 index 0000000..4ab582a --- /dev/null +++ b/gyre/core/coub.py @@ -0,0 +1,397 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import asyncio +import json +import pathlib +import re +import subprocess +import unicodedata + +from aiohttp import ClientError + +from gyre import utils +from gyre.core.settings import Settings + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Global variables +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +CANCELLED = False + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class CoubUnavailableError(Exception): + pass + +class CoubExistsError(Exception): + + def __init__(self, path): + self.path = path + + +class Coub: + + id = "" + title = "" + creation = "" + channel = "" + community = "" + tags = [] + + container = None + session = None + + video = False + audio = False + + video_link = "" + audio_link = "" + + video_file = None + audio_file = None + merged_file = None + + def __init__(self, id, container, session): + super().__init__() + self.id = id + self.container = container + self.session = session + # We want to be able to re-download coubs with different settings + self.video = Settings.get_default().download_video + self.audio = Settings.get_default().download_audio + # share version is basically like a video-only download + if Settings.get_default().download_share_version: + self.video = True + self.audio = False + + def _clean_up(self): + if Settings.get_default().keep_streams: + return + if not (self.audio_file or self.video_file): + return + + if self.video and self.audio: + self.audio_file.unlink(missing_ok=True) + if not self.video_file == self.merged_file: + self.video_file.unlink(missing_ok=True) + + def _finish(self): + self.container.done += 1 + self._clean_up() + + def _update_properties(self, api_json): + self.title = api_json["title"] + self.creation = api_json["created_at"] + self.channel = api_json["channel"]["title"] + self.tags = [t["title"] for t in api_json["tags"]] + + if api_json["communities"]: + self.community = api_json["communities"][0]["permalink"] + else: + self.community = "undefined" + + def _assemble_name(self): + if not Settings.get_default().name_template: + return self.id + + name = Settings.get_default().name_template + name = name.replace("%id%", self.id) + name = name.replace("%title%", self.title) + name = name.replace("%creation%", self.creation.replace(":", "-")) + name = name.replace("%channel%", self.channel) + name = name.replace("%community%", self.community) + name = name.replace("%tags%", Settings.get_default().tag_separator.join(self.tags)) + name = get_valid_filename(name, Settings.get_default().allow_unicode) + + if not name: + return self.id + + return name + + async def _fetch_infos(self): + if CANCELLED: + raise utils.CancelledError + + async with self.session.get(f"https://coub.com/api/v2/coubs/{self.id}") as response: + api_json = await response.read() + api_json = json.loads(api_json) + + video_streams, audio_streams = get_stream_lists(api_json) + self.video = bool(video_streams) if self.video else self.video + self.audio = bool(audio_streams) if self.audio else self.audio + + if not (self.video or self.audio): + raise CoubUnavailableError + + if self.video: + self.video_link = video_streams[Settings.get_default().video_resolution] + if self.audio: + self.audio_link = audio_streams[Settings.get_default().audio_quality] + + self._update_properties(api_json) + name = self._assemble_name() + path = pathlib.Path(Settings.get_default().output_path) + + self.video_file = path / f"{name}.mp4" + self.audio_file = path / f"{name}.mp3" + self.merged_file = path / f"{name}.{Settings.get_default().file_extension_nick}" + if Settings.get_default().download_share_version: + self.merged_file = self.video_file + + def _check_existence(self): + if CANCELLED: + raise utils.CancelledError + + exists = None + if self.merged_file.exists(): + exists = self.merged_file + elif self.video_file.exists(): + exists = self.video_file + elif self.audio_file.exists(): + exists = self.audio_file + + if exists and not Settings.get_default().overwrite: + raise CoubExistsError(exists) + + def _log_infos(self): + infos = { + "id": self.id, + "title": self.title, + "creation": self.creation, + "channel": self.channel, + "community": self.community, + "tags": self.tags, + } + with pathlib.Path(Settings.get_default().info_json_path).open("a") as f: + print(json.dumps(infos), file=f) + + def _log_archive_entry(self): + with pathlib.Path(Settings.get_default().archive_path).open("a") as f: + print(self.id, file=f) + + async def _download(self): + if CANCELLED: + raise utils.CancelledError + + args = [] + if self.video: + args.append([self.video_link, self.video_file, self.session]) + if self.audio: + args.append([self.audio_link, self.audio_file, self.session]) + + tasks = [save_stream(*a) for a in args] + await asyncio.gather(*tasks) + + # After this point the file won't be removed when the program quits + # Don't do it later to not mess with FFmpeg's automatic format detection + if self.video: + self.video_file.with_suffix(f"{self.video_file.suffix}.gyre").replace(self.video_file) + if self.audio: + self.audio_file.with_suffix(f"{self.audio_file.suffix}.gyre").replace(self.audio_file) + + def _merge_streams(self): + # temp_file uses prefix to not mess with FFmpeg's automatic muxer detection + temp_file = pathlib.Path(self.merged_file.parent, f"temp_{self.merged_file.name}") + concat_file = self.merged_file.with_suffix(".txt") + + with concat_file.open("w") as f: + for _ in range(Settings.get_default().loop_limit): + print(f"file 'file:{self.video_file}'", file=f) + + command = [ + "ffmpeg", "-y", "-v", "error", + "-f", "concat", "-safe", "0", + "-i", f"file:{concat_file}", + "-i", f"file:{self.audio_file}", + ] + if Settings.get_default().duration_limit: + command.extend(["-t", Settings.get_default().duration_limit]) + command.extend(["-c", "copy", "-shortest", f"file:{temp_file}"]) + + subprocess.run(command, check=False) + + concat_file.unlink() + # necessary as FFmpeg can't change files in-place, if merge ext is mp4 + temp_file.replace(self.merged_file) + + async def process(self): + if CANCELLED: + raise utils.CancelledError + + retries = Settings.get_default().retry_attempts + attempt = 0 + while retries < 0 or attempt <= retries: + try: + if not (self.video_link or self.audio_link): + await self._fetch_infos() + self._check_existence() + await self._download() + if self.audio and self.video and not Settings.get_default().download_share_version: + self._merge_streams() + if Settings.get_default().archive: + self._log_archive_entry() + if Settings.get_default().info_json: + self._log_infos() + break + except ClientError: + attempt += 1 + except CoubUnavailableError: + utils.write_error_log(f"https://coub.com/view/{self.id} is unavailable") + self.container.invalid += 1 + break + except CoubExistsError as error: + utils.write_error_log(f"{error.path.name} already exists") + self.container.exist += 1 + break + + self._finish() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Functions +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +def uncancel_coubs(): + global CANCELLED + CANCELLED = False + + +def cancel_coubs(): + global CANCELLED + CANCELLED = True + + +def get_valid_filename(title, allow_unicode): + if allow_unicode: + title = unicodedata.normalize("NFKC", title) + else: + title = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode("ascii") + + title = re.sub(r"[^\w\s().,+-]", " ", title) + title = re.sub(r"[\s]+", " ", title) + + # Make sure there are any words left after ASCII conversion + if not re.sub(r"[^\w]|_", "", title): + return "" + # Fix weird looking paranthesis when words are missing after ASCII conversion + title = re.sub(r"\( ", "(", title) + title = re.sub(r" \)", ")", title) + # Remove starting/trailing characters, which are either invalid or another + # byproduct of the Unicode->ASCII conversion + title = title.strip("-. ") + + try: + # Add example extension to simulate the full name length + test = pathlib.Path(title).with_suffix(".ext.gyre") + test.touch() + test.unlink(missing_ok=True) + except OSError: + return "" + + return title + + +def get_stream_lists(api_json): + # All the following resolutions are max. values + # Depending on the aspect ratio, one side can be smaller + # Think of them as windows, which the video is fit into + # + # 'html5' has 3 video and 2 audio versions + # video: med (640x480) + # high (1280x960) + # higher (1600x1200) + # audio: med (MP3@128Kbps CBR) + # high (MP3@160Kbps VBR) + # + # 'mobile' has 1 video and 2 audio versions + # video: video (640x480) + # audio: 0 (MP3@128Kbps CBR) + # + # 'share' has 1 version (video/audio combined) + # default (1280x960 or 640x480 and AAC@128Kbps CBR) + # + # More infos: + # All videos come with a watermark + # html5 video/audio may have less versions available + # html5 video med and mobile video are the same file + # html5 audio med and mobile audio are the same file + # mobile audio was available as AAC and MP3 in the past (now only MP3) + # share audio is always AAC + # share version is often cut short (never saw it exceed 30 seconds) + # videos come as mp4, audio as mp3 + # video versions may also be upscaled to fit the resolution window + # + # Streams that may still be unavailable: + # share + # html5 video higher + # html5 video med in a non-broken state (doesn't require \x00\x00 fix) + + # Api returns "error: Coub not found" if Coub unavailable + if "error" in api_json: + return ([], []) + + # Share video + if Settings.get_default().download_share_version: + share = api_json["file_versions"]["share"]["default"] + # Non-existence results in None or '{}' (the latter is rare) + if share and share != "{}": + return ([share], []) + return ([], []) + + # Video streams + available = api_json["file_versions"]["html5"]["video"] + formats = ["med", "high", "higher"] + lowest = Settings.get_default().min_video_resolution + highest = Settings.get_default().max_video_resolution + + video = [] + for f in formats[lowest:highest+1]: + if f in available and available[f]["size"]: + # html5 stream sizes can be 0 or None in case of a missing stream + # None is the exception and an irregularity in the Coub API + video.append(available[f]["url"]) + + # Audio streams + try: + available = api_json["file_versions"]["html5"]["audio"] + formats = ["med", "high"] + + audio = [] + for f in formats: + if f in available and available[f]["size"]: + audio.append(available[f]["url"]) + except KeyError: + # No audio + audio = [] + + return (video, audio) + + +async def save_stream(link, path, session): + async with session.get(link) as stream: + # Open file with .gyre suffix to easily distinguish temp files + # .gyre was chosen, to ensure no accidental file erasure (possible with .part) + with path.with_suffix(f"{path.suffix}.gyre").open("wb") as f: + while True: + if CANCELLED: + raise utils.CancelledError + chunk = await stream.content.read(Settings.get_default().download_chunk_size) + if not chunk: + break + f.write(chunk) diff --git a/gyre/core/settings.py b/gyre/core/settings.py new file mode 100644 index 0000000..4603e47 --- /dev/null +++ b/gyre/core/settings.py @@ -0,0 +1,277 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +from gi.repository import Gio + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class Settings(Gio.Settings): + """ + Gio.Settings handler + Implements the basic dconf-settings as properties + """ + + # Default Settings instance + instance = None + + def __init__(self): + super().__init__(self) + + @staticmethod + def valid(): + settings = Settings.get_default() + # Keep this list as short as possible + if settings.max_video_resolution < settings.min_video_resolution: + return False + + return True + + @staticmethod + def new(): + g_settings = Gio.Settings.new("io.github.helpseeker.Gyre") + g_settings.__class__ = Settings + return g_settings + + @staticmethod + def get_default(): + if Settings.instance is None: + Settings.instance = Settings.new() + + return Settings.instance + + @property + def output_path(self): + return self.get_string("output-path") + + @output_path.setter + def output_path(self, value): + self.set_string("output-path", value) + + @property + def file_extension(self): + return self.get_enum("file-extension") + + @file_extension.setter + def file_extension(self, value): + self.set_enum("file-extension", value) + + @property + def file_extension_nick(self): + value = self.file_extension + return ["mkv", "mp4", "asf", "avi", "flv", "f4v", "mov"][value] + + @property + def name_template(self): + return self.get_string("name-template") + + @name_template.setter + def name_template(self, value): + self.set_string("name-template", value) + + @property + def overwrite(self): + return self.get_boolean("overwrite") + + @overwrite.setter + def overwrite(self, value): + self.set_boolean("overwrite", value) + + @property + def loop_limit(self): + return self.get_int("loop-limit") + + @loop_limit.setter + def loop_limit(self, value): + self.set_int("loop-limit", value) + + @property + def duration_limit(self): + return self.get_string("duration-limit") + + @duration_limit.setter + def duration_limit(self, value): + self.set_string("duration-limit", value) + + @property + def keep_streams(self): + return self.get_boolean("keep-streams") + + @keep_streams.setter + def keep_streams(self, value): + self.set_boolean("keep-streams", value) + + @property + def download_video(self): + return self.get_boolean("download-video") + + @download_video.setter + def download_video(self, value): + self.set_boolean("download-video", value) + + @property + def video_resolution(self): + return self.get_enum("video-resolution") + + @video_resolution.setter + def video_resolution(self, value): + self.set_enum("video-resolution", value) + + @property + def max_video_resolution(self): + return self.get_enum("max-video-resolution") + + @max_video_resolution.setter + def max_video_resolution(self, value): + self.set_enum("max-video-resolution", value) + + @property + def min_video_resolution(self): + return self.get_enum("min-video-resolution") + + @min_video_resolution.setter + def min_video_resolution(self, value): + self.set_enum("min-video-resolution", value) + + @property + def download_audio(self): + return self.get_boolean("download-audio") + + @download_audio.setter + def download_audio(self, value): + self.set_boolean("download-audio", value) + + @property + def audio_quality(self): + return self.get_enum("audio-quality") + + @audio_quality.setter + def audio_quality(self, value): + self.set_enum("audio-quality", value) + + @property + def download_share_version(self): + return self.get_boolean("download-share-version") + + @download_share_version.setter + def download_share_version(self, value): + self.set_boolean("download-share-version", value) + + @property + def connections(self): + return self.get_int("connections") + + @connections.setter + def connections(self, value): + self.set_int("connections", value) + + @property + def retry_attempts(self): + return self.get_int("retry-attempts") + + @retry_attempts.setter + def retry_attempts(self, value): + self.set_int("retry-attempts", value) + + @property + def quantity_limit(self): + return self.get_int("quantity-limit") + + @quantity_limit.setter + def quantity_limit(self, value): + self.set_int("quantity-limit", value) + + @property + def download_recoubs(self): + return self.get_enum("download-recoubs") + + @download_recoubs.setter + def download_recoubs(self, value): + self.set_enum("download-recoubs", value) + + @property + def archive(self): + return self.get_boolean("archive") + + @archive.setter + def archive(self, value): + self.set_boolean("archive", value) + + @property + def archive_path(self): + return self.get_string("archive-path") + + @archive_path.setter + def archive_path(self, value): + self.set_string("archive-path", value) + + @property + def output_list(self): + return self.get_boolean("output-list") + + @output_list.setter + def output_list(self, value): + self.set_boolean("output-list", value) + + @property + def output_list_path(self): + return self.get_string("output-list-path") + + @output_list_path.setter + def output_list_path(self, value): + self.set_string("output-list-path", value) + + @property + def info_json(self): + return self.get_boolean("info-json") + + @info_json.setter + def info_json(self, value): + self.set_boolean("info-json", value) + + @property + def info_json_path(self): + return self.get_string("info-json-path") + + @info_json_path.setter + def info_json_path(self, value): + self.set_string("info-json-path", value) + + @property + def tag_separator(self): + return self.get_string("tag-separator") + + @tag_separator.setter + def tag_separator(self, value): + self.set_string("tag-separator", value) + + @property + def download_chunk_size(self): + return self.get_int("download-chunk-size") + + @download_chunk_size.setter + def download_chunk_size(self, value): + self.set_int("download-chunk-size", value) + + @property + def allow_unicode(self): + return self.get_boolean("allow-unicode") + + @allow_unicode.setter + def allow_unicode(self, value): + return self.set_boolean("allow-unicode", value) diff --git a/gyre/gyre.in b/gyre/gyre.in new file mode 100755 index 0000000..00f9596 --- /dev/null +++ b/gyre/gyre.in @@ -0,0 +1,43 @@ +#!@PYTHON@ + +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import os +import sys +import signal +import gettext + +VERSION = '@VERSION@' +pkgdatadir = '@pkgdatadir@' +localedir = '@localedir@' + +sys.path.insert(1, pkgdatadir) +signal.signal(signal.SIGINT, signal.SIG_DFL) +gettext.install('gyre', localedir) + +if __name__ == '__main__': + import gi + + from gi.repository import Gio + resource = Gio.Resource.load(os.path.join(pkgdatadir, 'gyre.gresource')) + resource._register() + + from gyre.application import Application + + app = Application() + sys.exit(app.run(sys.argv)) diff --git a/gyre/interface/about.py b/gyre/interface/about.py new file mode 100644 index 0000000..6c60e0c --- /dev/null +++ b/gyre/interface/about.py @@ -0,0 +1,26 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +from gi.repository import Gtk + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/about.ui") +class AboutWindow(Gtk.AboutDialog): + __gtype_name__ = "AboutWindow" diff --git a/gyre/interface/add.py b/gyre/interface/add.py new file mode 100644 index 0000000..a9548f1 --- /dev/null +++ b/gyre/interface/add.py @@ -0,0 +1,425 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import os + +from gi.repository import Gtk, Handy + +from gyre.core.container import create_container + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/add_url.ui") +class AddURLWindow(Handy.Window): + __gtype_name__ = "AddURLWindow" + + back_button = Gtk.Template.Child("back_button") + add_button = Gtk.Template.Child("add_button") + url_entry = Gtk.Template.Child("url_entry") + limit_spin_button = Gtk.Template.Child("limit_spin_button") + + def __init__(self, model): + super().__init__() + self.model = model + self.url = "" + self.limit = 0 + + self.limit_spin_button.set_adjustment( + Gtk.Adjustment( + value=0, + lower=0, + upper=99999, + step_increment=1, + page_increment=10, + ) + ) + + self.back_button.connect("clicked", lambda x: self.destroy()) + self.add_button.connect("clicked", self._on_add_clicked) + self.url_entry.connect("notify::text", self._on_entry_changed) + # TODO: Figure out whether to use notify::value or value-changed + self.limit_spin_button.connect("value-changed", self._on_spin_button_changed) + + def _on_entry_changed(self, *args): + self.url = self.url_entry.get_text() + self.add_button.set_sensitive(self.url) + + def _on_spin_button_changed(self, *args): + self.limit = self.limit_spin_button.get_value_as_int() + + def _on_add_clicked(self, *args): + self.model.append(map_input(self.url, self.limit)) + self.destroy() + + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/add_item.ui") +class AddWindow(Handy.Window): + __gtype_name__ = "AddWindow" + + back_button = Gtk.Template.Child("back_button") + add_button = Gtk.Template.Child("add_button") + type_dropdown = Gtk.Template.Child("type_dropdown") + entry_label = Gtk.Template.Child("entry_label") + id_entry = Gtk.Template.Child("id_entry") + file_chooser = Gtk.Template.Child("file_chooser") + sort_dropdown = Gtk.Template.Child("sort_dropdown") + limit_spin_button = Gtk.Template.Child("limit_spin_button") + + SUPPORTED_FORMATS = { + "Coub": { + "id": 0, + "entry_label": "ID", + "placeholder": "e.g. 1wtwnp", + "need_id": True, + "sort_list": [], + "default_sort": -1, + }, + "List": { + "id": 1, + "entry_label": "List Location", + "placeholder": None, + "need_id": True, + "sort_list": [], + "default_sort": -1, + }, + "Channel": { + "id": 2, + "entry_label": "Channel", + "placeholder": "e.g. spontaneous-coub", + "need_id": True, + "sort_list": [ + "Most Recent", + "Most Liked", + "Most Viewed", + "Oldest", + "Random", + ], + "default_sort": 0, + }, + "Search": { + "id": 3, + "entry_label": "Term", + "placeholder": "e.g. Kimetsu no Yaiba", + "need_id": True, + "sort_list": [ + "Relevance", + "Top", + "Views Count", + "Most Recent", + ], + "default_sort": 0, + }, + "Tag": { + "id": 4, + "entry_label": "Tag", + "placeholder": "e.g. grandson", + "need_id": True, + "sort_list": [ + "Popular", + "Top", + "Views Count", + "Fresh", + ], + "default_sort": 0, + }, + "Community": { + "id": 5, + "entry_label": "Community", + "placeholder": "e.g. science-technology", + "need_id": True, + "sort_list": [ + "Hot (Daily)", + "Hot (Weekly)", + "Hot (Monthly)", + "Hot (Quarterly)", + "Hot (Six Months)", + "Rising", + "Fresh", + "Top", + "Views Count", + "Random", + ], + "default_sort": 2, + }, + "Featured": { + "id": 6, + "entry_label": "No additional info required", + "placeholder": None, + "need_id": False, + "sort_list": [ + "Recent", + "Top of the Month", + "Undervalued", + ], + "default_sort": 0, + }, + "Coub of the Day": { + "id": 7, + "entry_label": "No additional info required", + "placeholder": None, + "need_id": False, + "sort_list": [ + "Recent", + "Top", + "Views Count", + ], + "default_sort": 0, + }, + "Story": { + "id": 8, + "entry_label": "ID", + "placeholder": "e.g. 903045", + "need_id": True, + "sort_list": [], + "default_sort": -1, + }, + "Hot Section": { + "id": 9, + "entry_label": "No additional info required", + "placeholder": None, + "need_id": False, + "sort_list": [ + "Hot (Daily)", + "Hot (Weekly)", + "Hot (Monthly)", + "Hot (Quarterly)", + "Hot (Six Months)", + "Rising", + "Fresh", + ], + "default_sort": 2, + }, + "Random": { + "id": 10, + "entry_label": "No additional info required", + "placeholder": None, + "need_id": False, + "sort_list": [ + "Popular", + "Top", + ], + "default_sort": 0, + }, + } + + def __init__(self, model, item=None): + super().__init__() + self.model = model + self.item = item + + self.type = self.item.type if self.item else "Coub" + self.id = self.item.id if self.item else "" + self.sort = self.item.sort if self.item else "" + self.limit = self.item.quantity if self.item else 0 + + if self.item: + self.add_button.set_label("Update") + + self.limit_spin_button.set_adjustment( + Gtk.Adjustment( + value=self.limit, + lower=0, + upper=99999, + step_increment=1, + page_increment=10, + ) + ) + + self.back_button.connect("clicked", lambda x: self.destroy()) + self.add_button.connect("clicked", self._on_add_clicked) + self.type_dropdown.connect("notify::active", self._on_type_changed) + self.id_entry.connect("notify::text", self._on_entry_changed) + self.file_chooser.connect("file-set", self._on_file_chosen) + self.sort_dropdown.connect("notify::active", self._on_sort_changed) + self.limit_spin_button.connect("value-changed", self._on_spin_button_changed) + + # Disable add button until input was provided + self.add_button.set_sensitive(False) + + for type in self.SUPPORTED_FORMATS: + self.type_dropdown.append_text(type) + self.type_dropdown.set_active(self.SUPPORTED_FORMATS[self.type]["id"]) + + def _update_add_button(self): + valid = bool(self.id) or not self.SUPPORTED_FORMATS[self.type]["need_id"] + self.add_button.set_sensitive(valid) + + def _on_type_changed(self, *args): + self.type = self.type_dropdown.get_active_text() + + self.entry_label.set_label(self.SUPPORTED_FORMATS[self.type]["entry_label"]) + + if self.type == "List": + self.id_entry.hide() + self.file_chooser.show() + + # Don't set default file, unless ID is an existing path + if self.id and os.path.isfile(self.id): + self.file_chooser.set_filename(self.id) + else: + self.file_chooser.hide() + self.id_entry.show() + self.id_entry.set_sensitive(self.SUPPORTED_FORMATS[self.type]["need_id"]) + self.id_entry.set_placeholder_text(self.SUPPORTED_FORMATS[self.type]["placeholder"]) + + # Don't set entry text, if ID is a list path + if self.id and not os.path.isfile(self.id): + self.id_entry.set_text(self.id) + + self.sort_dropdown.remove_all() + for sort in self.SUPPORTED_FORMATS[self.type]["sort_list"]: + self.sort_dropdown.append_text(sort) + if self.sort in self.SUPPORTED_FORMATS[self.type]["sort_list"]: + self.sort_dropdown.set_active(self.SUPPORTED_FORMATS[self.type]["sort_list"].index(self.sort)) + else: + self.sort_dropdown.set_active(self.SUPPORTED_FORMATS[self.type]["default_sort"]) + + self.limit_spin_button.set_sensitive(self.type != "Coub") + + self._update_add_button() + + def _on_entry_changed(self, *args): + self.id = self.id_entry.get_text() + self._update_add_button() + + def _on_file_chosen(self, *args): + self.id = self.file_chooser.get_filename() + self._update_add_button() + + def _on_sort_changed(self, *args): + self.sort = self.sort_dropdown.get_active_text() + + def _on_spin_button_changed(self, *args): + self.limit = self.limit_spin_button.get_value_as_int() + + def _on_add_clicked(self, *args): + # Switching types may preserve unnecessary ID or sort + if not self.SUPPORTED_FORMATS[self.type]["need_id"]: + self.id = "" + if not self.SUPPORTED_FORMATS[self.type]["sort_list"]: + self.sort = "" + + new = create_container(self.type, self.id, self.sort, self.limit) + if self.item: + pos = self.model.find(self.item)[1] + self.model.splice(pos, 1, [new]) + else: + self.model.append(new) + + self.destroy() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Functions +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# TODO: Prevent wrong input at this stage (to show error in URL Window) + +def map_input(url, quantity): + sort_map = { + "Channel": { + "/coubs": None, + "/reposts": None, + "/stories": None, + }, + "Search": { + "/likes": "Top", + "/views": "Views Count", + "/fresh": "Most Recent", + "/channels": None, + }, + "Tag": { + "/likes": "Top", + "/views": "Views Count", + "/fresh": "Fresh" + }, + "Community": { + "/rising": "Rising", + "/fresh": "Fresh", + "/top": "Top", + "/views": "Views Count", + "/random": "Random", + }, + "Featured": { + "/coubs/top_of_the_month": "Top of the Month", + "/coubs/undervalued": "Undervalued", + "/stories": None, + "/channels": None, + }, + "Hot Section": { + "/rising": "Rising", + "/fresh": "Fresh", + "/hot": "Hot (Monthly)", + }, + "Random": { + "/top": "Top", + }, + } + + # Shorten URL for easier parsing + url = url.strip(" /").lstrip("htps:/") + + # Type detection + if url.startswith("coub.com/view"): + type = "Coub" + elif url.startswith("coub.com/search"): + type = "Search" + elif url.startswith("coub.com/tags"): + type = "Tag" + elif url.startswith(("coub.com/community/featured", "coub.com/featured")): + type = "Featured" + elif url.startswith("coub.com/community/coub-of-the-day"): + type = "Coub of the Day" + elif url.startswith("coub.com/community"): + type = "Community" + elif url.startswith("coub.com/stories"): + type = "Story" + elif url.startswith("coub.com/random"): + type = "Random" + elif url in ["coub.com", "coub.com/rising", "coub.com/fresh", "coub.com/hot"]: + type = "Hot Section" + else: + type = "Channel" + + # Sort detection + sort = None + if type in sort_map: + for suffix in sort_map[type]: + # Despite its name, this string isn't necessarily at the very end (e.g. searches) + if suffix in url: + sort = sort_map[type][suffix] + url = url.replace(suffix, "") + + # ID detection + if type in ["Featured", "Coub of the Day", "Hot Section", "Random"]: + id = None + elif type == "Coub": + id = url.partition("coub.com/view/")[2] + elif type == "Channel": + id = url.partition("coub.com/")[2] + elif type == "Search": + id = url.partition("coub.com/search?q=")[2] + elif type == "Tag": + id = url.partition("coub.com/tags/")[2] + elif type == "Community": + id = url.partition("coub.com/community/")[2] + elif type == "Story": + id = url.partition("coub.com/stories/")[2] + + args = [type, id, sort, quantity] + return create_container(*args) diff --git a/gyre/interface/dialogs.py b/gyre/interface/dialogs.py new file mode 100644 index 0000000..a4246e6 --- /dev/null +++ b/gyre/interface/dialogs.py @@ -0,0 +1,145 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +from gi.repository import Gtk + +from gyre.utils import get_error_log +from gyre.core.settings import Settings + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class ProfileImporter(Gtk.FileChooserNative): + + def __init__(self, parent): + super().__init__( + title="Load Profile", + action=Gtk.FileChooserAction.OPEN, + modal=True, + transient_for=parent, + ) + + +class ProfileExporter(Gtk.FileChooserNative): + + def __init__(self, parent): + super().__init__( + title="Save Profile", + action=Gtk.FileChooserAction.SAVE, + modal=True, + transient_for=parent, + ) + + +class ErrorLogViewer(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.CLOSE, + message_type=Gtk.MessageType.INFO, + text="Unable to open error log", + secondary_text="Using internal viewer instead", + modal=True, + transient_for=parent, + ) + viewer = Gtk.ScrolledWindow( + propagate_natural_height=True, + propagate_natural_width=True, + child=Gtk.TextView( + buffer=Gtk.TextBuffer(text=get_error_log().read_text()), + editable=False, + cursor_visible=False, + ), + ) + self.get_message_area().add(viewer) + self.show_all() + + +class MissingPathWarning(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.CLOSE, + message_type=Gtk.MessageType.WARNING, + text="No existing output location found", + secondary_text="Please specify one before proceeding", + modal=True, + transient_for=parent, + ) + chooser = Gtk.FileChooserButton( + title="Choose Output Directory", + action=Gtk.FileChooserAction.SELECT_FOLDER, + ) + chooser.connect("file-set", self._on_output_path_changed) + self.get_message_area().add(chooser) + self.show_all() + + @staticmethod + def _on_output_path_changed(chooser): + Settings.get_default().output_path = chooser.get_filename() + + +class CloseConfirmation(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.YES_NO, + message_type=Gtk.MessageType.QUESTION, + text="Do you really want to quit while a download is running?", + modal=True, + transient_for=parent, + ) + + +class ImportDisabledInfo(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.CLOSE, + message_type=Gtk.MessageType.INFO, + text="Import disabled", + secondary_text="Please stop the running download before importing", + modal=True, + transient_for=parent, + ) + + +class NoConnectionError(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.CLOSE, + message_type=Gtk.MessageType.ERROR, + text="Unable to connect", + secondary_text="Please check your connection and try again", + modal=True, + transient_for=parent, + ) + + +class InvalidSettingsError(Gtk.MessageDialog): + + def __init__(self, parent): + super().__init__( + buttons=Gtk.ButtonsType.CLOSE, + message_type=Gtk.MessageType.ERROR, + text="Invalid settings detected", + secondary_text="Please open Preferences and resolve any warnings before continuing", + modal=True, + transient_for=parent, + ) diff --git a/gyre/interface/preferences.py b/gyre/interface/preferences.py new file mode 100644 index 0000000..fbc3aa8 --- /dev/null +++ b/gyre/interface/preferences.py @@ -0,0 +1,413 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import pathlib + +from gi.repository import Gtk, Gio, Handy + +from gyre.core.settings import Settings + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/preferences.ui") +class PreferenceWindow(Handy.PreferencesWindow): + __gtype_name__ = "PreferenceWindow" + + ### Output + + # Location + path_chooser = Gtk.Template.Child("path_chooser") + container_row = Gtk.Template.Child("container_row") + name_entry = Gtk.Template.Child("name_entry") + overwrite_switch = Gtk.Template.Child("overwrite_switch") + + # Length + loop_spin_button = Gtk.Template.Child("loop_spin_button") + duration_entry = Gtk.Template.Child("duration_entry") + + # Streams + keep_switch = Gtk.Template.Child("keep_switch") + + ### Quality + + # Video + video_row = Gtk.Template.Child("video_row") + video_switch = Gtk.Template.Child("video_switch") + resolution_row = Gtk.Template.Child("resolution_row") + max_res_row = Gtk.Template.Child("max_res_row") + min_res_row = Gtk.Template.Child("min_res_row") + + # Audio + audio_row = Gtk.Template.Child("audio_row") + audio_switch = Gtk.Template.Child("audio_switch") + audio_quality_row = Gtk.Template.Child("audio_quality_row") + + # Special + share_switch = Gtk.Template.Child("share_switch") + + ### Download + + # Network + connections_spin_button = Gtk.Template.Child("connections_spin_button") + retries_spin_button = Gtk.Template.Child("retries_spin_button") + + # Limits and Filters + quantity_spin_button = Gtk.Template.Child("quantity_spin_button") + recoubs_row = Gtk.Template.Child("recoubs_row") + + ### Misc + + archive_row = Gtk.Template.Child("archive_row") + archive_path_button = Gtk.Template.Child("archive_path_button") + output_list_row = Gtk.Template.Child("output_list_row") + output_list_path_button = Gtk.Template.Child("output_list_path_button") + json_row = Gtk.Template.Child("json_row") + json_path_button = Gtk.Template.Child("json_path_button") + + def __init__(self): + super().__init__() + + self.settings = Settings.get_default() + self._prepare_widgets() + + def _prepare_widgets(self): + + self._prepare_output_widgets() + self._prepare_quality_widgets() + self._prepare_download_widgets() + self._prepare_misc_widgets() + + def _prepare_output_widgets(self): + # Output Path + self.path_chooser.set_filename(self.settings.output_path) + self.path_chooser.connect("selection-changed", self._on_path_changed) + + # Container + liststore = Gio.ListStore.new(Handy.ValueObject) + for ext in ["mkv", "mp4", "asf", "avi", "flv", "f4v", "mov"]: + liststore.append(Handy.ValueObject.new(ext)) + + self.container_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + self.container_row.set_selected_index(self.settings.file_extension) + self.container_row.connect("notify::selected-index", self._on_container_changed) + + # Name Template + self.name_entry.set_text(self.settings.name_template) + self.name_entry.connect("notify::text", self._on_name_template_changed) + + # Overwrite + self.overwrite_switch.set_active(self.settings.overwrite) + self.overwrite_switch.connect("notify::active", self._on_overwrite_changed) + + # Loop Limit + self.loop_spin_button.set_adjustment( + Gtk.Adjustment( + value=self.settings.loop_limit, + lower=1, + upper=99999, + step_increment=1, + page_increment=10, + ) + ) + self.loop_spin_button.connect("notify::value", self._on_loop_limit_changed) + + # Duration Limit + # TODO: Create a better widget for duration (maybe 4 vertical spin buttons?) + self.duration_entry.set_text(self.settings.duration_limit) + self.duration_entry.connect("notify::text", self._on_duration_limit_changed) + + # Keep Streams + self.keep_switch.set_active(self.settings.keep_streams) + self.keep_switch.connect("notify::active", self._on_keep_streams_changed) + + def _prepare_quality_widgets(self): + # Download Video + self.video_switch.set_active(self.settings.download_video) + self.video_switch.connect("notify::active", self._on_video_switch_changed) + + # Video Resolution + liststore = Gio.ListStore.new(Handy.ValueObject) + liststore.append(Handy.ValueObject.new("Lowest")) + liststore.append(Handy.ValueObject.new("Highest")) + + self.resolution_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + # Worst -> 0, Best -> -1 + self.resolution_row.set_selected_index(self.settings.video_resolution*-1) + self.resolution_row.connect("notify::selected-index", self._on_video_resolution_changed) + + # Max Video Resolution + liststore = Gio.ListStore.new(Handy.ValueObject) + for res in ["640x480", "1280x960", "1600x1200"]: + liststore.append(Handy.ValueObject.new(res)) + + self.max_res_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + self.max_res_row.set_selected_index(self.settings.max_video_resolution) + self.max_res_row.connect("notify::selected-index", self._on_max_video_resolution_changed) + + # Min Video Resolution + self.min_res_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + self.min_res_row.set_selected_index(self.settings.min_video_resolution) + self.min_res_row.connect("notify::selected-index", self._on_min_video_resolution_changed) + + # Download Audio + self.audio_switch.set_active(self.settings.download_audio) + self.audio_switch.connect("notify::active", self._on_audio_switch_changed) + + # Audio Quality + liststore = Gio.ListStore.new(Handy.ValueObject) + liststore.append(Handy.ValueObject.new("Worst")) + liststore.append(Handy.ValueObject.new("Best")) + + self.audio_quality_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + # Worst -> 0, Best -> -1 + self.audio_quality_row.set_selected_index(self.settings.audio_quality*-1) + self.audio_quality_row.connect("notify::selected-index", self._on_audio_quality_changed) + + # Download 'share' version + self.share_switch.set_active(self.settings.download_share_version) + self.share_switch.connect("notify::active", self._on_share_switch_changed) + + self._update_quality_widgets() + + def _prepare_download_widgets(self): + # Connections + self.connections_spin_button.set_adjustment( + Gtk.Adjustment( + value=self.settings.connections, + lower=1, + upper=1000, + step_increment=1, + page_increment=10, + ) + ) + self.connections_spin_button.connect("notify::value", self._on_connections_changed) + + # Retries + self.retries_spin_button.set_adjustment( + Gtk.Adjustment( + value=self.settings.retry_attempts, + lower=-1, + upper=99999, + step_increment=1, + page_increment=10, + ) + ) + self.retries_spin_button.connect("notify::value", self._on_retries_changed) + + # Quantity + self.quantity_spin_button.set_adjustment( + Gtk.Adjustment( + value=self.settings.quantity_limit, + lower=0, + upper=99999, + step_increment=1, + page_increment=10, + ) + ) + self.quantity_spin_button.connect("notify::value", self._on_quantity_changed) + + # Recoubs + liststore = Gio.ListStore.new(Handy.ValueObject) + for mode in ["No Recoubs", "With Recoubs", "Only Recoubs"]: + liststore.append(Handy.ValueObject.new(mode)) + + self.recoubs_row.bind_name_model(liststore, Handy.ValueObject.dup_string) + self.recoubs_row.set_selected_index(self.settings.download_recoubs) + self.recoubs_row.connect('notify::selected-index', self._on_recoubs_download_changed) + + def _prepare_misc_widgets(self): + # Archive + self.archive_row.set_expanded(self.settings.archive) + self.archive_row.set_enable_expansion(self.settings.archive) + self.archive_row.connect("notify::enable-expansion", self._on_archive_changed) + + if self.settings.archive_path: + self.archive_path_button.set_label(f"{pathlib.Path(self.settings.archive_path).name} ") + else: + self.archive_path_button.set_label("(None) ") + self.archive_path_button.connect("clicked", self._on_archive_path_button_clicked) + + # Output List + self.output_list_row.set_expanded(self.settings.output_list) + self.output_list_row.set_enable_expansion(self.settings.output_list) + self.output_list_row.connect("notify::enable-expansion", self._on_output_list_changed) + + if self.settings.output_list_path: + self.output_list_path_button.set_label(f"{pathlib.Path(self.settings.output_list_path).name} ") + else: + self.output_list_path_button.set_label("(None) ") + self.output_list_path_button.connect("clicked", self._on_output_list_path_button_clicked) + + # Info JSON + self.json_row.set_expanded(self.settings.info_json) + self.json_row.set_enable_expansion(self.settings.info_json) + self.json_row.connect("notify::enable-expansion", self._on_info_json_changed) + + if self.settings.info_json_path: + self.json_path_button.set_label(f"{pathlib.Path(self.settings.info_json_path).name} ") + else: + self.json_path_button.set_label("(None) ") + self.json_path_button.connect("clicked", self._on_json_path_button_clicked) + + def _update_quality_widgets(self): + # Video download + video = self.settings.download_video and not self.settings.download_share_version + self.resolution_row.set_sensitive(video) + self.max_res_row.set_sensitive(video) + self.min_res_row.set_sensitive(video) + + if self.settings.max_video_resolution < self.settings.min_video_resolution: + # Unfortunately these icons are massive (32x32) + # Fortunately libhandy devs aren't happy with it either and want to redesign it + # Unfortunately we have to wait until that happens + self.max_res_row.set_icon_name("dialog-warning-symbolic") + self.min_res_row.set_icon_name("dialog-warning-symbolic") + self.max_res_row.set_subtitle("Max. resolution larger than min. resolution") + self.min_res_row.set_subtitle("Max. resolution larger than min. resolution") + else: + self.max_res_row.set_icon_name("") + self.min_res_row.set_icon_name("") + self.max_res_row.set_subtitle("Limit max. resolution considered for download") + self.min_res_row.set_subtitle("Limit min. resolution considered for download") + + # Audio download + audio = self.settings.download_audio and not self.settings.download_share_version + self.audio_quality_row.set_sensitive(audio) + + # Share download + self.video_row.set_sensitive(not self.settings.download_share_version) + self.audio_row.set_sensitive(not self.settings.download_share_version) + + def _on_archive_path_button_clicked(self, button): + dialog = Gtk.FileChooserNative.new( + "Save Archive File", + self, + Gtk.FileChooserAction.SAVE, + None, + None + ) + + # FileChooserNative doesn't have any signals, only the returned response + if dialog.run() == Gtk.ResponseType.ACCEPT: + self.settings.archive_path = dialog.get_filename() + button.set_label(f"{pathlib.Path(self.settings.archive_path).name} ") + + def _on_output_list_path_button_clicked(self, button): + dialog = Gtk.FileChooserNative.new( + "Save Link List", + self, + Gtk.FileChooserAction.SAVE, + None, + None + ) + + # FileChooserNative doesn't have any signals, only the returned response + if dialog.run() == Gtk.ResponseType.ACCEPT: + self.settings.output_list_path = dialog.get_filename() + button.set_label(f"{pathlib.Path(self.settings.output_list_path).name} ") + + def _on_json_path_button_clicked(self, button): + dialog = Gtk.FileChooserNative.new( + "Save Info JSON", + self, + Gtk.FileChooserAction.SAVE, + None, + None + ) + + # FileChooserNative doesn't have any signals, only the returned response + if dialog.run() == Gtk.ResponseType.ACCEPT: + self.settings.info_json_path = dialog.get_filename() + button.set_label(f"{pathlib.Path(self.settings.info_json_path).name} ") + + def _on_path_changed(self, chooser): + self.settings.output_path = chooser.get_filename() + + def _on_container_changed(self, combo_row, prop_name): + self.settings.file_extension = combo_row.get_selected_index() + + def _on_name_template_changed(self, entry, prop_name): + self.settings.name_template = entry.get_text() + + def _on_overwrite_changed(self, toggle_button, prop_name): + self.settings.overwrite = toggle_button.get_active() + + def _on_loop_limit_changed(self, spin_button, prop_name): + self.settings.loop_limit = spin_button.get_value_as_int() + + def _on_duration_limit_changed(self, entry, prop_name): + self.settings.duration_limit = entry.get_text() + + def _on_keep_streams_changed(self, toggle_button, prop_name): + self.settings.keep_streams = toggle_button.get_active() + + def _on_video_switch_changed(self, toggle_button, prop_name): + self.settings.download_video = toggle_button.get_active() + # Force-toggle audio if also video and share are deactivated + if not (self.settings.download_video or self.settings.download_audio or self.settings.download_share_version): + self.audio_switch.set_active(True) + self._update_quality_widgets() + + def _on_video_resolution_changed(self, combo_row, prop_name): + # Worst -> 0, Best -> -1 + self.settings.video_resolution = combo_row.get_selected_index() * -1 + + def _on_max_video_resolution_changed(self, combo_row, prop_name): + self.settings.max_video_resolution = combo_row.get_selected_index() + self._update_quality_widgets() + + def _on_min_video_resolution_changed(self, combo_row, prop_name): + self.settings.min_video_resolution = combo_row.get_selected_index() + self._update_quality_widgets() + + def _on_audio_switch_changed(self, toggle_button, prop_name): + self.settings.download_audio = toggle_button.get_active() + # Force-toggle video if also audio and share are deactivated + if not (self.settings.download_video or self.settings.download_audio or self.settings.download_share_version): + self.video_switch.set_active(True) + self._update_quality_widgets() + + def _on_audio_quality_changed(self, combo_row, prop_name): + # Worst -> 0, Best -> -1 + self.settings.audio_quality = combo_row.get_selected_index() * -1 + + def _on_share_switch_changed(self, toggle_button, prop_name): + self.settings.download_share_version = toggle_button.get_active() + self._update_quality_widgets() + + def _on_connections_changed(self, spin_button, prop_name): + self.settings.connections = spin_button.get_value_as_int() + + def _on_retries_changed(self, spin_button, prop_name): + self.settings.retry_attempts = spin_button.get_value_as_int() + + def _on_quantity_changed(self, spin_button, prop_name): + self.settings.quantity_limit = spin_button.get_value_as_int() + + def _on_recoubs_download_changed(self, combo_row, prop_name): + self.settings.download_recoubs = combo_row.get_selected_index() + + def _on_archive_changed(self, row, prop_name): + self.settings.archive = row.get_enable_expansion() + + def _on_output_list_changed(self, row, prop_name): + self.settings.output_list = row.get_enable_expansion() + + def _on_info_json_changed(self, row, prop_name): + self.settings.info_json = row.get_enable_expansion() diff --git a/gyre/interface/row.py b/gyre/interface/row.py new file mode 100644 index 0000000..23cfef3 --- /dev/null +++ b/gyre/interface/row.py @@ -0,0 +1,121 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +from gi.repository import Gtk, GLib + +from gyre.core.settings import Settings +from gyre.interface.add import AddWindow + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/row.ui") +class InputRow(Gtk.ListBoxRow): + __gtype_name__ = "InputRow" + + main_label = Gtk.Template.Child("main_label") + subtitle = Gtk.Template.Child("subtitle") + edit_button = Gtk.Template.Child("edit_button") + delete_button = Gtk.Template.Child("delete_button") + progress_bar = Gtk.Template.Child("progress_bar") + + def __init__(self, item, model, window): + super().__init__() + + self.item = item + self.model = model + self.window = window + + self.main_label.set_label("".join([ + self.item.type, + f": {self.item.id}" if self.item.id else "", + f" (limit: {self.item.quantity})" if self.item.quantity else "", + + + ])) + self.subtitle.set_label(f"sorted by '{self.item.sort}'" if self.item.sort else "") + + self.edit_button.connect("clicked", self._on_edit) + self.delete_button.connect("clicked", self._on_delete) + self.item.connect("notify::status", lambda *args: GLib.idle_add(self._on_item_status_changed)) + self.item.connect("notify::page-progress", lambda *args: GLib.idle_add(self._on_progress_update)) + self.item.connect("notify::done", lambda *args: GLib.idle_add(self._on_progress_update)) + + def set_editable(self, boolean): + self.edit_button.set_sensitive(boolean) + self.delete_button.set_sensitive(boolean) + + def _on_edit(self, *args): + update_window = AddWindow(self.model, self.item) + update_window.set_transient_for(self.window) + update_window.show_all() + + def _on_delete(self, *args): + self.model.remove(self.model.find(self.item)[1]) + + def _on_progress_update(self, *args): + if self.item.status == "Parsing" and self.item.pages: + self.progress_bar.set_fraction(self.item.page_progress/self.item.pages) + elif self.item.status == "Downloading" and self.item.count: + self.progress_bar.set_fraction(self.item.done/self.item.count) + self.progress_bar.set_text(" ".join([ + "Downloading coubs...", + f"({self.item.done}/{self.item.count})", + f"({self.item.exist} exist)" if self.item.exist else "", + f"({self.item.invalid} errors)" if self.item.invalid else "", + ])) + if self.item.done == self.item.count: + self.item.status = "Finished" + + def _on_item_status_changed(self, *args): + self.progress_bar.set_sensitive(True) + self.progress_bar.set_visible(self.item.status) + if self.item.status == "Started": + self.progress_bar.set_fraction(0) + self.progress_bar.set_text("Waiting to start...") + elif self.item.status == "Parsing": + self.progress_bar.set_fraction(0) + self.progress_bar.set_text("Fetching links...") + elif self.item.status == "Waiting": + if Settings.get_default().output_list: + self.progress_bar.set_fraction(1) + self.progress_bar.set_text("Done parsing!") + else: + self.progress_bar.set_fraction(0) + self.progress_bar.set_text("Waiting to download...") + elif self.item.status == "Downloading": + self.progress_bar.set_fraction(0) + self.progress_bar.set_text("Downloading coubs...") + elif self.item.status == "No new coubs": + self.progress_bar.set_fraction(1) + self.progress_bar.set_text("Finished! (no new coubs or limit exceeded)") + elif self.item.status == "Finished": + self.progress_bar.set_fraction(1) + self.progress_bar.set_text(" ".join([ + "Finished!", + f"({self.item.exist} exist)" if self.item.exist else "", + f"({self.item.invalid} errors)" if self.item.invalid else "", + ])) + else: + self.progress_bar.set_text(self.item.status) + self.progress_bar.set_sensitive(False) + if self.item.status.startswith("Error"): + # Stop watching for item signals after it has become invalid + # thaw_notify() will never be called as doing any changes to the item + # would create a new instance anyway + self.item.freeze_notify() diff --git a/gyre/interface/window.py b/gyre/interface/window.py new file mode 100644 index 0000000..68d12b7 --- /dev/null +++ b/gyre/interface/window.py @@ -0,0 +1,75 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +from gi.repository import Gtk, Gio, Handy + +from gyre.core.container import BaseContainer +from gyre.interface.row import InputRow + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +@Gtk.Template(resource_path="/io/github/helpseeker/Gyre/ui/window.ui") +class GyreWindow(Handy.ApplicationWindow): + __gtype_name__ = "GyreWindow" + + add_button = Gtk.Template.Child("add_button") + clean_button = Gtk.Template.Child("clean_button") + menu_button = Gtk.Template.Child("menu_button") + start_button = Gtk.Template.Child("start_button") + stop_button = Gtk.Template.Child("stop_button") + listbox = Gtk.Template.Child("listbox") + + listbox_window = Gtk.Template.Child("listbox_window") + no_item_box = Gtk.Template.Child("no_item_box") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.builder = Gtk.Builder() + self.builder.add_from_resource("/io/github/helpseeker/Gyre/menu/add.xml") + self.builder.add_from_resource("/io/github/helpseeker/Gyre/menu/menu.xml") + self.add_button.set_menu_model(self.builder.get_object("add-popover")) + self.menu_button.set_menu_model(self.builder.get_object("menu-popover")) + + self.list = Gio.ListStore.new(BaseContainer) + self.listbox.bind_model(self.list, InputRow, self.list, self) + + self.list.connect("items_changed", self.update_widgets) + self.update_widgets() + + def update_widgets(self, *args): + has_input = bool(self.listbox.get_children()) + + # gray out download controls for empty list + self.start_button.set_sensitive(has_input) + self.stop_button.set_sensitive(has_input) + + # Hide either no_item_box or listbox + self.no_item_box.set_no_show_all(has_input) + self.no_item_box.set_visible(not has_input) + self.listbox_window.set_no_show_all(not has_input) + self.listbox_window.set_visible(has_input) + + # Highlight add button for empty list + if not has_input: + self.add_button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION) + else: + self.add_button.get_style_context().remove_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION) + + self.show_all() diff --git a/gyre/meson.build b/gyre/meson.build new file mode 100644 index 0000000..96c867c --- /dev/null +++ b/gyre/meson.build @@ -0,0 +1,44 @@ +pkgdatadir = get_option('prefix') / get_option('datadir') / meson.project_name() +moduledir = pkgdatadir / 'gyre' + +python = import('python') + +conf = configuration_data() +conf.set('PYTHON', python.find_installation('python3').path()) +conf.set('VERSION', meson.project_version()) +conf.set('localedir', get_option('prefix') / get_option('localedir')) +conf.set('pkgdatadir', pkgdatadir) + +configure_file( + input: 'gyre.in', + output: 'gyre', + configuration: conf, + install: true, + install_dir: get_option('bindir') +) + +gyre_sources = [ + '__init__.py', + 'application.py', + 'utils.py', +] + +core_sources = [ + 'core' / 'container.py', + 'core' / 'coub.py', + 'core' / 'settings.py', +] + +interface_sources = [ + 'interface' / 'about.py', + 'interface' / 'add.py', + 'interface' / 'dialogs.py', + 'interface' / 'preferences.py', + 'interface' / 'row.py', + 'interface' / 'window.py', +] + +install_data(gyre_sources, install_dir: moduledir) +install_data(core_sources, install_dir: moduledir / 'core') +install_data(interface_sources, install_dir: moduledir / 'interface') + diff --git a/gyre/utils.py b/gyre/utils.py new file mode 100644 index 0000000..71fd642 --- /dev/null +++ b/gyre/utils.py @@ -0,0 +1,142 @@ +# Copyright (C) 2020 HelpSeeker +# +# This file is part of Gyre. +# +# Gyre 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. +# +# Gyre 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 Gyre. If not, see . + +import json +import pathlib +import threading +import time + +from gi.repository import GLib + +from gyre.core.settings import Settings + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Classes +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +class CancelledError(Exception): + pass + + +class WorkThread(threading.Thread): + + def __init__(self, *args, parent=None, **kwargs): + self.parent = parent + super().__init__(*args, **kwargs) + + def run(self): + self.parent.idle = False + super().run() + self.parent.idle = True + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Functions +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +def get_cache_dir(): + cache_dir = pathlib.Path(GLib.get_user_cache_dir()) + + # Check if we're inside a Flatpak + if is_flatpak(): + return cache_dir + + cache_dir = cache_dir / "gyre" + if not cache_dir.exists(): + cache_dir.mkdir() + + return cache_dir + + +def is_flatpak(): + return pathlib.Path(GLib.get_user_runtime_dir(), "flatpak-info").exists() + + +def get_error_log(): + error_log = get_cache_dir() / "error.log" + + if not error_log.exists(): + error_log.touch(exist_ok=True) + + return error_log + + +def write_error_log(error): + with get_error_log().open("a") as f: + print(f"[{time.asctime()}] {error}", file=f) + + +def import_profile(path, liststore): + from gyre.core.container import create_container + + with path.open("r") as f: + content = json.load(f) + + for opt in content["Settings"]: + setattr(Settings.get_default(), opt, content["Settings"][opt]) + + liststore.remove_all() + liststore.splice(0, 0, [create_container(**item) for item in content["Input"]]) + + +def export_profile(path, liststore): + options = [ + "output_path", + "file_extension", + "name_template", + "overwrite", + "loop_limit", + "duration_limit", + "keep_streams", + "download_video", + "video_resolution", + "max_video_resolution", + "min_video_resolution", + "download_audio", + "audio_quality", + "download_share_version", + "connections", + "retry_attempts", + "quantity_limit", + "download_recoubs", + "archive", + "archive_path", + "output_list", + "output_list_path", + "info_json", + "info_json_path", + "tag_separator", + "tag_separator", + "download_chunk_size", + "allow_unicode", + ] + + content = { + "Settings": { + opt: getattr(Settings.get_default(), opt) for opt in options + }, + "Input": [ + { + "type": item.type, + "id": item.id, + "sort": item.sort, + "quantity": item.quantity + } for item in liststore + ] + } + + with path.open("w") as f: + json.dump(content, f) diff --git a/local_build.sh b/local_build.sh new file mode 100755 index 0000000..9b76df5 --- /dev/null +++ b/local_build.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +meson . _build +cd _build +meson configure -Dprefix=$(pwd)/testdir +ninja install + +GSETTINGS_SCHEMA_DIR=testdir/share/glib-2.0/schemas ./testdir/bin/gyre + diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..bc31f97 --- /dev/null +++ b/meson.build @@ -0,0 +1,13 @@ +project('gyre', + version: '0.1.0', + meson_version: '>= 0.50.0', + default_options: [ 'warning_level=2', + ], +) + +dependency('libhandy-1', version: '>= 1.0.0') + +subdir('data') +subdir('gyre') + +meson.add_install_script('build-aux/meson/postinstall.py')