diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12768e0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +dist/ +build/ +*.spec +.venv/ \ No newline at end of file diff --git a/Archived/icon.icns b/Archived/icon.icns new file mode 100644 index 0000000..2e652f9 Binary files /dev/null and b/Archived/icon.icns differ diff --git a/Archived/icon.svg b/Archived/icon.svg new file mode 100644 index 0000000..11c11d5 --- /dev/null +++ b/Archived/icon.svg @@ -0,0 +1,11 @@ + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..72af7f4 --- /dev/null +++ b/README.md @@ -0,0 +1,161 @@ +[![GitHub All Releases](https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?style=for-the-badge)](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases) + +![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330) + +
+Twitter/X Media Batch Downloader is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts using gallery-dl +
+ +## 📥 Download + +- **Windows**: [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.1/TwitterXMediaBatchDownloader.exe) +- **Linux**: [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.1/TwitterXMediaBatchDownloader) +- **Mac**: [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.1/TwitterXMediaBatchDownloader.app.zip) +- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157) + +### The downloaded application won't run❓ + +🐧 **Solution (Ubuntu/Linux)**: Open your terminal and run: + +```bash +chmod +x TwitterXMediaBatchDownloader +./TwitterXMediaBatchDownloader +``` + +https://github.com/user-attachments/assets/2048555f-393e-469d-a8bd-4275e33a81bd + +🍎 **Solution (macOS)**: Open your terminal and run: + +```bash +xattr -rd com.apple.quarantine ~/Downloads/TwitterXMediaBatchDownloader.app +``` + +https://github.com/user-attachments/assets/f0fcd2ba-e1dd-4205-bda7-2b4154b982ee + +## ✨ Features + +- Powered by `gallery-dl`, similar to `yt-dlp` +- **Bulk download**: Download multiple items at once +- Media-type selection: All (Images + GIFs + Videos) or specific (Images / GIFs / Videos) +- **MP4 → GIF conversion:** Convert downloaded MP4 videos into GIF format +- Downloads at original quality + +## 🖼️ Screenshots + +![image](https://github.com/user-attachments/assets/7295213a-d9ba-4d75-8359-d43907b74aef) + +![image](https://github.com/user-attachments/assets/67bb51ef-0051-4470-b89b-66f653093543) + +![image](https://github.com/user-attachments/assets/9ccc945c-7318-4232-8ba3-9fbb636fa065) + +## 🐧 Build Yourself (Ubuntu/Linux) + +### 1. Install Required Packages + +```bash +sudo apt install git python3-pip python3-venv +``` + +### 2. Clone the Repository + +```bash +git clone https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader.git +cd Twitter-X-Media-Batch-Downloader +``` + +### 3. Create and Activate a Virtual Environment + +```bash +python3 -m venv .venv +source .venv/bin/activate +``` + +### 4. Install Python Dependencies + +```bash +pip install -r requirements.txt +pip install pyinstaller +``` + +### 5. Build the Application + +```bash +pyinstaller --onefile --windowed TwitterXMediaBatchDownloader.py +``` + +### 6. Run the Application + +The compiled binary will be located in the `dist/` folder: + +```bash +./dist/TwitterXMediaBatchDownloader +``` + +## 🍎 Build Yourself (macOS) + +### 1. Install Homebrew (if not already installed) + +```bash +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" +``` + +### 2. Install Git and Python + +```bash +brew install git python +``` + +### 3. Go to Downloads and Clone the Repository + +```bash +cd ~/Downloads +git clone https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader.git +cd Twitter-X-Media-Batch-Downloader +``` + +### 4. Create and Activate a Virtual Environment + +```bash +python3 -m venv .venv +source .venv/bin/activate +``` + +### 5. Install Python Dependencies + +```bash +pip install -r requirements.txt +pip install pyinstaller +``` + +### 6. Build the Application + +```bash +pyinstaller --onefile --windowed --icon=Archived/icon.icns TwitterXMediaBatchDownloader.py +``` + +The `.app` bundle will be generated inside the `dist/` folder. + +## 🔑 How to Obtain Auth Token + +> [!Warning] +> - I suggest not using the **main account** to obtain the token. +> - You can use https://temp-mail.io to register a Twitter account. +> - Using an auth token or cookies has the potential to get the **account suspended.** +> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode. + +### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894) + +1. Go to [Twitter's website](https://www.x.com/) +2. Log into your account +3. Open the Developer Tools by pressing `F12` +4. Navigate to the **Application** tab, then select **Storage → Cookies** +5. Find and copy the `auth_token` value or use the browser extension [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip) +6. Do not log out of your account, as a new `auth_token` will be generated by Twitter + +> X.com Auth Token Grabber + +![image](https://github.com/user-attachments/assets/4bf5f787-d34f-4259-837c-07a6432c4360) + +> Developer Tools + +![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9) diff --git a/TwitterXMediaBatchDownloader.py b/TwitterXMediaBatchDownloader.py new file mode 100644 index 0000000..5718d51 --- /dev/null +++ b/TwitterXMediaBatchDownloader.py @@ -0,0 +1,1715 @@ +import sys +import os +import asyncio +import aiohttp +import requests +import subprocess +import imageio_ffmpeg +import json +import tempfile +from datetime import datetime +from pathlib import Path +from packaging import version +from dataclasses import dataclass +from PyQt6.QtWidgets import ( + QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, + QLabel, QFileDialog, QListWidget, QTextEdit, QTabWidget, QAbstractItemView, QSpacerItem, QSizePolicy, QProgressBar, QCheckBox, QDialog, + QDialogButtonBox, QComboBox, QListWidgetItem +) +from PyQt6.QtCore import Qt, QThread, pyqtSignal, QUrl, QTimer, QTime, QSettings, QSize +from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest +from PyQt6.QtGui import QIcon, QTextCursor, QDesktopServices, QPixmap, QPainter, QPainterPath +from getMetadata import get_metadata + +@dataclass +class Account: + username: str + nick: str + followers: int + following: int + posts: int + media_type: str + profile_image: str = None + media_list: list = None + +class MetadataFetchWorker(QThread): + finished = pyqtSignal(dict) + error = pyqtSignal(str) + + def __init__(self, username, media_type='all', batch_mode=False, batch_size=0, page=0): + super().__init__() + self.username = username + self.media_type = media_type + self.batch_mode = batch_mode + self.batch_size = batch_size + self.page = page + self.auth_token = None + + def normalize_url(self, url_or_username): + url_or_username = url_or_username.strip() + username = url_or_username + + if "x.com/" in url_or_username or "twitter.com/" in url_or_username: + parts = url_or_username.split('/') + for i, part in enumerate(parts): + if part in ['x.com', 'twitter.com'] and i + 1 < len(parts): + username = parts[i + 1] + username = username.split('/')[0] + break + + username = username.strip() + return username + + def run(self): + try: + normalized = self.normalize_url(self.username) + data = get_metadata( + username=normalized, + auth_token=self.auth_token, + timeline_type='media', + batch_size=self.batch_size if self.batch_mode else 0, + page=self.page, + media_type=self.media_type + ) + self.finished.emit(data) + except Exception as e: + self.error.emit(str(e)) + +class DownloadWorker(QThread): + finished = pyqtSignal(bool, str) + progress = pyqtSignal(str, int) + conversion_progress = pyqtSignal(str, int) + download_progress = pyqtSignal(str, int) + + def __init__(self, accounts, outpath, auth_token, filename_format='username_date', + download_batch_size=25, convert_gif=False, gif_resolution='original'): + super().__init__() + self.accounts = accounts + self.outpath = outpath + self.auth_token = auth_token + self.filename_format = filename_format + self.download_batch_size = download_batch_size + self.convert_gif = convert_gif + self.gif_resolution = gif_resolution + self.is_paused = False + self.is_stopped = False + self.filepath_map = [] + + async def download_file(self, session, url, filepath): + try: + if os.path.exists(filepath): + return True, True + if self.is_stopped: + return False, False + + os.makedirs(os.path.dirname(filepath), exist_ok=True) + + async with session.get(url) as response: + if response.status == 200: + with open(filepath, 'wb') as f: + f.write(await response.read()) + return True, False + return False, False + except Exception as e: + return False, False + + async def download_account_media(self, account): + if not account.media_list: + return 0, 0, 0 + + account_output_dir = os.path.join(self.outpath, account.username) + os.makedirs(account_output_dir, exist_ok=True) + timeout = aiohttp.ClientTimeout(total=30) + connector = aiohttp.TCPConnector(limit=self.download_batch_size) + + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: + total = len(account.media_list) + completed = 0 + skipped = 0 + failed = 0 + + used_filenames = set() + + for i in range(0, total, self.download_batch_size): + if self.is_stopped: + break + + while self.is_paused: + if self.is_stopped: + return completed, skipped, failed + await asyncio.sleep(0.1) + + batch = account.media_list[i:i + self.download_batch_size] + tasks = [] + + for item in batch: + url = item['url'] + date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S") + formatted_date = date.strftime("%Y%m%d_%H%M%S") + tweet_id = str(item.get('tweet_id', '')) + + item_type = item.get('type', '') + if item_type == 'animated_gif': + media_type_folder = 'gif' + extension = 'mp4' + elif item_type == 'video' or 'video.twimg.com' in url: + media_type_folder = 'video' + extension = 'mp4' + else: + media_type_folder = 'image' + extension = 'jpg' + media_output_dir = os.path.join(account_output_dir, media_type_folder) + + if self.filename_format == "username_date": + base_filename = f"{account.username}_{formatted_date}_{tweet_id}" + else: + base_filename = f"{formatted_date}_{account.username}_{tweet_id}" + + filename = f"{base_filename}.{extension}" + counter = 1 + while filename in used_filenames: + filename = f"{base_filename}_{counter:02d}.{extension}" + counter += 1 + + used_filenames.add(filename) + filepath = os.path.join(media_output_dir, filename) + self.filepath_map.append((item, filepath)) + task = asyncio.create_task(self.download_file(session, url, filepath)) + tasks.append(task) + results = await asyncio.gather(*tasks, return_exceptions=True) + for result in results: + if isinstance(result, tuple): + success, was_skipped = result + if success: + completed += 1 + if was_skipped: + skipped += 1 + else: + failed += 1 + else: + failed += 1 + + progress_percent = int((completed + failed) / total * 100) + media_type_display = account.media_type if account.media_type != 'all' else 'media' + self.download_progress.emit(f"Downloading {account.username}'s {media_type_display}: {completed + failed:,}/{total:,}", progress_percent) + + await asyncio.sleep(0.1) + + return completed, skipped, failed + + def run(self): + try: + total_accounts = len(self.accounts) + overall_completed = 0 + overall_skipped = 0 + overall_failed = 0 + + for i, account in enumerate(self.accounts): + if self.is_stopped: + break + + while self.is_paused: + if self.is_stopped: + return + self.msleep(100) + media_type_display = account.media_type if account.media_type != 'all' else 'media' + self.progress.emit(f"Downloading from account: {account.username} ({media_type_display}) - ({i+1}/{total_accounts})", + int((i) / total_accounts * 100)) + + completed, skipped, failed = asyncio.run(self.download_account_media(account)) + overall_completed += completed + overall_skipped += skipped + overall_failed += failed + self.progress.emit(f"Account {account.username} ({media_type_display}): {completed:,} downloaded, {skipped:,} skipped, {failed:,} failed", + int((i + 1) / total_accounts * 100)) + + if not self.is_stopped: + if self.convert_gif: + try: + ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe() + gif_items = [(item, fp) for item, fp in self.filepath_map if item.get('type') == 'animated_gif'] + total_gifs = len(gif_items) + if total_gifs > 0: + creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0 + converted_count = 0 + skipped_count = 0 + self.progress.emit("Starting GIF conversion...", 0) + + for idx, (item, fp) in enumerate(gif_items, start=1): + if self.is_stopped: + break + + while self.is_paused: + if self.is_stopped: + break + self.msleep(100) + + if self.is_stopped: + break + + gif_fp = fp.rsplit('.', 1)[0] + '.gif' + + if os.path.exists(gif_fp): + try: + os.remove(fp) + skipped_count += 1 + conv_progress = int((idx / total_gifs) * 100) + self.conversion_progress.emit(f"Converting GIF {idx:,}/{total_gifs:,} ({self.gif_resolution}) - Skipped (exists)", conv_progress) + continue + except Exception: + pass + + if self.gif_resolution == 'high': + ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=800:-1:flags=lanczos', '-r', '15', gif_fp] + elif self.gif_resolution == 'medium': + ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=600:-1:flags=lanczos', '-r', '10', gif_fp] + elif self.gif_resolution == 'low': + ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=400:-1:flags=lanczos', '-r', '8', gif_fp] + else: + ffmpeg_args = [ffmpeg_exe, '-i', fp, gif_fp] + + result = subprocess.run(ffmpeg_args, capture_output=True, creationflags=creationflags) + if result.returncode == 0 and os.path.exists(gif_fp): + try: + os.remove(fp) + converted_count += 1 + except Exception: + pass + else: + pass + + conv_progress = int((idx / total_gifs) * 100) + self.conversion_progress.emit(f"Converting GIF {idx:,}/{total_gifs:,} ({self.gif_resolution})", conv_progress) + if converted_count > 0 or skipped_count > 0: + completion_msg = f"GIF conversion completed: {converted_count:,} converted" + if skipped_count > 0: + completion_msg += f", {skipped_count:,} skipped (already exists)" + self.progress.emit(completion_msg, 100) + else: + self.progress.emit("GIF conversion completed", 100) + except Exception as conv_e: + self.progress.emit(f"GIF conversion error: {conv_e}", 0) + + success_message = f"Download completed! {overall_completed:,} files downloaded" + if overall_skipped > 0: + success_message += f", {overall_skipped:,} skipped" + if overall_failed > 0: + success_message += f", {overall_failed:,} failed" + self.finished.emit(True, success_message) + + except Exception as e: + self.finished.emit(False, str(e)) + + def pause(self): + self.is_paused = True + + def resume(self): + self.is_paused = False + + def stop(self): + self.is_stopped = True + self.is_paused = False + +class UpdateDialog(QDialog): + def __init__(self, current_version, new_version, parent=None): + super().__init__(parent) + self.setWindowTitle("Update Available") + self.setFixedWidth(400) + self.setModal(True) + + layout = QVBoxLayout() + + message = QLabel(f"A new version of Twitter/X Media Batch Downloader is available!\n\n" + f"Current version: v{current_version}\n" + f"New version: v{new_version}") + message.setWordWrap(True) + layout.addWidget(message) + + self.disable_check = QCheckBox("Turn off update checking") + self.disable_check.setCursor(Qt.CursorShape.PointingHandCursor) + layout.addWidget(self.disable_check) + + button_box = QDialogButtonBox() + self.update_button = QPushButton("Update") + self.update_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.cancel_button = QPushButton("Cancel") + self.cancel_button.setCursor(Qt.CursorShape.PointingHandCursor) + + button_box.addButton(self.update_button, QDialogButtonBox.ButtonRole.AcceptRole) + button_box.addButton(self.cancel_button, QDialogButtonBox.ButtonRole.RejectRole) + + layout.addWidget(button_box) + + self.setLayout(layout) + + self.update_button.clicked.connect(self.accept) + self.cancel_button.clicked.connect(self.reject) + +class TwitterMediaDownloaderGUI(QWidget): + def __init__(self): + super().__init__() + self.current_version = "3.1" + self.accounts = [] + self.temp_dir = os.path.join(tempfile.gettempdir(), "twitterxmediabatchdownloader") + os.makedirs(self.temp_dir, exist_ok=True) + self.reset_state() + + self.settings = QSettings('TwitterMediaDownloader', 'Settings') + self.last_output_path = self.settings.value('output_path', str(Path.home() / "Pictures")) + self.last_url = self.settings.value('twitter_url', '') + self.last_auth_token = self.settings.value('auth_token', '') + self.filename_format = self.settings.value('filename_format', 'username_date') + self.download_batch_size = self.settings.value('download_batch_size', 25, type=int) + self.batch_mode = self.settings.value('batch_mode', False, type=bool) + self.batch_size = self.settings.value('batch_size', 100, type=int) + self.timeline_type = self.settings.value('timeline_type', 'media') + self.media_type = self.settings.value('media_type', 'all') + self.convert_gif = self.settings.value('convert_gif', False, type=bool) + self.gif_resolution = self.settings.value('gif_resolution', 'original') + self.check_for_updates = self.settings.value('check_for_updates', True, type=bool) + + self.current_page = 0 + self.media_info = None + + self.is_auto_fetching = False + self.current_fetch_username = None + self.current_fetch_media_type = None + self.current_fetch_metadata = None + + self.profile_image_cache = {} + self.pending_downloads = {} + self.network_manager = QNetworkAccessManager() + + self.elapsed_time = QTime(0, 0, 0) + self.timer = QTimer(self) + self.timer.timeout.connect(self.update_timer) + self.initUI() + self.load_settings() + self.load_all_cached_accounts() + + if self.check_for_updates: + QTimer.singleShot(0, self.check_updates) + + def check_updates(self): + try: + response = requests.get("https://raw.githubusercontent.com/afkarxyz/Twitter-X-Media-Batch-Downloader/refs/heads/main/version.json") + if response.status_code == 200: + data = response.json() + new_version = data.get("version") + + if new_version and version.parse(new_version) > version.parse(self.current_version): + dialog = UpdateDialog(self.current_version, new_version, self) + result = dialog.exec() + + if dialog.disable_check.isChecked(): + self.settings.setValue('check_for_updates', False) + self.check_for_updates = False + + if result == QDialog.DialogCode.Accepted: + QDesktopServices.openUrl(QUrl("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")) + + except Exception as e: + pass + + def reset_state(self): + self.accounts.clear() + + def reset_ui(self): + self.account_list.clear() + self.log_output.clear() + self.progress_bar.setValue(0) + self.progress_bar.hide() + self.stop_btn.hide() + self.pause_resume_btn.hide() + self.pause_resume_btn.setText('Pause') + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.hide() + self.is_auto_fetching = False + self.enable_batch_buttons() + self.hide_account_buttons() + + def initUI(self): + self.setWindowTitle('Twitter/X Media Batch Downloader') + self.setMinimumWidth(650) + self.setMinimumHeight(350) + self.resize(650, 350) + + icon_path = os.path.join(os.path.dirname(__file__), "icon.svg") + if os.path.exists(icon_path): + self.setWindowIcon(QIcon(icon_path)) + + self.main_layout = QVBoxLayout() + + self.setup_twitter_section() + self.setup_tabs() + + self.setLayout(self.main_layout) + + def setup_twitter_section(self): + twitter_layout = QHBoxLayout() + twitter_label = QLabel('Username/URL:') + twitter_label.setFixedWidth(100) + + self.twitter_url = QLineEdit() + self.twitter_url.setPlaceholderText("e.g. Takomayuyi or https://x.com/Takomayuyi") + self.twitter_url.setClearButtonEnabled(True) + self.twitter_url.setText(self.last_url) + self.twitter_url.textChanged.connect(self.save_url) + self.fetch_btn = QPushButton('Fetch') + self.fetch_btn.setFixedWidth(100) + self.fetch_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.fetch_btn.clicked.connect(self.fetch_account) + + twitter_layout.addWidget(twitter_label) + twitter_layout.addWidget(self.twitter_url) + twitter_layout.addWidget(self.fetch_btn) + self.main_layout.addLayout(twitter_layout) + + def setup_tabs(self): + self.tab_widget = QTabWidget() + self.main_layout.addWidget(self.tab_widget) + + self.setup_dashboard_tab() + self.setup_process_tab() + self.setup_settings_tab() + self.setup_about_tab() + + def setup_dashboard_tab(self): + dashboard_tab = QWidget() + dashboard_layout = QVBoxLayout() + + self.account_list = QListWidget() + self.account_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.account_list.itemSelectionChanged.connect(self.update_button_states) + self.account_list.setIconSize(QSize(36, 36)) + self.account_list.setStyleSheet(""" + QListWidget { + background-color: palette(base); + border: 1px solid palette(mid); + border-radius: 4px; + padding: 0px; + outline: none; + } + QListWidget::item { + padding: 8px 12px; + margin: 2px 0px; + border: none; + border-radius: 4px; + outline: none; + } + QListWidget::item:selected { + background-color: palette(highlight); + border: none; + outline: none; + } + QListWidget::item:focus { + border: none; + outline: none; + } + QListWidget::item:hover { + background-color: palette(midlight); + } + """) + + dashboard_layout.addWidget(self.account_list) + + self.setup_account_buttons() + dashboard_layout.addLayout(self.btn_layout) + dashboard_tab.setLayout(dashboard_layout) + self.tab_widget.addTab(dashboard_tab, "Dashboard") + + self.hide_account_buttons() + + def setup_account_buttons(self): + self.btn_layout = QHBoxLayout() + self.download_selected_btn = QPushButton('Download Selected') + self.download_all_btn = QPushButton('Download All') + self.remove_btn = QPushButton('Remove Selected') + self.clear_btn = QPushButton('Clear') + + for btn in [self.download_selected_btn, self.download_all_btn, self.remove_btn, self.clear_btn]: + btn.setFixedWidth(150) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + + self.download_selected_btn.clicked.connect(self.download_selected) + self.download_all_btn.clicked.connect(self.download_all) + self.remove_btn.clicked.connect(self.remove_selected_accounts) + self.clear_btn.clicked.connect(self.clear_accounts) + + self.btn_layout.addStretch() + for btn in [self.download_selected_btn, self.download_all_btn, self.remove_btn, self.clear_btn]: + self.btn_layout.addWidget(btn) + self.btn_layout.addStretch() + + def setup_process_tab(self): + self.process_tab = QWidget() + process_layout = QVBoxLayout() + process_layout.setSpacing(5) + + self.log_output = QTextEdit() + self.log_output.setReadOnly(True) + process_layout.addWidget(self.log_output) + + progress_time_layout = QVBoxLayout() + progress_time_layout.setSpacing(2) + + self.progress_bar = QProgressBar() + progress_time_layout.addWidget(self.progress_bar) + + self.time_label = QLabel("00:00:00") + self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + progress_time_layout.addWidget(self.time_label) + + process_layout.addLayout(progress_time_layout) + + download_control_layout = QHBoxLayout() + self.stop_btn = QPushButton('Stop') + self.pause_resume_btn = QPushButton('Pause') + + self.stop_btn.setFixedWidth(150) + self.pause_resume_btn.setFixedWidth(150) + self.stop_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.pause_resume_btn.setCursor(Qt.CursorShape.PointingHandCursor) + + self.stop_btn.clicked.connect(self.stop_download) + self.pause_resume_btn.clicked.connect(self.toggle_pause_resume) + + download_control_layout.addStretch() + download_control_layout.addWidget(self.stop_btn) + download_control_layout.addWidget(self.pause_resume_btn) + download_control_layout.addStretch() + process_layout.addLayout(download_control_layout) + + batch_control_layout = QHBoxLayout() + self.next_batch_btn = QPushButton('Next Batch') + self.auto_batch_btn = QPushButton('Auto Batch') + self.stop_fetch_btn = QPushButton('Stop Fetch') + + for btn in [self.next_batch_btn, self.auto_batch_btn, self.stop_fetch_btn]: + btn.setFixedWidth(150) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + + self.next_batch_btn.setToolTip("Fetch next batch manually") + self.auto_batch_btn.setToolTip("Start automatic batch fetching") + self.stop_fetch_btn.setToolTip("Stop automatic batch fetching") + + self.next_batch_btn.clicked.connect(self.fetch_next_batch) + self.auto_batch_btn.clicked.connect(self.start_auto_batch) + self.stop_fetch_btn.clicked.connect(self.stop_auto_fetch) + + batch_control_layout.addStretch() + batch_control_layout.addWidget(self.next_batch_btn) + batch_control_layout.addWidget(self.auto_batch_btn) + batch_control_layout.addWidget(self.stop_fetch_btn) + batch_control_layout.addStretch() + process_layout.addLayout(batch_control_layout) + + self.process_tab.setLayout(process_layout) + + self.tab_widget.addTab(self.process_tab, "Process") + + self.progress_bar.hide() + self.time_label.hide() + self.stop_btn.hide() + self.pause_resume_btn.hide() + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.hide() + + def setup_settings_tab(self): + settings_tab = QWidget() + settings_layout = QVBoxLayout() + settings_layout.setSpacing(0) + settings_layout.setContentsMargins(9, 9, 9, 9) + + output_group = QWidget() + output_layout = QVBoxLayout(output_group) + output_layout.setSpacing(5) + + output_label = QLabel('Output Directory') + output_label.setStyleSheet("font-weight: bold;") + output_layout.addWidget(output_label) + + output_dir_layout = QHBoxLayout() + self.output_dir = QLineEdit() + self.output_dir.setText(self.last_output_path) + self.output_dir.textChanged.connect(self.save_settings) + self.output_browse = QPushButton('Browse') + self.output_browse.setCursor(Qt.CursorShape.PointingHandCursor) + self.output_browse.clicked.connect(self.browse_output) + + output_dir_layout.addWidget(self.output_dir) + output_dir_layout.addWidget(self.output_browse) + output_layout.addLayout(output_dir_layout) + + settings_layout.addWidget(output_group) + + auth_group = QWidget() + auth_layout = QVBoxLayout(auth_group) + auth_layout.setSpacing(5) + + auth_label = QLabel('Authentication') + auth_label.setStyleSheet("font-weight: bold;") + auth_layout.addWidget(auth_label) + + auth_token_layout = QHBoxLayout() + auth_token_label = QLabel('Auth Token:') + + self.auth_token_input = QLineEdit() + self.auth_token_input.setPlaceholderText("Enter your Twitter/X auth_token") + self.auth_token_input.setText(self.last_auth_token) + self.auth_token_input.textChanged.connect(self.save_settings) + self.auth_token_input.setClearButtonEnabled(True) + + auth_token_layout.addWidget(auth_token_label) + auth_token_layout.addWidget(self.auth_token_input) + auth_layout.addLayout(auth_token_layout) + + settings_layout.addWidget(auth_group) + + gallery_dl_group = QWidget() + gallery_dl_layout = QVBoxLayout(gallery_dl_group) + gallery_dl_layout.setSpacing(5) + + gallery_dl_label = QLabel('gallery-dl Settings') + gallery_dl_label.setStyleSheet("font-weight: bold;") + gallery_dl_layout.addWidget(gallery_dl_label) + + first_row_layout = QHBoxLayout() + first_row_layout.setSpacing(5) + + self.batch_checkbox = QCheckBox("Batch") + self.batch_checkbox.setCursor(Qt.CursorShape.PointingHandCursor) + self.batch_checkbox.setToolTip("Enable for accounts with thousands of media") + self.batch_checkbox.stateChanged.connect(self.handle_batch_checkbox) + self.batch_checkbox.setChecked(self.batch_mode) + first_row_layout.addWidget(self.batch_checkbox) + + self.size_label = QLabel("Size:") + first_row_layout.addWidget(self.size_label) + self.batch_size_combo = QComboBox() + self.batch_size_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.batch_size_combo.setFixedWidth(60) + for size in [50, 100, 150, 200]: + self.batch_size_combo.addItem(str(size)) + self.batch_size_combo.setCurrentIndex(1) + self.batch_size_combo.currentTextChanged.connect(self.save_batch_size) + first_row_layout.addWidget(self.batch_size_combo) + + self.size_label.hide() + self.batch_size_combo.hide() + + first_row_layout.addSpacing(5) + + timeline_label = QLabel("Timeline Type:") + self.timeline_type_combo = QComboBox() + self.timeline_type_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.timeline_type_combo.setFixedWidth(75) + timeline_types = [ + ('media', 'Media'), + ('timeline', 'Post'), + ('tweets', 'Tweets'), + ('with_replies', 'Replies') + ] + for value, display in timeline_types: + self.timeline_type_combo.addItem(display, value) + self.timeline_type_combo.currentTextChanged.connect(self.save_settings) + first_row_layout.addWidget(timeline_label) + first_row_layout.addWidget(self.timeline_type_combo) + + first_row_layout.addSpacing(5) + + media_type_label = QLabel("Media Type:") + self.media_type_combo = QComboBox() + self.media_type_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.media_type_combo.setFixedWidth(85) + media_types = [('all', 'All'), ('image', 'Image'), ('video', 'Video'), ('gif', 'GIF')] + for value, display in media_types: + self.media_type_combo.addItem(display, value) + self.media_type_combo.currentTextChanged.connect(self.save_settings) + first_row_layout.addWidget(media_type_label) + first_row_layout.addWidget(self.media_type_combo) + + first_row_layout.addStretch() + gallery_dl_layout.addLayout(first_row_layout) + + settings_layout.addWidget(gallery_dl_group) + + download_group = QWidget() + download_layout = QVBoxLayout(download_group) + download_layout.setSpacing(5) + + download_label = QLabel('Download Settings') + download_label.setStyleSheet("font-weight: bold;") + download_layout.addWidget(download_label) + + batch_layout = QHBoxLayout() + batch_label = QLabel('Batch Size:') + + self.download_batch_combo = QComboBox() + self.download_batch_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.download_batch_combo.setFixedWidth(80) + for size in range(5, 101, 5): + self.download_batch_combo.addItem(str(size)) + self.download_batch_combo.setCurrentText(str(self.download_batch_size)) + self.download_batch_combo.currentTextChanged.connect(self.save_settings) + + self.convert_gif_checkbox = QCheckBox("Convert GIF") + self.convert_gif_checkbox.setCursor(Qt.CursorShape.PointingHandCursor) + self.convert_gif_checkbox.setChecked(self.convert_gif) + self.convert_gif_checkbox.toggled.connect(self.handle_gif_checkbox) + + batch_layout.addWidget(batch_label) + batch_layout.addWidget(self.download_batch_combo) + batch_layout.addWidget(self.convert_gif_checkbox) + + self.gif_resolution_label = QLabel("GIF Quality:") + self.gif_resolution_combo = QComboBox() + self.gif_resolution_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.gif_resolution_combo.setFixedWidth(85) + gif_resolutions = [ + ('original', 'Original'), + ('high', 'High'), + ('medium', 'Medium'), + ('low', 'Low') + ] + for value, display in gif_resolutions: + self.gif_resolution_combo.addItem(display, value) + self.gif_resolution_combo.currentTextChanged.connect(self.save_settings) + batch_layout.addWidget(self.gif_resolution_label) + batch_layout.addWidget(self.gif_resolution_combo) + + if not self.convert_gif: + self.gif_resolution_label.hide() + self.gif_resolution_combo.hide() + + batch_layout.addStretch() + download_layout.addLayout(batch_layout) + + settings_layout.addWidget(download_group) + settings_layout.addStretch() + + settings_tab.setLayout(settings_layout) + self.tab_widget.addTab(settings_tab, "Settings") + + def setup_about_tab(self): + about_tab = QWidget() + about_layout = QVBoxLayout() + about_layout.setAlignment(Qt.AlignmentFlag.AlignCenter) + about_layout.setSpacing(3) + + sections = [ + ("Check for Updates", "https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"), + ("Report an Issue", "https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues"), + ("gallery-dl Repository", "https://github.com/mikf/gallery-dl") + ] + + for title, url in sections: + section_widget = QWidget() + section_layout = QVBoxLayout(section_widget) + section_layout.setSpacing(10) + section_layout.setContentsMargins(0, 0, 0, 0) + + label = QLabel(title) + label.setStyleSheet("color: palette(text); font-weight: bold;") + label.setAlignment(Qt.AlignmentFlag.AlignCenter) + section_layout.addWidget(label) + + button = QPushButton("Click Here!") + button.setFixedWidth(150) + button.setStyleSheet(""" + QPushButton { + background-color: palette(button); + color: palette(button-text); + border: 1px solid palette(mid); + padding: 6px; + border-radius: 15px; + } + QPushButton:hover { + background-color: palette(light); + } + QPushButton:pressed { + background-color: palette(midlight); + } + """) + button.setCursor(Qt.CursorShape.PointingHandCursor) + button.clicked.connect(lambda _, url=url: QDesktopServices.openUrl(QUrl(url if url.startswith(('http://', 'https://')) else f'https://{url}'))) + section_layout.addWidget(button, alignment=Qt.AlignmentFlag.AlignCenter) + about_layout.addWidget(section_widget) + if sections.index((title, url)) < len(sections) - 1: + spacer = QSpacerItem(20, 6, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) + about_layout.addItem(spacer) + + footer_label = QLabel("v3.1 | gallery-dl v1.30.0 | July 2025") + footer_label.setStyleSheet("font-size: 12px; margin-top: 10px;") + about_layout.addWidget(footer_label, alignment=Qt.AlignmentFlag.AlignCenter) + about_tab.setLayout(about_layout) + self.tab_widget.addTab(about_tab, "About") + + def save_url(self): + self.settings.setValue('twitter_url', self.twitter_url.text().strip()) + self.settings.sync() + + def save_batch_size(self): + self.batch_size = int(self.batch_size_combo.currentText()) + self.settings.setValue('batch_size', self.batch_size) + self.settings.sync() + + def save_settings(self): + self.settings.setValue('output_path', self.output_dir.text().strip()) + self.settings.setValue('auth_token', self.auth_token_input.text().strip()) + self.settings.setValue('media_type', self.media_type_combo.currentData()) + self.settings.setValue('download_batch_size', int(self.download_batch_combo.currentText())) + + if hasattr(self, 'convert_gif_checkbox'): + self.settings.setValue('convert_gif', self.convert_gif_checkbox.isChecked()) + self.convert_gif = self.convert_gif_checkbox.isChecked() + + if hasattr(self, 'gif_resolution_combo'): + self.settings.setValue('gif_resolution', self.gif_resolution_combo.currentData()) + self.gif_resolution = self.gif_resolution_combo.currentData() + + self.settings.sync() + + def load_settings(self): + try: + if not hasattr(self, 'batch_checkbox') or not hasattr(self, 'size_label') or not hasattr(self, 'batch_size_combo'): + return + + batch_mode = self.settings.value('batch_mode', False, type=bool) + + self.batch_checkbox.blockSignals(True) + self.batch_checkbox.setChecked(batch_mode) + self.batch_checkbox.blockSignals(False) + + if batch_mode: + self.size_label.show() + self.batch_size_combo.show() + self.fetch_btn.setText('Fetch Batch') + else: + self.size_label.hide() + self.batch_size_combo.hide() + self.fetch_btn.setText('Fetch') + + fetch_batch_size = str(self.settings.value('batch_size', 100)) + index = self.batch_size_combo.findText(fetch_batch_size) + if index >= 0: + self.batch_size_combo.setCurrentIndex(index) + else: + self.batch_size_combo.setCurrentIndex(1) + + download_batch_size = str(self.settings.value('download_batch_size', 25)) + index = self.download_batch_combo.findText(download_batch_size) + if index >= 0: + self.download_batch_combo.setCurrentIndex(index) + else: + self.download_batch_combo.setCurrentIndex(0) + media_type = self.settings.value('media_type', 'all') + for i in range(self.media_type_combo.count()): + if self.media_type_combo.itemData(i) == media_type: + self.media_type_combo.setCurrentIndex(i) + break + + convert_gif = self.settings.value('convert_gif', False, type=bool) + if hasattr(self, 'convert_gif_checkbox'): + self.convert_gif_checkbox.blockSignals(True) + self.convert_gif_checkbox.setChecked(convert_gif) + self.convert_gif_checkbox.blockSignals(False) + + if convert_gif: + self.gif_resolution_label.show() + self.gif_resolution_combo.show() + else: + self.gif_resolution_label.hide() + self.gif_resolution_combo.hide() + + gif_resolution = self.settings.value('gif_resolution', 'original') + if hasattr(self, 'gif_resolution_combo'): + for i in range(self.gif_resolution_combo.count()): + if self.gif_resolution_combo.itemData(i) == gif_resolution: + self.gif_resolution_combo.setCurrentIndex(i) + break + + last_username_url = self.settings.value('twitter_url', '') + if last_username_url and hasattr(self, 'twitter_url'): + self.twitter_url.setText(last_username_url) + + except Exception as e: + pass + + def handle_batch_checkbox(self, state): + if not hasattr(self, 'size_label') or not hasattr(self, 'batch_size_combo'): + return + + self.batch_mode = self.batch_checkbox.isChecked() + self.settings.setValue('batch_mode', self.batch_mode) + + if self.batch_checkbox.isChecked(): + self.size_label.show() + self.batch_size_combo.show() + self.fetch_btn.setText('Fetch Batch') + else: + self.size_label.hide() + self.batch_size_combo.hide() + self.fetch_btn.setText('Fetch') + self.update_button_states() + + def handle_gif_checkbox(self, checked): + self.convert_gif = checked + self.save_settings() + + if checked: + self.gif_resolution_label.show() + self.gif_resolution_combo.show() + else: + self.gif_resolution_label.hide() + self.gif_resolution_combo.hide() + + def browse_output(self): + directory = QFileDialog.getExistingDirectory(self, "Select Output Directory") + if directory: + self.output_dir.setText(directory) + self.save_settings() + + def get_cache_file_path(self, username, media_type, is_batch=None): + timeline_type = self.timeline_type_combo.currentData() or 'media' + + filename = f"{username}_{timeline_type}_{media_type}.json" + return os.path.join(self.temp_dir, filename) + + def load_cached_data(self, username, media_type, is_batch=None): + cache_path = self.get_cache_file_path(username, media_type, is_batch) + if os.path.exists(cache_path): + try: + with open(cache_path, 'r', encoding='utf-8') as f: + return json.load(f) + except: + pass + return None + + def save_cached_data(self, username, media_type, data, is_batch=None): + cache_path = self.get_cache_file_path(username, media_type, is_batch) + try: + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + with open(cache_path, 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except: + pass + + def load_all_cached_accounts(self): + try: + if not os.path.exists(self.temp_dir): + return + + cache_files = [f for f in os.listdir(self.temp_dir) if f.endswith('.json')] + + if not cache_files: + return + + loaded_count = 0 + + for cache_file in cache_files: + try: + filename_parts = cache_file.replace('.json', '').split('_') + + if len(filename_parts) >= 3: + media_type = filename_parts[-1] + + if len(filename_parts) == 4 and filename_parts[1] == 'batch': + username = filename_parts[0] + timeline_type = filename_parts[2] + is_batch_file = True + elif len(filename_parts) == 3: + username = filename_parts[0] + timeline_type = filename_parts[1] + is_batch_file = False + else: + username = '_'.join(filename_parts[:-2]) + timeline_type = filename_parts[-2] + is_batch_file = False + + already_exists = any( + acc.username == username and acc.media_type == media_type + for acc in self.accounts + ) + if not already_exists: + cached_data = self.load_cached_data(username, media_type, is_batch=is_batch_file) + if cached_data: + account_info = cached_data.get('account_info', {}) + timeline = cached_data.get('timeline', []) + + if account_info and timeline: + followers = account_info.get('followers_count', 0) + following = account_info.get('friends_count', 0) + posts = account_info.get('statuses_count', 0) + nick = account_info.get('nick', account_info.get('name', '')) + profile_image_url = account_info.get('profile_image', '') + + account = Account( + username=username, + nick=nick, + followers=followers, + following=following, + posts=posts, + media_type=media_type, + profile_image=profile_image_url, + media_list=timeline + ) + + self.accounts.append(account) + loaded_count += 1 + except Exception as e: + continue + + if self.accounts: + self.update_account_list() + + except Exception as e: + pass + + def fetch_account(self): + url = self.twitter_url.text().strip() + + if not url: + self.log_output.append('Warning: Please enter a Twitter username/URL.') + return + + if not self.auth_token_input.text().strip(): + self.log_output.append('Warning: Please enter your auth token.') + return + + username = url + if "x.com/" in url or "twitter.com/" in url: + parts = url.split('/') + for i, part in enumerate(parts): + if part in ['x.com', 'twitter.com'] and i + 1 < len(parts): + username = parts[i + 1] + username = username.split('/')[0] + break + username = username.strip() + + media_type = self.media_type_combo.currentData() + + existing_account = None + for account in self.accounts: + if account.username == username and account.media_type == media_type: + existing_account = account + break + + if existing_account: + self.accounts.remove(existing_account) + + for is_batch in [True, False]: + cache_file = self.get_cache_file_path(username, media_type, is_batch=is_batch) + try: + if os.path.exists(cache_file): + os.remove(cache_file) + self.log_output.append(f'Removed existing cache: {os.path.basename(cache_file)}') + except Exception as e: + self.log_output.append(f'Warning: Could not remove cache {os.path.basename(cache_file)}: {str(e)}') + + self.log_output.append(f'Preparing new batch for {username} ({media_type}) - cache cleared') + self.update_account_list() + + if not existing_account: + cached_data = self.load_cached_data(username, media_type, is_batch=self.batch_mode) + if cached_data: + try: + account_info = cached_data.get('account_info', {}) + timeline = cached_data.get('timeline', []) + if account_info and timeline: + followers = account_info.get('followers_count', 0) + following = account_info.get('friends_count', 0) + posts = account_info.get('statuses_count', 0) + nick = account_info.get('nick', account_info.get('name', '')) + + account = Account( + username=username, + nick=nick, + followers=followers, + following=following, + posts=posts, + media_type=media_type, + media_list=timeline + ) + + self.accounts.append(account) + self.update_account_list() + self.log_output.append(f'Loaded from cache: {username} - Followers: {followers:,} - Posts: {posts:,} • {media_type.title()}') + self.twitter_url.clear() + return + except: + pass + + try: + self.reset_ui() + + self.is_auto_fetching = False + self.current_fetch_username = username + self.current_fetch_media_type = media_type + + self.disable_batch_buttons() + + self.log_output.append(f'Fetching metadata for {username}...') + self.tab_widget.setCurrentWidget(self.process_tab) + + self.metadata_worker = MetadataFetchWorker( + username, + media_type, + batch_mode=self.batch_mode, + batch_size=self.batch_size if self.batch_mode else 0, + page=0 + ) + self.metadata_worker.auth_token = self.auth_token_input.text().strip() + self.metadata_worker.finished.connect(lambda data: self.on_metadata_fetched(data, username, media_type)) + self.metadata_worker.error.connect(self.on_metadata_error) + self.metadata_worker.start() + + except Exception as e: + self.log_output.append(f'Error: Failed to start metadata fetch: {str(e)}') + self.update_account_list() + + def on_metadata_fetched(self, data, username, media_type): + try: + if 'error' in data: + self.log_output.append(f'Error: {data["error"]}') + self.update_account_list() + return + + account_info = data.get('account_info', {}) + timeline = data.get('timeline', []) + metadata = data.get('metadata', {}) + if not account_info: + self.log_output.append('Error: Invalid account data received') + self.update_account_list() + return + + if not timeline: + media_type_display = media_type if media_type != 'all' else 'media' + self.log_output.append(f'Error: No {media_type_display} found for account {username}') + self.update_account_list() + return + existing_account = None + for account in self.accounts: + if account.username == username and account.media_type == media_type: + existing_account = account + break + + if existing_account: + existing_account.media_list.extend(timeline) + new_items = len(timeline) + total_items = len(existing_account.media_list) + self.log_output.append(f'Added {new_items:,} items. Total: {total_items:,} media items for {username}') + else: + followers = account_info.get('followers_count', 0) + following = account_info.get('friends_count', 0) + posts = account_info.get('statuses_count', 0) + nick = account_info.get('nick', account_info.get('name', '')) + profile_image_url = account_info.get('profile_image', '') + + account = Account( + username=username, + nick=nick, + followers=followers, + following=following, + posts=posts, + media_type=media_type, + profile_image=profile_image_url, + media_list=timeline + ) + + self.accounts.append(account) + self.log_output.append(f'Successfully fetched: {username} - Followers: {followers:,} - Posts: {posts:,} • {media_type.title()}') + existing_account = account + + updated_data = { + 'account_info': account_info, + 'timeline': existing_account.media_list, + 'metadata': metadata + } + self.save_cached_data(username, media_type, updated_data, is_batch=self.batch_mode) + + self.update_account_list() + + self.current_fetch_username = username + self.current_fetch_media_type = media_type + self.current_fetch_metadata = metadata + + if self.batch_mode and metadata.get('has_more', False): + current_page = metadata.get('page', 0) + next_page = current_page + 1 + self.log_output.append(f'Batch {current_page + 1} completed. Next batch ({next_page + 1}) available.') + + if self.is_auto_fetching: + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.show() + self.fetch_next_batch_internal() + else: + self.next_batch_btn.show() + self.auto_batch_btn.show() + self.stop_fetch_btn.hide() + self.enable_batch_buttons() + self.log_output.append('Use "Next Batch" for manual fetch or "Auto Batch" for automatic fetching.') + else: + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.hide() + self.is_auto_fetching = False + self.enable_batch_buttons() + + if self.batch_mode: + total_items = len(existing_account.media_list) + self.log_output.append(f'All batches complete! Total: {total_items:,} media items for {username}') + + self.twitter_url.clear() + self.tab_widget.setCurrentIndex(0) + except Exception as e: + self.log_output.append(f'Error: {str(e)}') + self.update_account_list() + + def on_metadata_error(self, error_message): + self.log_output.append(f'Error: {error_message}') + + if self.is_auto_fetching: + self.stop_auto_fetch() + + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.hide() + + self.enable_batch_buttons() + + self.update_account_list() + + def update_account_list(self): + self.account_list.clear() + for i, account in enumerate(self.accounts, 1): + media_count = len(account.media_list) if account.media_list else 0 + media_type_display = "GIF" if account.media_type.lower() == "gif" else account.media_type.title() + + line1 = f"{i}. {account.username} ({account.nick})" + line2 = f"Followers: {account.followers:,} • Following: {account.following:,} • Posts: {account.posts:,} • {media_type_display}: {media_count:,}" + display_text = f"{line1}\n{line2}" + item = QListWidgetItem() + item.setText(display_text) + item.setSizeHint(QSize(0, 52)) + + if account.profile_image: + if account.profile_image in self.profile_image_cache: + item.setIcon(QIcon(self.profile_image_cache[account.profile_image])) + else: + self.download_profile_image(account.profile_image) + placeholder = self.create_placeholder_icon(52) + if placeholder: + item.setIcon(QIcon(placeholder)) + else: + placeholder = self.create_placeholder_icon(52) + if placeholder: + item.setIcon(QIcon(placeholder)) + + self.account_list.addItem(item) + + self.update_button_states() + + def create_placeholder_icon(self, size=36): + pixmap = QPixmap(size, size) + pixmap.fill(Qt.GlobalColor.transparent) + + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + + painter.setBrush(Qt.GlobalColor.gray) + painter.setPen(Qt.PenStyle.NoPen) + painter.drawRoundedRect(0, 0, size, size, 8, 8) + + painter.setPen(Qt.GlobalColor.white) + font_size = int(size * 0.4) + painter.setFont(painter.font()) + painter.drawText(pixmap.rect(), Qt.AlignmentFlag.AlignCenter, "👤") + + painter.end() + return pixmap + + def create_square_pixmap(self, original_pixmap, size=36): + if original_pixmap.isNull(): + return self.create_placeholder_icon(size) + + square_pixmap = QPixmap(size, size) + square_pixmap.fill(Qt.GlobalColor.transparent) + + painter = QPainter(square_pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + + path = QPainterPath() + path.addRoundedRect(0, 0, size, size, 8, 8) + painter.setClipPath(path) + + scaled_pixmap = original_pixmap.scaled( + size, size, + Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation + ) + + x = (size - scaled_pixmap.width()) // 2 + y = (size - scaled_pixmap.height()) // 2 + painter.drawPixmap(x, y, scaled_pixmap) + + painter.end() + return square_pixmap + + def download_profile_image(self, url): + if not url or url in self.profile_image_cache or url in self.pending_downloads: + return + + try: + request = QNetworkRequest(QUrl(url)) + request.setHeader(QNetworkRequest.KnownHeaders.UserAgentHeader, + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36") + + reply = self.network_manager.get(request) + self.pending_downloads[url] = reply + reply.finished.connect(lambda: self.on_profile_image_downloaded(reply, url)) + except Exception as e: + pass + + def on_profile_image_downloaded(self, reply, image_url): + try: + if reply.error() == reply.NetworkError.NoError: + data = reply.readAll() + pixmap = QPixmap() + if pixmap.loadFromData(data): + square_pixmap = self.create_square_pixmap(pixmap, 52) + self.profile_image_cache[image_url] = square_pixmap + + self.update_account_list() + + if image_url in self.pending_downloads: + del self.pending_downloads[image_url] + + except Exception as e: + pass + finally: + reply.deleteLater() + + def update_button_states(self): + has_accounts = len(self.accounts) > 0 + + self.download_selected_btn.setEnabled(has_accounts) + self.download_all_btn.setEnabled(has_accounts) + self.remove_btn.setEnabled(has_accounts) + self.clear_btn.setEnabled(has_accounts) + + if has_accounts: + self.download_selected_btn.show() + self.download_all_btn.show() + self.remove_btn.show() + self.clear_btn.show() + else: + self.hide_account_buttons() + + def hide_account_buttons(self): + buttons = [ + self.download_selected_btn, + self.download_all_btn, + self.remove_btn, + self.clear_btn + ] + for btn in buttons: + btn.hide() + + def download_selected(self): + selected_items = self.account_list.selectedItems() + if not selected_items: + self.log_output.append('Warning: Please select accounts to download.') + return + self.download_accounts([self.account_list.row(item) for item in selected_items]) + + def download_all(self): + self.download_accounts(range(len(self.accounts))) + + def download_accounts(self, indices): + self.log_output.clear() + outpath = self.output_dir.text() + if not os.path.exists(outpath): + self.log_output.append('Warning: Invalid output directory.') + return + + if not self.auth_token_input.text().strip(): + self.log_output.append("Error: Please enter your auth token") + return + + accounts_to_download = [self.accounts[i] for i in indices] + + try: + self.start_download_worker(accounts_to_download, outpath) + except Exception as e: + self.log_output.append(f"Error: An error occurred while starting the download: {str(e)}") + + def start_download_worker(self, accounts_to_download, outpath): + self.worker = DownloadWorker( + accounts_to_download, + outpath, + self.auth_token_input.text().strip(), + self.filename_format, + self.download_batch_size, + self.convert_gif, + self.gif_resolution + ) + self.worker.finished.connect(self.on_download_finished) + self.worker.progress.connect(self.update_progress) + self.worker.conversion_progress.connect(self.update_conversion_progress) + self.worker.download_progress.connect(self.update_download_progress) + self.worker.start() + self.start_timer() + self.update_ui_for_download_start(len(accounts_to_download)) + + def update_ui_for_download_start(self, account_count): + self.download_selected_btn.setEnabled(False) + self.download_all_btn.setEnabled(False) + self.stop_btn.show() + self.pause_resume_btn.show() + + self.next_batch_btn.hide() + self.auto_batch_btn.hide() + self.stop_fetch_btn.hide() + + self.progress_bar.show() + self.progress_bar.setValue(0) + + self.tab_widget.setCurrentWidget(self.process_tab) + + def update_progress(self, message, percentage): + cursor = self.log_output.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.End) + cursor.select(QTextCursor.SelectionType.LineUnderCursor) + current_text = cursor.selectedText() + progress_indicators = [ + "Downloading", + "Account", + "files downloaded" + ] + + should_replace = False + for indicator in progress_indicators: + if indicator in current_text and indicator in message: + should_replace = True + break + if should_replace and current_text.strip(): + cursor.removeSelectedText() + cursor.deletePreviousChar() + + self.log_output.append(message) + self.log_output.moveCursor(QTextCursor.MoveOperation.End) + + if percentage > 0: + self.progress_bar.setValue(percentage) + + def update_conversion_progress(self, message, percentage): + cursor = self.log_output.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.End) + cursor.select(QTextCursor.SelectionType.LineUnderCursor) + current_text = cursor.selectedText() + if "Converting GIF" in current_text: + cursor.removeSelectedText() + cursor.deletePreviousChar() + + self.log_output.append(message) + self.log_output.moveCursor(QTextCursor.MoveOperation.End) + + if percentage > 0: + self.progress_bar.setValue(percentage) + + def update_download_progress(self, message, percentage): + cursor = self.log_output.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.End) + cursor.select(QTextCursor.SelectionType.LineUnderCursor) + + current_text = cursor.selectedText() + if "Downloading" in current_text and ":" in current_text and "/" in current_text: + cursor.removeSelectedText() + cursor.deletePreviousChar() + + self.log_output.append(message) + self.log_output.moveCursor(QTextCursor.MoveOperation.End) + + if percentage > 0: + self.progress_bar.setValue(percentage) + + def stop_download(self): + if hasattr(self, 'worker'): + self.worker.stop() + self.stop_timer() + self.on_download_finished(True, "Download stopped by user.") + + def on_download_finished(self, success, message): + self.progress_bar.hide() + self.stop_btn.hide() + self.pause_resume_btn.hide() + self.pause_resume_btn.setText('Pause') + self.stop_timer() + + self.download_selected_btn.setEnabled(True) + self.download_all_btn.setEnabled(True) + + if (self.batch_mode and self.current_fetch_metadata and + self.current_fetch_metadata.get('has_more', False) and not self.is_auto_fetching): + self.next_batch_btn.show() + self.auto_batch_btn.show() + self.enable_batch_buttons() + + if success: + self.log_output.append(f"\nStatus: {message}") + else: + self.log_output.append(f"Error: {message}") + + self.tab_widget.setCurrentWidget(self.process_tab) + + def toggle_pause_resume(self): + if hasattr(self, 'worker'): + if self.worker.is_paused: + self.worker.resume() + self.pause_resume_btn.setText('Pause') + self.timer.start(1000) + else: + self.worker.pause() + self.pause_resume_btn.setText('Resume') + + def remove_selected_accounts(self): + selected_indices = sorted([self.account_list.row(item) for item in self.account_list.selectedItems()], reverse=True) + + if not selected_indices: + return + + for index in selected_indices: + account = self.accounts[index] + username = account.username + if username: + for is_batch in [True, False]: + cache_file = self.get_cache_file_path(username, account.media_type, is_batch=is_batch) + try: + if os.path.exists(cache_file): + os.remove(cache_file) + self.log_output.append(f'Removed temp file: {os.path.basename(cache_file)}') + except Exception as e: + self.log_output.append(f'Warning: Could not remove temp file {os.path.basename(cache_file)}: {str(e)}') + + self.accounts.pop(index) + + self.update_account_list() + self.update_button_states() + + def clear_accounts(self): + for account in self.accounts: + username = account.username + if username: + for is_batch in [True, False]: + cache_file = self.get_cache_file_path(username, account.media_type, is_batch=is_batch) + try: + if os.path.exists(cache_file): + os.remove(cache_file) + self.log_output.append(f'Removed temp file: {os.path.basename(cache_file)}') + except Exception as e: + self.log_output.append(f'Warning: Could not remove temp file {os.path.basename(cache_file)}: {str(e)}') + + self.reset_state() + self.reset_ui() + self.tab_widget.setCurrentIndex(0) + + + + def update_timer(self): + self.elapsed_time = self.elapsed_time.addSecs(1) + self.time_label.setText(self.elapsed_time.toString("hh:mm:ss")) + + def start_timer(self): + self.elapsed_time = QTime(0, 0, 0) + self.time_label.setText("00:00:00") + self.time_label.show() + self.timer.start(1000) + + def stop_timer(self): + self.timer.stop() + self.time_label.hide() + + def fetch_next_batch(self): + if not self.current_fetch_metadata or not self.current_fetch_metadata.get('has_more', False): + self.log_output.append('No more batches available.') + return + + self.disable_batch_buttons() + self.fetch_next_batch_internal() + + def start_auto_batch(self): + if not self.current_fetch_metadata or not self.current_fetch_metadata.get('has_more', False): + self.log_output.append('No more batches available.') + return + + self.is_auto_fetching = True + self.auto_batch_btn.hide() + self.next_batch_btn.hide() + self.stop_fetch_btn.show() + + self.log_output.append('Auto batch mode enabled. Fetching will continue automatically...') + self.fetch_next_batch_internal() + + def stop_auto_fetch(self): + self.is_auto_fetching = False + self.stop_fetch_btn.hide() + + if self.current_fetch_metadata and self.current_fetch_metadata.get('has_more', False): + self.next_batch_btn.show() + self.auto_batch_btn.show() + self.log_output.append('Auto batch mode stopped. Use "Next Batch" or "Auto Batch" to continue.') + else: + self.log_output.append('Auto batch mode stopped.') + + def disable_batch_buttons(self): + self.next_batch_btn.setEnabled(False) + self.auto_batch_btn.setEnabled(False) + + def enable_batch_buttons(self): + self.next_batch_btn.setEnabled(True) + self.auto_batch_btn.setEnabled(True) + + def fetch_next_batch_internal(self): + if not self.current_fetch_username or not self.current_fetch_media_type or not self.current_fetch_metadata: + return + + self.disable_batch_buttons() + + current_page = self.current_fetch_metadata.get('page', 0) + next_page = current_page + 1 + + self.log_output.append(f'Fetching batch {next_page + 1} for {self.current_fetch_username}...') + + self.metadata_worker = MetadataFetchWorker( + self.current_fetch_username, + self.current_fetch_media_type, + batch_mode=True, + batch_size=self.batch_size, + page=next_page + ) + self.metadata_worker.auth_token = self.auth_token_input.text().strip() + self.metadata_worker.finished.connect(lambda data: self.on_metadata_fetched(data, self.current_fetch_username, self.current_fetch_media_type)) + self.metadata_worker.error.connect(self.on_metadata_error) + self.metadata_worker.start() + + def show_account_buttons(self): + self.download_selected_btn.show() + self.download_all_btn.show() + self.remove_btn.show() + self.clear_btn.show() + +def main(): + if getattr(sys, 'frozen', False): + os.chdir(os.path.dirname(sys.executable)) + + app = QApplication(sys.argv) + window = TwitterMediaDownloaderGUI() + window.show() + sys.exit(app.exec()) + +if __name__ == "__main__": + main() diff --git a/getMetadata.py b/getMetadata.py new file mode 100644 index 0000000..e41ab09 --- /dev/null +++ b/getMetadata.py @@ -0,0 +1,186 @@ +import re +import json +from datetime import datetime +from gallery_dl.extractor import twitter + +def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, media_type="all"): + url = f"https://x.com/{username}/{timeline_type}" + + if timeline_type == "media": + extractor_class = twitter.TwitterMediaExtractor + elif timeline_type == "tweets": + extractor_class = twitter.TwitterTweetsExtractor + elif timeline_type == "with_replies": + extractor_class = twitter.TwitterRepliesExtractor + else: + extractor_class = twitter.TwitterTimelineExtractor + + match = re.match(extractor_class.pattern, url) + if not match: + raise ValueError(f"Invalid URL for {timeline_type}: {url}") + + extractor = extractor_class(match) + + config_dict = { + "cookies": { + "auth_token": auth_token + } + } + + if batch_size > 0: + config_dict["count"] = batch_size + + extractor.config = lambda key, default=None: config_dict.get(key, default) + + try: + extractor.initialize() + + api = twitter.TwitterAPI(extractor) + try: + if username.startswith("id:"): + user = api.user_by_rest_id(username[3:]) + else: + user = api.user_by_screen_name(username) + + if "legacy" in user and user["legacy"].get("withheld_scope"): + raise ValueError("withheld") + + except Exception as e: + error_msg = str(e).lower() + if "withheld" in error_msg or (hasattr(e, "response") and "withheld" in str(e.response.text).lower()): + raise ValueError("withheld") + raise + + structured_output = { + 'account_info': {}, + 'total_urls': 0, + 'timeline': [] + } + + iterator = iter(extractor) + + if batch_size > 0 and page > 0: + items_to_skip = page * batch_size + + if hasattr(extractor, '_cursor') and extractor._cursor: + pass + else: + skipped = 0 + try: + for _ in range(items_to_skip): + next(iterator) + skipped += 1 + except StopIteration: + pass + + new_timeline_entries = [] + + items_to_fetch = batch_size if batch_size > 0 else float('inf') + items_fetched = 0 + + try: + while items_fetched < items_to_fetch: + item = next(iterator) + items_fetched += 1 + + if isinstance(item, tuple) and len(item) >= 3: + media_url = item[1] + tweet_data = item[2] + + if not structured_output['account_info'] and 'user' in tweet_data: + user = tweet_data['user'] + user_date = user.get('date', '') + if isinstance(user_date, datetime): + user_date = user_date.strftime("%Y-%m-%d %H:%M:%S") + + structured_output['account_info'] = { + 'name': user.get('name', ''), + 'nick': user.get('nick', ''), + 'date': user_date, + 'followers_count': user.get('followers_count', 0), + 'friends_count': user.get('friends_count', 0), + 'profile_image': user.get('profile_image', ''), + 'statuses_count': user.get('statuses_count', 0) + } + + if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url: + tweet_date = tweet_data.get('date', datetime.now()) + if isinstance(tweet_date, datetime): + tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S") + + timeline_entry = { + 'url': media_url, + 'date': tweet_date, + 'tweet_id': tweet_data.get('tweet_id', 0), + } + + if 'type' in tweet_data: + timeline_entry['type'] = tweet_data['type'] + + if media_type == 'all' or ( + (media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or + (media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or + (media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif') + ): + new_timeline_entries.append(timeline_entry) + structured_output['total_urls'] += 1 + except StopIteration: + pass + + structured_output['timeline'].extend(new_timeline_entries) + + cursor_info = None + if hasattr(extractor, '_cursor') and extractor._cursor: + cursor_info = extractor._cursor + + structured_output['metadata'] = { + "new_entries": len(new_timeline_entries), + "page": page, + "batch_size": batch_size, + "has_more": batch_size > 0 and items_fetched == batch_size, + "cursor": cursor_info + } + + if not structured_output['account_info']: + raise ValueError("Failed to fetch account information. Please check the username and auth token.") + + return structured_output + + except Exception as e: + error_msg = str(e).lower() + if "withheld" in error_msg or e.__class__.__name__ == "ValueError" and str(e) == "withheld": + return {"error": "To download withheld accounts, use this userscript version: https://www.patreon.com/exyezed"} + else: + error_str = str(e) + if error_str == "None": + return {"error": "Failed to authenticate. Please verify your auth token is valid and not expired."} + else: + return {"error": error_str} + +def main(): + username = "" + auth_token = "" + timeline_type = "media" + batch_size = 100 + page = 0 + media_type = "all" + + try: + data = get_metadata( + username=username, + auth_token=auth_token, + timeline_type=timeline_type, + batch_size=batch_size, + page=page, + media_type=media_type + ) + print(json.dumps(data, ensure_ascii=False, indent=2)) + except Exception as e: + error_str = str(e) + if error_str == "None": + print(json.dumps({"error": "Failed to authenticate. Please verify your auth token is valid and not expired."}, ensure_ascii=False)) + else: + print(json.dumps({"error": error_str}, ensure_ascii=False)) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..58c6c56 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +PyQt6 +requests +aiohttp +imageio-ffmpeg +packaging +gallery-dl \ No newline at end of file diff --git a/version.json b/version.json new file mode 100644 index 0000000..7427771 --- /dev/null +++ b/version.json @@ -0,0 +1,3 @@ +{ + "version": "3.1" +}