diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..66bcc74 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,22 @@ +name: Manually Deploy to Heroku + +on: workflow_dispatch + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: akhileshns/heroku-deploy@v3.12.12 + with: + heroku_api_key: ${{secrets.HEROKU_API_KEY}} + heroku_app_name: ${{secrets.HEROKU_APP_NAME}} + heroku_email: ${{secrets.HEROKU_EMAIL}} + usedocker: true + docker_heroku_process_type: web + stack: "container" + region: "us" + env: + HD_CONFIG_FILE_URL: ${{secrets.CONFIG_FILE_URL}} + HD_HEROKU_API_KEY: ${{secrets.HEROKU_API_KEY}} + HD_HEROKU_APP_NAME: ${{secrets.HEROKU_APP_NAME}} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a183365 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +config.env +Thumbnails/* +drive_folder +cookies.txt +*auth_token.txt +*.pyc +data* +.vscode +.idea +*.json +*.pickle +.netrc +log.txt +authorized_chats.txt +sudo_users.txt +accounts/* + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bdf8cbe --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM anasty17/mltb:latest + +WORKDIR /usr/src/app +RUN chmod 777 /usr/src/app + +COPY requirements.txt . +RUN pip3 install --no-cache-dir -r requirements.txt +RUN apt-get update && apt-get upgrade -y +RUN apt -qq update --fix-missing && \ + apt -qq install -y \ + mediainfo + +COPY . . + +CMD ["bash", "start.sh"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /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 +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..5102247 --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +

+ + + WeebZone Logo + + +

+ +

+

+ +[![GitHub forks](https://img.shields.io/github/forks/weebzone/WZML?style=social)](https://github.com/weebzone/WZML/fork) +[![GitHub followers](https://img.shields.io/github/followers/weebzone?style=social&label=weebzone%20Followers)](https://github.com/weebzone) + +---- + +[![](https://img.shields.io/github/repo-size/weebzone/WZML?color=green&label=Repo%20Size&labelColor=292c3b)](#) [![](https://img.shields.io/github/commit-activity/m/weebzone/WZML?logo=github&labelColor=292c3b&label=Github%20Commits)](#) [![](https://img.shields.io/github/license/weebzone/WZML?style=flat&label=License&labelColor=292c3b)](#)|[![](https://img.shields.io/github/issues-raw/weebzone/WZML?style=flat&label=Open%20Issues&labelColor=292c3b)](#) [![](https://img.shields.io/github/issues-closed-raw/weebzone/WZML?style=flat&label=Closed%20Issues&labelColor=292c3b)](#) [![](https://img.shields.io/github/issues-pr-raw/weebzone/WZML?style=flat&label=Open%20Pull%20Requests&labelColor=292c3b)](#) [![](https://img.shields.io/github/issues-pr-closed-raw/weebzone/WZML?style=flat&label=Closed%20Pull%20Requests&labelColor=292c3b)](#) +:---:|:---:| +[![](https://img.shields.io/github/languages/count/weebzone/WZML?style=flat&label=Total%20Languages&labelColor=292c3b&color=blueviolet)](#) [![](https://img.shields.io/github/languages/top/weebzone/WZML?style=flat&logo=python&labelColor=292c3b)](#) [![](https://img.shields.io/github/last-commit/weebzone/WZML?style=flat&label=Last%20Commit&labelColor=292c3b&color=important)](#) [![](https://badgen.net/github/branches/weebzone/WZML?label=Total%20Branches&labelColor=292c3b)](#)|[![](https://img.shields.io/github/forks/weebzone/WZML?style=flat&logo=github&label=Forks&labelColor=292c3b&color=critical)](#) [![](https://img.shields.io/github/stars/weebzone/WZML?style=flat&logo=github&label=Stars&labelColor=292c3b&color=yellow)](#) [![](https://badgen.net/docker/pulls/codewithweeb/weebzone?icon=docker&label=Pulls&labelColor=292c3b&color=blue)](#) +[![](https://img.shields.io/badge/Telegram%20Channel-Join-9cf?style=for-the-badge&logo=telegram&logoColor=blue&style=flat&labelColor=292c3b)](https://t.me/WeebZone_updates) |[![](https://img.shields.io/badge/Support%20Group-Join-9cf?style=for-the-badge&logo=telegram&logoColor=blue&style=flat&labelColor=292c3b)](https://t.me/WeebZ) | + +
+ +---- + +## ***WeebZone MLTB*** + +
+ +ℹ️ A Powerful Pyrogram Based Telegram Mirror Leech Bot Modded by Codewithweeb to directly Mirror to Google Drive or Leech to Telegram, with Multi Direct Links Support for Enhanced Mirroring & Leeching.| +---| + +### ***Source Code*** : [Repo](https://github.com/weebzone/WZML) + +#### Note: `If you Like My Work, Give Stars ⭐ to the Repo and Follow Me on Github` + +---- +
+

+ +### 1. [***Getting Started***](https://github.com/weebzone/WZML/wiki/Getting-Started) +Introduction To the Bot + +### 2. [***Features***](https://github.com/weebzone/WZML/wiki/Features) +List of features supported by bot + +### 3. [***config.env Variables***](https://github.com/weebzone/WZML/wiki/Setting-up-the-config.env-file) +List of Variables used by the Bot + +### 4. [***Deploy***](https://github.com/weebzone/WZML/wiki/Deployment) +Steps to Deploy the Bot to Run for Yourself + +--- + +## License ⚠️ + +[![](https://www.gnu.org/graphics/gplv3-with-text-136x68.png)](https://www.gnu.org/licenses/gpl-3.0.html) + +```text +Copyright (C) 2022 WeebZone + + 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. < https://github.com/weebzone/WZML/blob/update/LICENSE >. +``` + +--- + +## Contributors 🏆 +
+ Click Here For Description + +|![](https://avatars.githubusercontent.com/u/113664541)|![](https://avatars.githubusercontent.com/u/77075674)|![](https://avatars.githubusercontent.com/u/94453305)|![](https://avatars.githubusercontent.com/u/56303690)|![](https://avatars.githubusercontent.com/u/91935990)|![](https://avatars.githubusercontent.com/u/80155750)| +|---|---|---|---|---|---| +|[`CodeWithWeeb`](https://github.com/weebzone)|[`Anasty17`](https://github.com/anasty17)|[`Ajay Choudhary`](https://github.com/ajay0916) |[`Arshsisodiya`](https://github.com/arshsisodiya/helios-mirror) |[`ToxyTech`](https://github.com/dipeshpatil123)|[`MysterySD`](https://github.com/5MysterySD)| +| `me` add modules and fixes & many more|Base Repo|For suggestion & fixing| For there BOT_PM and LOG feature| For Task Limit| For Help and PIXIBAY Support| + +
diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..ddeb671 --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-time-machine \ No newline at end of file diff --git a/add_to_team_drive.py b/add_to_team_drive.py new file mode 100644 index 0000000..8b53ec4 --- /dev/null +++ b/add_to_team_drive.py @@ -0,0 +1,77 @@ +from __future__ import print_function +from google.oauth2.service_account import Credentials +import googleapiclient.discovery, json, progress.bar, glob, sys, argparse, time +from google_auth_oauthlib.flow import InstalledAppFlow +from google.auth.transport.requests import Request +import os, pickle + +stt = time.time() + +parse = argparse.ArgumentParser( + description='A tool to add service accounts to a shared drive from a folder containing credential files.') +parse.add_argument('--path', '-p', default='accounts', + help='Specify an alternative path to the service accounts folder.') +parse.add_argument('--credentials', '-c', default='./credentials.json', + help='Specify the relative path for the credentials file.') +parse.add_argument('--yes', '-y', default=False, action='store_true', help='Skips the sanity prompt.') +parsereq = parse.add_argument_group('required arguments') +parsereq.add_argument('--drive-id', '-d', help='The ID of the Shared Drive.', required=True) + +args = parse.parse_args() +acc_dir = args.path +did = args.drive_id +credentials = glob.glob(args.credentials) + +try: + open(credentials[0], 'r') + print('>> Found credentials.') +except IndexError: + print('>> No credentials found.') + sys.exit(0) + +if not args.yes: + # input('Make sure the following client id is added to the shared drive as Manager:\n' + json.loads((open( + # credentials[0],'r').read()))['installed']['client_id']) + input('>> Make sure the **Google account** that has generated credentials.json\n is added into your Team Drive ' + '(shared drive) as Manager\n>> (Press any key to continue)') + +creds = None +if os.path.exists('token_sa.pickle'): + with open('token_sa.pickle', 'rb') as token: + creds = pickle.load(token) +# If there are no (valid) credentials available, let the user log in. +if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file(credentials[0], scopes=[ + 'https://www.googleapis.com/auth/admin.directory.group', + 'https://www.googleapis.com/auth/admin.directory.group.member' + ]) + # creds = flow.run_local_server(port=0) + creds = flow.run_console() + # Save the credentials for the next run + with open('token_sa.pickle', 'wb') as token: + pickle.dump(creds, token) + +drive = googleapiclient.discovery.build("drive", "v3", credentials=creds) +batch = drive.new_batch_http_request() + +aa = glob.glob('%s/*.json' % acc_dir) +pbar = progress.bar.Bar("Readying accounts", max=len(aa)) +for i in aa: + ce = json.loads(open(i, 'r').read())['client_email'] + batch.add(drive.permissions().create(fileId=did, supportsAllDrives=True, body={ + "role": "organizer", + "type": "user", + "emailAddress": ce + })) + pbar.next() +pbar.finish() +print('Adding...') +batch.execute() + +print('Complete.') +hours, rem = divmod((time.time() - stt), 3600) +minutes, sec = divmod(rem, 60) +print("Elapsed Time:\n{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), sec)) \ No newline at end of file diff --git a/aria.sh b/aria.sh new file mode 100644 index 0000000..b63f1a4 --- /dev/null +++ b/aria.sh @@ -0,0 +1,13 @@ +if [ -z $TORRENT_TIMEOUT ] +then + TORRENT_TIMEOUT=0 +fi +tracker_list=$(curl -Ns https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all.txt https://ngosang.github.io/trackerslist/trackers_all_http.txt https://newtrackon.com/api/all https://raw.githubusercontent.com/hezhijie0327/Trackerslist/main/trackerslist_tracker.txt | awk '$0' | tr '\n\n' ',') +aria2c --allow-overwrite=true --auto-file-renaming=true --bt-enable-lpd=true --bt-detach-seed-only=true \ + --bt-remove-unselected-file=true --bt-stop-timeout=$TORRENT_TIMEOUT --bt-tracker="[$tracker_list]" \ + --check-certificate=false --check-integrity=true --continue=true --content-disposition-default-utf8=true \ + --daemon=true --disk-cache=40M --enable-rpc=true --follow-torrent=mem --force-save=true --http-accept-gzip=true \ + --max-connection-per-server=10 --max-concurrent-downloads=10 --max-file-not-found=0 --max-tries=20 \ + --min-split-size=10M --netrc-path=/usr/src/app/.netrc --optimize-concurrent-downloads=true \ + --peer-id-prefix=-qB4430- --peer-agent=qBittorrent/4.4.3 --quiet=true --reuse-uri=true \ + --rpc-max-request-size=1024M --seed-ratio=0 --split=10 --summary-interval=0 --user-agent=Wget/1.12 \ No newline at end of file diff --git a/bot/__init__.py b/bot/__init__.py new file mode 100644 index 0000000..4725771 --- /dev/null +++ b/bot/__init__.py @@ -0,0 +1,848 @@ +import re +from os import environ +from logging import getLogger, FileHandler, StreamHandler, INFO, basicConfig, error as log_error, info as log_info, warning as log_warning +from socket import setdefaulttimeout +from faulthandler import enable as faulthandler_enable +from telegram.ext import Updater as tgUpdater +from qbittorrentapi import Client as qbClient +from aria2p import API as ariaAPI, Client as ariaClient +from os import remove as osremove, path as ospath, environ +from requests import get as rget +from json import loads as jsonloads +from subprocess import Popen, run as srun, check_output +from time import sleep, time +from threading import Thread, Lock +from dotenv import load_dotenv +from pyrogram import Client, enums +from asyncio import get_event_loop + +main_loop = get_event_loop() + +faulthandler_enable() + +setdefaulttimeout(600) + +botStartTime = time() + +basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[FileHandler('log.txt'), StreamHandler()], + level=INFO) + +LOGGER = getLogger(__name__) + + +def getConfig(name: str): + return environ[name] + + +load_dotenv('config.env', override=True) + +try: + NETRC_URL = getConfig('NETRC_URL') + if len(NETRC_URL) == 0: + raise KeyError + try: + res = rget(NETRC_URL) + if res.status_code == 200: + with open('.netrc', 'wb+') as f: + f.write(res.content) + else: + log_error(f"Failed to download .netrc {res.status_code}") + except Exception as e: + log_error(f"NETRC_URL: {e}") +except: + pass +try: + SERVER_PORT = getConfig('SERVER_PORT') + if len(SERVER_PORT) == 0: + raise KeyError +except: + SERVER_PORT = 80 + +Popen(f"gunicorn web.wserver:app --bind 0.0.0.0:{SERVER_PORT}", shell=True) +srun(["qbittorrent-nox", "-d", "--profile=."]) +if not ospath.exists('.netrc'): + srun(["touch", ".netrc"]) +srun(["cp", ".netrc", "/root/.netrc"]) +srun(["chmod", "600", ".netrc"]) +srun(["chmod", "+x", "aria.sh"]) +srun("./aria.sh", shell=True) +sleep(0.5) + +Interval = [] +DRIVES_NAMES = [] +DRIVES_IDS = [] +INDEX_URLS = [] + +try: + if bool(getConfig('_____REMOVE_THIS_LINE_____')): + log_error('The README.md file there to be read! Exiting now!') + exit() +except: + pass + +aria2 = ariaAPI( + ariaClient( + host="http://localhost", + port=6800, + secret="", + ) +) + +def get_client(): + return qbClient(host="localhost", port=8090, VERIFY_WEBUI_CERTIFICATE=False, REQUESTS_ARGS={'timeout': (30, 60)}) + +DOWNLOAD_DIR = None +BOT_TOKEN = None + +download_dict_lock = Lock() +status_reply_dict_lock = Lock() +# Key: update.effective_chat.id +# Value: telegram.Message +status_reply_dict = {} +# Key: update.message.message_id +# Value: An object of Status +download_dict = {} +# key: rss_title +# value: [rss_feed, last_link, last_title, filter] +rss_dict = {} + +AUTHORIZED_CHATS = set() +SUDO_USERS = set() +AS_DOC_USERS = set() +AS_MEDIA_USERS = set() +EXTENSION_FILTER = set(['.aria2']) +LEECH_LOG = set() +MIRROR_LOGS = set() +LINK_LOGS = set() + + +try: + BOT_TOKEN = getConfig('BOT_TOKEN') + parent_id = getConfig('GDRIVE_FOLDER_ID') + DOWNLOAD_DIR = getConfig('DOWNLOAD_DIR') + if not DOWNLOAD_DIR.endswith("/"): + DOWNLOAD_DIR = DOWNLOAD_DIR + '/' + DOWNLOAD_STATUS_UPDATE_INTERVAL = int(getConfig('DOWNLOAD_STATUS_UPDATE_INTERVAL')) + OWNER_ID = int(getConfig('OWNER_ID')) + AUTO_DELETE_MESSAGE_DURATION = int(getConfig('AUTO_DELETE_MESSAGE_DURATION')) + TELEGRAM_API = getConfig('TELEGRAM_API') + TELEGRAM_HASH = getConfig('TELEGRAM_HASH') +except: + log.error("One or more env variables missing! Exiting now") + exit(1) + + +try: + aid = getConfig('AUTHORIZED_CHATS') + aid = aid.split() + for _id in aid: + AUTHORIZED_CHATS.add(int(_id.strip())) +except: + pass +try: + aid = getConfig('SUDO_USERS') + aid = aid.split() + for _id in aid: + SUDO_USERS.add(int(_id.strip())) +except: + pass +try: + fx = getConfig('EXTENSION_FILTER') + if len(fx) > 0: + fx = fx.split() + for x in fx: + EXTENSION_FILTER.add(x.strip().lower()) +except: + pass +try: + aid = getConfig('LEECH_LOG') + aid = aid.split(' ') + for _id in aid: + LEECH_LOG.add(int(_id)) +except: + pass +try: + aid = getConfig('MIRROR_LOGS') + aid = aid.split(' ') + for _id in aid: + MIRROR_LOGS.add(int(_id)) +except: + pass +try: + aid = getConfig('LINK_LOGS') + aid = aid.split(' ') + for _id in aid: + LINK_LOGS.add(int(_id)) +except: + pass + + +try: + AUTO_DELETE_UPLOAD_MESSAGE_DURATION = int(getConfig('AUTO_DELETE_UPLOAD_MESSAGE_DURATION')) +except KeyError as e: + AUTO_DELETE_UPLOAD_MESSAGE_DURATION = -1 + LOGGER.warning("AUTO_DELETE_UPLOAD_MESSAGE_DURATION var missing!") + pass + +LOGGER.info("Generating SESSION_STRING") +app = Client(name='pyrogram', api_id=int(TELEGRAM_API), api_hash=TELEGRAM_HASH, bot_token=BOT_TOKEN, parse_mode=enums.ParseMode.HTML, no_updates=True) + +def aria2c_init(): + try: + log_info("Initializing Aria2c") + link = "https://linuxmint.com/torrents/lmde-5-cinnamon-64bit.iso.torrent" + dire = DOWNLOAD_DIR.rstrip("/") + aria2.add_uris([link], {'dir': dire}) + sleep(3) + downloads = aria2.get_downloads() + sleep(20) + for download in downloads: + aria2.remove([download], force=True, files=True) + except Exception as e: + log_error(f"Aria2c initializing error: {e}") +Thread(target=aria2c_init).start() +sleep(1.5) + +try: + MEGA_API_KEY = getConfig('MEGA_API_KEY') + if len(MEGA_API_KEY) == 0: + raise KeyError +except: + log_warning('MEGA API KEY not provided!') + MEGA_API_KEY = None +try: + MEGA_EMAIL_ID = getConfig('MEGA_EMAIL_ID') + MEGA_PASSWORD = getConfig('MEGA_PASSWORD') + if len(MEGA_EMAIL_ID) == 0 or len(MEGA_PASSWORD) == 0: + raise KeyError +except: + log_warning('MEGA Credentials not provided!') + MEGA_EMAIL_ID = None + MEGA_PASSWORD = None + +try: + DB_URI = getConfig('DATABASE_URL') + if len(DB_URI) == 0: + raise KeyError +except: + DB_URI = None + + +tgBotMaxFileSize = 2097151000 +try: + TG_SPLIT_SIZE = getConfig('TG_SPLIT_SIZE') + if len(TG_SPLIT_SIZE) == 0 or int(TG_SPLIT_SIZE) > tgBotMaxFileSize: + raise KeyError + TG_SPLIT_SIZE = int(TG_SPLIT_SIZE) +except: + TG_SPLIT_SIZE = tgBotMaxFileSize +try: + USER_SESSION_STRING = getConfig('USER_SESSION_STRING') + if len(USER_SESSION_STRING) == 0: + raise KeyError + premium_session = Client(name='premium_session', api_id=int(TELEGRAM_API), api_hash=TELEGRAM_HASH, session_string=USER_SESSION_STRING, parse_mode=enums.ParseMode.HTML, no_updates=True) + if not premium_session: + LOGGER.error("Cannot initialized User Session. Please regenerate USER_SESSION_STRING") + else: + premium_session.start() + if (premium_session.get_me()).is_premium: + if not LEECH_LOG: + LOGGER.error("You must set LEECH_LOG for uploads. Eiting now.") + try: premium_session.send_message(OWNER_ID, "You must set LEECH_LOG for uploads, Exiting Now...") + except Exception as e: LOGGER.exception(e) + premium_session.stop() + app.stop() + exit(1) + TG_SPLIT_SIZE = 4194304000 + LOGGER.info("Telegram Premium detected! Leech limit is 4GB now.") + elif (not DB_URI) or (not RSS_CHAT_ID): + premium_session.stop() + LOGGER.info(f"Not using rss. if you want to use fill RSS_CHAT_ID and DB_URI variables.") +except: + USER_SESSION_STRING = None + premium_session = None +LOGGER.info(f"TG_SPLIT_SIZE: {TG_SPLIT_SIZE}") +try: + STATUS_LIMIT = getConfig('STATUS_LIMIT') + if len(STATUS_LIMIT) == 0: + raise KeyError + STATUS_LIMIT = int(STATUS_LIMIT) +except: + STATUS_LIMIT = None +try: + UPTOBOX_TOKEN = getConfig('UPTOBOX_TOKEN') + if len(UPTOBOX_TOKEN) == 0: + raise KeyError +except: + UPTOBOX_TOKEN = None +try: + INDEX_URL = getConfig('INDEX_URL').rstrip("/") + if len(INDEX_URL) == 0: + raise KeyError + INDEX_URLS.append(INDEX_URL) +except: + INDEX_URL = None + INDEX_URLS.append(None) +try: + SEARCH_API_LINK = getConfig('SEARCH_API_LINK').rstrip("/") + if len(SEARCH_API_LINK) == 0: + raise KeyError +except: + SEARCH_API_LINK = None +try: + SEARCH_LIMIT = getConfig('SEARCH_LIMIT') + if len(SEARCH_LIMIT) == 0: + raise KeyError + SEARCH_LIMIT = int(SEARCH_LIMIT) +except: + SEARCH_LIMIT = 0 +try: + RSS_COMMAND = getConfig('RSS_COMMAND') + if len(RSS_COMMAND) == 0: + raise KeyError +except: + RSS_COMMAND = None +try: + CMD_INDEX = getConfig('CMD_INDEX') + if len(CMD_INDEX) == 0: + raise KeyError +except: + CMD_INDEX = '' +try: + SHOW_LIMITS_IN_STATS = getConfig('SHOW_LIMITS_IN_STATS') + SHOW_LIMITS_IN_STATS = SHOW_LIMITS_IN_STATS.lower() == 'true' +except KeyError: + SHOW_LIMITS_IN_STATS = False +try: + TORRENT_DIRECT_LIMIT = getConfig('TORRENT_DIRECT_LIMIT') + if len(TORRENT_DIRECT_LIMIT) == 0: + raise KeyError + TORRENT_DIRECT_LIMIT = float(TORRENT_DIRECT_LIMIT) +except: + TORRENT_DIRECT_LIMIT = None +try: + CLONE_LIMIT = getConfig('CLONE_LIMIT') + if len(CLONE_LIMIT) == 0: + raise KeyError + CLONE_LIMIT = float(CLONE_LIMIT) +except: + CLONE_LIMIT = None +try: + LEECH_LIMIT = getConfig('LEECH_LIMIT') + if len(LEECH_LIMIT) == 0: + raise KeyError + LEECH_LIMIT = float(LEECH_LIMIT) +except: + LEECH_LIMIT = None +try: + MEGA_LIMIT = getConfig('MEGA_LIMIT') + if len(MEGA_LIMIT) == 0: + raise KeyError + MEGA_LIMIT = float(MEGA_LIMIT) +except: + MEGA_LIMIT = None +try: + TOTAL_TASKS_LIMIT = getConfig('TOTAL_TASKS_LIMIT') + if len(TOTAL_TASKS_LIMIT) == 0: + raise KeyError + TOTAL_TASKS_LIMIT = int(TOTAL_TASKS_LIMIT) +except KeyError: + TOTAL_TASKS_LIMIT = None +try: + USER_TASKS_LIMIT = getConfig('USER_TASKS_LIMIT') + if len(USER_TASKS_LIMIT) == 0: + raise KeyError + USER_TASKS_LIMIT = int(USER_TASKS_LIMIT) +except KeyError: + USER_TASKS_LIMIT = None +try: + STORAGE_THRESHOLD = getConfig('STORAGE_THRESHOLD') + if len(STORAGE_THRESHOLD) == 0: + raise KeyError + STORAGE_THRESHOLD = float(STORAGE_THRESHOLD) +except: + STORAGE_THRESHOLD = None +try: + ZIP_UNZIP_LIMIT = getConfig('ZIP_UNZIP_LIMIT') + if len(ZIP_UNZIP_LIMIT) == 0: + raise KeyError + ZIP_UNZIP_LIMIT = float(ZIP_UNZIP_LIMIT) +except: + ZIP_UNZIP_LIMIT = None +try: + RSS_CHAT_ID = getConfig('RSS_CHAT_ID') + if len(RSS_CHAT_ID) == 0: + raise KeyError + RSS_CHAT_ID = int(RSS_CHAT_ID) +except: + RSS_CHAT_ID = None + + + +try: + RSS_USER_SESSION_STRING = getConfig('RSS_USER_SESSION_STRING') + if len(RSS_USER_SESSION_STRING) == 0: + raise KeyError + rss_session = Client(name='rss_session', api_id=int(TELEGRAM_API), api_hash=TELEGRAM_HASH, session_string=RSS_USER_SESSION_STRING, parse_mode=enums.ParseMode.HTML, no_updates=True) +except: + USER_SESSION_STRING = None + rss_session = None +try: + RSS_DELAY = getConfig('RSS_DELAY') + if len(RSS_DELAY) == 0: + raise KeyError + RSS_DELAY = int(RSS_DELAY) +except: + RSS_DELAY = 900 +try: + TORRENT_TIMEOUT = getConfig('TORRENT_TIMEOUT') + if len(TORRENT_TIMEOUT) == 0: + raise KeyError + TORRENT_TIMEOUT = int(TORRENT_TIMEOUT) +except: + TORRENT_TIMEOUT = None + +try: + BUTTON_FOUR_NAME = getConfig('BUTTON_FOUR_NAME') + BUTTON_FOUR_URL = getConfig('BUTTON_FOUR_URL') + if len(BUTTON_FOUR_NAME) == 0 or len(BUTTON_FOUR_URL) == 0: + raise KeyError +except: + BUTTON_FOUR_NAME = None + BUTTON_FOUR_URL = None +try: + BUTTON_FIVE_NAME = getConfig('BUTTON_FIVE_NAME') + BUTTON_FIVE_URL = getConfig('BUTTON_FIVE_URL') + if len(BUTTON_FIVE_NAME) == 0 or len(BUTTON_FIVE_URL) == 0: + raise KeyError +except: + BUTTON_FIVE_NAME = None + BUTTON_FIVE_URL = None +try: + BUTTON_SIX_NAME = getConfig('BUTTON_SIX_NAME') + BUTTON_SIX_URL = getConfig('BUTTON_SIX_URL') + if len(BUTTON_SIX_NAME) == 0 or len(BUTTON_SIX_URL) == 0: + raise KeyError +except: + BUTTON_SIX_NAME = None + BUTTON_SIX_URL = None +try: + INCOMPLETE_TASK_NOTIFIER = getConfig('INCOMPLETE_TASK_NOTIFIER') + INCOMPLETE_TASK_NOTIFIER = INCOMPLETE_TASK_NOTIFIER.lower() == 'true' +except: + INCOMPLETE_TASK_NOTIFIER = False +try: + STOP_DUPLICATE = getConfig('STOP_DUPLICATE') + STOP_DUPLICATE = STOP_DUPLICATE.lower() == 'true' +except: + STOP_DUPLICATE = False +try: + VIEW_LINK = getConfig('VIEW_LINK') + VIEW_LINK = VIEW_LINK.lower() == 'true' +except: + VIEW_LINK = False +try: + SET_BOT_COMMANDS = getConfig('SET_BOT_COMMANDS') + SET_BOT_COMMANDS = SET_BOT_COMMANDS.lower() == 'true' +except: + SET_BOT_COMMANDS = False +try: + IS_TEAM_DRIVE = getConfig('IS_TEAM_DRIVE') + IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true' +except: + IS_TEAM_DRIVE = False +try: + USE_SERVICE_ACCOUNTS = getConfig('USE_SERVICE_ACCOUNTS') + USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true' +except: + USE_SERVICE_ACCOUNTS = False +try: + WEB_PINCODE = getConfig('WEB_PINCODE') + WEB_PINCODE = WEB_PINCODE.lower() == 'true' +except: + WEB_PINCODE = False +try: + SHORTENER = getConfig('SHORTENER') + SHORTENER_API = getConfig('SHORTENER_API') + if len(SHORTENER) == 0 or len(SHORTENER_API) == 0: + raise KeyError +except: + SHORTENER = None + SHORTENER_API = None +try: + IGNORE_PENDING_REQUESTS = getConfig("IGNORE_PENDING_REQUESTS") + IGNORE_PENDING_REQUESTS = IGNORE_PENDING_REQUESTS.lower() == 'true' +except: + IGNORE_PENDING_REQUESTS = False +try: + BASE_URL = getConfig('BASE_URL_OF_BOT').rstrip("/") + if len(BASE_URL) == 0: + raise KeyError +except: + log_warning('BASE_URL_OF_BOT not provided!') + BASE_URL = None + +try: + AS_DOCUMENT = getConfig('AS_DOCUMENT') + AS_DOCUMENT = AS_DOCUMENT.lower() == 'true' +except: + AS_DOCUMENT = False +try: + EQUAL_SPLITS = getConfig('EQUAL_SPLITS') + EQUAL_SPLITS = EQUAL_SPLITS.lower() == 'true' +except: + EQUAL_SPLITS = False +try: + CUSTOM_FILENAME = getConfig('CUSTOM_FILENAME') + if len(CUSTOM_FILENAME) == 0: + raise KeyError +except: + CUSTOM_FILENAME = None +try: + MIRROR_ENABLED = getConfig("MIRROR_ENABLED") + MIRROR_ENABLED = MIRROR_ENABLED.lower() == "true" +except: + MIRROR_ENABLED = False +try: + LEECH_ENABLED = getConfig("LEECH_ENABLED") + LEECH_ENABLED = LEECH_ENABLED.lower() == "true" +except: + LEECH_ENABLED = False + +try: + WATCH_ENABLED = getConfig("WATCH_ENABLED") + WATCH_ENABLED = WATCH_ENABLED.lower() == "true" +except: + WATCH_ENABLED = False +try: + CLONE_ENABLED = getConfig("CLONE_ENABLED") + CLONE_ENABLED = CLONE_ENABLED.lower() == "true" +except: + CLONE_ENABLED = False +try: + ANILIST_ENABLED = getConfig("ANILIST_ENABLED") + ANILIST_ENABLED = ANILIST_ENABLED.lower() == "true" +except: + ANILIST_ENABLED = False +try: + WAYBACK_ENABLED = getConfig("WAYBACK_ENABLED") + WAYBACK_ENABLED = WAYBACK_ENABLED.lower() == "true" +except: + WAYBACK_ENABLED = False +try: + MEDIAINFO_ENABLED = getConfig("MEDIAINFO_ENABLED") + MEDIAINFO_ENABLED = MEDIAINFO_ENABLED.lower() == "true" +except: + MEDIAINFO_ENABLED = False +try: + TIMEZONE = getConfig("TIMEZONE") + if len(TIMEZONE) == 0: + TIMEZONE = None +except: + TIMEZONE = "Asia/Kolkata" +try: + CRYPT = getConfig('CRYPT') + if len(CRYPT) == 0: + raise KeyError +except: + CRYPT = None +try: + UNIFIED_EMAIL = getConfig('UNIFIED_EMAIL') + if len(UNIFIED_EMAIL) == 0: + raise KeyError +except: + UNIFIED_EMAIL = None +try: + UNIFIED_PASS = getConfig('UNIFIED_PASS') + if len(UNIFIED_PASS) == 0: + raise KeyError +except: + UNIFIED_PASS = None +try: + HUBDRIVE_CRYPT = getConfig('HUBDRIVE_CRYPT') + if len(HUBDRIVE_CRYPT) == 0: + raise KeyError +except: + HUBDRIVE_CRYPT = None +try: + KATDRIVE_CRYPT = getConfig('KATDRIVE_CRYPT') + if len(KATDRIVE_CRYPT) == 0: + raise KeyError +except: + KATDRIVE_CRYPT = None +try: + DRIVEFIRE_CRYPT = getConfig('DRIVEFIRE_CRYPT') + if len(DRIVEFIRE_CRYPT) == 0: + raise KeyError +except: + DRIVEFIRE_CRYPT = None +try: + SOURCE_LINK = getConfig('SOURCE_LINK') + SOURCE_LINK = SOURCE_LINK.lower() == 'true' +except KeyError: + SOURCE_LINK = False +try: + BOT_PM = getConfig('BOT_PM') + BOT_PM = BOT_PM.lower() == 'true' +except KeyError: + BOT_PM = False +try: + FORCE_BOT_PM = getConfig('FORCE_BOT_PM') + FORCE_BOT_PM = FORCE_BOT_PM.lower() == 'true' +except KeyError: + FORCE_BOT_PM = False +try: + MIRROR_LOG_URL = getConfig('MIRROR_LOG_URL') + if len(MIRROR_LOG_URL) == 0: + MIRROR_LOG_URL = '' +except KeyError: + MIRROR_LOG_URL = '' +try: + LEECH_LOG_URL = getConfig('LEECH_LOG_URL') + if len(LEECH_LOG_URL) == 0: + LEECH_LOG_URL = '' +except KeyError: + LEECH_LOG_URL = '' +try: + LEECH_LOG_INDEXING = getConfig('LEECH_LOG_INDEXING') + LEECH_LOG_INDEXING = LEECH_LOG_INDEXING.lower() == 'true' +except KeyError: + LEECH_LOG_INDEXING = False +try: + AUTHOR_NAME = getConfig('AUTHOR_NAME') + if len(AUTHOR_NAME) == 0: + AUTHOR_NAME = 'Karan' +except KeyError: + AUTHOR_NAME = 'Karan' + +try: + AUTHOR_URL = getConfig('AUTHOR_URL') + if len(AUTHOR_URL) == 0: + AUTHOR_URL = 'https://t.me/WeebZone_updates' +except KeyError: + AUTHOR_URL = 'https://t.me/WeebZone_updates' +try: + GD_INFO = getConfig('GD_INFO') + if len(GD_INFO) == 0: + GD_INFO = 'Uploaded by WeebZone Mirror Bot' +except KeyError: + GD_INFO = 'Uploaded by WeebZone Mirror Bot' +try: + DISABLE_DRIVE_LINK = getConfig('DISABLE_DRIVE_LINK') + DISABLE_DRIVE_LINK = DISABLE_DRIVE_LINK.lower() == 'true' +except KeyError: + DISABLE_DRIVE_LINK = False +try: + TITLE_NAME = getConfig('TITLE_NAME') + if len(TITLE_NAME) == 0: + TITLE_NAME = 'WeebZone' +except KeyError: + TITLE_NAME = 'WeebZone' +try: + START_BTN1_NAME = getConfig('START_BTN1_NAME') + START_BTN1_URL = getConfig('START_BTN1_URL') + if len(START_BTN1_NAME) == 0 or len(START_BTN1_URL) == 0: + raise KeyError +except: + START_BTN1_NAME = 'Master' + START_BTN1_URL = 'https://t.me/krn_adhikari' + +try: + START_BTN2_NAME = getConfig('START_BTN2_NAME') + START_BTN2_URL = getConfig('START_BTN2_URL') + if len(START_BTN2_NAME) == 0 or len(START_BTN2_URL) == 0: + raise KeyError +except: + START_BTN2_NAME = 'Support Group' + START_BTN2_URL = 'https://t.me/WeebZone_updates' +try: + CREDIT_NAME = getConfig('CREDIT_NAME') + if len(CREDIT_NAME) == 0: + CREDIT_NAME = 'WeebZone' +except KeyError: + CREDIT_NAME = 'WeebZone' +try: + NAME_FONT = getConfig('NAME_FONT') + if len(NAME_FONT) == 0: + NAME_FONT = 'code' +except KeyError: + NAME_FONT = 'code' +try: + CAPTION_FONT = getConfig('CAPTION_FONT') + if len(CAPTION_FONT) == 0: + CAPTION_FONT = 'code' +except KeyError: + CAPTION_FONT = 'code' +try: + FINISHED_PROGRESS_STR = getConfig('FINISHED_PROGRESS_STR') + UN_FINISHED_PROGRESS_STR = getConfig('UN_FINISHED_PROGRESS_STR') +except: + FINISHED_PROGRESS_STR = '●' # '■' + UN_FINISHED_PROGRESS_STR = '○' # '□' +try: + FSUB = getConfig('FSUB') + FSUB = FSUB.lower() == 'true' +except BaseException: + FSUB = False + LOGGER.info("Force Subscribe is disabled") +try: + CHANNEL_USERNAME = getConfig("CHANNEL_USERNAME") + if len(CHANNEL_USERNAME) == 0: + raise KeyError +except KeyError: + log_info("CHANNEL_USERNAME not provided! Using default @WeebZone_updates") + CHANNEL_USERNAME = "WeebZone_updates" +try: + FSUB_CHANNEL_ID = getConfig("FSUB_CHANNEL_ID") + if len(FSUB_CHANNEL_ID) == 0: + raise KeyError + FSUB_CHANNEL_ID = int(FSUB_CHANNEL_ID) +except KeyError: + log_info("CHANNEL_ID not provided! Using default id of @WeebZone_updates") + FSUB_CHANNEL_ID = -1001512307861 +try: + TOKEN_PICKLE_URL = getConfig('TOKEN_PICKLE_URL') + if len(TOKEN_PICKLE_URL) == 0: + raise KeyError + try: + res = rget(TOKEN_PICKLE_URL) + if res.status_code == 200: + with open('token.pickle', 'wb+') as f: + f.write(res.content) + else: + log_error(f"Failed to download token.pickle, link got HTTP response: {res.status_code}") + except Exception as e: + log_error(f"TOKEN_PICKLE_URL: {e}") +except: + pass +try: + ACCOUNTS_ZIP_URL = getConfig('ACCOUNTS_ZIP_URL') + if len(ACCOUNTS_ZIP_URL) == 0: + raise KeyError + try: + res = rget(ACCOUNTS_ZIP_URL) + if res.status_code == 200: + with open('accounts.zip', 'wb+') as f: + f.write(res.content) + else: + log_error(f"Failed to download accounts.zip, link got HTTP response: {res.status_code}") + except Exception as e: + log_error(f"ACCOUNTS_ZIP_URL: {e}") + raise KeyError + srun(["unzip", "-q", "-o", "accounts.zip"]) + srun(["chmod", "-R", "777", "accounts"]) + osremove("accounts.zip") +except: + pass +try: + MULTI_SEARCH_URL = getConfig('MULTI_SEARCH_URL') + if len(MULTI_SEARCH_URL) == 0: + raise KeyError + try: + res = rget(MULTI_SEARCH_URL) + if res.status_code == 200: + with open('drive_folder', 'wb+') as f: + f.write(res.content) + else: + log_error(f"Failed to download drive_folder, link got HTTP response: {res.status_code}") + except Exception as e: + log_error(f"MULTI_SEARCH_URL: {e}") +except: + pass +try: + YT_COOKIES_URL = getConfig('YT_COOKIES_URL') + if len(YT_COOKIES_URL) == 0: + raise KeyError + try: + res = rget(YT_COOKIES_URL) + if res.status_code == 200: + with open('cookies.txt', 'wb+') as f: + f.write(res.content) + else: + log_error(f"Failed to download cookies.txt, link got HTTP response: {res.status_code}") + except Exception as e: + log_error(f"YT_COOKIES_URL: {e}") +except: + pass + +DRIVES_NAMES.append("Main") +DRIVES_IDS.append(parent_id) +if ospath.exists('drive_folder'): + with open('drive_folder', 'r+') as f: + lines = f.readlines() + for line in lines: + try: + temp = line.strip().split() + DRIVES_IDS.append(temp[1]) + DRIVES_NAMES.append(temp[0].replace("_", " ")) + except: + pass + try: + INDEX_URLS.append(temp[2]) + except: + INDEX_URLS.append(None) +try: + SEARCH_PLUGINS = getConfig('SEARCH_PLUGINS') + if len(SEARCH_PLUGINS) == 0: + raise KeyError + SEARCH_PLUGINS = jsonloads(SEARCH_PLUGINS) +except: + SEARCH_PLUGINS = None +try: + IMAGE_URL = getConfig('IMAGE_URL') +except KeyError: + IMAGE_URL = 'https://graph.org/file/6b22ef7b8a733c5131d3f.jpg' +try: + EMOJI_THEME = getConfig('EMOJI_THEME') + EMOJI_THEME = EMOJI_THEME.lower() == 'true' +except: + EMOJI_THEME = False +try: + TELEGRAPH_STYLE = getConfig('TELEGRAPH_STYLE') + TELEGRAPH_STYLE = TELEGRAPH_STYLE.lower() == 'true' +except: + TELEGRAPH_STYLE = False +try: + PIXABAY_API_KEY = getConfig('PIXABAY_API_KEY') + if len(PIXABAY_API_KEY) == 0: + raise KeyError +except: + PIXABAY_API_KEY = None +try: + PIXABAY_CATEGORY = getConfig('PIXABAY_CATEGORY') + if len(PIXABAY_CATEGORY) == 0: + raise KeyError +except: + PIXABAY_CATEGORY = None +try: + PIXABAY_SEARCH = getConfig('PIXABAY_SEARCH') + if len(PIXABAY_SEARCH) == 0: + raise KeyError +except: + PIXABAY_SEARCH = None +try: + WALLFLARE_SEARCH = getConfig('WALLFLARE_SEARCH') + if len(WALLFLARE_SEARCH) == 0: + raise KeyError +except: + WALLFLARE_SEARCH = None +try: + WALLTIP_SEARCH = getConfig('WALLTIP_SEARCH') + if len(WALLTIP_SEARCH) == 0: + raise KeyError +except: + WALLTIP_SEARCH = None +try: + WALLCRAFT_CATEGORY = getConfig('WALLCRAFT_CATEGORY') + if len(WALLCRAFT_CATEGORY) == 0: + raise KeyError +except: + WALLCRAFT_CATEGORY = None +PICS = (environ.get('PICS', '')).split() + +updater = tgUpdater(token=BOT_TOKEN, request_kwargs={'read_timeout': 20, 'connect_timeout': 15}) +bot = updater.bot +dispatcher = updater.dispatcher +job_queue = updater.job_queue +botname = bot.username diff --git a/bot/__main__.py b/bot/__main__.py new file mode 100644 index 0000000..ad65ec7 --- /dev/null +++ b/bot/__main__.py @@ -0,0 +1,489 @@ +import random +from bs4 import BeautifulSoup +from signal import signal, SIGINT +from requests import get as rget +from urllib.parse import quote as q +from random import choice +from os import path as ospath, remove as osremove, execl as osexecl +from subprocess import run as srun, check_output +from datetime import datetime, timedelta +from psutil import disk_usage, cpu_percent, swap_memory, cpu_count, virtual_memory, net_io_counters, boot_time +from time import time +from sys import executable +from telegram import ParseMode +from telegram.ext import CommandHandler +import requests +import pytz +from bot import bot, dispatcher, updater, botStartTime, TIMEZONE, IGNORE_PENDING_REQUESTS, LOGGER, Interval, INCOMPLETE_TASK_NOTIFIER, \ + DB_URI, app, main_loop, SET_BOT_COMMANDS, AUTHORIZED_CHATS, EMOJI_THEME, \ + START_BTN1_NAME, START_BTN1_URL, START_BTN2_NAME, START_BTN2_URL, CREDIT_NAME, TITLE_NAME, PICS, FINISHED_PROGRESS_STR, UN_FINISHED_PROGRESS_STR, \ + SHOW_LIMITS_IN_STATS, LEECH_LIMIT, TORRENT_DIRECT_LIMIT, CLONE_LIMIT, MEGA_LIMIT, ZIP_UNZIP_LIMIT, TOTAL_TASKS_LIMIT, USER_TASKS_LIMIT, \ + PIXABAY_API_KEY, PIXABAY_CATEGORY, PIXABAY_SEARCH, WALLCRAFT_CATEGORY, WALLTIP_SEARCH, WALLFLARE_SEARCH +from .helper.ext_utils.fs_utils import start_cleanup, clean_all, exit_clean_up +from .helper.ext_utils.telegraph_helper import telegraph +from .helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time +from .helper.ext_utils.db_handler import DbManger +from .helper.telegram_helper.bot_commands import BotCommands +from .helper.telegram_helper.message_utils import sendMessage, sendMarkup, editMessage, sendLogFile, sendPhoto +from .helper.telegram_helper.filters import CustomFilters +from .helper.telegram_helper.button_build import ButtonMaker +from bot.modules.wayback import getRandomUserAgent +from .modules import authorize, list, cancel_mirror, mirror_status, mirror_leech, clone, ytdlp, shell, eval, \ + delete, count, leech_settings, search, rss, wayback, speedtest, anilist, bt_select, mediainfo, hash +from datetime import datetime + +def progress_bar(percentage): + p_used = FINISHED_PROGRESS_STR + p_total = UN_FINISHED_PROGRESS_STR + if isinstance(percentage, str): + return 'NaN' + try: + percentage=int(percentage) + except: + percentage = 0 + return ''.join( + p_used if i <= percentage // 10 else p_total for i in range(1, 11) + ) + +now=datetime.now(pytz.timezone(f'{TIMEZONE}')) + +def stats(update, context): + if ospath.exists('.git'): + if EMOJI_THEME is True: + last_commit = check_output(["git log -1 --date=short --pretty=format:'%cd \n 🛠From %cr'"], shell=True).decode() + botVersion = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() + else: + last_commit = check_output(["git log -1 --date=short --pretty=format:'%cd \n From %cr'"], shell=True).decode() + botVersion = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() + else: + botVersion = 'No UPSTREAM_REPO' + last_commit = 'No UPSTREAM_REPO' + currentTime = get_readable_time(time() - botStartTime) + current = now.strftime('%m/%d %I:%M:%S %p') + osUptime = get_readable_time(time() - boot_time()) + total, used, free, disk= disk_usage('/') + total = get_readable_file_size(total) + used = get_readable_file_size(used) + free = get_readable_file_size(free) + sent = get_readable_file_size(net_io_counters().bytes_sent) + recv = get_readable_file_size(net_io_counters().bytes_recv) + cpuUsage = cpu_percent(interval=0.5) + p_core = cpu_count(logical=False) + t_core = cpu_count(logical=True) + swap = swap_memory() + swap_p = swap.percent + swap_t = get_readable_file_size(swap.total) + swap_u = get_readable_file_size(swap.used) + memory = virtual_memory() + mem_p = memory.percent + mem_t = get_readable_file_size(memory.total) + mem_a = get_readable_file_size(memory.available) + mem_u = get_readable_file_size(memory.used) + if EMOJI_THEME is True: + stats = f'╭─《🌐 BOT STATISTICS 🌐》\n' \ + f'├ 🛠 Updated On: {last_commit}\n'\ + f'├ ⌛ Uptime: {currentTime}\n'\ + f'├ 🟢 OS Uptime: {osUptime}\n'\ + f'├ 🖥️ CPU: [{progress_bar(cpuUsage)}] {cpuUsage}%\n'\ + f'├ 🎮 RAM: [{progress_bar(mem_p)}] {mem_p}%\n'\ + f'├ 💾 Disk: [{progress_bar(disk)}] {disk}%\n'\ + f'├ 💿 Disk Free: {free}\n'\ + f'├ 🔺 Upload Data: {sent}\n'\ + f'╰ 🔻 Download Data: {recv}\n\n' + + else: + stats = f'╭─《 BOT STATISTICS 》\n' \ + f'├ Updated On: {last_commit}\n'\ + f'├ Uptime: {currentTime}\n'\ + f'├ OS Uptime: {osUptime}\n'\ + f'├ CPU: [{progress_bar(cpuUsage)}] {cpuUsage}%\n'\ + f'├ RAM: [{progress_bar(mem_p)}] {mem_p}%\n'\ + f'├ Disk: [{progress_bar(disk)}] {disk}%\n'\ + f'├ Disk Free: {free}\n'\ + f'├ Upload Data: {sent}\n'\ + f'╰ Download Data: {recv}\n\n' + + + + if SHOW_LIMITS_IN_STATS is True: + torrent_direct = 'No Limit Set' if TORRENT_DIRECT_LIMIT is None else f'{TORRENT_DIRECT_LIMIT}GB/Link' + clone_limit = 'No Limit Set' if CLONE_LIMIT is None else f'{CLONE_LIMIT}GB/Link' + mega_limit = 'No Limit Set' if MEGA_LIMIT is None else f'{MEGA_LIMIT}GB/Link' + leech_limit = 'No Limit Set' if LEECH_LIMIT is None else f'{LEECH_LIMIT}GB/Link' + zip_unzip = 'No Limit Set' if ZIP_UNZIP_LIMIT is None else f'{ZIP_UNZIP_LIMIT}GB/Link' + total_task = 'No Limit Set' if TOTAL_TASKS_LIMIT is None else f'{TOTAL_TASKS_LIMIT} Total Tasks/Time' + user_task = 'No Limit Set' if USER_TASKS_LIMIT is None else f'{USER_TASKS_LIMIT} Tasks/user' + + if EMOJI_THEME is True: + stats += f'╭─《 ⚠️ BOT LIMITS ⚠️ 》\n'\ + f'├ 🧲 Torrent/Direct: {torrent_direct}\n'\ + f'├ 🔐 Zip/Unzip: {zip_unzip}\n'\ + f'├ 🔷 Leech: {leech_limit}\n'\ + f'├ ♻️ Clone: {clone_limit}\n'\ + f'├ 🔰 Mega: {mega_limit}\n'\ + f'├ 💣 Total Tasks: {total_task}\n'\ + f'╰ 🔫 User Tasks: {user_task}\n\n' + else: + stats += f'╭─《 BOT LIMITS 》\n'\ + f'├ Torrent/Direct: {torrent_direct}\n'\ + f'├ Zip/Unzip: {zip_unzip}\n'\ + f'├ Leech: {leech_limit}\n'\ + f'├ Clone: {clone_limit}\n'\ + f'├ Mega: {mega_limit}\n'\ + f'├ Total Tasks: {total_task}\n'\ + f'╰ User Tasks: {user_task}\n\n' + + if PICS: + sendPhoto(stats, context.bot, update.message, random.choice(PICS)) + else: + sendMessage(stats, context.bot, update.message) + +def start(update, context): + buttons = ButtonMaker() + if EMOJI_THEME is True: + buttons.buildbutton(f"😎 {START_BTN1_NAME}", f"{START_BTN1_URL}") + buttons.buildbutton(f"🔥 {START_BTN2_NAME}", f"{START_BTN2_URL}") + else: + buttons.buildbutton(f"{START_BTN1_NAME}", f"{START_BTN1_URL}") + buttons.buildbutton(f"{START_BTN2_NAME}", f"{START_BTN2_URL}") + reply_markup = buttons.build_menu(2) + if CustomFilters.authorized_user(update) or CustomFilters.authorized_chat(update): + start_string = f'''This bot can mirror all your links to Google Drive! +Type /{BotCommands.HelpCommand} to get a list of available commands +''' + if PICS: + sendPhoto(start_string, context.bot, update.message, random.choice(PICS), reply_markup) + else: + sendMarkup(start_string, context.bot, update.message, reply_markup) + else: + text = f"Not Authorized user, deploy your own mirror bot" + if PICS: + sendPhoto(text, context.bot, update.message, random.choice(PICS), reply_markup) + else: + sendMarkup(text, context.bot, update.message, reply_markup) + + +def restart(update, context): + restart_message = sendMessage("Restarting...", context.bot, update.message) + if Interval: + Interval[0].cancel() + Interval.clear() + clean_all() + srun(["pkill", "-f", "gunicorn|aria2c|qbittorrent-nox|ffmpeg"]) + srun(["python3", "update.py"]) + with open(".restartmsg", "w") as f: + f.truncate(0) + f.write(f"{restart_message.chat.id}\n{restart_message.message_id}\n") + osexecl(executable, executable, "-m", "bot") + + +def ping(update, context): + if EMOJI_THEME is True: + start_time = int(round(time() * 1000)) + reply = sendMessage("Starting_Ping ⛔", context.bot, update.message) + end_time = int(round(time() * 1000)) + editMessage(f'{end_time - start_time} ms 🔥', reply) + else: + start_time = int(round(time() * 1000)) + reply = sendMessage("Starting_Ping ", context.bot, update.message) + end_time = int(round(time() * 1000)) + editMessage(f'{end_time - start_time} ms ', reply) + +def log(update, context): + sendLogFile(context.bot, update.message) + + +help_string = ''' +WeebZone - The Ultimate Telegram MIrror-Leech Bot to Upload Your File & Link in Google Drive & Telegram +Choose a help category: +''' + +help_string_telegraph_user = f''' +👤 User Commands +

+• /{BotCommands.HelpCommand}: To get this message +

+• /{BotCommands.MirrorCommand} [download_url][magnet_link]: Start mirroring to Google Drive. Send /{BotCommands.MirrorCommand} for more help +

+• /{BotCommands.ZipMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the file/folder compressed with zip extension +

+• /{BotCommands.UnzipMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the file/folder extracted from any archive extension +

+• /{BotCommands.QbMirrorCommand} [magnet_link][torrent_file][torrent_file_url]: Start Mirroring using qBittorrent, Use /{BotCommands.QbMirrorCommand} s to select files before downloading +

+• /{BotCommands.QbZipMirrorCommand} [magnet_link][torrent_file][torrent_file_url]: Start mirroring using qBittorrent and upload the file/folder compressed with zip extension +

+• /{BotCommands.QbUnzipMirrorCommand} [magnet_link][torrent_file][torrent_file_url]: Start mirroring using qBittorrent and upload the file/folder extracted from any archive extension +

+• /{BotCommands.LeechCommand} [download_url][magnet_link]: Start leeching to Telegram, Use /{BotCommands.LeechCommand} s to select files before leeching +

+• /{BotCommands.ZipLeechCommand} [download_url][magnet_link]: Start leeching to Telegram and upload the file/folder compressed with zip extension +

+• /{BotCommands.UnzipLeechCommand} [download_url][magnet_link][torent_file]: Start leeching to Telegram and upload the file/folder extracted from any archive extension +

+• /{BotCommands.QbLeechCommand} [magnet_link][torrent_file][torrent_file_url]: Start leeching to Telegram using qBittorrent, Use /{BotCommands.QbLeechCommand} s to select files before leeching +

+• /{BotCommands.QbZipLeechCommand} [magnet_link][torrent_file][torrent_file_url]: Start leeching to Telegram using qBittorrent and upload the file/folder compressed with zip extension +

+• /{BotCommands.QbUnzipLeechCommand} [magnet_link][torrent_file][torrent_file_url]: Start leeching to Telegram using qBittorrent and upload the file/folder extracted from any archive extension +

+• /{BotCommands.CloneCommand} [drive_url][gdtot_url]: Copy file/folder to Google Drive +

+• /{BotCommands.CountCommand} [drive_url][gdtot_url]: Count file/folder of Google Drive +

+• /{BotCommands.DeleteCommand} [drive_url]: Delete file/folder from Google Drive (Only Owner & Sudo) +

+• /{BotCommands.WatchCommand} [yt-dlp supported link]: Mirror yt-dlp supported link. Send /{BotCommands.WatchCommand} for more help +

+• /{BotCommands.ZipWatchCommand} [yt-dlp supported link]: Mirror yt-dlp supported link as zip +

+• /{BotCommands.LeechWatchCommand} [yt-dlp supported link]: Leech yt-dlp supported link +

+• /{BotCommands.LeechZipWatchCommand} [yt-dlp supported link]: Leech yt-dlp supported link as zip +

+• /{BotCommands.LeechSetCommand}: Leech settings +

+• /{BotCommands.SetThumbCommand}: Reply photo to set it as Thumbnail +

+• /{BotCommands.RssListCommand}: List all subscribed rss feed info +

+• /{BotCommands.RssGetCommand}: [Title] [Number](last N links): Force fetch last N links +

+• /{BotCommands.RssSubCommand}: [Title] [Rss Link] f: [filter]: Subscribe new rss feed +

+• /{BotCommands.RssUnSubCommand}: [Title]: Unubscribe rss feed by title +

+• /{BotCommands.RssSettingsCommand}: Rss Settings +

+• /{BotCommands.CancelMirror}: Reply to the message by which the download was initiated and that download will be cancelled +

+• /{BotCommands.CancelAllCommand}: Cancel all downloading tasks +

+• /{BotCommands.ListCommand} [query]: Search in Google Drive(s) +

+• /{BotCommands.SearchCommand} [query]: Search for torrents with API +
sites: rarbg, 1337x, yts, etzv, tgx, torlock, piratebay, nyaasi, ettv

+• /{BotCommands.StatusCommand}: Shows a status of all the downloads +

+• /{BotCommands.StatsCommand}: Show Stats of the machine the bot is hosted on +

+• /{BotCommands.SpeedCommand}: Speedtest of server +

+• /weebhelp: Okatu helper +''' + +help_user = telegraph.create_page( + title=f"{TITLE_NAME} Help", + content=help_string_telegraph_user)["path"] + +help_string_telegraph_admin = f''' +🛡️ Admin Commands +

+• /{BotCommands.PingCommand}: Check how long it takes to Ping the Bot +

+• /{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Can only be invoked by Owner & Sudo of the bot) +

+• /{BotCommands.UnAuthorizeCommand}: Unauthorize a chat or a user to use the bot (Can only be invoked by Owner & Sudo of the bot) +

+• /{BotCommands.AuthorizedUsersCommand}: Show authorized users (Only Owner & Sudo) +

+• /{BotCommands.AddSudoCommand}: Add sudo user (Only Owner) +

+• /{BotCommands.RmSudoCommand}: Remove sudo users (Only Owner) +

+• /{BotCommands.RestartCommand}: Restart and update the bot +

+• /{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports +''' + +help_admin = telegraph.create_page( + title=f"{TITLE_NAME} Help", + content=help_string_telegraph_admin)["path"] + + +def bot_help(update, context): + button = ButtonMaker() + if EMOJI_THEME is True: + button.buildbutton("👤 User", f"https://graph.org/{help_user}") + button.buildbutton("🛡️ Admin", f"https://graph.org/{help_admin}") + else: + button.buildbutton("User", f"https://graph.org/{help_user}") + button.buildbutton("Admin", f"https://graph.org/{help_admin}") + sendMarkup(help_string, context.bot, update.message, button.build_menu(2)) + + +if SET_BOT_COMMANDS: + botcmds = [ + (f'{BotCommands.MirrorCommand}', 'Mirror'), + (f'{BotCommands.ZipMirrorCommand}','Mirror and upload as zip'), + (f'{BotCommands.UnzipMirrorCommand}','Mirror and extract files'), + (f'{BotCommands.QbMirrorCommand}','Mirror torrent using qBittorrent'), + (f'{BotCommands.QbZipMirrorCommand}','Mirror torrent and upload as zip using qb'), + (f'{BotCommands.QbUnzipMirrorCommand}','Mirror torrent and extract files using qb'), + (f'{BotCommands.WatchCommand}','Mirror yt-dlp supported link'), + (f'{BotCommands.ZipWatchCommand}','Mirror yt-dlp supported link as zip'), + (f'{BotCommands.CloneCommand}','Copy file/folder to Drive'), + (f'{BotCommands.LeechCommand}','Leech'), + (f'{BotCommands.ZipLeechCommand}','Leech and upload as zip'), + (f'{BotCommands.UnzipLeechCommand}','Leech and extract files'), + (f'{BotCommands.QbLeechCommand}','Leech torrent using qBittorrent'), + (f'{BotCommands.QbZipLeechCommand}','Leech torrent and upload as zip using qb'), + (f'{BotCommands.QbUnzipLeechCommand}','Leech torrent and extract using qb'), + (f'{BotCommands.LeechWatchCommand}','Leech yt-dlp supported link'), + (f'{BotCommands.LeechZipWatchCommand}','Leech yt-dlp supported link as zip'), + (f'{BotCommands.CountCommand}','Count file/folder of Drive'), + (f'{BotCommands.DeleteCommand}','Delete file/folder from Drive'), + (f'{BotCommands.CancelMirror}','Cancel a task'), + (f'{BotCommands.CancelAllCommand}','Cancel all downloading tasks'), + (f'{BotCommands.ListCommand}','Search in Drive'), + (f'{BotCommands.SearchCommand}','Search in Torrent'), + (f'{BotCommands.LeechSetCommand}','Leech settings'), + (f'{BotCommands.SetThumbCommand}','Set thumbnail'), + (f'{BotCommands.StatusCommand}','Get mirror status message'), + (f'{BotCommands.SpeedCommand}','Speedtest'), + (f'{BotCommands.WayBackCommand}','Internet Archive'), + (f'{BotCommands.MediaInfoCommand}','Get Information of telegram Files'), + (f'{BotCommands.HashCommand}','Get Hash of telegram Files'), + (f'{BotCommands.PingCommand}','Ping the bot'), + (f'{BotCommands.RestartCommand}','Restart the bot'), + (f'{BotCommands.LogCommand}','Get the bot Log'), + (f'{BotCommands.HelpCommand}','Get detailed help'), + (f'{BotCommands.AuthorizedUsersCommand}','Authorized Users/Chats'), + (f'{BotCommands.AuthorizeCommand}','Authorize user/chat'), + (f'{BotCommands.UnAuthorizeCommand}','UnAuthorize user/chat'), + (f'{BotCommands.AddSudoCommand}','Add Sudo'), + (f'{BotCommands.RmSudoCommand}','Remove Sudo'), + (f'{BotCommands.AddleechlogCommand}','Add Leech Log Channel'), + (f'{BotCommands.RmleechlogCommand}','Remove Leech Log Channel') + ] + + +def main(): + + if WALLCRAFT_CATEGORY: + for page in range(1,20): + r2 = rget(f"https://wallpaperscraft.com/catalog/{WALLCRAFT_CATEGORY}/1280x720/page{page}") + soup2 = BeautifulSoup(r2.text, "html.parser") + x = soup2.select('img[src^="https://images.wallpaperscraft.com/image/single"]') + for img in x: + PICS.append((img['src']).replace("300x168", "1280x720")) + + if WALLTIP_SEARCH: + for page in range(1,3): + r2 = rget(f"https://www.wallpapertip.com/s/{WALLTIP_SEARCH}/{page}") + soup2 = BeautifulSoup(r2.text, "html.parser") + divTag = soup2.select('#flex_grid div.item') + aTag = [x.find('a') for x in divTag] + imgsrc = [x.find('img') for x in aTag] + scrList = [img['data-original'] for img in imgsrc] + for o in scrList: + PICS.append(o) + + if WALLFLARE_SEARCH: + try: + for page in range(1,20): + r2 = rget(f"https://www.wallpaperflare.com/search?wallpaper={WALLFLARE_SEARCH}&width=1280&height=720&page={page}") + soup2 = BeautifulSoup(r2.text, "html.parser") + x = soup2.select('img[data-src^="https://c4.wallpaperflare.com/wallpaper"]') + for img in x: + PICS.append(img['data-src']) + except Exception as err: + LOGGER.info(f"WallFlare Error: {err}") + + if PIXABAY_API_KEY: + try: + PIXABAY_ENDPOINT = f"https://pixabay.com/api/?key={PIXABAY_API_KEY}&image_type=all&orientation=horizontal&min_width=1280&min_height=720&per_page=200&safesearch=true&editors_choice=true" + if PIXABAY_CATEGORY: PIXABAY_ENDPOINT += f"&category={PIXABAY_CATEGORY}" + if PIXABAY_SEARCH: PIXABAY_ENDPOINT += f"&q={q(PIXABAY_SEARCH)}" + resp = rget(PIXABAY_ENDPOINT) + jdata = resp.json() + for x in range(0, 200): + largeImageURL = jdata['hits'][x]['largeImageURL'] + PICS.append(largeImageURL) + except Exception as err: + LOGGER.info(f"Pixabay API Error: {err}") + + if SET_BOT_COMMANDS: + bot.set_my_commands(botcmds) + start_cleanup() + date = now.strftime('%d/%m/%y') + time = now.strftime('%I:%M:%S %p') + notifier_dict = False + if INCOMPLETE_TASK_NOTIFIER and DB_URI is not None: + if notifier_dict := DbManger().get_incomplete_tasks(): + for cid, data in notifier_dict.items(): + if ospath.isfile(".restartmsg"): + with open(".restartmsg") as f: + chat_id, msg_id = map(int, f) + msg = f"😎Restarted successfully❗\n" + msg += f"📅DATE: {date}\n" + msg += f"⌚TIME: {time}\n" + msg += f"🌐TIMEZONE: {TIMEZONE}\n" + else: + msg = f"😎Bot Restarted!\n" + msg += f"📅DATE: {date}\n" + msg += f"⌚TIME: {time}\n" + msg += f"🌐TIMEZONE: {TIMEZONE}" + + for tag, links in data.items(): + msg += f"\n{tag}: " + for index, link in enumerate(links, start=1): + msg += f" {index} |" + if len(msg.encode()) > 4000: + if '😎Restarted successfully❗' in msg and cid == chat_id: + bot.editMessageText(msg, chat_id, msg_id, parse_mode='HTML', disable_web_page_preview=True) + osremove(".restartmsg") + else: + try: + bot.sendMessage(cid, msg, 'HTML', disable_web_page_preview=True) + except Exception as e: + LOGGER.error(e) + msg = '' + if '😎Restarted successfully❗' in msg and cid == chat_id: + bot.editMessageText(msg, chat_id, msg_id, parse_mode='HTML', disable_web_page_preview=True) + osremove(".restartmsg") + else: + try: + bot.sendMessage(cid, msg, 'HTML', disable_web_page_preview=True) + except Exception as e: + LOGGER.error(e) + + if ospath.isfile(".restartmsg"): + with open(".restartmsg") as f: + chat_id, msg_id = map(int, f) + msg = f"😎Restarted successfully❗\n📅DATE: {date}\n⌚TIME: {time}\n🌐TIMEZONE: {TIMEZONE}\n" + bot.edit_message_text(msg, chat_id, msg_id) + osremove(".restartmsg") + elif not notifier_dict and AUTHORIZED_CHATS: + text = f"😎Bot Restarted❗ \n📅DATE: {date} \n⌚TIME: {time} \n🌐TIMEZONE: {TIMEZONE}" + for id_ in AUTHORIZED_CHATS: + try: + bot.sendMessage(chat_id=id_, text=text, parse_mode=ParseMode.HTML) + except Exception as e: + LOGGER.error(e) + + + start_handler = CommandHandler(BotCommands.StartCommand, start, run_async=True) + ping_handler = CommandHandler(BotCommands.PingCommand, ping, + filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + restart_handler = CommandHandler(BotCommands.RestartCommand, restart, + filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True) + help_handler = CommandHandler(BotCommands.HelpCommand, + bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + stats_handler = CommandHandler(BotCommands.StatsCommand, + stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True) + dispatcher.add_handler(start_handler) + dispatcher.add_handler(ping_handler) + dispatcher.add_handler(restart_handler) + dispatcher.add_handler(help_handler) + dispatcher.add_handler(stats_handler) + dispatcher.add_handler(log_handler) + updater.start_polling(drop_pending_updates=IGNORE_PENDING_REQUESTS) + LOGGER.info("💥𝐁𝐨𝐭 𝐒𝐭𝐚𝐫𝐭𝐞𝐝❗") + signal(SIGINT, exit_clean_up) + +app.start() +main() + +main_loop.run_forever() diff --git a/bot/helper/__init__.py b/bot/helper/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/ext_utils/__init__.py b/bot/helper/ext_utils/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/ext_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/ext_utils/bot_utils.py b/bot/helper/ext_utils/bot_utils.py new file mode 100644 index 0000000..2a77185 --- /dev/null +++ b/bot/helper/ext_utils/bot_utils.py @@ -0,0 +1,454 @@ +from re import match as re_match, findall as re_findall +from threading import Thread, Event +from time import time +from math import ceil +from html import escape +from psutil import virtual_memory, cpu_percent, disk_usage +from requests import head as rhead +from urllib.request import urlopen + +from bot.helper.telegram_helper.bot_commands import BotCommands +from bot import FINISHED_PROGRESS_STR, UN_FINISHED_PROGRESS_STR, download_dict, download_dict_lock, STATUS_LIMIT, botStartTime, DOWNLOAD_DIR, WEB_PINCODE, BASE_URL, EMOJI_THEME, TOTAL_TASKS_LIMIT, USER_TASKS_LIMIT, LEECH_LIMIT, MEGA_LIMIT, CREDIT_NAME, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT +from bot.helper.telegram_helper.button_build import ButtonMaker + +import shutil +import psutil +from telegram.error import RetryAfter +from telegram.ext import CallbackQueryHandler +from telegram.message import Message +from telegram.update import Update +from bot import * + +MAGNET_REGEX = r"magnet:\?xt=urn:btih:[a-zA-Z0-9]*" + +URL_REGEX = r"(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+" + +COUNT = 0 +PAGE_NO = 1 +PAGES = 0 + + +class MirrorStatus: + if EMOJI_THEME is True: + STATUS_UPLOADING = "📤 Upload" + STATUS_DOWNLOADING = "📥 Download" + STATUS_CLONING = "♻️ Clone" + STATUS_WAITING = "💤 Queue" + STATUS_PAUSED = "⛔️ Pause" + STATUS_ARCHIVING = "🔐 Archive" + STATUS_EXTRACTING = "📂 Extract" + STATUS_SPLITTING = "✂️ Split" + STATUS_CHECKING = "📝 CheckUp" + STATUS_SEEDING = "🌧 Seed" + else: + STATUS_UPLOADING = "Upload" + STATUS_DOWNLOADING = "Download" + STATUS_CLONING = "Clone" + STATUS_WAITING = "Queue" + STATUS_PAUSED = "Pause" + STATUS_ARCHIVING = "Archive" + STATUS_EXTRACTING = "Extract" + STATUS_SPLITTING = "Split" + STATUS_CHECKING = "CheckUp" + STATUS_SEEDING = "Seed" + +class EngineStatus: + STATUS_ARIA = "Aria2c v1.35.0" + STATUS_GD = "Google Api v2.51.0" + STATUS_MEGA = "MegaSDK v3.12.0" + STATUS_QB = "qBittorrent v4.3.9" + STATUS_TG = "Pyrogram v2.0.27" + STATUS_YT = "YT-dlp v22.5.18" + STATUS_EXT = "Extract | pExtract" + STATUS_SPLIT = "FFmpeg v2.9.1" + STATUS_ZIP = "p7zip v16.02" + + +SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] + + +class setInterval: + def __init__(self, interval, action): + self.interval = interval + self.action = action + self.stopEvent = Event() + thread = Thread(target=self.__setInterval) + thread.start() + + def __setInterval(self): + nextTime = time() + self.interval + while not self.stopEvent.wait(nextTime - time()): + nextTime += self.interval + self.action() + + def cancel(self): + self.stopEvent.set() + +def get_readable_file_size(size_in_bytes) -> str: + if size_in_bytes is None: + return '0B' + index = 0 + while size_in_bytes >= 1024: + size_in_bytes /= 1024 + index += 1 + try: + return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}' + except IndexError: + return 'File too large' + +def getDownloadByGid(gid): + with download_dict_lock: + for dl in list(download_dict.values()): + if dl.gid() == gid: + return dl + return None + +def getAllDownload(req_status: str): + with download_dict_lock: + for dl in list(download_dict.values()): + status = dl.status() + if req_status in ['all', status]: + return dl + return None + +def bt_selection_buttons(id_: str): + if len(id_) > 20: + gid = id_[:12] + else: + gid = id_ + + pincode = "" + for n in id_: + if n.isdigit(): + pincode += str(n) + if len(pincode) == 4: + break + + buttons = ButtonMaker() + if WEB_PINCODE: + buttons.buildbutton("Select Files", f"{BASE_URL}/app/files/{id_}") + buttons.sbutton("Pincode", f"btsel pin {gid} {pincode}") + else: + buttons.buildbutton("Select Files", f"{BASE_URL}/app/files/{id_}?pin_code={pincode}") + buttons.sbutton("Done Selecting", f"btsel done {gid} {id_}") + return buttons.build_menu(2) + + +def get_user_task(user_id): + user_task = 0 + for task in list(download_dict.values()): + userid = task.message.from_user.id + if userid == user_id: user_task += 1 + return user_task + +def get_progress_bar_string(status): + completed = status.processed_bytes() / 8 + total = status.size_raw() / 8 + p = 0 if total == 0 else round(completed * 100 / total) + p = min(max(p, 0), 100) + cFull = p // 8 + p_str = FINISHED_PROGRESS_STR * cFull + p_str += UN_FINISHED_PROGRESS_STR * (12 - cFull) + p_str = f"[{p_str}]" + return p_str + + +def get_readable_message(): + with download_dict_lock: + msg = f"" + if STATUS_LIMIT is not None: + tasks = len(download_dict) + global pages + globals()['PAGES'] = ceil(tasks/STATUS_LIMIT) + if PAGE_NO > PAGES and PAGES != 0: + globals()['COUNT'] -= STATUS_LIMIT + globals()['PAGE_NO'] -= 1 + for index, download in enumerate(list(download_dict.values())[COUNT:], start=1): + msg += f"{download.status()}: " + msg += f"{escape(str(download.name()))}" + if download.status() not in [MirrorStatus.STATUS_SEEDING, MirrorStatus.STATUS_SPLITTING]: + if EMOJI_THEME is True: + msg += f"\n{get_progress_bar_string(download)} {download.progress()}" + msg += f"\n├🔄 Process: {get_readable_file_size(download.processed_bytes())} of {download.size()}" + msg += f"\n├⚡ Speed: {download.speed()}" + msg += f"\n├⏳ ETA: {download.eta()}" + msg += f" | Elapsed: {get_readable_time(time() - download.message.date.timestamp())}" + msg += f"\n├⛓️ Engine : {download.eng()}" + + else: + msg += f"\n{get_progress_bar_string(download)} {download.progress()}" + msg += f"\n├ Process: {get_readable_file_size(download.processed_bytes())} of {download.size()}" + msg += f"\n├ Speed: {download.speed()}" + msg += f"\n├ ETA: {download.eta()}" + msg += f" | Elapsed: {get_readable_time(time() - download.message.date.timestamp())}" + msg += f"\n├ Engine : {download.eng()}" + + if hasattr(download, 'seeders_num'): + try: + if EMOJI_THEME is True: + msg += f"\n├🌱 Seeders: {download.seeders_num()} | 🐌 Leechers: {download.leechers_num()}" + # msg += f"\n├🧿 To Select: /{BotCommands.BtSelectCommand} {download.gid()}" + else: + msg += f"\n├ Seeders: {download.seeders_num()} | Leechers: {download.leechers_num()}" + # msg += f"\n├ To Select: /{BotCommands.BtSelectCommand} {download.gid()}" + except: + pass + if download.message.chat.type != 'private': + try: + chatid = str(download.message.chat.id)[4:] + if EMOJI_THEME is True: + msg += f'\n├🌐 Source: {download.message.from_user.first_name} | Id : {download.message.from_user.id}' + msg += f"\n╰❌ /{BotCommands.CancelMirror} {download.gid()}" + else: + msg += f'\n├ Source: {download.message.from_user.first_name} | Id : {download.message.from_user.id}' + msg += f"\n/{BotCommands.CancelMirror} {download.gid()}" + except: + pass + else: + if EMOJI_THEME is True: + msg += f'\n├👤 User:{download.message.from_user.first_name} | Id: {download.message.from_user.id}' + msg += f"\n╰❌ /{BotCommands.CancelMirror} {download.gid()}" + else: + msg += f'\n├ User:{download.message.from_user.first_name} | Id: {download.message.from_user.id}' + msg += f"\n/{BotCommands.CancelMirror} {download.gid()}" + + elif download.status() == MirrorStatus.STATUS_SEEDING: + if EMOJI_THEME is True: + msg += f"\n├📦 Size: {download.size()}" + msg += f"\n├⛓️ Engine: qBittorrent v4.4.2" + msg += f"\n├⚡ Speed: {download.upload_speed()}" + msg += f"\n├🔺 Uploaded: {download.uploaded_bytes()}" + msg += f"\n├📎 Ratio: {download.ratio()}" + msg += f" | ⏲️ Time: {download.seeding_time()}" + msg += f"\n├⏳ Elapsed: {get_readable_time(time() - download.message.date.timestamp())}" + msg += f"\n╰❌ /{BotCommands.CancelMirror} {download.gid()}" + else: + msg += f"\n├ Size: {download.size()}" + msg += f"\n├ Engine: qBittorrent v4.4.2" + msg += f"\n├ Speed: {download.upload_speed()}" + msg += f"\n├ Uploaded: {download.uploaded_bytes()}" + msg += f"\n├ Ratio: {download.ratio()}" + msg += f" | Time: {download.seeding_time()}" + msg += f"\n├ Elapsed: {get_readable_time(time() - download.message.date.timestamp())}" + msg += f"\n/{BotCommands.CancelMirror} {download.gid()}" + else: + if EMOJI_THEME is True: + msg += f"\n├⛓️ Engine : {download.eng()}" + msg += f"\n╰📐 Size: {download.size()}" + else: + msg += f"\n├ Engine : {download.eng()}" + msg += f"\n╰ Size: {download.size()}" + msg += f"\n_____________________________________" + msg += "\n\n" + if STATUS_LIMIT is not None and index == STATUS_LIMIT: + break + if len(msg) == 0: + return None, None + dl_speed = 0 + up_speed = 0 + for download in list(download_dict.values()): + spd = download.speed() + if download.status() == MirrorStatus.STATUS_DOWNLOADING: + spd = download.speed() + if 'K' in spd: + dl_speed += float(spd.split('K')[0]) * 1024 + elif 'M' in spd: + dl_speed += float(spd.split('M')[0]) * 1048576 + elif download.status() == MirrorStatus.STATUS_UPLOADING: + spd = download.speed() + if 'KB/s' in spd: + up_speed += float(spd.split('K')[0]) * 1024 + elif 'MB/s' in spd: + up_speed += float(spd.split('M')[0]) * 1048576 + elif download.status() == MirrorStatus.STATUS_SEEDING: + spd = download.upload_speed() + if 'K' in spd: + up_speed += float(spd.split('K')[0]) * 1024 + elif 'M' in spd: + up_speed += float(spd.split('M')[0]) * 1048576 + if EMOJI_THEME is True: + bmsg = f"🖥 CPU: {cpu_percent()}% | 💿 FREE: {get_readable_file_size(disk_usage(DOWNLOAD_DIR).free)}" + bmsg += f"\n🎮 RAM: {virtual_memory().percent}% | 🟢 UPTIME: {get_readable_time(time() - botStartTime)}" + bmsg += f"\n🔻 DL: {get_readable_file_size(dl_speed)}/s | 🔺 UL: {get_readable_file_size(up_speed)}/s" + else: + bmsg = f"CPU: {cpu_percent()}% | FREE: {get_readable_file_size(disk_usage(DOWNLOAD_DIR).free)}" + bmsg += f"\nRAM: {virtual_memory().percent}% | UPTIME: {get_readable_time(time() - botStartTime)}" + bmsg += f"\nDL: {get_readable_file_size(dl_speed)}/s | UL: {get_readable_file_size(up_speed)}/s" + + buttons = ButtonMaker() + buttons.sbutton("Refresh", "status refresh") + buttons.sbutton("Statistics", str(THREE)) + buttons.sbutton("Close", "status close") + sbutton = buttons.build_menu(3) + + if STATUS_LIMIT is not None and tasks > STATUS_LIMIT: + msg += f"Tasks: {tasks}\n" + buttons = ButtonMaker() + if EMOJI_THEME is True: + buttons.sbutton("⏪Previous", "status pre") + buttons.sbutton(f"{PAGE_NO}/{PAGES}", str(THREE)) + buttons.sbutton("Next⏩", "status nex") + buttons.sbutton("Refresh", "status refresh") + buttons.sbutton("Close", "status close") + else: + buttons.sbutton("Previous", "status pre") + buttons.sbutton(f"{PAGE_NO}/{PAGES}", str(THREE)) + buttons.sbutton("Next", "status nex") + buttons.sbutton("Refresh", "status refresh") + buttons.sbutton("Close", "status close") + button = buttons.build_menu(3) + return msg + bmsg, button + return msg + bmsg, sbutton + +def turn(data): + try: + with download_dict_lock: + global COUNT, PAGE_NO + if data[1] == "nex": + if PAGE_NO == PAGES: + COUNT = 0 + PAGE_NO = 1 + else: + COUNT += STATUS_LIMIT + PAGE_NO += 1 + elif data[1] == "pre": + if PAGE_NO == 1: + COUNT = STATUS_LIMIT * (PAGES - 1) + PAGE_NO = PAGES + else: + COUNT -= STATUS_LIMIT + PAGE_NO -= 1 + return True + except: + return False + +def get_readable_time(seconds: int) -> str: + result = '' + (days, remainder) = divmod(seconds, 86400) + days = int(days) + if days != 0: + result += f'{days}d' + (hours, remainder) = divmod(remainder, 3600) + hours = int(hours) + if hours != 0: + result += f'{hours}h' + (minutes, seconds) = divmod(remainder, 60) + minutes = int(minutes) + if minutes != 0: + result += f'{minutes}m' + seconds = int(seconds) + result += f'{seconds}s' + return result + +def is_url(url: str): + url = re_findall(URL_REGEX, url) + return bool(url) + +def is_gdrive_link(url: str): + return "drive.google.com" in url + +def is_gdtot_link(url: str): + url = re_match(r'https?://.+\.gdtot\.\S+', url) + return bool(url) + +def is_unified_link(url: str): + url = re_match(r'https?://(appdrive|driveapp|driveace|gdflix|drivebit|drivesharer|drivepro)\.\S+', url) + if bool(url) == True: + return bool(url) + else: + return False + +def is_udrive_link(url: str): + if 'drivehub.ws' in url: + return 'drivehub.ws' in url + else: + url = re_match(r'https?://(hubdrive|katdrive|kolop|drivefire|drivebuzz)\.\S+', url) + return bool(url) + +def is_mega_link(url: str): + return "mega.nz" in url or "mega.co.nz" in url + +def get_mega_link_type(url: str): + if "folder" in url: + return "folder" + elif "file" in url: + return "file" + elif "/#F!" in url: + return "folder" + return "file" + +def is_magnet(url: str): + magnet = re_findall(MAGNET_REGEX, url) + return bool(magnet) + +def new_thread(fn): + """To use as decorator to make a function call threaded. + Needs import + from threading import Thread""" + + def wrapper(*args, **kwargs): + thread = Thread(target=fn, args=args, kwargs=kwargs) + thread.start() + return thread + + return wrapper + +def get_content_type(link: str) -> str: + try: + res = rhead(link, allow_redirects=True, timeout=5, headers = {'user-agent': 'Wget/1.12'}) + content_type = res.headers.get('content-type') + except: + try: + res = urlopen(link, timeout=5) + info = res.info() + content_type = info.get_content_type() + except: + content_type = None + return content_type + + +ONE, TWO, THREE = range(3) +def pop_up_stats(update, context): + query = update.callback_query + stats = bot_sys_stats() + query.answer(text=stats, show_alert=True) +def bot_sys_stats(): + currentTime = get_readable_time(time() - botStartTime) + cpu = psutil.cpu_percent() + mem = psutil.virtual_memory().percent + disk = psutil.disk_usage(DOWNLOAD_DIR).percent + total, used, free = shutil.disk_usage(DOWNLOAD_DIR) + total = get_readable_file_size(total) + used = get_readable_file_size(used) + free = get_readable_file_size(free) + recv = get_readable_file_size(psutil.net_io_counters().bytes_recv) + sent = get_readable_file_size(psutil.net_io_counters().bytes_sent) + num_active = 0 + num_upload = 0 + num_split = 0 + num_extract = 0 + num_archi = 0 + tasks = len(download_dict) + for stats in list(download_dict.values()): + if stats.status() == MirrorStatus.STATUS_DOWNLOADING: + num_active += 1 + if stats.status() == MirrorStatus.STATUS_UPLOADING: + num_upload += 1 + if stats.status() == MirrorStatus.STATUS_ARCHIVING: + num_archi += 1 + if stats.status() == MirrorStatus.STATUS_EXTRACTING: + num_extract += 1 + if stats.status() == MirrorStatus.STATUS_SPLITTING: + num_split += 1 + stats = f""" +CPU : {cpu}% | RAM : {mem}% +DL : {num_active} | UP : {num_upload} | SPLIT : {num_split} +ZIP : {num_archi} | UNZIP : {num_extract} | TOTAL : {tasks} +Limits : T/D : {TORRENT_DIRECT_LIMIT}GB | Z/U : {ZIP_UNZIP_LIMIT}GB + L : {LEECH_LIMIT}GB | M : {MEGA_LIMIT}GB +Made with ❤️ by {CREDIT_NAME} +""" + return stats +dispatcher.add_handler( + CallbackQueryHandler(pop_up_stats, pattern="^" + str(THREE) + "$") +) \ No newline at end of file diff --git a/bot/helper/ext_utils/db_handler.py b/bot/helper/ext_utils/db_handler.py new file mode 100644 index 0000000..cd1291c --- /dev/null +++ b/bot/helper/ext_utils/db_handler.py @@ -0,0 +1,274 @@ +from os import path as ospath, makedirs +from psycopg2 import connect, DatabaseError + +from bot import DB_URI, AUTHORIZED_CHATS, SUDO_USERS, AS_DOC_USERS, AS_MEDIA_USERS, rss_dict, LOGGER, botname, LEECH_LOG + +class DbManger: + def __init__(self): + self.err = False + self.connect() + + def connect(self): + try: + self.conn = connect(DB_URI) + self.cur = self.conn.cursor() + except DatabaseError as error: + LOGGER.error(f"Error in DB connection: {error}") + self.err = True + + def disconnect(self): + self.cur.close() + self.conn.close() + + def db_init(self): + if self.err: + return + sql = """CREATE TABLE IF NOT EXISTS users ( + uid bigint, + sudo boolean DEFAULT FALSE, + auth boolean DEFAULT FALSE, + media boolean DEFAULT FALSE, + doc boolean DEFAULT FALSE, + thumb bytea DEFAULT NULL, + leechlog boolean DEFAULT FALSE + ) + """ + self.cur.execute(sql) + sql = """CREATE TABLE IF NOT EXISTS rss ( + name text, + link text, + last text, + title text, + filters text + ) + """ + self.cur.execute(sql) + self.cur.execute("CREATE TABLE IF NOT EXISTS {} (cid bigint, link text, tag text)".format(botname)) + self.conn.commit() + LOGGER.info("Database Initiated") + self.db_load() + + def db_load(self): + # User Data + self.cur.execute("SELECT * from users") + rows = self.cur.fetchall() # return a list ==> (uid, sudo, auth, media, doc, thumb) + if rows: + for row in rows: + if row[1] and row[0] not in SUDO_USERS: + SUDO_USERS.add(row[0]) + elif row[2] and row[0] not in AUTHORIZED_CHATS: + AUTHORIZED_CHATS.add(row[0]) + if row[3]: + AS_MEDIA_USERS.add(row[0]) + elif row[4]: + AS_DOC_USERS.add(row[0]) + path = f"Thumbnails/{row[0]}.jpg" + if row[5] is not None and not ospath.exists(path): + if not ospath.exists('Thumbnails'): + makedirs('Thumbnails') + with open(path, 'wb+') as f: + f.write(row[5]) + if row[6] and row[0] not in LEECH_LOG: + LEECH_LOG.add(row[0]) + LOGGER.info("Users data has been imported from Database") + # Rss Data + self.cur.execute("SELECT * FROM rss") + rows = self.cur.fetchall() # return a list ==> (name, feed_link, last_link, last_title, filters) + if rows: + for row in rows: + f_lists = [] + if row[4] is not None: + filters_list = row[4].split('|') + for x in filters_list: + y = x.split(' or ') + f_lists.append(y) + rss_dict[row[0]] = [row[1], row[2], row[3], f_lists] + LOGGER.info("Rss data has been imported from Database.") + self.disconnect() + + def user_auth(self, chat_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif not self.user_check(chat_id): + sql = 'INSERT INTO users (uid, auth) VALUES ({}, TRUE)'.format(chat_id) + else: + sql = 'UPDATE users SET auth = TRUE WHERE uid = {}'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Authorized successfully' + + def user_unauth(self, chat_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif self.user_check(chat_id): + sql = 'UPDATE users SET auth = FALSE WHERE uid = {}'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Unauthorized successfully' + + def user_addsudo(self, user_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif not self.user_check(user_id): + sql = 'INSERT INTO users (uid, sudo) VALUES ({}, TRUE)'.format(user_id) + else: + sql = 'UPDATE users SET sudo = TRUE WHERE uid = {}'.format(user_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Successfully Promoted as Sudo' + + def user_rmsudo(self, user_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif self.user_check(user_id): + sql = 'UPDATE users SET sudo = FALSE WHERE uid = {}'.format(user_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Successfully removed from Sudo' + + def user_media(self, user_id: int): + if self.err: + return + elif not self.user_check(user_id): + sql = 'INSERT INTO users (uid, media) VALUES ({}, TRUE)'.format(user_id) + else: + sql = 'UPDATE users SET media = TRUE, doc = FALSE WHERE uid = {}'.format(user_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + + def user_doc(self, user_id: int): + if self.err: + return + elif not self.user_check(user_id): + sql = 'INSERT INTO users (uid, doc) VALUES ({}, TRUE)'.format(user_id) + else: + sql = 'UPDATE users SET media = FALSE, doc = TRUE WHERE uid = {}'.format(user_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + + def user_save_thumb(self, user_id: int, path): + if self.err: + return + image = open(path, 'rb+') + image_bin = image.read() + if not self.user_check(user_id): + sql = 'INSERT INTO users (thumb, uid) VALUES (%s, %s)' + else: + sql = 'UPDATE users SET thumb = %s WHERE uid = %s' + self.cur.execute(sql, (image_bin, user_id)) + self.conn.commit() + self.disconnect() + + def user_rm_thumb(self, user_id: int, path): + if self.err: + return + elif self.user_check(user_id): + sql = 'UPDATE users SET thumb = NULL WHERE uid = {}'.format(user_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + + def addleech_log(self, chat_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif not self.user_check(chat_id): + sql = 'INSERT INTO users (uid, leechlog) VALUES ({}, TRUE)'.format(chat_id) + else: + sql = 'UPDATE users SET leechlog = TRUE WHERE uid = {}'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Successfully added to leech logs' + + def rmleech_log(self, chat_id: int): + if self.err: + return "Error in DB connection, check log for details" + elif self.user_check(chat_id): + sql = 'UPDATE users SET leechlog = FALSE WHERE uid = {}'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + return 'Removed from leech logs successfully' + + def user_check(self, uid: int): + self.cur.execute("SELECT * FROM users WHERE uid = {}".format(uid)) + res = self.cur.fetchone() + return res + + def rss_add(self, name, link, last, title, filters): + if self.err: + return + q = (name, link, last, title, filters) + self.cur.execute("INSERT INTO rss (name, link, last, title, filters) VALUES (%s, %s, %s, %s, %s)", q) + self.conn.commit() + self.disconnect() + + def rss_update(self, name, last, title): + if self.err: + return + q = (last, title, name) + self.cur.execute("UPDATE rss SET last = %s, title = %s WHERE name = %s", q) + self.conn.commit() + self.disconnect() + + def rss_delete(self, name): + if self.err: + return + self.cur.execute("DELETE FROM rss WHERE name = %s", (name,)) + self.conn.commit() + self.disconnect() + + def add_incomplete_task(self, cid: int, link: str, tag: str): + if self.err: + return + q = (cid, link, tag) + self.cur.execute("INSERT INTO {} (cid, link, tag) VALUES (%s, %s, %s)".format(botname), q) + self.conn.commit() + self.disconnect() + + def rm_complete_task(self, link: str): + if self.err: + return + self.cur.execute("DELETE FROM {} WHERE link = %s".format(botname), (link,)) + self.conn.commit() + self.disconnect() + + def get_incomplete_tasks(self): + if self.err: + return False + self.cur.execute("SELECT * from {}".format(botname)) + rows = self.cur.fetchall() # return a list ==> (cid, link, tag) + notifier_dict = {} + if rows: + for row in rows: + if row[0] in list(notifier_dict.keys()): + if row[2] in list(notifier_dict[row[0]].keys()): + notifier_dict[row[0]][row[2]].append(row[1]) + else: + notifier_dict[row[0]][row[2]] = [row[1]] + else: + usr_dict = {} + usr_dict[row[2]] = [row[1]] + notifier_dict[row[0]] = usr_dict + self.cur.execute("TRUNCATE TABLE {}".format(botname)) + self.conn.commit() + self.disconnect() + return notifier_dict # return a dict ==> {cid: {tag: [mid, mid, ...]}} + + + def trunc_table(self, name): + if self.err: + return + self.cur.execute("TRUNCATE TABLE {}".format(name)) + self.conn.commit() + self.disconnect() + +if DB_URI is not None: + DbManger().db_init() + diff --git a/bot/helper/ext_utils/exceptions.py b/bot/helper/ext_utils/exceptions.py new file mode 100644 index 0000000..a2f600c --- /dev/null +++ b/bot/helper/ext_utils/exceptions.py @@ -0,0 +1,8 @@ +class DirectDownloadLinkException(Exception): + """Not method found for extracting direct download link from the http link""" + pass + + +class NotSupportedExtractionArchive(Exception): + """The archive format use is trying to extract is not supported""" + pass diff --git a/bot/helper/ext_utils/fs_utils.py b/bot/helper/ext_utils/fs_utils.py new file mode 100644 index 0000000..fc1665f --- /dev/null +++ b/bot/helper/ext_utils/fs_utils.py @@ -0,0 +1,277 @@ +from os import remove as osremove, path as ospath, mkdir, walk, listdir, rmdir, makedirs +from sys import exit as sysexit +from json import loads as jsonloads +from shutil import rmtree, disk_usage +from PIL import Image +from magic import Magic +from subprocess import run as srun, check_output, Popen +from time import time +from math import ceil +from re import split as re_split, I +from .exceptions import NotSupportedExtractionArchive +from bot import aria2, app, LOGGER, DOWNLOAD_DIR, get_client, TG_SPLIT_SIZE, EQUAL_SPLITS, STORAGE_THRESHOLD, premium_session + + +ARCH_EXT = [".tar.bz2", ".tar.gz", ".bz2", ".gz", ".tar.xz", ".tar", ".tbz2", ".tgz", ".lzma2", + ".zip", ".7z", ".z", ".rar", ".iso", ".wim", ".cab", ".apm", ".arj", ".chm", + ".cpio", ".cramfs", ".deb", ".dmg", ".fat", ".hfs", ".lzh", ".lzma", ".mbr", + ".msi", ".mslz", ".nsis", ".ntfs", ".rpm", ".squashfs", ".udf", ".vhd", ".xar"] + +def clean_target(path: str): + if ospath.exists(path): + LOGGER.info(f"Cleaning Target: {path}") + if ospath.isdir(path): + try: + rmtree(path) + except: + pass + elif ospath.isfile(path): + try: + osremove(path) + except: + pass + +def clean_download(path: str): + if ospath.exists(path): + LOGGER.info(f"Cleaning Download: {path}") + try: + rmtree(path) + except: + pass + +def start_cleanup(): + try: + rmtree(DOWNLOAD_DIR) + except: + pass + makedirs(DOWNLOAD_DIR) + +def clean_all(): + aria2.remove_all(True) + get_client().torrents_delete(torrent_hashes="all") + app.stop() + if premium_session: premium_session.stop() + try: + rmtree(DOWNLOAD_DIR) + except: + pass + +def exit_clean_up(signal, frame): + try: + LOGGER.info("Please wait, while we clean up the downloads and stop running downloads") + clean_all() + sysexit(0) + except KeyboardInterrupt: + LOGGER.warning("Force Exiting before the cleanup finishes!") + sysexit(1) + +def clean_unwanted(path: str): + LOGGER.info(f"Cleaning unwanted files/folders: {path}") + for dirpath, subdir, files in walk(path, topdown=False): + for filee in files: + if filee.endswith(".!qB") or filee.endswith('.parts') and filee.startswith('.'): + osremove(ospath.join(dirpath, filee)) + if dirpath.endswith((".unwanted", "splited_files_wz")): + rmtree(dirpath) + for dirpath, subdir, files in walk(path, topdown=False): + if not listdir(dirpath): + rmdir(dirpath) + +def get_path_size(path: str): + if ospath.isfile(path): + return ospath.getsize(path) + total_size = 0 + for root, dirs, files in walk(path): + for f in files: + abs_path = ospath.join(root, f) + total_size += ospath.getsize(abs_path) + return total_size + +def check_storage_threshold(size: int, arch=False, alloc=False): + if not alloc: + if not arch: + if disk_usage(DOWNLOAD_DIR).free - size < STORAGE_THRESHOLD * 1024**3: + return False + elif disk_usage(DOWNLOAD_DIR).free - (size * 2) < STORAGE_THRESHOLD * 1024**3: + return False + elif not arch: + if disk_usage(DOWNLOAD_DIR).free < STORAGE_THRESHOLD * 1024**3: + return False + elif disk_usage(DOWNLOAD_DIR).free - size < STORAGE_THRESHOLD * 1024**3: + return False + return True + +def get_base_name(orig_path: str): + if ext := [ext for ext in ARCH_EXT if orig_path.lower().endswith(ext)]: + ext = ext[0] + return re_split(f'{ext}$', orig_path, maxsplit=1, flags=I)[0] + else: + raise NotSupportedExtractionArchive('File format not supported for extraction') + +def get_mime_type(file_path): + mime = Magic(mime=True) + mime_type = mime.from_file(file_path) + mime_type = mime_type or "text/plain" + return mime_type + +def take_ss(video_file, duration): + des_dir = 'Thumbnails' + if not ospath.exists(des_dir): + mkdir(des_dir) + des_dir = ospath.join(des_dir, f"{time()}.jpg") + if duration is None: + duration = get_media_info(video_file)[0] + if duration == 0: + duration = 3 + duration = duration // 2 + + status = srun(["ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(duration), + "-i", video_file, "-frames:v", "1", des_dir]) + + if status.returncode != 0 or not ospath.lexists(des_dir): + return None + + with Image.open(des_dir) as img: + img.convert("RGB").save(des_dir, "JPEG") + + return des_dir + +def split_file(path, size, file_, dirpath, split_size, listener, start_time=0, i=1, inLoop=False, noMap=False): + if listener.seed and not listener.newDir: + dirpath = f"{dirpath}/splited_files_wz" + if not ospath.exists(dirpath): + mkdir(dirpath) + parts = ceil(size/TG_SPLIT_SIZE) + if EQUAL_SPLITS and not inLoop: + split_size = ceil(size/parts) + 1000 + if get_media_streams(path)[0]: + duration = get_media_info(path)[0] + base_name, extension = ospath.splitext(file_) + split_size = split_size - 5000000 + while i <= parts: + parted_name = f"{str(base_name)}.part{str(i).zfill(3)}{str(extension)}" + out_path = ospath.join(dirpath, parted_name) + if not noMap: + listener.suproc = Popen(["ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(start_time), + "-i", path, "-fs", str(split_size), "-map", "0", "-map_chapters", "-1", + "-c", "copy", out_path]) + else: + listener.suproc = Popen(["ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(start_time), + "-i", path, "-fs", str(split_size), "-map_chapters", "-1", "-c", "copy", + out_path]) + listener.suproc.wait() + if listener.suproc.returncode == -9: + return False + elif listener.suproc.returncode != 0 and not noMap: + LOGGER.warning(f"Retrying without map, -map 0 not working in all situations. Path: {path}") + try: + osremove(out_path) + except: + pass + return split_file(path, size, file_, dirpath, split_size, listener, start_time, i, True, True) + elif listener.suproc.returncode != 0: + LOGGER.warning(f"Unable to split this video, if it's size less than {TG_SPLIT_SIZE} will be uploaded as it is. Path: {path}") + try: + osremove(out_path) + except: + pass + return "errored" + out_size = get_path_size(out_path) + if out_size > (TG_SPLIT_SIZE + 1000): + dif = out_size - (TG_SPLIT_SIZE + 1000) + split_size = split_size - dif + 5000000 + osremove(out_path) + return split_file(path, size, file_, dirpath, split_size, listener, start_time, i, True, noMap) + lpd = get_media_info(out_path)[0] + if lpd == 0: + LOGGER.error(f'Something went wrong while splitting mostly file is corrupted. Path: {path}') + break + elif duration == lpd: + if not noMap: + LOGGER.warning(f"Retrying without map, -map 0 not working in all situations. Path: {path}") + try: + osremove(out_path) + except: + pass + return split_file(path, size, file_, dirpath, split_size, listener, start_time, i, True, True) + else: + LOGGER.warning(f"This file has been splitted with default stream and audio, so you will only see one part with less size from orginal one because it doesn't have all streams and audios. This happens mostly with MKV videos. noMap={noMap}. Path: {path}") + break + elif lpd <= 4: + osremove(out_path) + break + start_time += lpd - 3 + i = i + 1 + else: + out_path = ospath.join(dirpath, f"{file_}.") + listener.suproc = Popen(["split", "--numeric-suffixes=1", "--suffix-length=3", + f"--bytes={split_size}", path, out_path]) + listener.suproc.wait() + if listener.suproc.returncode == -9: + return False + return True + +def get_media_info(path): + + try: + result = check_output(["ffprobe", "-hide_banner", "-loglevel", "error", "-print_format", + "json", "-show_format", "-show_streams", path]).decode('utf-8') + except Exception as e: + LOGGER.error(f'{e} Mostly file not Found!') + return 0, None, None + + fields = jsonloads(result).get('format') + if fields is None: + LOGGER.error(f"get_media_info: {result}") + return 0, None, None + + duration = round(float(fields.get('duration', 0))) + + fields = fields.get('tags') + if fields: + artist = fields.get('artist') + if artist is None: + artist = fields.get('ARTIST') + title = fields.get('title') + if title is None: + title = fields.get('TITLE') + else: + title = None + artist = None + + return duration, artist, title + + + +def get_media_streams(path): + + is_video = False + is_audio = False + + mime_type = get_mime_type(path) + if mime_type.startswith('audio'): + is_audio = True + return is_video, is_audio + + if not mime_type.startswith('video'): + return is_video, is_audio + + try: + result = check_output(["ffprobe", "-hide_banner", "-loglevel", "error", "-print_format", + "json", "-show_streams", path]).decode('utf-8') + except Exception as e: + LOGGER.error(f'{e}. Mostly file not found!') + return is_video, is_audio + + fields = jsonloads(result).get('streams') + if fields is None: + LOGGER.error(f"get_media_streams: {result}") + return is_video, is_audio + + + for stream in fields: + if stream.get('codec_type') == 'video': + is_video = True + elif stream.get('codec_type') == 'audio': + is_audio = True + return is_video, is_audio diff --git a/bot/helper/ext_utils/html_helper.py b/bot/helper/ext_utils/html_helper.py new file mode 100644 index 0000000..6152d3d --- /dev/null +++ b/bot/helper/ext_utils/html_helper.py @@ -0,0 +1,125 @@ +hmtl_content = """ + + + + + + {fileName} + + + + + + + +{msg} + + +""" + +html_template = """ + + + + + + {title} + + + + + + + +{msg} + + +""" \ No newline at end of file diff --git a/bot/helper/ext_utils/shortenurl.py b/bot/helper/ext_utils/shortenurl.py new file mode 100644 index 0000000..f1baad3 --- /dev/null +++ b/bot/helper/ext_utils/shortenurl.py @@ -0,0 +1,53 @@ + + +from random import random, choice + +from cfscrape import create_scraper +from base64 import b64encode +from urllib.parse import quote, unquote +from urllib3 import disable_warnings + +from bot import LOGGER, SHORTENER, SHORTENER_API + + +def short_url(longurl): + if SHORTENER is None and SHORTENER_API is None: + return longurl + try: + cget = create_scraper().get + try: + unquote(longurl).encode('ascii') + if "{" in unquote(longurl) or "}" in unquote(longurl): + raise TypeError + except (UnicodeEncodeError, TypeError): + longurl = cget('http://tinyurl.com/api-create.php', params=dict(url=longurl)).text + if "shorte.st" in SHORTENER: + disable_warnings() + return cget(f'http://api.shorte.st/stxt/{SHORTENER_API}/{longurl}', verify=False).text + elif "linkvertise" in SHORTENER: + url = quote(b64encode(longurl.encode("utf-8"))) + linkvertise = [ + f"https://link-to.net/{SHORTENER_API}/{random() * 1000}/dynamic?r={url}", + f"https://up-to-down.net/{SHORTENER_API}/{random() * 1000}/dynamic?r={url}", + f"https://direct-link.net/{SHORTENER_API}/{random() * 1000}/dynamic?r={url}", + f"https://file-link.net/{SHORTENER_API}/{random() * 1000}/dynamic?r={url}"] + return choice(linkvertise) + elif "bitly.com" in SHORTENER: + shorten_url = "https://api-ssl.bit.ly/v4/shorten" + headers = {"Authorization": f"Bearer {SHORTENER_API}"} + response = create_scraper().post(shorten_url, json={"long_url": longurl}, headers=headers).json() + return response["link"] + elif "ouo.io" in SHORTENER: + disable_warnings() + return cget(f'http://ouo.io/api/{SHORTENER_API}?s={longurl}', verify=False).text + elif "adfoc.us" in SHORTENER: + disable_warnings() + return cget(f'http://adfoc.us/api/?key={SHORTENER_API}&url={longurl}', verify=False).text + elif "cutt.ly" in SHORTENER: + disable_warnings() + return cget(f'http://cutt.ly/api/api.php?key={SHORTENER_API}&short={longurl}', verify=False).json()['url']['shortLink'] + else: + return cget(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={quote(longurl)}&format=text').text + except Exception as e: + LOGGER.error(e) + return longurl diff --git a/bot/helper/ext_utils/telegraph_helper.py b/bot/helper/ext_utils/telegraph_helper.py new file mode 100644 index 0000000..69eb3d4 --- /dev/null +++ b/bot/helper/ext_utils/telegraph_helper.py @@ -0,0 +1,81 @@ +# Implement By - @VarnaX-279 + +from string import ascii_letters +from random import SystemRandom + +from time import sleep +from telegraph import Telegraph +from telegraph.exceptions import RetryAfterError + +from bot import LOGGER, AUTHOR_NAME, AUTHOR_URL, TITLE_NAME + + +class TelegraphHelper: + def __init__(self, author_name=None, author_url=None): + self.telegraph = Telegraph() + self.short_name = ''.join(SystemRandom().choices(ascii_letters, k=8)) + self.access_token = None + self.author_name = author_name + self.author_url = author_url + self.create_account() + + def create_account(self): + self.telegraph.create_account( + short_name=self.short_name, + author_name=self.author_name, + author_url=self.author_url + ) + self.access_token = self.telegraph.get_access_token() + LOGGER.info("Creating Telegraph Account") + + def create_page(self, title, content): + try: + return self.telegraph.create_page( + title = title, + author_name=self.author_name, + author_url=self.author_url, + html_content=content + ) + except RetryAfterError as st: + LOGGER.warning(f'Telegraph Flood control exceeded. I will sleep for {st.retry_after} seconds.') + sleep(st.retry_after) + return self.create_page(title, content) + + def edit_page(self, path, title, content): + try: + return self.telegraph.edit_page( + path = path, + title = title, + author_name=self.author_name, + author_url=self.author_url, + html_content=content + ) + except RetryAfterError as st: + LOGGER.warning(f'Telegraph Flood control exceeded. I will sleep for {st.retry_after} seconds.') + sleep(st.retry_after) + return self.edit_page(path, title, content) + + def edit_telegraph(self, path, telegraph_content): + nxt_page = 1 + prev_page = 0 + num_of_path = len(path) + for content in telegraph_content : + if nxt_page == 1 : + content += f'Next' + nxt_page += 1 + else : + if prev_page <= num_of_path: + content += f'Prev' + prev_page += 1 + if nxt_page < num_of_path: + content += f' | Next' + nxt_page += 1 + self.edit_page( + path = path[prev_page], + title = f"{TITLE_NAME} Torrent Search", + content=content + ) + return + + +telegraph=TelegraphHelper(f'{AUTHOR_NAME}', f'{AUTHOR_URL}') diff --git a/bot/helper/mirror_utils/__init__.py b/bot/helper/mirror_utils/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/mirror_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_utils/download_utils/__init__.py b/bot/helper/mirror_utils/download_utils/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_utils/download_utils/aria2_download.py b/bot/helper/mirror_utils/download_utils/aria2_download.py new file mode 100644 index 0000000..e0963b8 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/aria2_download.py @@ -0,0 +1,230 @@ +from time import sleep, time +from os import remove, path as ospath +from bot import LEECH_LIMIT, TELEGRAPH_STYLE, aria2, download_dict_lock, download_dict, STOP_DUPLICATE, BASE_URL, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT, LEECH_LIMIT, LOGGER, STORAGE_THRESHOLD +from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper +from bot.helper.ext_utils.bot_utils import is_magnet, getDownloadByGid, new_thread, bt_selection_buttons, get_readable_file_size +from bot.helper.mirror_utils.status_utils.aria_download_status import AriaDownloadStatus +from bot.helper.telegram_helper.message_utils import sendMarkup, sendStatusMessage, sendMessage, deleteMessage, update_all_messages, sendFile +from bot.helper.ext_utils.fs_utils import get_base_name, check_storage_threshold, clean_unwanted + + +@new_thread +def __onDownloadStarted(api, gid): + download = api.get_download(gid) + if download.is_metadata: + LOGGER.info(f'onDownloadStarted: {gid} METADATA') + sleep(1) + if dl := getDownloadByGid(gid): + listener = dl.listener() + if listener.select: + metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait." + meta = sendMessage(metamsg, listener.bot, listener.message) + while True: + if download.is_removed or download.followed_by_ids: + deleteMessage(listener.bot, meta) + break + download = download.live + return + else: + LOGGER.info(f'onDownloadStarted: {download.name} - Gid: {gid}') + try: + if any([STOP_DUPLICATE, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT, LEECH_LIMIT, STORAGE_THRESHOLD]): + sleep(1) + if dl := getDownloadByGid(gid): + listener = dl.listener() + if listener.select: + return + download = api.get_download(gid) + if not download.is_torrent: + sleep(3) + download = download.live + if STOP_DUPLICATE and not dl.listener().isLeech: + LOGGER.info('Checking File/Folder if already in Drive...') + sname = download.name + if listener.isZip: + sname = f"{sname}.zip" + elif listener.extract: + try: + sname = get_base_name(sname) + except: + sname = None + if sname is not None: + if TELEGRAPH_STYLE is True: + + smsg, button = GoogleDriveHelper().drive_list(sname, True) + if smsg: + listener.onDownloadError('Someone already mirrored it for you !\n\n') + api.remove([download], force=True, files=True) + return sendMarkup("Here you go:", listener.bot, listener.message, button) + + else: + + cap, f_name = GoogleDriveHelper().drive_list(sname, True) + if cap: + listener.onDownloadError('File/Folder already available in Drive.') + api.remove([download], force=True, files=True) + cap = f"Here are the search results:\n\n{cap}" + sendFile(listener.bot, listener.message, f_name, cap) + return + + if any([ZIP_UNZIP_LIMIT, LEECH_LIMIT, TORRENT_DIRECT_LIMIT, STORAGE_THRESHOLD]): + sleep(1) + limit = None + size = download.total_length + arch = any([listener.isZip, listener.isLeech, listener.extract]) + if STORAGE_THRESHOLD is not None: + acpt = check_storage_threshold(size, arch, True) + # True if files allocated, if allocation disabled remove True arg + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(size)}' + listener.onDownloadError(msg) + return api.remove([download], force=True, files=True) + if ZIP_UNZIP_LIMIT is not None and arch: + mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB' + limit = ZIP_UNZIP_LIMIT + if LEECH_LIMIT is not None and arch: + mssg = f'Leech limit is {LEECH_LIMIT}GB' + limit = LEECH_LIMIT + elif TORRENT_DIRECT_LIMIT is not None: + mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}GB' + limit = TORRENT_DIRECT_LIMIT + if limit is not None: + LOGGER.info('Checking File/Folder Size...') + if size > limit * 1024**3: + listener.onDownloadError(f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}') + return api.remove([download], force=True, files=True) + except Exception as e: + LOGGER.error(f"{e} onDownloadStart: {gid} stop duplicate and size check didn't pass") + +@new_thread +def __onDownloadComplete(api, gid): + try: + download = api.get_download(gid) + except: + return + if download.followed_by_ids: + new_gid = download.followed_by_ids[0] + LOGGER.info(f'Gid changed from {gid} to {new_gid}') + if dl := getDownloadByGid(new_gid): + listener = dl.listener() + if BASE_URL is not None and listener.select: + api.client.force_pause(new_gid) + SBUTTONS = bt_selection_buttons(new_gid) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + sendMarkup(msg, listener.bot, listener.message, SBUTTONS) + elif download.is_torrent: + sleep(2) + if dl := getDownloadByGid(gid): + if hasattr(dl, 'listener') and dl.seeding: + LOGGER.info(f"Cancelling Seed: {download.name} onDownloadComplete") + dl.listener().onUploadError(f"Seeding stopped with Ratio: {dl.ratio()} and Time: {dl.seeding_time()}") + api.remove([download], force=True, files=True) + else: + LOGGER.info(f"onDownloadComplete: {download.name} - Gid: {gid}") + if dl := getDownloadByGid(gid): + dl.listener().onDownloadComplete() + api.remove([download], force=True, files=True) + +@new_thread +def __onBtDownloadComplete(api, gid): + seed_start_time = time() + sleep(1) + download = api.get_download(gid) + LOGGER.info(f"onBtDownloadComplete: {download.name} - Gid: {gid}") + if dl := getDownloadByGid(gid): + listener = dl.listener() + if listener.select: + res = download.files + for file_o in res: + f_path = file_o.path + if not file_o.selected and ospath.exists(f_path): + try: + remove(f_path) + except: + pass + clean_unwanted(download.dir) + if listener.seed: + try: + api.set_options({'max-upload-limit': '0'}, [download]) + except Exception as e: + LOGGER.error(f'{e} You are not able to seed because you added global option seed-time=0 without adding specific seed_time for this torrent') + else: + try: + api.client.force_pause(gid) + except Exception as e: + LOGGER.error(f"{e} GID: {gid}" ) + listener.onDownloadComplete() + if listener.seed: + with download_dict_lock: + if listener.uid not in download_dict: + api.remove([download], force=True, files=True) + return + download_dict[listener.uid] = AriaDownloadStatus(gid, listener, True) + download_dict[listener.uid].start_time = seed_start_time + LOGGER.info(f"Seeding started: {download.name} - Gid: {gid}") + download = download.live + if download.is_complete: + if dl := getDownloadByGid(gid): + LOGGER.info(f"Cancelling Seed: {download.name}") + listener.onUploadError(f"Seeding stopped with Ratio: {dl.ratio()} and Time: {dl.seeding_time()}") + api.remove([download], force=True, files=True) + else: + update_all_messages() + else: + api.remove([download], force=True, files=True) + +@new_thread +def __onDownloadStopped(api, gid): + sleep(6) + if dl := getDownloadByGid(gid): + dl.listener().onDownloadError('Dead torrent!') + +@new_thread +def __onDownloadError(api, gid): + LOGGER.info(f"onDownloadError: {gid}") + error = "None" + try: + download = api.get_download(gid) + error = download.error_message + LOGGER.info(f"Download Error: {error}") + except: + pass + if dl := getDownloadByGid(gid): + dl.listener().onDownloadError(error) + +def start_listener(): + aria2.listen_to_notifications(threaded=True, + on_download_start=__onDownloadStarted, + on_download_error=__onDownloadError, + on_download_stop=__onDownloadStopped, + on_download_complete=__onDownloadComplete, + on_bt_download_complete=__onBtDownloadComplete, + timeout=60) + +def add_aria2c_download(link: str, path, listener, filename, auth, ratio, seed_time): + args = {'dir': path, 'max-upload-limit': '1K'} + if filename: + args['out'] = filename + if auth: + args['header'] = f"authorization: {auth}" + if ratio: + args['seed-ratio'] = ratio + if seed_time: + args['seed-time'] = seed_time + if is_magnet(link): + download = aria2.add_magnet(link, args) + else: + download = aria2.add_uris([link], args) + if download.error_message: + error = str(download.error_message).replace('<', ' ').replace('>', ' ') + LOGGER.info(f"Download Error: {error}") + return sendMessage(error, listener.bot, listener.message) + with download_dict_lock: + download_dict[listener.uid] = AriaDownloadStatus(download.gid, listener) + LOGGER.info(f"Aria2Download started: {download.gid}") + listener.onDownloadStart() + if not listener.select: + sendStatusMessage(listener.message, listener.bot) + +start_listener() \ No newline at end of file diff --git a/bot/helper/mirror_utils/download_utils/direct_link_generator.py b/bot/helper/mirror_utils/download_utils/direct_link_generator.py new file mode 100644 index 0000000..cc5138a --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/direct_link_generator.py @@ -0,0 +1,601 @@ +# Copyright (C) 2019 The Raphielscape Company LLC. +# +# Licensed under the Raphielscape Public License, Version 1.c (the "License"); +# you may not use this file except in compliance with the License. +# +""" Helper Module containing various sites direct links generators. This module is copied and modified as per need +from https://github.com/AvinashReddy3108/PaperplaneExtended . I hereby take no credit of the following code other +than the modifications. See https://github.com/AvinashReddy3108/PaperplaneExtended/commits/master/userbot/modules/direct_links.py +for original authorship. """ + +import math + +from requests import get as rget, head as rhead, post as rpost, Session as rsession +from re import findall as re_findall, sub as re_sub, match as re_match, search as re_search +import requests +import re +from time import sleep +from base64 import b64decode +from urllib.parse import urlparse, unquote, parse_qs +from json import loads as jsonloads +from lk21 import Bypass +from lxml import etree +from cfscrape import create_scraper +import cloudscraper +from bs4 import BeautifulSoup +from base64 import standard_b64encode +from selenium import webdriver +from selenium.webdriver.common.by import By + +from bot import LOGGER, UPTOBOX_TOKEN, CRYPT, UNIFIED_EMAIL, UNIFIED_PASS, HUBDRIVE_CRYPT, KATDRIVE_CRYPT, DRIVEFIRE_CRYPT +from bot.helper.telegram_helper.bot_commands import BotCommands +from bot.helper.ext_utils.bot_utils import * +from bot.helper.ext_utils.exceptions import DirectDownloadLinkException + +fmed_list = ['fembed.net', 'fembed.com', 'femax20.com', 'fcdn.stream', 'feurl.com', 'layarkacaxxi.icu', + 'naniplay.nanime.in', 'naniplay.nanime.biz', 'naniplay.com', 'mm9842.com'] + + +def direct_link_generator(link: str): + """ direct links generator """ + if 'youtube.com' in link or 'youtu.be' in link: + raise DirectDownloadLinkException(f"ERROR: Use /{BotCommands.WatchCommand} to mirror Youtube link\nUse /{BotCommands.ZipWatchCommand} to make zip of Youtube playlist") + elif 'zippyshare.com' in link: + return zippy_share(link) + elif 'yadi.sk' in link or 'disk.yandex.com' in link: + return yandex_disk(link) + elif 'mediafire.com' in link: + return mediafire(link) + elif 'uptobox.com' in link: + return uptobox(link) + elif 'osdn.net' in link: + return osdn(link) + elif 'github.com' in link: + return github(link) + elif 'hxfile.co' in link: + return hxfile(link) + elif 'anonfiles.com' in link: + return anonfiles(link) + elif 'letsupload.io' in link: + return letsupload(link) + elif '1drv.ms' in link: + return onedrive(link) + elif 'pixeldrain.com' in link: + return pixeldrain(link) + elif 'antfiles.com' in link: + return antfiles(link) + elif 'streamtape.com' in link: + return streamtape(link) + elif 'bayfiles.com' in link: + return anonfiles(link) + elif 'racaty.net' in link: + return racaty(link) + elif '1fichier.com' in link: + return fichier(link) + elif 'solidfiles.com' in link: + return solidfiles(link) + elif 'krakenfiles.com' in link: + return krakenfiles(link) + elif is_gdtot_link(link): + return gdtot(link) + elif is_unified_link(link): + return unified(link) + elif is_udrive_link(link): + return udrive(link) + elif any(x in link for x in fmed_list): + return fembed(link) + elif any(x in link for x in ['sbembed.com', 'watchsb.com', 'streamsb.net', 'sbplay.org']): + return sbembed(link) + else: + raise DirectDownloadLinkException(f'No Direct link function found for {link}') + +def zippy_share(url: str) -> str: + base_url = re_search('http.+.zippyshare.com', url).group() + response = rget(url) + pages = BeautifulSoup(response.text, "html.parser") + js_script = pages.find("div", style="margin-left: 24px; margin-top: 20px; text-align: center; width: 303px; height: 105px;") + if js_script is None: + js_script = pages.find("div", style="margin-left: -22px; margin-top: -5px; text-align: center;width: 303px;") + js_script = str(js_script) + + try: + var_a = re_findall(r"var.a.=.(\d+)", js_script)[0] + mtk = int(math.pow(int(var_a),3) + 3) + uri1 = re_findall(r"\.href.=.\"/(.*?)/\"", js_script)[0] + uri2 = re_findall(r"\+\"/(.*?)\"", js_script)[0] + except: + try: + a, b = re_findall(r"var.[ab].=.(\d+)", js_script) + mtk = eval(f"{math.floor(int(a)/3) + int(a) % int(b)}") + uri1 = re_findall(r"\.href.=.\"/(.*?)/\"", js_script)[0] + uri2 = re_findall(r"\)\+\"/(.*?)\"", js_script)[0] + except: + try: + mtk = eval(re_findall(r"\+\((.*?).\+", js_script)[0] + "+ 11") + uri1 = re_findall(r"\.href.=.\"/(.*?)/\"", js_script)[0] + uri2 = re_findall(r"\)\+\"/(.*?)\"", js_script)[0] + except: + try: + mtk = eval(re_findall(r"\+.\((.*?)\).\+", js_script)[0]) + uri1 = re_findall(r"\.href.=.\"/(.*?)/\"", js_script)[0] + uri2 = re_findall(r"\+.\"/(.*?)\"", js_script)[0] + except Exception as err: + LOGGER.error(err) + raise DirectDownloadLinkException("ERROR: Failed to Get Direct Link") + dl_url = f"{base_url}/{uri1}/{int(mtk)}/{uri2}" + return dl_url + +def yandex_disk(url: str) -> str: + """ Yandex.Disk direct link generator + Based on https://github.com/wldhx/yadisk-direct """ + try: + link = re_findall(r'\b(https?://(yadi.sk|disk.yandex.com|disk.yandex.ru|disk.yandex.com.tr|disk.yandex.com.ru)\S+)', url)[0][0] + except IndexError: + return "No Yandex.Disk links found\n" + api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}' + try: + return rget(api.format(link)).json()['href'] + except KeyError: + raise DirectDownloadLinkException("ERROR: File not found/Download limit reached\n") + +def uptobox(url: str) -> str: + """ Uptobox direct link generator + based on https://github.com/jovanzers/WinTenCermin and https://github.com/sinoobie/noobie-mirror """ + try: + link = re_findall(r'\bhttps?://.*uptobox\.com\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No Uptobox links found\n") + if UPTOBOX_TOKEN is None: + LOGGER.error('UPTOBOX_TOKEN not provided!') + dl_url = link + else: + try: + link = re_findall(r'\bhttp?://.*uptobox\.com/dl\S+', url)[0] + dl_url = link + except: + file_id = re_findall(r'\bhttps?://.*uptobox\.com/(\w+)', url)[0] + file_link = 'https://uptobox.com/api/link?token=%s&file_code=%s' % (UPTOBOX_TOKEN, file_id) + req = rget(file_link) + result = req.json() + if result['message'].lower() == 'success': + dl_url = result['data']['dlLink'] + elif result['message'].lower() == 'waiting needed': + waiting_time = result["data"]["waiting"] + 1 + waiting_token = result["data"]["waitingToken"] + sleep(waiting_time) + req2 = rget(f"{file_link}&waitingToken={waiting_token}") + result2 = req2.json() + dl_url = result2['data']['dlLink'] + elif result['message'].lower() == 'you need to wait before requesting a new download link': + cooldown = divmod(result['data']['waiting'], 60) + raise DirectDownloadLinkException(f"ERROR: Uptobox is being limited please wait {cooldown[0]} min {cooldown[1]} sec.") + else: + LOGGER.info(f"UPTOBOX_ERROR: {result}") + raise DirectDownloadLinkException(f"ERROR: {result['message']}") + return dl_url + +def mediafire(url: str) -> str: + """ MediaFire direct link generator """ + try: + link = re_findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No MediaFire links found\n") + page = BeautifulSoup(rget(link).content, 'lxml') + info = page.find('a', {'aria-label': 'Download file'}) + return info.get('href') + + +def osdn(url: str) -> str: + """ OSDN direct link generator """ + osdn_link = 'https://osdn.net' + try: + link = re_findall(r'\bhttps?://.*osdn\.net\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No OSDN links found\n") + page = BeautifulSoup( + rget(link, allow_redirects=True).content, 'lxml') + info = page.find('a', {'class': 'mirror_link'}) + link = unquote(osdn_link + info['href']) + mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr') + urls = [] + for data in mirrors[1:]: + mirror = data.find('input')['value'] + urls.append(re_sub(r'm=(.*)&f', f'm={mirror}&f', link)) + return urls[0] + +def github(url: str) -> str: + """ GitHub direct links generator """ + try: + re_findall(r'\bhttps?://.*github\.com.*releases\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No GitHub Releases links found\n") + download = rget(url, stream=True, allow_redirects=False) + try: + return download.headers["location"] + except KeyError: + raise DirectDownloadLinkException("ERROR: Can't extract the link\n") + +def hxfile(url: str) -> str: + """ Hxfile direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + return Bypass().bypass_filesIm(url) + +def anonfiles(url: str) -> str: + """ Anonfiles direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + return Bypass().bypass_anonfiles(url) + +def letsupload(url: str) -> str: + """ Letsupload direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + try: + link = re_findall(r'\bhttps?://.*letsupload\.io\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No Letsupload links found\n") + return Bypass().bypass_url(link) + +def fembed(link: str) -> str: + """ Fembed direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + dl_url= Bypass().bypass_fembed(link) + count = len(dl_url) + lst_link = [dl_url[i] for i in dl_url] + return lst_link[count-1] + +def sbembed(link: str) -> str: + """ Sbembed direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + dl_url= Bypass().bypass_sbembed(link) + count = len(dl_url) + lst_link = [dl_url[i] for i in dl_url] + return lst_link[count-1] + +def onedrive(link: str) -> str: + """ Onedrive direct link generator + Based on https://github.com/UsergeTeam/Userge """ + link_without_query = urlparse(link)._replace(query=None).geturl() + direct_link_encoded = str(standard_b64encode(bytes(link_without_query, "utf-8")), "utf-8") + direct_link1 = f"https://api.onedrive.com/v1.0/shares/u!{direct_link_encoded}/root/content" + resp = rhead(direct_link1) + if resp.status_code != 302: + raise DirectDownloadLinkException("ERROR: Unauthorized link, the link may be private") + return resp.next.url + +def pixeldrain(url: str) -> str: + """ Based on https://github.com/yash-dk/TorToolkit-Telegram """ + url = url.strip("/ ") + file_id = url.split("/")[-1] + if url.split("/")[-2] == "l": + info_link = f"https://pixeldrain.com/api/list/{file_id}" + dl_link = f"https://pixeldrain.com/api/list/{file_id}/zip" + else: + info_link = f"https://pixeldrain.com/api/file/{file_id}/info" + dl_link = f"https://pixeldrain.com/api/file/{file_id}" + resp = rget(info_link).json() + if resp["success"]: + return dl_link + else: + raise DirectDownloadLinkException(f"ERROR: Cant't download due {resp['message']}.") + +def antfiles(url: str) -> str: + """ Antfiles direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + return Bypass().bypass_antfiles(url) + +def streamtape(url: str) -> str: + """ Streamtape direct link generator + Based on https://github.com/zevtyardt/lk21 + """ + return Bypass().bypass_streamtape(url) + +def racaty(url: str) -> str: + """ Racaty direct link generator + based on https://github.com/SlamDevs/slam-mirrorbot""" + dl_url = '' + try: + re_findall(r'\bhttps?://.*racaty\.net\S+', url)[0] + except IndexError: + raise DirectDownloadLinkException("No Racaty links found\n") + scraper = create_scraper() + r = scraper.get(url) + soup = BeautifulSoup(r.text, "lxml") + op = soup.find("input", {"name": "op"})["value"] + ids = soup.find("input", {"name": "id"})["value"] + rpost = scraper.post(url, data = {"op": op, "id": ids}) + rsoup = BeautifulSoup(rpost.text, "lxml") + dl_url = rsoup.find("a", {"id": "uniqueExpirylink"})["href"].replace(" ", "%20") + return dl_url + +def fichier(link: str) -> str: + """ 1Fichier direct link generator + Based on https://github.com/Maujar + """ + regex = r"^([http:\/\/|https:\/\/]+)?.*1fichier\.com\/\?.+" + gan = re_match(regex, link) + if not gan: + raise DirectDownloadLinkException("ERROR: The link you entered is wrong!") + if "::" in link: + pswd = link.split("::")[-1] + url = link.split("::")[-2] + else: + pswd = None + url = link + try: + if pswd is None: + req = rpost(url) + else: + pw = {"pass": pswd} + req = rpost(url, data=pw) + except: + raise DirectDownloadLinkException("ERROR: Unable to reach 1fichier server!") + if req.status_code == 404: + raise DirectDownloadLinkException("ERROR: File not found/The link you entered is wrong!") + soup = BeautifulSoup(req.content, 'lxml') + if soup.find("a", {"class": "ok btn-general btn-orange"}) is not None: + dl_url = soup.find("a", {"class": "ok btn-general btn-orange"})["href"] + if dl_url is None: + raise DirectDownloadLinkException("ERROR: Unable to generate Direct Link 1fichier!") + else: + return dl_url + elif len(soup.find_all("div", {"class": "ct_warn"})) == 3: + str_2 = soup.find_all("div", {"class": "ct_warn"})[-1] + if "you must wait" in str(str_2).lower(): + numbers = [int(word) for word in str(str_2).split() if word.isdigit()] + if not numbers: + raise DirectDownloadLinkException("ERROR: 1fichier is on a limit. Please wait a few minutes/hour.") + else: + raise DirectDownloadLinkException(f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute.") + elif "protect access" in str(str_2).lower(): + raise DirectDownloadLinkException(f"ERROR: This link requires a password!\n\nThis link requires a password!\n- Insert sign :: after the link and write the password after the sign.\n\nExample:\n/{BotCommands.MirrorCommand} https://1fichier.com/?smmtd8twfpm66awbqz04::love you\n\n* No spaces between the signs ::\n* For the password, you can use a space!") + else: + print(str_2) + raise DirectDownloadLinkException("ERROR: Failed to generate Direct Link from 1fichier!") + elif len(soup.find_all("div", {"class": "ct_warn"})) == 4: + str_1 = soup.find_all("div", {"class": "ct_warn"})[-2] + str_3 = soup.find_all("div", {"class": "ct_warn"})[-1] + if "you must wait" in str(str_1).lower(): + numbers = [int(word) for word in str(str_1).split() if word.isdigit()] + if not numbers: + raise DirectDownloadLinkException("ERROR: 1fichier is on a limit. Please wait a few minutes/hour.") + else: + raise DirectDownloadLinkException(f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute.") + elif "bad password" in str(str_3).lower(): + raise DirectDownloadLinkException("ERROR: The password you entered is wrong!") + else: + raise DirectDownloadLinkException("ERROR: Error trying to generate Direct Link from 1fichier!") + else: + raise DirectDownloadLinkException("ERROR: Error trying to generate Direct Link from 1fichier!") + +def solidfiles(url: str) -> str: + """ Solidfiles direct link generator + Based on https://github.com/Xonshiz/SolidFiles-Downloader + By https://github.com/Jusidama18 """ + headers = { + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36' + } + pageSource = rget(url, headers = headers).text + mainOptions = str(re_search(r'viewerOptions\'\,\ (.*?)\)\;', pageSource).group(1)) + return jsonloads(mainOptions)["downloadUrl"] + +def krakenfiles(page_link: str) -> str: + """ krakenfiles direct link generator + Based on https://github.com/tha23rd/py-kraken + By https://github.com/junedkh """ + page_resp = rsession().get(page_link) + soup = BeautifulSoup(page_resp.text, "lxml") + try: + token = soup.find("input", id="dl-token")["value"] + except: + raise DirectDownloadLinkException(f"Page link is wrong: {page_link}") + + hashes = [ + item["data-file-hash"] + for item in soup.find_all("div", attrs={"data-file-hash": True}) + ] + if not hashes: + raise DirectDownloadLinkException(f"ERROR: Hash not found for : {page_link}") + + + dl_hash = hashes[0] + + payload = f'------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name="token"\r\n\r\n{token}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--' + headers = { + "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", + "cache-control": "no-cache", + "hash": dl_hash, + } + + dl_link_resp = rsession().post( + f"https://krakenfiles.com/download/{hash}", data=payload, headers=headers) + + dl_link_json = dl_link_resp.json() + + if "url" in dl_link_json: + return dl_link_json["url"] + else: + raise DirectDownloadLinkException(f"ERROR: Failed to acquire download URL from kraken for : {page_link}") + + +def gdtot(url: str) -> str: + """ Gdtot google drive link generator + By https://github.com/xcscxr """ + + if CRYPT is None: + raise DirectDownloadLinkException("ERROR: CRYPT cookie not provided") + + match = re_findall(r'https?://(.+)\.gdtot\.(.+)\/\S+\/\S+', url)[0] + + with rsession() as client: + client.cookies.update({'crypt': CRYPT}) + client.get(url) + res = client.get(f"https://{match[0]}.gdtot.{match[1]}/dld?id={url.split('/')[-1]}") + matches = re_findall('gd=(.*?)&', res.text) + try: + decoded_id = b64decode(str(matches[0])).decode('utf-8') + except: + raise DirectDownloadLinkException("ERROR: Try in your broswer, mostly file not found or user limit exceeded!") + return f'https://drive.google.com/open?id={decoded_id}' + +account = { + 'email': UNIFIED_EMAIL, + 'passwd': UNIFIED_PASS +} +def account_login(client, url, email, password): + data = { + 'email': email, + 'password': password + } + client.post(f'https://{urlparse(url).netloc}/login', data=data) +def gen_payload(data, boundary=f'{"-"*6}_'): + data_string = '' + for item in data: + data_string += f'{boundary}\r\n' + data_string += f'Content-Disposition: form-data; name="{item}"\r\n\r\n{data[item]}\r\n' + data_string += f'{boundary}--\r\n' + return data_string + +def parse_infou(data): + info = re_findall('>(.*?)<\/li>', data) + info_parsed = {} + for item in info: + kv = [s.strip() for s in item.split(':', maxsplit = 1)] + info_parsed[kv[0].lower()] = kv[1] + return info_parsed + +def unified(url: str) -> str: + if (UNIFIED_EMAIL or UNIFIED_PASS) is None: + raise DirectDownloadLinkException("UNIFIED_EMAIL and UNIFIED_PASS env vars not provided") + client = cloudscraper.create_scraper(delay=10, browser='chrome') + client.headers.update({ + "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36" + }) + account_login(client, url, account['email'], account['passwd']) + res = client.get(url) + key = re_findall('"key",\s+"(.*?)"', res.text)[0] + ddl_btn = etree.HTML(res.content).xpath("//button[@id='drc']") + info_parsed = parse_infou(res.text) + info_parsed['error'] = False + info_parsed['link_type'] = 'login' # direct/login + headers = { + "Content-Type": f"multipart/form-data; boundary={'-'*4}_", + } + data = { + 'type': 1, + 'key': key, + 'action': 'original' + } + if len(ddl_btn): + info_parsed['link_type'] = 'direct' + data['action'] = 'direct' + while data['type'] <= 3: + try: + response = client.post(url, data=gen_payload(data), headers=headers).json() + break + except: data['type'] += 1 + if 'url' in response: + info_parsed['gdrive_link'] = response['url'] + elif 'error' in response and response['error']: + info_parsed['error'] = True + info_parsed['error_message'] = response['message'] + else: + info_parsed['error'] = True + info_parsed['error_message'] = 'Something went wrong :(' + + if info_parsed['error']: + raise DirectDownloadLinkException(f"ERROR! {info_parsed['error_message']}") + + if urlparse(url).netloc == 'appdrive.info': + flink = info_parsed['gdrive_link'] + return flink + + elif urlparse(url).netloc == 'driveapp.in': + res = client.get(info_parsed['gdrive_link']) + drive_link = etree.HTML(res.content).xpath("//a[contains(@class,'btn')]/@href")[0] + flink = drive_link + return flink + + else: + res = client.get(info_parsed['gdrive_link']) + drive_link = etree.HTML(res.content).xpath("//a[contains(@class,'btn btn-primary')]/@href")[0] + flink = drive_link + info_parsed['src_url'] = url + return flink + +def parse_info(res, url): + info_parsed = {} + if 'drivebuzz' in url: + info_chunks = re.findall('(.*?)<\/td>', res.text) + else: + info_chunks = re_findall('>(.*?)<\/td>', res.text) + for i in range(0, len(info_chunks), 2): + info_parsed[info_chunks[i]] = info_chunks[i+1] + return info_parsed + +def udrive(url: str) -> str: + if 'katdrive' or 'hubdrive' in url: + client = rsession() + else: + client = cloudscraper.create_scraper(delay=10, browser='chrome') + + if 'hubdrive' in url: + if "hubdrive.in" in url: + url = url.replace(".in",".pro") + client.cookies.update({'crypt': HUBDRIVE_CRYPT}) + if 'drivehub' in url: + client.cookies.update({'crypt': KATDRIVE_CRYPT}) + if 'katdrive' in url: + client.cookies.update({'crypt': KATDRIVE_CRYPT}) + if 'kolop' in url: + client.cookies.update({'crypt': KATDRIVE_CRYPT}) + if 'drivefire' in url: + client.cookies.update({'crypt': DRIVEFIRE_CRYPT}) + if 'drivebuzz' in url: + client.cookies.update({'crypt': DRIVEFIRE_CRYPT}) + + res = client.get(url) + info_parsed = parse_info(res, url) + + + info_parsed['error'] = False + + up = urlparse(url) + req_url = f"{up.scheme}://{up.netloc}/ajax.php?ajax=download" + + file_id = url.split('/')[-1] + + data = { 'id': file_id } + + headers = { + 'x-requested-with': 'XMLHttpRequest' + } + + try: + res = client.post(req_url, headers=headers, data=data).json()['file'] + except: return {'error': True, 'src_url': url} + + if 'drivefire' in url: + decoded_id = res.rsplit('/', 1)[-1] + flink = f"https://drive.google.com/file/d/{decoded_id}" + return flink + elif 'drivehub' in url: + gd_id = res.rsplit("=", 1)[-1] + flink = f"https://drive.google.com/open?id={gd_id}" + return flink + elif 'drivebuzz' in url: + gd_id = res.rsplit("=", 1)[-1] + flink = f"https://drive.google.com/open?id={gd_id}" + return flink + else: + gd_id = re_findall('gd=(.*)', res, re.DOTALL)[0] + + info_parsed['gdrive_url'] = f"https://drive.google.com/open?id={gd_id}" + info_parsed['src_url'] = url + flink = info_parsed['gdrive_url'] + + return flink diff --git a/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md b/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md new file mode 100644 index 0000000..c37c0d9 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md @@ -0,0 +1,82 @@ + RAPHIELSCAPE PUBLIC LICENSE + Version 1.c, June 2019 + + Copyright (C) 2019 Raphielscape LLC. + Copyright (C) 2019 Devscapes Open Source Holding GmbH. + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + RAPHIELSCAPE PUBLIC LICENSE + A-1. DEFINITIONS + +0. “This License” refers to version 1.c of the Raphielscape Public License. + +1. “Copyright” also means copyright-like laws that apply to other kinds of works. + +2. “The Work" refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. + “Licensees” and “recipients” may be individuals or organizations. + +3. 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. + +4. Source Form. The “source form” 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. + + 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. + + 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. + +5. "The author" refers to "author" of the code, which is the one that made the particular code which exists inside of + the Corresponding Source. + +6. "Owner" refers to any parties which is made the early form of the Corresponding Source. + + A-2. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. You must give any other recipients of the Work or Derivative Works a copy of this License; and + +1. You must cause any modified files to carry prominent notices stating that You changed the files; and + +2. You must retain, in the Source form of any Derivative Works that You distribute, + this license, all copyright, patent, trademark, authorships and attribution notices + from the Source form of the Work; and + +3. Respecting the author and owner of works that are distributed in any way. + + You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, +or distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + + B. DISCLAIMER OF WARRANTY + + THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + C. REVISED VERSION OF THIS LICENSE + + The Devscapes Open Source Holding GmbH. may publish revised and/or new versions of the +Raphielscape 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 Raphielscape 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 Devscapes Open Source Holding GmbH. If the Program does not specify a +version number of the Raphielscape Public License, you may choose any version ever published +by the Devscapes Open Source Holding GmbH. + + END OF LICENSE \ No newline at end of file diff --git a/bot/helper/mirror_utils/download_utils/gd_downloader.py b/bot/helper/mirror_utils/download_utils/gd_downloader.py new file mode 100644 index 0000000..1215148 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/gd_downloader.py @@ -0,0 +1,72 @@ +from random import SystemRandom +from string import ascii_letters, digits +from bot import TELEGRAPH_STYLE, download_dict, download_dict_lock, ZIP_UNZIP_LIMIT, LOGGER, STOP_DUPLICATE, STORAGE_THRESHOLD, TORRENT_DIRECT_LIMIT, LEECH_LIMIT +from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper +from bot.helper.mirror_utils.status_utils.gd_download_status import GdDownloadStatus +from bot.helper.telegram_helper.message_utils import sendMessage, sendStatusMessage, sendMarkup, sendFile +from bot.helper.ext_utils.bot_utils import get_readable_file_size +from bot.helper.ext_utils.fs_utils import get_base_name, check_storage_threshold + + +def add_gd_download(link, path, listener, is_gdtot, is_unified, is_udrive, newname): + res, size, name, files = GoogleDriveHelper().helper(link) + if res != "": + return sendMessage(res, listener.bot, listener.message) + if newname: + name = newname + if STOP_DUPLICATE and not listener.isLeech: + LOGGER.info('Checking File/Folder if already in Drive...') + if listener.isZip: + gname = f"{name}.zip" + elif listener.extract: + try: + gname = get_base_name(name) + except: + gname = None + if gname is not None: + if TELEGRAPH_STYLE is True: + gmsg, button = GoogleDriveHelper().drive_list(gname, True) + if gmsg: + msg = "File/Folder is already available in Drive.\nHere are the search results:" + return sendMarkup(msg, listener.bot, listener.message, button) + + else: + cap, f_name = GoogleDriveHelper().drive_list(gname, True) + if cap: + cap = f"File/Folder is already available in Drive. Here are the search results:\n\n{cap}" + sendFile(listener.bot, listener.message, f_name, cap) + return + if any([ZIP_UNZIP_LIMIT, STORAGE_THRESHOLD, TORRENT_DIRECT_LIMIT, LEECH_LIMIT]): + arch = any([listener.extract, listener.isZip]) + limit = None + if STORAGE_THRESHOLD is not None: + acpt = check_storage_threshold(size, arch) + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(size)}' + return sendMessage(msg, listener.bot, listener.message) + if ZIP_UNZIP_LIMIT is not None and arch: + mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB' + limit = ZIP_UNZIP_LIMIT + if LEECH_LIMIT is not None and listener.isLeech: + mssg = f'Leech limit is {LEECH_LIMIT}GB' + limit = LEECH_LIMIT + elif TORRENT_DIRECT_LIMIT is not None: + mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}GB' + limit = TORRENT_DIRECT_LIMIT + if limit is not None: + LOGGER.info('Checking File/Folder Size...') + if size > limit * 1024**3: + msg = f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}.' + return sendMessage(msg, listener.bot, listener.message) + LOGGER.info(f"Download Name: {name}") + drive = GoogleDriveHelper(name, path, size, listener) + gid = ''.join(SystemRandom().choices(ascii_letters + digits, k=12)) + download_status = GdDownloadStatus(drive, size, listener, gid) + with download_dict_lock: + download_dict[listener.uid] = download_status + listener.onDownloadStart() + sendStatusMessage(listener.message, listener.bot) + drive.download(link) + if (is_gdtot or is_unified or is_udrive): + drive.deletefile(link) \ No newline at end of file diff --git a/bot/helper/mirror_utils/download_utils/mega_downloader.py b/bot/helper/mirror_utils/download_utils/mega_downloader.py new file mode 100644 index 0000000..0dd9b17 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/mega_downloader.py @@ -0,0 +1,290 @@ +from random import SystemRandom +from string import ascii_letters, digits +from os import makedirs +from threading import Event +from mega import (MegaApi, MegaListener, MegaRequest, MegaTransfer, MegaError) + + +from bot import LOGGER, MEGA_API_KEY, TELEGRAPH_STYLE, download_dict, download_dict_lock, MEGA_LIMIT, STOP_DUPLICATE, ZIP_UNZIP_LIMIT, STORAGE_THRESHOLD, LEECH_LIMIT, MEGA_EMAIL_ID, MEGA_PASSWORD +from bot.helper.telegram_helper.message_utils import sendMessage, sendMarkup, sendStatusMessage, sendStatusMessage, sendFile +from bot.helper.ext_utils.bot_utils import get_readable_file_size, setInterval, get_mega_link_type +from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper +from bot.helper.ext_utils.fs_utils import get_base_name, check_storage_threshold +from bot.helper.mirror_utils.status_utils.mega_download_status import MegaDownloadStatus + + +class MegaAppListener(MegaListener): + _NO_EVENT_ON = (MegaRequest.TYPE_LOGIN,MegaRequest.TYPE_FETCH_NODES) + NO_ERROR = "no error" + + def __init__(self, continue_event: Event, listener): + self.continue_event = continue_event + self.node = None + self.public_node = None + self.listener = listener + self.__bytes_transferred = 0 + self.is_cancelled = False + self.__speed = 0 + self.__name = '' + self.__size = 0 + self.error = None + self.gid = "" + super(MegaAppListener, self).__init__() + + @property + def speed(self): + """Returns speed of the download in bytes/second""" + return self.__speed + + @property + def name(self): + """Returns name of the download""" + return self.__name + + def setValues(self, name, size, gid): + self.__name = name + self.__size = size + self.gid = gid + + @property + def size(self): + """Size of download in bytes""" + return self.__size + + @property + def downloaded_bytes(self): + return self.__bytes_transferred + + def onRequestFinish(self, api, request, error): + if str(error).lower() != "no error": + self.error = error.copy() + LOGGER.error(self.error) + self.continue_event.set() + return + request_type = request.getType() + if request_type == MegaRequest.TYPE_LOGIN: + api.fetchNodes() + elif request_type == MegaRequest.TYPE_GET_PUBLIC_NODE: + self.public_node = request.getPublicMegaNode() + elif request_type == MegaRequest.TYPE_FETCH_NODES: + LOGGER.info("Fetching Root Node.") + self.node = api.getRootNode() + LOGGER.info(f"Node Name: {self.node.getName()}") + if request_type not in self._NO_EVENT_ON or self.node and "cloud drive" not in self.node.getName().lower(): + self.continue_event.set() + + def onRequestTemporaryError(self, api, request, error: MegaError): + LOGGER.error(f'Mega Request error in {error}') + if not self.is_cancelled: + self.is_cancelled = True + self.listener.onDownloadError(f"RequestTempError: {error.toString()}") + self.error = error.toString() + self.continue_event.set() + + def onTransferUpdate(self, api: MegaApi, transfer: MegaTransfer): + if self.is_cancelled: + api.cancelTransfer(transfer, None) + self.continue_event.set() + return + self.__speed = transfer.getSpeed() + self.__bytes_transferred = transfer.getTransferredBytes() + + def onTransferFinish(self, api: MegaApi, transfer: MegaTransfer, error): + try: + if self.is_cancelled: + self.continue_event.set() + elif transfer.isFinished() and (transfer.isFolderTransfer() or transfer.getFileName() == self.name): + self.listener.onDownloadComplete() + self.continue_event.set() + except Exception as e: + LOGGER.error(e) + + def onTransferTemporaryError(self, api, transfer, error): + filen = transfer.getFileName() + state = transfer.getState() + errStr = error.toString() + LOGGER.error(f'Mega download error in file {transfer} {filen}: {error}') + if state in [1, 4]: + # Sometimes MEGA (offical client) can't stream a node either and raises a temp failed error. + # Don't break the transfer queue if transfer's in queued (1) or retrying (4) state [causes seg fault] + return + + self.error = errStr + if not self.is_cancelled: + self.is_cancelled = True + self.listener.onDownloadError(f"TransferTempError: {errStr} ({filen})") + self.continue_event.set() + + def cancel_download(self): + self.is_cancelled = True + self.listener.onDownloadError("Download Canceled by user") + + +class AsyncExecutor: + + def __init__(self): + self.continue_event = Event() + + def do(self, function, args): + self.continue_event.clear() + function(*args) + self.continue_event.wait() + + +def add_mega_download(mega_link: str, path: str, listener, name: str): + executor = AsyncExecutor() + api = MegaApi(MEGA_API_KEY, None, None, 'mirror-leech-telegram-bot') + folder_api = None + mega_listener = MegaAppListener(executor.continue_event, listener) + api.addListener(mega_listener) + if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None: + executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD)) + if get_mega_link_type(mega_link) == "file": + executor.do(api.getPublicNode, (mega_link,)) + node = mega_listener.public_node + else: + folder_api = MegaApi(MEGA_API_KEY, None, None, 'mltb') + folder_api.addListener(mega_listener) + executor.do(folder_api.loginToFolder, (mega_link,)) + node = folder_api.authorizeNode(mega_listener.node) + if mega_listener.error is not None: + sendMessage(str(mega_listener.error), listener.bot, listener.message) + api.removeListener(mega_listener) + if folder_api is not None: + folder_api.removeListener(mega_listener) + return + mname = name or node.getName() + if STOP_DUPLICATE and not listener.isLeech: + LOGGER.info('Checking File/Folder if already in Drive') + if listener.isZip: + mname = f"{mname}.zip" + elif listener.extract: + try: + mname = get_base_name(mname) + except: + mname = None + if mname is not None: + + if TELEGRAPH_STYLE is True: + smsg, button = GoogleDriveHelper().drive_list(mname, True) + if smsg: + msg1 = "File/Folder is already available in Drive.\nHere are the search results:" + return sendMarkup(msg1, listener.bot, listener.message, button) + else: + cap, f_name = GoogleDriveHelper().drive_list(mname, True) + if cap: + cap = f"File/Folder is already available in Drive. Here are the search results:\n\n{cap}" + sendFile(listener.bot, listener.message, f_name, cap) + + + # cap, f_name = GoogleDriveHelper().drive_list(mname, True) + # if cap: + # cap = f"File/Folder is already available in Drive. Here are the search results:\n\n{cap}" + # sendFile(listener.bot, listener.message, f_name, cap) + api.removeListener(mega_listener) + if folder_api is not None: + folder_api.removeListener(mega_listener) + return + + if any([STORAGE_THRESHOLD, ZIP_UNZIP_LIMIT, MEGA_LIMIT, LEECH_LIMIT]): + size = api.getSize(node) + arch = any([listener.isZip, listener.isLeech, listener.extract]) + if STORAGE_THRESHOLD is not None: + acpt = check_storage_threshold(size, arch) + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(size)}' + return sendMessage(msg, listener.bot, listener.message) + limit = None + if ZIP_UNZIP_LIMIT is not None and arch: + msg3 = f'Failed, Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.' + limit = ZIP_UNZIP_LIMIT + if LEECH_LIMIT is not None and arch: + msg3 = f'Failed, Leech limit is {LEECH_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.' + limit = LEECH_LIMIT + if MEGA_LIMIT is not None: + msg3 = f'Failed, Mega limit is {MEGA_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.' + limit = MEGA_LIMIT + if limit is not None: + LOGGER.info('Checking File/Folder Size...') + if size > limit * 1024**3: + return sendMessage(msg3, listener.bot, listener.message) + + with download_dict_lock: + download_dict[listener.uid] = MegaDownloadStatus(mega_listener, listener) + listener.onDownloadStart() + makedirs(path) + gid = ''.join(SystemRandom().choices(ascii_letters + digits, k=8)) + mname = name or node.getName() + mega_listener.setValues(mname, api.getSize(node), gid) + sendStatusMessage(listener.message, listener.bot) + executor.do(api.startDownload, (node, path, name, None, False, None)) + api.removeListener(mega_listener) + if folder_api is not None: + folder_api.removeListener(mega_listener) + + + + + + # def add_download(self, link, path): + # Path(path).mkdir(parents=True, exist_ok=True) + # try: + # dl = self.__mega_client.addDl(link, path) + # except Exception as err: + # LOGGER.error(err) + # return sendMessage(str(err), self.__listener.bot, self.__listener.message) + # gid = dl['gid'] + # info = self.__mega_client.getDownloadInfo(gid) + # file_name = info['name'] + # file_size = info['total_length'] + # if STOP_DUPLICATE and not self.__listener.isLeech: + # LOGGER.info('Checking File/Folder if already in Drive') + # mname = file_name + # if self.__listener.isZip: + # mname = f"{mname}.zip" + # elif self.__listener.extract: + # try: + # mname = get_base_name(mname) + # except: + # mname = None + # if mname is not None: + # if TELEGRAPH_STYLE is True: + # smsg, button = GoogleDriveHelper().drive_list(mname, True) + # if smsg: + # msg1 = "File/Folder is already available in Drive.\nHere are the search results:" + # return sendMarkup(msg1, self.__listener.bot, self.__listener.message, button) + # else: + # cap, f_name = GoogleDriveHelper().drive_list(mname, True) + # if cap: + # cap = f"File/Folder is already available in Drive. Here are the search results:\n\n{cap}" + # sendFile(self.__listener.bot, self.__listener.message, f_name, cap) + # return + # if any([STORAGE_THRESHOLD, ZIP_UNZIP_LIMIT, MEGA_LIMIT, LEECH_LIMIT]): + # arch = any([self.__listener.isZip, self.__listener.extract]) + # if STORAGE_THRESHOLD is not None: + # acpt = check_storage_threshold(file_size, arch) + # if not acpt: + # msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + # msg += f'\nYour File/Folder size is {get_readable_file_size(file_size)}' + # return sendMessage(msg, self.__listener.bot, self.__listener.message) + # limit = None + # if ZIP_UNZIP_LIMIT is not None and arch: + # msg3 = f'Failed, Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(file_size)}.' + # limit = ZIP_UNZIP_LIMIT + # if LEECH_LIMIT is not None and self.__listener.isLeech: + # msg3 = f'Failed, Leech limit is {LEECH_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(file_size)}.' + # limit = LEECH_LIMIT + # elif MEGA_LIMIT is not None: + # msg3 = f'Failed, Mega limit is {MEGA_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(file_size)}.' + # limit = MEGA_LIMIT + # if limit is not None: + # LOGGER.info('Checking File/Folder Size...') + # if file_size > limit * 1024**3: + # return sendMessage(msg3, self.__listener.bot, self.__listener.message) + # self.__onDownloadStart(file_name, file_size, gid) + # LOGGER.info(f'Mega download started with gid: {gid}') + + # def cancel_download(self): + # LOGGER.info(f'Cancelling download on user request: {self.gid}') + # self.__mega_client.cancelDl(self.gid) diff --git a/bot/helper/mirror_utils/download_utils/qbit_downloader.py b/bot/helper/mirror_utils/download_utils/qbit_downloader.py new file mode 100644 index 0000000..01da154 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/qbit_downloader.py @@ -0,0 +1,212 @@ +from os import path as ospath, listdir +from time import sleep, time +from re import search as re_search + +from bot import TELEGRAPH_STYLE, download_dict, download_dict_lock, BASE_URL, get_client, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT, STOP_DUPLICATE, TORRENT_TIMEOUT, LOGGER, STORAGE_THRESHOLD, LEECH_LIMIT +from bot.helper.mirror_utils.status_utils.qbit_download_status import QbDownloadStatus +from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper +from bot.helper.telegram_helper.message_utils import sendMessage, sendMarkup, deleteMessage, sendStatusMessage, update_all_messages, sendFile +from bot.helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time, setInterval, bt_selection_buttons +from bot.helper.ext_utils.fs_utils import clean_unwanted, get_base_name, check_storage_threshold +from bot.helper.telegram_helper import button_build + + +class QbDownloader: + POLLING_INTERVAL = 3 + + def __init__(self, listener): + self.is_seeding = False + self.ext_hash = '' + self.client = get_client() + self.__listener = listener + self.__path = '' + self.__name = '' + self.__stalled_time = time() + self.__uploaded = False + self.__sizeChecked = False + self.__dupChecked = False + self.__rechecked = False + self.__stopDup_check = False + self.__periodic = None + + def add_qb_torrent(self, link, path, ratio, seed_time): + self.__path = path + try: + op = self.client.torrents_add(link, save_path=path, tags=self.__listener.uid, + ratio_limit=ratio, seeding_time_limit=seed_time, + headers={'user-agent': 'Wget/1.12'}) + sleep(0.3) + if op.lower() == "ok.": + tor_info = self.client.torrents_info(tag=self.__listener.uid) + if len(tor_info) == 0: + while True: + tor_info = self.client.torrents_info(tag=self.__listener.uid) + if len(tor_info) > 0: + break + elif time() - self.__stalled_time >= 12: + self.client.torrents_delete_tags(tags=self.__listener.uid) + msg = "This Torrent already added or not a torrent. If something wrong please report." + sendMessage(msg, self.__listener.bot, self.__listener.message) + self.client.auth_log_out() + return + else: + sendMessage("This is an unsupported/invalid link.", self.__listener.bot, self.__listener.message) + self.client.auth_log_out() + return + tor_info = tor_info[0] + self.__name = tor_info.name + self.ext_hash = tor_info.hash + with download_dict_lock: + download_dict[self.__listener.uid] = QbDownloadStatus(self.__listener, self) + self.__listener.onDownloadStart() + LOGGER.info(f"QbitDownload started: {self.__name} - Hash: {self.ext_hash}") + self.__periodic = setInterval(self.POLLING_INTERVAL, self.__qb_listener) + if BASE_URL is not None and self.__listener.select: + if link.startswith('magnet:'): + metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait." + meta = sendMessage(metamsg, self.__listener.bot, self.__listener.message) + while True: + tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) + if len(tor_info) == 0: + deleteMessage(self.__listener.bot, meta) + return + try: + tor_info = tor_info[0] + if tor_info.state not in ["metaDL", "checkingResumeData", "pausedDL"]: + deleteMessage(self.__listener.bot, meta) + break + except: + return deleteMessage(self.__listener.bot, meta) + self.client.torrents_pause(torrent_hashes=self.ext_hash) + SBUTTONS = bt_selection_buttons(self.ext_hash) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + sendMarkup(msg, self.__listener.bot, self.__listener.message, SBUTTONS) + else: + sendStatusMessage(self.__listener.message, self.__listener.bot) + except Exception as e: + sendMessage(str(e), self.__listener.bot, self.__listener.message) + self.client.auth_log_out() + + def __qb_listener(self): + try: + tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) + if len(tor_info) == 0: + return + tor_info = tor_info[0] + if tor_info.state == "metaDL": + self.__stalled_time = time() + if TORRENT_TIMEOUT is not None and time() - tor_info.added_on >= TORRENT_TIMEOUT: + self.__onDownloadError("Dead Torrent!") + elif tor_info.state == "downloading": + self.__stalled_time = time() + if not self.__stopDup_check and not self.__listener.select and STOP_DUPLICATE and not self.__listener.isLeech: + LOGGER.info('Checking File/Folder if already in Drive') + qbname = tor_info.content_path.rsplit('/', 1)[-1].rsplit('.!qB', 1)[0] + if self.__listener.isZip: + qbname = f"{qbname}.zip" + elif self.__listener.extract: + try: + qbname = get_base_name(qbname) + except: + qbname = None + if qbname is not None: + if TELEGRAPH_STYLE is True: + qbmsg, button = GoogleDriveHelper().drive_list(qbname, True) + if qbmsg: + self.__onDownloadError("File/Folder is already available in Drive.") + sendMarkup("Here are the search results:", self.__listener.bot, self.__listener.message, button) + else: + cap, f_name = GoogleDriveHelper().drive_list(qbname, True) + if cap: + self.__onDownloadError("File/Folder is already available in Drive.") + cap = f"Here are the search results:\n\n{cap}" + sendFile(self.__listener.bot, self.__listener.message, f_name, cap) + self.__stopDup_check = True + if not self.__sizeChecked: + size = tor_info.size + arch = any([self.__listener.isZip, self.__listener.extract]) + if STORAGE_THRESHOLD is not None: + acpt = check_storage_threshold(size, arch) + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(size)}' + self.__onDownloadError(msg) + return + limit = None + if ZIP_UNZIP_LIMIT is not None and arch: + mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB' + limit = ZIP_UNZIP_LIMIT + if LEECH_LIMIT is not None and self.__listener.isLeech: + mssg = f'Leech limit is {LEECH_LIMIT}GB' + limit = LEECH_LIMIT + elif TORRENT_DIRECT_LIMIT is not None: + mssg = f'Torrent limit is {TORRENT_DIRECT_LIMIT}GB' + limit = TORRENT_DIRECT_LIMIT + if limit is not None: + LOGGER.info('Checking File/Folder Size...') + if size > limit * 1024**3: + fmsg = f"{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}" + self.__onDownloadError(fmsg) + self.__sizeChecked = True + elif tor_info.state == "stalledDL": + if not self.__rechecked and 0.99989999999999999 < tor_info.progress < 1: + msg = f"Force recheck - Name: {self.__name} Hash: " + msg += f"{self.ext_hash} Downloaded Bytes: {tor_info.downloaded} " + msg += f"Size: {tor_info.size} Total Size: {tor_info.total_size}" + LOGGER.info(msg) + self.client.torrents_recheck(torrent_hashes=self.ext_hash) + self.__rechecked = True + elif TORRENT_TIMEOUT is not None and time() - self.__stalled_time >= TORRENT_TIMEOUT: + self.__onDownloadError("Dead Torrent!") + elif tor_info.state == "missingFiles": + self.client.torrents_recheck(torrent_hashes=self.ext_hash) + elif tor_info.state == "error": + self.__onDownloadError("No enough space for this torrent on device") + elif (tor_info.state.lower().endswith("up") or tor_info.state == "uploading") and not self.__uploaded: + self.__uploaded = True + if not self.__listener.seed: + self.client.torrents_pause(torrent_hashes=self.ext_hash) + if self.__listener.select: + clean_unwanted(self.__path) + self.__listener.onDownloadComplete() + if self.__listener.seed: + with download_dict_lock: + if self.__listener.uid not in list(download_dict.keys()): + self.__remove_torrent() + return + download_dict[self.__listener.uid] = QbDownloadStatus(self.__listener, self) + self.is_seeding = True + update_all_messages() + LOGGER.info(f"Seeding started: {self.__name} - Hash: {self.ext_hash}") + else: + self.__remove_torrent() + elif tor_info.state == 'pausedUP' and self.__listener.seed: + self.__listener.onUploadError(f"Seeding stopped with Ratio: {round(tor_info.ratio, 3)} and Time: {get_readable_time(tor_info.seeding_time)}") + self.__remove_torrent() + elif tor_info.state == 'pausedDL' and tor_info.completion_on != 0: + # recheck torrent incase one of seed limits reached + # sometimes it stuck on pausedDL from maxRatioAction but it should be pausedUP + LOGGER.info("Recheck on complete manually! PausedDL") + self.client.torrents_recheck(torrent_hashes=self.ext_hash) + except Exception as e: + LOGGER.error(str(e)) + + def __onDownloadError(self, err): + LOGGER.info(f"Cancelling Download: {self.__name}") + self.client.torrents_pause(torrent_hashes=self.ext_hash) + sleep(0.3) + self.__listener.onDownloadError(err) + self.__remove_torrent() + + def __remove_torrent(self): + self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True) + self.client.torrents_delete_tags(tags=self.__listener.uid) + self.client.auth_log_out() + self.__periodic.cancel() + + def cancel_download(self): + if self.is_seeding: + LOGGER.info(f"Cancelling Seed: {self.__name}") + self.client.torrents_pause(torrent_hashes=self.ext_hash) + else: + self.__onDownloadError('Download stopped by user!') \ No newline at end of file diff --git a/bot/helper/mirror_utils/download_utils/telegram_downloader.py b/bot/helper/mirror_utils/download_utils/telegram_downloader.py new file mode 100644 index 0000000..3e6e9ea --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/telegram_downloader.py @@ -0,0 +1,128 @@ +from logging import getLogger, WARNING +from time import time +from threading import RLock, Lock + +from bot import LOGGER, TELEGRAPH_STYLE, download_dict, download_dict_lock, STOP_DUPLICATE, STORAGE_THRESHOLD, app +from bot.helper.ext_utils.bot_utils import get_readable_file_size +from ..status_utils.telegram_download_status import TelegramDownloadStatus +from bot.helper.telegram_helper.message_utils import sendMarkup, sendMessage, sendStatusMessage, sendStatusMessage, sendFile +from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper +from bot.helper.ext_utils.fs_utils import check_storage_threshold + +global_lock = Lock() +GLOBAL_GID = set() +getLogger("pyrogram").setLevel(WARNING) + + +class TelegramDownloadHelper: + + def __init__(self, listener): + self.name = "" + self.size = 0 + self.progress = 0 + self.downloaded_bytes = 0 + self.__start_time = time() + self.__listener = listener + self.__id = "" + self.__is_cancelled = False + self.__resource_lock = RLock() + + @property + def download_speed(self): + with self.__resource_lock: + return self.downloaded_bytes / (time() - self.__start_time) + + def __onDownloadStart(self, name, size, file_id): + with global_lock: + GLOBAL_GID.add(file_id) + with self.__resource_lock: + self.name = name + self.size = size + self.__id = file_id + with download_dict_lock: + download_dict[self.__listener.uid] = TelegramDownloadStatus(self, self.__listener, self.__id) + self.__listener.onDownloadStart() + sendStatusMessage(self.__listener.message, self.__listener.bot) + + def __onDownloadProgress(self, current, total): + if self.__is_cancelled: + app.stop_transmission() + return + with self.__resource_lock: + self.downloaded_bytes = current + try: + self.progress = current / self.size * 100 + except ZeroDivisionError: + pass + + def __onDownloadError(self, error): + with global_lock: + try: + GLOBAL_GID.remove(self.__id) + except: + pass + self.__listener.onDownloadError(error) + + def __onDownloadComplete(self): + with global_lock: + GLOBAL_GID.remove(self.__id) + self.__listener.onDownloadComplete() + + def __download(self, message, path): + try: + download = message.download(file_name=path, progress=self.__onDownloadProgress) + except Exception as e: + LOGGER.error(str(e)) + return self.__onDownloadError(str(e)) + if download is not None: + self.__onDownloadComplete() + elif not self.__is_cancelled: + self.__onDownloadError('Internal error occurred') + + def add_download(self, message, path, filename): + _dmsg = app.get_messages(message.chat.id, reply_to_message_ids=message.message_id) + media = _dmsg.document or _dmsg.video or _dmsg.audio or None + if media is not None: + with global_lock: + # For avoiding locking the thread lock for long time unnecessarily + download = media.file_unique_id not in GLOBAL_GID + if filename == "": + name = media.file_name + else: + name = filename + path = path + name + + if download: + size = media.file_size + if STOP_DUPLICATE and not self.__listener.isLeech: + LOGGER.info('Checking File/Folder if already in Drive...') + if TELEGRAPH_STYLE is True: + smsg, button = GoogleDriveHelper().drive_list(name, True, True) + if smsg: + msg = "File/Folder is already available in Drive.\nHere are the search results:" + return sendMarkup(msg, self.__listener.bot, self.__listener.message, button) + else: + cap, f_name = GoogleDriveHelper().drive_list(name, True, True) + if cap: + cap = f"File/Folder is already available in Drive. Here are the search results:\n\n{cap}" + sendFile(self.__listener.bot, self.__listener.message, f_name, cap) + return + if STORAGE_THRESHOLD is not None: + arch = any([self.__listener.isZip, self.__listener.extract]) + acpt = check_storage_threshold(size, arch) + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(size)}' + return sendMessage(msg, self.__listener.bot, self.__listener.message) + self.__onDownloadStart(name, size, media.file_unique_id) + LOGGER.info(f'Downloading Telegram file with id: {media.file_unique_id}') + self.__download(_dmsg, path) + else: + self.__onDownloadError('File already being downloaded!') + else: + self.__onDownloadError('No document in the replied message') + + def cancel_download(self): + LOGGER.info(f'Cancelling download on user request: {self.__id}') + self.__is_cancelled = True + self.__onDownloadError('Cancelled by user!') diff --git a/bot/helper/mirror_utils/download_utils/yt_dlp_download_helper.py b/bot/helper/mirror_utils/download_utils/yt_dlp_download_helper.py new file mode 100644 index 0000000..9781d30 --- /dev/null +++ b/bot/helper/mirror_utils/download_utils/yt_dlp_download_helper.py @@ -0,0 +1,245 @@ +from random import SystemRandom +from string import ascii_letters, digits +from logging import getLogger +from yt_dlp import YoutubeDL, DownloadError +from threading import RLock +from time import time +from json import loads as jsonloads +from re import search as re_search + +from bot import download_dict_lock, download_dict, STORAGE_THRESHOLD +from bot.helper.ext_utils.bot_utils import get_readable_file_size +from bot.helper.telegram_helper.message_utils import sendStatusMessage +from ..status_utils.yt_dlp_download_status import YtDlpDownloadStatus +from bot.helper.ext_utils.fs_utils import check_storage_threshold + +LOGGER = getLogger(__name__) + + +class MyLogger: + def __init__(self, obj): + self.obj = obj + + def debug(self, msg): + # Hack to fix changing extension + if not self.obj.is_playlist: + if match := re_search(r'.Merger..Merging formats into..(.*?).$', msg) or \ + re_search(r'.ExtractAudio..Destination..(.*?)$', msg): + LOGGER.info(msg) + newname = match.group(1) + newname = newname.rsplit("/", 1)[-1] + self.obj.name = newname + + @staticmethod + def warning(msg): + LOGGER.warning(msg) + + @staticmethod + def error(msg): + if msg != "ERROR: Cancelling...": + LOGGER.error(msg) + + +class YoutubeDLHelper: + def __init__(self, listener): + self.name = "" + self.is_playlist = False + self._last_downloaded = 0 + self.__size = 0 + self.__progress = 0 + self.__downloaded_bytes = 0 + self.__download_speed = 0 + self.__eta = '-' + self.__start_time = time() + self.__listener = listener + self.__gid = "" + self.__is_cancelled = False + self.__downloading = False + self.__resource_lock = RLock() + self.opts = {'progress_hooks': [self.__onDownloadProgress], + 'logger': MyLogger(self), + 'usenetrc': True, + 'cookiefile': 'cookies.txt', + 'allow_multiple_video_streams': True, + 'allow_multiple_audio_streams': True, + 'noprogress': True, + 'allow_playlist_files': True, + 'overwrites': True, + 'trim_file_name': 200} + + @property + def download_speed(self): + with self.__resource_lock: + return self.__download_speed + + @property + def downloaded_bytes(self): + with self.__resource_lock: + return self.__downloaded_bytes + + @property + def size(self): + with self.__resource_lock: + return self.__size + + @property + def progress(self): + with self.__resource_lock: + return self.__progress + + @property + def eta(self): + with self.__resource_lock: + return self.__eta + + + def __onDownloadProgress(self, d): + self.__downloading = True + if self.__is_cancelled: + raise ValueError("Cancelling...") + if d['status'] == "finished": + if self.is_playlist: + self._last_downloaded = 0 + elif d['status'] == "downloading": + with self.__resource_lock: + self.__download_speed = d['speed'] + if self.is_playlist: + downloadedBytes = d['downloaded_bytes'] + chunk_size = downloadedBytes - self._last_downloaded + self._last_downloaded = downloadedBytes + self.__downloaded_bytes += chunk_size + else: + if d.get('total_bytes'): + self.__size = d['total_bytes'] + elif d.get('total_bytes_estimate'): + self.__size = d['total_bytes_estimate'] + self.__downloaded_bytes = d['downloaded_bytes'] + self.__eta = d.get('eta', '-') + try: + self.__progress = (self.__downloaded_bytes / self.__size) * 100 + except: + pass + + def __onDownloadStart(self): + with download_dict_lock: + download_dict[self.__listener.uid] = YtDlpDownloadStatus(self, self.__listener, self.__gid) + self.__listener.onDownloadStart() + sendStatusMessage(self.__listener.message, self.__listener.bot) + + def __onDownloadComplete(self): + self.__listener.onDownloadComplete() + + def __onDownloadError(self, error): + self.__is_cancelled = True + self.__listener.onDownloadError(error) + + def extractMetaData(self, link, name, args, get_info=False): + if args is not None: + self.__set_args(args) + if get_info: + self.opts['playlist_items'] = '0' + if link.startswith(('rtmp', 'mms', 'rstp')): + self.opts['external_downloader'] = 'ffmpeg' + with YoutubeDL(self.opts) as ydl: + try: + result = ydl.extract_info(link, download=False) + if get_info: + return result + elif result is None: + raise ValueError('Info result is None') + realName = ydl.prepare_filename(result) + except Exception as e: + if get_info: + raise e + return self.__onDownloadError(str(e)) + if 'entries' in result: + for v in result['entries']: + if not v: + continue + elif 'filesize_approx' in v: + self.__size += v['filesize_approx'] + elif 'filesize' in v: + self.__size += v['filesize'] + if name == "": + self.name = realName.split(f" [{result['id'].replace('*', '_')}]")[0] + else: + self.name = name + else: + ext = realName.split('.')[-1] + if name == "": + newname = str(realName).split(f" [{result['id'].replace('*', '_')}]") + self.name = newname[0] + '.' + ext if len(newname) > 1 else newname[0] + else: + self.name = f"{name}.{ext}" + + def __download(self, link): + try: + with YoutubeDL(self.opts) as ydl: + try: + ydl.download([link]) + except DownloadError as e: + if not self.__is_cancelled: + self.__onDownloadError(str(e)) + return + if self.__is_cancelled: + raise ValueError + self.__onDownloadComplete() + except ValueError: + self.__onDownloadError("Download Stopped by User!") + + def add_download(self, link, path, name, qual, playlist, args): + if playlist: + self.opts['ignoreerrors'] = True + self.is_playlist = True + self.__gid = ''.join(SystemRandom().choices(ascii_letters + digits, k=10)) + self.__onDownloadStart() + if qual.startswith('ba/b-'): + mp3_info = qual.split('-') + qual = mp3_info[0] + rate = mp3_info[1] + self.opts['postprocessors'] = [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': rate}] + self.opts['format'] = qual + LOGGER.info(f"Downloading with YT-DLP: {link}") + self.extractMetaData(link, name, args) + if self.__is_cancelled: + return + if STORAGE_THRESHOLD is not None: + acpt = check_storage_threshold(self.size, self.__listener.isZip) + if not acpt: + msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.' + msg += f'\nYour File/Folder size is {get_readable_file_size(self.size)}' + return self.__onDownloadError(msg) + if self.is_playlist: + self.opts['outtmpl'] = f"{path}/{self.name}/%(title)s.%(ext)s" + elif args is None: + self.opts['outtmpl'] = f"{path}/{self.name}" + else: + folder_name = self.name.rsplit('.', 1)[0] + self.opts['outtmpl'] = f"{path}/{folder_name}/{self.name}" + self.name = folder_name + self.__download(link) + + def cancel_download(self): + self.__is_cancelled = True + LOGGER.info(f"Cancelling Download: {self.name}") + if not self.__downloading: + self.__onDownloadError("Download Cancelled by User!") + + def __set_args(self, args): + args = args.split('|') + for arg in args: + xy = arg.split(':', 1) + karg = xy[0].strip() + varg = xy[1].strip() + if varg.startswith('^'): + varg = int(varg.split('^')[1]) + elif varg.lower() == 'true': + varg = True + elif varg.lower() == 'false': + varg = False + elif varg.startswith('(') and varg.endswith(')'): + varg = varg.replace('(', '').replace(')', '') + varg = tuple(map(int, varg.split(','))) + elif varg.startswith('{') and varg.endswith('}'): + varg = jsonloads(varg) + self.opts[karg] = varg \ No newline at end of file diff --git a/bot/helper/mirror_utils/status_utils/__init__.py b/bot/helper/mirror_utils/status_utils/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_utils/status_utils/aria_download_status.py b/bot/helper/mirror_utils/status_utils/aria_download_status.py new file mode 100644 index 0000000..a8f88a5 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/aria_download_status.py @@ -0,0 +1,118 @@ +from time import time +from bot import aria2, LOGGER +from bot.helper.ext_utils.bot_utils import MirrorStatus, EngineStatus, get_readable_time + +def get_download(gid): + try: + return aria2.get_download(gid) + except Exception as e: + LOGGER.error(f'{e}: while getting torrent info') + + +class AriaDownloadStatus: + + def __init__(self, gid, listener, seeding=False): + self.__gid = gid + self.__download = get_download(gid) + self.__listener = listener + self.start_time = 0 + self.seeding = seeding + self.message = listener.message + + + def __update(self): + self.__download = self.__download.live + if self.__download.followed_by_ids: + self.__gid = self.__download.followed_by_ids[0] + self.__download = get_download(self.__gid) + + def progress(self): + """ + Calculates the progress of the mirror (upload or download) + :return: returns progress in percentage + """ + return self.__download.progress_string() + + def size_raw(self): + """ + Gets total size of the mirror file/folder + :return: total size of mirror + """ + return self.__download.total_length + + def processed_bytes(self): + return self.__download.completed_length + + def speed(self): + self.__update() + return self.__download.download_speed_string() + + def name(self): + return self.__download.name + + + def size(self): + return self.__download.total_length_string() + + def eta(self): + return self.__download.eta_string() + + def status(self): + self.__update() + download = self.__download + if download.is_waiting: + return MirrorStatus.STATUS_WAITING + elif download.is_paused: + return MirrorStatus.STATUS_PAUSED + elif download.seeder and self.seeding: + return MirrorStatus.STATUS_SEEDING + else: + return MirrorStatus.STATUS_DOWNLOADING + + def seeders_num(self): + return self.__download.num_seeders + + def leechers_num(self): + return self.__download.connections + + def uploaded_bytes(self): + return self.__download.upload_length_string() + + def upload_speed(self): + self.__update() + return self.__download.upload_speed_string() + + def ratio(self): + return f"{round(self.__download.upload_length / self.__download.completed_length, 3)}" + + def seeding_time(self): + return f"{get_readable_time(time() - self.start_time)}" + + def download(self): + return self + + def listener(self): + return self.__listener + + def gid(self): + self.__update() + return self.__gid + + def cancel_download(self): + self.__update() + if self.__download.seeder: + LOGGER.info(f"Cancelling Seed: {self.name()}") + self.__listener.onUploadError(f"Seeding stopped with Ratio: {self.ratio()} and Time: {self.seeding_time()}") + aria2.remove([self.__download], force=True, files=True) + elif len(self.__download.followed_by_ids) != 0: + LOGGER.info(f"Cancelling Download: {self.name()}") + downloads = aria2.get_downloads(self.__download.followed_by_ids) + self.__listener.onDownloadError('Download stopped by user!') + aria2.remove(downloads, force=True, files=True) + else: + LOGGER.info(f"Cancelling Download: {self.name()}") + self.__listener.onDownloadError('Download stopped by user!') + aria2.remove([self.__download], force=True, files=True) + + def eng(self): + return EngineStatus.STATUS_ARIA diff --git a/bot/helper/mirror_utils/status_utils/clone_status.py b/bot/helper/mirror_utils/status_utils/clone_status.py new file mode 100644 index 0000000..c4fd61a --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/clone_status.py @@ -0,0 +1,58 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class CloneStatus: + def __init__(self, obj, size, message, gid): + self.__obj = obj + self.__size = size + self.__gid = gid + self.message = message + + def processed_bytes(self): + return self.__obj.transferred_size + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def status(self): + return MirrorStatus.STATUS_CLONING + + def name(self): + return self.__obj.name + + def gid(self) -> str: + return self.__gid + + def progress_raw(self): + try: + return self.__obj.transferred_size / self.__size * 100 + except: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Download speed in Bytes/Seconds + """ + return self.__obj.cspeed() + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + try: + seconds = (self.__size - self.__obj.transferred_size) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_GD diff --git a/bot/helper/mirror_utils/status_utils/extract_status.py b/bot/helper/mirror_utils/status_utils/extract_status.py new file mode 100644 index 0000000..bf9e5b1 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/extract_status.py @@ -0,0 +1,70 @@ +from time import time + +from bot import DOWNLOAD_DIR, LOGGER +from bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus, EngineStatus, get_readable_time +from bot.helper.ext_utils.fs_utils import get_path_size + +class ExtractStatus: + def __init__(self, name, size, gid, listener): + self.__name = name + self.__size = size + self.__gid = gid + self.__listener = listener + self.__uid = listener.uid + self.__start_time = time() + self.message = listener.message + + def gid(self): + return self.__gid + + def speed_raw(self): + return self.processed_bytes() / (time() - self.__start_time) + + def progress_raw(self): + try: + return self.processed_bytes() / self.__size * 100 + except: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def name(self): + return self.__name + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def eta(self): + try: + seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def status(self): + return MirrorStatus.STATUS_EXTRACTING + + def processed_bytes(self): + if self.__listener.newDir: + return get_path_size(f"{DOWNLOAD_DIR}{self.__uid}10000") + else: + return get_path_size(f"{DOWNLOAD_DIR}{self.__uid}") - self.__size + + def download(self): + return self + + def cancel_download(self): + LOGGER.info(f'Cancelling Extract: {self.__name}') + if self.__listener.suproc is not None: + self.__listener.suproc.kill() + self.__listener.onUploadError('extracting stopped by user!') + + def eng(self): + return EngineStatus.STATUS_EXT diff --git a/bot/helper/mirror_utils/status_utils/gd_download_status.py b/bot/helper/mirror_utils/status_utils/gd_download_status.py new file mode 100644 index 0000000..877abb6 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/gd_download_status.py @@ -0,0 +1,58 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class GdDownloadStatus: + def __init__(self, obj, size, listener, gid): + self.__obj = obj + self.__size = size + self.__gid = gid + self.message = listener.message + + def processed_bytes(self): + return self.__obj.processed_bytes + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def status(self): + return MirrorStatus.STATUS_DOWNLOADING + + def name(self): + return self.__obj.name + + def gid(self) -> str: + return self.__gid + + def progress_raw(self): + try: + return self.__obj.processed_bytes / self.__size * 100 + except: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Download speed in Bytes/Seconds + """ + return self.__obj.speed() + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + try: + seconds = (self.__size - self.__obj.processed_bytes) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_GD \ No newline at end of file diff --git a/bot/helper/mirror_utils/status_utils/mega_download_status.py b/bot/helper/mirror_utils/status_utils/mega_download_status.py new file mode 100644 index 0000000..52ee0f3 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/mega_download_status.py @@ -0,0 +1,59 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class MegaDownloadStatus: + + def __init__(self, obj, listener): + self.__listener = listener + self.__obj = obj + self.message = listener.message + + def name(self) -> str: + return self.__obj.name + + def progress_raw(self): + try: + return round(self.processed_bytes() / self.__obj.size * 100,2) + except: + return 0.0 + + def progress(self): + """Progress of download in percentage""" + return f"{self.progress_raw()}%" + + def status(self) -> str: + return MirrorStatus.STATUS_DOWNLOADING + + def processed_bytes(self): + return self.__obj.downloaded_bytes + + def eta(self): + try: + seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except ZeroDivisionError: + return '-' + + def size_raw(self): + return self.__obj.size + + def size(self) -> str: + return get_readable_file_size(self.size_raw()) + + def downloaded(self) -> str: + return get_readable_file_size(self.__obj.downloadedBytes) + + def speed_raw(self): + return self.__obj.speed + + def speed(self) -> str: + return f'{get_readable_file_size(self.speed_raw())}/s' + + def gid(self) -> str: + return self.__obj.gid + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_MEGA diff --git a/bot/helper/mirror_utils/status_utils/qbit_download_status.py b/bot/helper/mirror_utils/status_utils/qbit_download_status.py new file mode 100644 index 0000000..564e6b7 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/qbit_download_status.py @@ -0,0 +1,101 @@ +from bot import LOGGER +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + +def get_download(client, uid): + try: + return client.torrents_info(tag=uid)[0] + except Exception as e: + LOGGER.error(f'{e}: while getting torrent info') + + +class QbDownloadStatus: + + def __init__(self, listener, obj): + self.__obj = obj + self.__listener = listener + self.__uid = listener.uid + self.__info = get_download(obj.client, self.__uid) + self.message = listener.message + + def __update(self): + self.__info = get_download(self.__obj.client, self.__uid) + + def progress(self): + """ + Calculates the progress of the mirror (upload or download) + :return: returns progress in percentage + """ + return f'{round(self.__info.progress*100, 2)}%' + + def size_raw(self): + """ + Gets total size of the mirror file/folder + :return: total size of mirror + """ + return self.__info.size + + def processed_bytes(self): + return self.__info.downloaded + + def speed(self): + self.__update() + return f"{get_readable_file_size(self.__info.dlspeed)}/s" + + def name(self): + self.__update() + if self.__info.state in ["metaDL", "checkingResumeData"]: + return f"[METADATA]{self.__info.name}" + else: + return self.__info.name + + def size(self): + return get_readable_file_size(self.__info.size) + + def eta(self): + return get_readable_time(self.__info.eta) + + def status(self): + download = self.__info.state + if download in ["queuedDL", "queuedUP"]: + return MirrorStatus.STATUS_WAITING + elif download in ["pausedDL", "pausedUP"]: + return MirrorStatus.STATUS_PAUSED + elif download in ["checkingUP", "checkingDL"]: + return MirrorStatus.STATUS_CHECKING + elif download in ["stalledUP", "uploading"] and self.__obj.is_seeding: + return MirrorStatus.STATUS_SEEDING + else: + return MirrorStatus.STATUS_DOWNLOADING + + def seeders_num(self): + return self.__info.num_seeds + + def leechers_num(self): + return self.__info.num_leechs + + def uploaded_bytes(self): + return f"{get_readable_file_size(self.__info.uploaded)}" + + def upload_speed(self): + return f"{get_readable_file_size(self.__info.upspeed)}/s" + + def ratio(self): + return f"{round(self.__info.ratio, 3)}" + + def seeding_time(self): + return f"{get_readable_time(self.__info.seeding_time)}" + + def download(self): + return self.__obj + + def gid(self): + return self.__obj.ext_hash[:12] + + def client(self): + return self.__obj.client + + def listener(self): + return self.__listener + + def eng(self): + return EngineStatus.STATUS_QB \ No newline at end of file diff --git a/bot/helper/mirror_utils/status_utils/split_status.py b/bot/helper/mirror_utils/status_utils/split_status.py new file mode 100644 index 0000000..65f06ed --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/split_status.py @@ -0,0 +1,46 @@ +from bot import LOGGER +from bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus, EngineStatus + + +class SplitStatus: + def __init__(self, name, size, gid, listener): + self.__name = name + self.__gid = gid + self.__size = size + self.__listener = listener + self.message = listener.message + + def gid(self): + return self.__gid + + def progress(self): + return '0' + + def speed(self): + return '0' + + def name(self): + return self.__name + + def size(self): + return get_readable_file_size(self.__size) + + def eta(self): + return '0s' + + def status(self): + return MirrorStatus.STATUS_SPLITTING + + def processed_bytes(self): + return 0 + + def download(self): + return self + + def cancel_download(self): + LOGGER.info(f'Cancelling Split: {self.__name}') + self.__listener.split_proc.kill() + self.__listener.onUploadError('splitting stopped by user!') + + def eng(self): + return EngineStatus.STATUS_SPLIT diff --git a/bot/helper/mirror_utils/status_utils/telegram_download_status.py b/bot/helper/mirror_utils/status_utils/telegram_download_status.py new file mode 100644 index 0000000..def90d6 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/telegram_download_status.py @@ -0,0 +1,54 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class TelegramDownloadStatus: + def __init__(self, obj, listener, gid): + self.__obj = obj + self.__gid = gid + self.message = listener.message + + def gid(self): + return self.__gid + + def processed_bytes(self): + return self.__obj.downloaded_bytes + + def size_raw(self): + return self.__obj.size + + def size(self): + return get_readable_file_size(self.size_raw()) + + def status(self): + return MirrorStatus.STATUS_DOWNLOADING + + def name(self): + return self.__obj.name + + def progress_raw(self): + return self.__obj.progress + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Download speed in Bytes/Seconds + """ + return self.__obj.download_speed + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + try: + seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_TG diff --git a/bot/helper/mirror_utils/status_utils/tg_upload_status.py b/bot/helper/mirror_utils/status_utils/tg_upload_status.py new file mode 100644 index 0000000..c0121cd --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/tg_upload_status.py @@ -0,0 +1,58 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class TgUploadStatus: + def __init__(self, obj, size, gid, listener): + self.__obj = obj + self.__size = size + self.__gid = gid + self.message = listener.message + + def processed_bytes(self): + return self.__obj.uploaded_bytes + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def status(self): + return MirrorStatus.STATUS_UPLOADING + + def name(self): + return self.__obj.name + + def progress_raw(self): + try: + return self.__obj.uploaded_bytes / self.__size * 100 + except ZeroDivisionError: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Upload speed in Bytes/Seconds + """ + return self.__obj.speed + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + try: + seconds = (self.__size - self.__obj.uploaded_bytes) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except ZeroDivisionError: + return '-' + + def gid(self) -> str: + return self.__gid + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_TG diff --git a/bot/helper/mirror_utils/status_utils/upload_status.py b/bot/helper/mirror_utils/status_utils/upload_status.py new file mode 100644 index 0000000..b2fd073 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/upload_status.py @@ -0,0 +1,59 @@ +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus + + +class UploadStatus: + def __init__(self, obj, size, gid, listener): + self.__obj = obj + self.__size = size + self.__gid = gid + self.message = listener.message + + + def processed_bytes(self): + return self.__obj.processed_bytes + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def status(self): + return MirrorStatus.STATUS_UPLOADING + + def name(self): + return self.__obj.name + + def progress_raw(self): + try: + return self.__obj.processed_bytes / self.__size * 100 + except ZeroDivisionError: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Upload speed in Bytes/Seconds + """ + return self.__obj.speed() + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + try: + seconds = (self.__size - self.__obj.processed_bytes) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except ZeroDivisionError: + return '-' + + def gid(self) -> str: + return self.__gid + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_GD \ No newline at end of file diff --git a/bot/helper/mirror_utils/status_utils/yt_dlp_download_status.py b/bot/helper/mirror_utils/status_utils/yt_dlp_download_status.py new file mode 100644 index 0000000..8de65da --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/yt_dlp_download_status.py @@ -0,0 +1,62 @@ +from bot import DOWNLOAD_DIR +from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus +from bot.helper.ext_utils.fs_utils import get_path_size + +class YtDlpDownloadStatus: + def __init__(self, obj, listener, gid): + self.__obj = obj + self.__uid = listener.uid + self.__gid = gid + self.message = listener.message + + def gid(self): + return self.__gid + + + def processed_bytes(self): + if self.__obj.downloaded_bytes != 0: + return self.__obj.downloaded_bytes + else: + return get_path_size(f"{DOWNLOAD_DIR}{self.__uid}") + + def size_raw(self): + return self.__obj.size + + def size(self): + return get_readable_file_size(self.size_raw()) + + def status(self): + return MirrorStatus.STATUS_DOWNLOADING + + def name(self): + return self.__obj.name + + def progress_raw(self): + return self.__obj.progress + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed_raw(self): + """ + :return: Download speed in Bytes/Seconds + """ + return self.__obj.download_speed + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def eta(self): + if self.__obj.eta != '-': + return f'{get_readable_time(self.__obj.eta)}' + try: + seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def download(self): + return self.__obj + + def eng(self): + return EngineStatus.STATUS_YT diff --git a/bot/helper/mirror_utils/status_utils/zip_status.py b/bot/helper/mirror_utils/status_utils/zip_status.py new file mode 100644 index 0000000..9841c68 --- /dev/null +++ b/bot/helper/mirror_utils/status_utils/zip_status.py @@ -0,0 +1,70 @@ +from time import time + +from bot import DOWNLOAD_DIR, LOGGER +from bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus, EngineStatus, get_readable_time +from bot.helper.ext_utils.fs_utils import get_path_size + +class ZipStatus: + def __init__(self, name, size, gid, listener): + self.__name = name + self.__size = size + self.__gid = gid + self.__listener = listener + self.__uid = listener.uid + self.__start_time = time() + self.message = listener.message + + def gid(self): + return self.__gid + + def speed_raw(self): + return self.processed_bytes() / (time() - self.__start_time) + + def progress_raw(self): + try: + return self.processed_bytes() / self.__size * 100 + except: + return 0 + + def progress(self): + return f'{round(self.progress_raw(), 2)}%' + + def speed(self): + return f'{get_readable_file_size(self.speed_raw())}/s' + + def name(self): + return self.__name + + def size_raw(self): + return self.__size + + def size(self): + return get_readable_file_size(self.__size) + + def eta(self): + try: + seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw() + return f'{get_readable_time(seconds)}' + except: + return '-' + + def status(self): + return MirrorStatus.STATUS_ARCHIVING + + def processed_bytes(self): + if self.__listener.newDir: + return get_path_size(f"{DOWNLOAD_DIR}{self.__uid}10000") + else: + return get_path_size(f"{DOWNLOAD_DIR}{self.__uid}") - self.__size + + def download(self): + return self + + def cancel_download(self): + LOGGER.info(f'Cancelling Archive: {self.__name}') + if self.__listener.suproc is not None: + self.__listener.suproc.kill() + self.__listener.onUploadError('archiving stopped by user!') + + def eng(self): + return EngineStatus.STATUS_ZIP diff --git a/bot/helper/mirror_utils/upload_utils/__init__.py b/bot/helper/mirror_utils/upload_utils/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bot/helper/mirror_utils/upload_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_utils/upload_utils/gdriveTools.py b/bot/helper/mirror_utils/upload_utils/gdriveTools.py new file mode 100644 index 0000000..f4218c8 --- /dev/null +++ b/bot/helper/mirror_utils/upload_utils/gdriveTools.py @@ -0,0 +1,992 @@ +from asyncio import exceptions +from logging import getLogger, ERROR +from time import time +from pickle import load as pload +from json import loads as jsnloads +from os import makedirs, path as ospath, listdir, remove as osremove +from requests.utils import quote as rquote +from io import FileIO +from re import search as re_search +from urllib.parse import parse_qs, urlparse +from random import randrange +from google.oauth2 import service_account +from googleapiclient.discovery import build +from googleapiclient.errors import HttpError, Error as GCError +from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload +from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type, RetryError +from bot.helper.ext_utils.html_helper import hmtl_content + +from bot.helper.telegram_helper.button_build import ButtonMaker +from bot import TELEGRAPH_STYLE, parent_id, IS_TEAM_DRIVE, INDEX_URL, USE_SERVICE_ACCOUNTS, BUTTON_FOUR_NAME, \ + BUTTON_FOUR_URL, BUTTON_FIVE_NAME, BUTTON_FIVE_URL, BUTTON_SIX_NAME, BUTTON_SIX_URL, VIEW_LINK, \ + DRIVES_NAMES, DRIVES_IDS, INDEX_URLS, EXTENSION_FILTER, SOURCE_LINK, TITLE_NAME, GD_INFO, EMOJI_THEME +from bot.helper.ext_utils.telegraph_helper import telegraph +from bot.helper.ext_utils.bot_utils import get_readable_file_size, setInterval +from bot.helper.ext_utils.fs_utils import get_mime_type +from bot.helper.ext_utils.shortenurl import short_url + +LOGGER = getLogger(__name__) +getLogger('googleapiclient.discovery').setLevel(ERROR) + +if USE_SERVICE_ACCOUNTS: + SERVICE_ACCOUNTS_NUMBER = len(listdir("accounts")) + + +class GoogleDriveHelper: + + def __init__(self, name=None, path=None, size=0, listener=None): + self.__G_DRIVE_TOKEN_FILE = "token.pickle" + self.__OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive'] + self.__G_DRIVE_DIR_MIME_TYPE = "application/vnd.google-apps.folder" + self.__G_DRIVE_BASE_DOWNLOAD_URL = "https://drive.google.com/uc?id={}&export=download" + self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL = "https://drive.google.com/drive/folders/{}" + self.__listener = listener + self.__path = path + self.__total_bytes = 0 + self.__total_files = 0 + self.__total_folders = 0 + self.__sa_count = 0 + self.__start_time = 0 + self.__total_time = 0 + self.__alt_auth = False + self.__is_uploading = False + self.__is_downloading = False + self.__is_cloning = False + self.__is_cancelled = False + self.__is_errored = False + self.__status = None + self.__updater = None + self.__update_interval = 3 + self.__size = size + self._file_processed_bytes = 0 + self.name = name + self.processed_bytes = 0 + self.transferred_size = 0 + self.__service = self.__authorize() + + + def speed(self): + """ + It calculates the average upload speed and returns it in bytes/seconds unit + :return: Upload speed in bytes/second + """ + try: + return self.processed_bytes / self.__total_time + except: + return 0 + + def cspeed(self): + try: + return self.transferred_size / int(time() - self.__start_time) + except: + return 0 + + def __authorize(self): + # Get credentials + credentials = None + if USE_SERVICE_ACCOUNTS: + if self.__sa_count == 0: + self.__service_account_index = randrange(SERVICE_ACCOUNTS_NUMBER) + LOGGER.info(f"Authorizing with {self.__service_account_index}.json service account") + credentials = service_account.Credentials.from_service_account_file( + f'accounts/{self.__service_account_index}.json', + scopes=self.__OAUTH_SCOPE) + elif ospath.exists(self.__G_DRIVE_TOKEN_FILE): + with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f: + credentials = pload(f) + else: + LOGGER.error('token.pickle not found!') + return build('drive', 'v3', credentials=credentials, cache_discovery=False) + + def __alt_authorize(self): + credentials = None + if USE_SERVICE_ACCOUNTS and not self.__alt_auth: + self.__alt_auth = True + if ospath.exists(self.__G_DRIVE_TOKEN_FILE): + LOGGER.info("Authorize with token.pickle") + with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f: + credentials = pload(f) + return build('drive', 'v3', credentials=credentials, cache_discovery=False) + return None + + def __switchServiceAccount(self): + if self.__service_account_index == SERVICE_ACCOUNTS_NUMBER - 1: + self.__service_account_index = 0 + else: + self.__service_account_index += 1 + self.__sa_count += 1 + LOGGER.info(f"Switching to {self.__service_account_index}.json service account") + self.__service = self.__authorize() + + @staticmethod + def __getIdFromUrl(link: str): + if "folders" in link or "file" in link: + regex = r"https:\/\/drive\.google\.com\/(?:drive(.*?)\/folders\/|file(.*?)?\/d\/)([-\w]+)" + res = re_search(regex,link) + if res is None: + raise IndexError("G-Drive ID not found.") + return res.group(3) + parsed = urlparse(link) + return parse_qs(parsed.query)['id'][0] + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=retry_if_exception_type(GCError)) + def __set_permission(self, drive_id): + permissions = { + 'role': 'reader', + 'type': 'anyone', + 'value': None, + 'withLink': True + } + return self.__service.permissions().create(supportsTeamDrives=True, fileId=drive_id, + body=permissions).execute() + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=retry_if_exception_type(GCError)) + def __getFileMetadata(self, file_id): + return self.__service.files().get(supportsAllDrives=True, fileId=file_id, + fields="name,id,mimeType,size").execute() + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=retry_if_exception_type(GCError)) + def __getFilesByFolderId(self, folder_id): + page_token = None + files = [] + while True: + response = self.__service.files().list(supportsTeamDrives=True, + includeTeamDriveItems=True, + q=f"'{folder_id}' in parents and trashed = false", + spaces='drive', + pageSize=200, + fields='nextPageToken, files(id, name, mimeType, size, shortcutDetails)', + orderBy='folder, name', + pageToken=page_token).execute() + files.extend(response.get('files', [])) + page_token = response.get('nextPageToken') + if page_token is None: + break + return files + + def _progress(self): + if self.__status is not None: + chunk_size = self.__status.total_size * self.__status.progress() - self._file_processed_bytes + self._file_processed_bytes = self.__status.total_size * self.__status.progress() + self.processed_bytes += chunk_size + self.__total_time += self.__update_interval + + def deletefile(self, link: str): + try: + file_id = self.__getIdFromUrl(link) + except (KeyError, IndexError): + msg = "Google Drive ID could not be found in the provided link" + return msg + msg = '' + try: + self.__service.files().delete(fileId=file_id, supportsTeamDrives=IS_TEAM_DRIVE).execute() + msg = "Successfully deleted" + LOGGER.info(f"Delete Result: {msg}") + except HttpError as err: + if "File not found" in str(err): + msg = "No such file exist" + elif "insufficientFilePermissions" in str(err): + msg = "Insufficient File Permissions" + token_service = self.__alt_authorize() + if token_service is not None: + self.__service = token_service + return self.deletefile(link) + else: + msg = err + LOGGER.error(f"Delete Result: {msg}") + finally: + return msg + + def upload(self, file_name: str): + self.__is_uploading = True + file_path = f"{self.__path}/{file_name}" + size = get_readable_file_size(self.__size) + LOGGER.info(f"Uploading File: {file_path}") + self.__updater = setInterval(self.__update_interval, self._progress) + try: + if ospath.isfile(file_path): + mime_type = get_mime_type(file_path) + link = self.__upload_file(file_path, file_name, mime_type, parent_id) + if self.__is_cancelled: + return + if link is None: + raise Exception('Upload has been manually cancelled') + LOGGER.info(f"Uploaded To G-Drive: {file_path}") + else: + mime_type = 'Folder' + dir_id = self.__create_directory(ospath.basename(ospath.abspath(file_name)), parent_id) + result = self.__upload_dir(file_path, dir_id) + if result is None: + raise Exception('Upload has been manually cancelled!') + link = f"https://drive.google.com/folderview?id={dir_id}" + if self.__is_cancelled: + return + LOGGER.info(f"Uploaded To G-Drive: {file_name}") + except Exception as err: + if isinstance(err, RetryError): + LOGGER.info(f"Total Attempts: {err.last_attempt.attempt_number}") + err = err.last_attempt.exception() + self.__listener.onUploadError(str(err)) + self.__is_errored = True + finally: + self.__updater.cancel() + if self.__is_cancelled and not self.__is_errored: + if mime_type == 'Folder': + LOGGER.info("Deleting uploaded data from Drive...") + link = f"https://drive.google.com/folderview?id={dir_id}" + self.deletefile(link) + return + elif self.__is_errored: + return + self.__listener.onUploadComplete(link, size, self.__total_files, self.__total_folders, mime_type, self.name) + + def __upload_dir(self, input_directory, parent_id): + list_dirs = listdir(input_directory) + if len(list_dirs) == 0: + return parent_id + new_id = None + for item in list_dirs: + current_file_name = ospath.join(input_directory, item) + if ospath.isdir(current_file_name): + current_dir_id = self.__create_directory(item, parent_id) + new_id = self.__upload_dir(current_file_name, current_dir_id) + self.__total_folders += 1 + elif not item.lower().endswith(tuple(EXTENSION_FILTER)): + mime_type = get_mime_type(current_file_name) + file_name = current_file_name.split("/")[-1] + # current_file_name will have the full path + self.__upload_file(current_file_name, file_name, mime_type, parent_id) + self.__total_files += 1 + new_id = parent_id + if self.__is_cancelled: + break + return new_id + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=retry_if_exception_type(GCError)) + def __create_directory(self, directory_name, parent_id): + file_metadata = { + "name": directory_name, + "description": "Uploaded by Mirror-leech-telegram-bot", + "mimeType": self.__G_DRIVE_DIR_MIME_TYPE + } + if parent_id is not None: + file_metadata["parents"] = [parent_id] + file = self.__service.files().create(supportsTeamDrives=True, body=file_metadata).execute() + file_id = file.get("id") + if not IS_TEAM_DRIVE: + self.__set_permission(file_id) + LOGGER.info("Created G-Drive Folder:\nName: {}\nID: {} ".format(file.get("name"), file_id)) + return file_id + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=(retry_if_exception_type(GCError) | retry_if_exception_type(IOError))) + def __upload_file(self, file_path, file_name, mime_type, parent_id): + # File body description + file_metadata = { + 'name': file_name, + 'description': f'{GD_INFO}', + 'mimeType': mime_type, + } + if parent_id is not None: + file_metadata['parents'] = [parent_id] + + if ospath.getsize(file_path) == 0: + media_body = MediaFileUpload(file_path, + mimetype=mime_type, + resumable=False) + response = self.__service.files().create(supportsTeamDrives=True, + body=file_metadata, media_body=media_body).execute() + if not IS_TEAM_DRIVE: + self.__set_permission(response['id']) + + drive_file = self.__service.files().get(supportsTeamDrives=True, + fileId=response['id']).execute() + download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id')) + return download_url + media_body = MediaFileUpload(file_path, + mimetype=mime_type, + resumable=True, + chunksize=50 * 1024 * 1024) + + # Insert a file + drive_file = self.__service.files().create(supportsTeamDrives=True, + body=file_metadata, media_body=media_body) + response = None + while response is None: + if self.__is_cancelled: + break + try: + self.__status, response = drive_file.next_chunk() + except HttpError as err: + if err.resp.get('content-type', '').startswith('application/json'): + reason = jsnloads(err.content).get('error').get('errors')[0].get('reason') + if reason not in [ + 'userRateLimitExceeded', + 'dailyLimitExceeded', + ]: + raise err + if USE_SERVICE_ACCOUNTS: + self.__switchServiceAccount() + LOGGER.info(f"Got: {reason}, Trying Again.") + return self.__upload_file(file_path, file_name, mime_type, parent_id) + else: + LOGGER.error(f"Got: {reason}") + raise err + if self.__is_cancelled: + return + if not self.__listener.seed or self.__listener.newDir: + try: + osremove(file_path) + except: + pass + self._file_processed_bytes = 0 + # Insert new permissions + if not IS_TEAM_DRIVE: + self.__set_permission(response['id']) + # Define file instance and get url for download + drive_file = self.__service.files().get(supportsTeamDrives=True, fileId=response['id']).execute() + download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id')) + return download_url + + + def clone(self, link): + self.__is_cloning = True + self.__start_time = time() + self.__total_files = 0 + self.__total_folders = 0 + try: + file_id = self.__getIdFromUrl(link) + except (KeyError, IndexError): + msg = "Google Drive ID could not be found in the provided link" + return msg + msg = "" + LOGGER.info(f"File ID: {file_id}") + try: + meta = self.__getFileMetadata(file_id) + mime_type = meta.get("mimeType") + if mime_type == self.__G_DRIVE_DIR_MIME_TYPE: + dir_id = self.__create_directory(meta.get('name'), parent_id) + self.__cloneFolder(meta.get('name'), meta.get('name'), meta.get('id'), dir_id) + durl = self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id) + if self.__is_cancelled: + LOGGER.info("Deleting cloned data from Drive...") + self.deletefile(durl) + return "your clone has been stopped and cloned data has been deleted!", "cancelled" + if EMOJI_THEME is True: + msg += f'╭🗂️ Name: {meta.get("name")}' + msg += f'\n├📦 Size: {get_readable_file_size(self.transferred_size)}' + msg += f'\n├♻ Type: Folder' + msg += f'\n├🗃️ SubFolders: {self.__total_folders}' + msg += f'\n├🗂️ Files: {self.__total_files}' + else: + msg += f'╭ Name: {meta.get("name")}' + msg += f'\n├ Size: {get_readable_file_size(self.transferred_size)}' + msg += f'\n├ Type: Folder' + msg += f'\n├ SubFolders: {self.__total_folders}' + msg += f'\n├ Files: {self.__total_files}' + buttons = ButtonMaker() + durl = short_url(durl) + buttons.buildbutton("☁️ Drive Link", durl) + if INDEX_URL is not None: + url_path = rquote(f'{meta.get("name")}', safe='') + url = f'{INDEX_URL}/{url_path}/' + url = short_url(url) + buttons.buildbutton("⚡ Index Link", url) + else: + file = self.__copyFile(meta.get('id'), parent_id) + if EMOJI_THEME is True: + msg += f'╭🗂️ Name: {file.get("name")}' + else: + msg += f'╭ Name: {file.get("name")}' + durl = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(file.get("id")) + buttons = ButtonMaker() + durl = short_url(durl) + buttons.buildbutton("☁️ Drive Link", durl) + if mime_type is None: + mime_type = 'File' + if EMOJI_THEME is True: + msg += f'\n├📦 Size: {get_readable_file_size(int(meta.get("size", 0)))}' + msg += f'\n├♻ Type: {mime_type}' + else: + msg += f'\n├ Size: {get_readable_file_size(int(meta.get("size", 0)))}' + msg += f'\n├ Type: {mime_type}' + if INDEX_URL is not None: + url_path = rquote(f'{file.get("name")}', safe='') + url = f'{INDEX_URL}/{url_path}' + url = short_url(url) + buttons.buildbutton("⚡ Index Link", url) + if VIEW_LINK: + urls = f'{INDEX_URL}/{url_path}?a=view' + urls = short_url(urls) + buttons.buildbutton("🌐 View Link", urls) + if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None: + buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}") + if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None: + buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}") + if BUTTON_SIX_NAME is not None and BUTTON_SIX_URL is not None: + buttons.buildbutton(f"{BUTTON_SIX_NAME}", f"{BUTTON_SIX_URL}") + if SOURCE_LINK is True: + buttons.buildbutton(f"🔗 Source Link", link) + except Exception as err: + if isinstance(err, RetryError): + LOGGER.info(f"Total Attempts: {err.last_attempt.attempt_number}") + err = err.last_attempt.exception() + err = str(err).replace('>', '').replace('<', '') + if "User rate limit exceeded" in err: + msg = "User rate limit exceeded." + elif "File not found" in err: + token_service = self.__alt_authorize() + if token_service is not None: + self.__service = token_service + return self.clone(link) + msg = "File not found." + else: + msg = f"Error.\n{err}" + return msg, "" + return msg, buttons.build_menu(2) + + def __cloneFolder(self, name, local_path, folder_id, parent_id): + LOGGER.info(f"Syncing: {local_path}") + files = self.__getFilesByFolderId(folder_id) + if len(files) == 0: + return parent_id + for file in files: + if file.get('mimeType') == self.__G_DRIVE_DIR_MIME_TYPE: + self.__total_folders += 1 + file_path = ospath.join(local_path, file.get('name')) + current_dir_id = self.__create_directory(file.get('name'), parent_id) + self.__cloneFolder(file.get('name'), file_path, file.get('id'), current_dir_id) + elif not file.get('name').lower().endswith(tuple(EXTENSION_FILTER)): + self.__total_files += 1 + self.transferred_size += int(file.get('size', 0)) + self.__copyFile(file.get('id'), parent_id) + if self.__is_cancelled: + break + + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(3), + retry=retry_if_exception_type(GCError)) + def __copyFile(self, file_id, dest_id): + body = {'parents': [dest_id]} + try: + return ( + self.__service.files() + .copy(supportsAllDrives=True, fileId=file_id, body=body) + .execute() + ) + except HttpError as err: + if err.resp.get('content-type', '').startswith('application/json'): + reason = jsnloads(err.content).get('error').get('errors')[0].get('reason') + if reason in ['userRateLimitExceeded', 'dailyLimitExceeded']: + if USE_SERVICE_ACCOUNTS: + if self.__sa_count == SERVICE_ACCOUNTS_NUMBER: + self.__is_cancelled = True + raise err + else: + self.__switchServiceAccount() + return self.__copyFile(file_id, dest_id) + else: + self.__is_cancelled = True + LOGGER.error(f"Got: {reason}") + raise err + else: + raise err + + def __escapes(self, estr): + chars = ['\\', "'", '"', r'\a', r'\b', r'\f', r'\n', r'\r', r'\t'] + for char in chars: + estr = estr.replace(char, f'\\{char}') + return estr.strip() + + def __get_recursive_list(self, file, rootid): + rtnlist = [] + if not rootid: + rootid = file.get('teamDriveId') + if rootid == "root": + rootid = self.__service.files().get(fileId = 'root', fields="id").execute().get('id') + x = file.get("name") + y = file.get("id") + while(y != rootid): + rtnlist.append(x) + file = self.__service.files().get( + fileId=file.get("parents")[0], + supportsAllDrives=True, + fields='id, name, parents' + ).execute() + x = file.get("name") + y = file.get("id") + rtnlist.reverse() + return rtnlist + + def __drive_query(self, parent_id, fileName, stopDup, isRecursive, itemType): + try: + if isRecursive: + if stopDup: + query = f"name = '{fileName}' and " + else: + fileName = fileName.split() + query = "".join( + f"name contains '{name}' and " + for name in fileName + if name != '' + ) + if itemType == "files": + query += "mimeType != 'application/vnd.google-apps.folder' and " + elif itemType == "folders": + query += "mimeType = 'application/vnd.google-apps.folder' and " + query += "trashed = false" + if parent_id == "root": + return ( + self.__service.files() + .list(q=f"{query} and 'me' in owners", + pageSize=200, + spaces='drive', + fields='files(id, name, mimeType, size, parents)', + orderBy='folder, name asc' + ) + .execute() + ) + else: + return ( + self.__service.files() + .list(supportsTeamDrives=True, + includeTeamDriveItems=True, + teamDriveId=parent_id, + q=query, + corpora='drive', + spaces='drive', + pageSize=200, + fields='files(id, name, mimeType, size, teamDriveId, parents)', + orderBy='folder, name asc' + ) + .execute() + ) + else: + if stopDup: + query = f"'{parent_id}' in parents and name = '{fileName}' and " + else: + query = f"'{parent_id}' in parents and " + fileName = fileName.split() + for name in fileName: + if name != '': + query += f"name contains '{name}' and " + if itemType == "files": + query += "mimeType != 'application/vnd.google-apps.folder' and " + elif itemType == "folders": + query += "mimeType = 'application/vnd.google-apps.folder' and " + query += "trashed = false" + return ( + self.__service.files() + .list( + supportsTeamDrives=True, + includeTeamDriveItems=True, + q=query, + spaces='drive', + pageSize=200, + fields='files(id, name, mimeType, size)', + orderBy='folder, name asc', + ) + .execute() + ) + except Exception as err: + err = str(err).replace('>', '').replace('<', '') + LOGGER.error(err) + return {'files': []} + + def drive_list(self, fileName, stopDup=False, noMulti=False, isRecursive=True, itemType=""): + if TELEGRAPH_STYLE is True: + + msg = "" + fileName = self.__escapes(str(fileName)) + contents_count = 0 + telegraph_content = [] + path = [] + Title = False + if len(DRIVES_IDS) > 1: + token_service = self.__alt_authorize() + if token_service is not None: + self.__service = token_service + for index, parent_id in enumerate(DRIVES_IDS): + isRecur = False if isRecursive and len(parent_id) > 23 else isRecursive + response = self.__drive_query(parent_id, fileName, stopDup, isRecur, itemType) + if not response["files"]: + if noMulti: + break + else: + continue + if not Title: + msg += f'

Search Result For {fileName}

' + Title = True + if len(DRIVES_NAMES) > 1 and DRIVES_NAMES[index] is not None: + msg += f"╾────────────╼
{DRIVES_NAMES[index]}
╾────────────╼
" + for file in response.get('files', []): + mime_type = file.get('mimeType') + if mime_type == "application/vnd.google-apps.folder": + furl = f"https://drive.google.com/drive/folders/{file.get('id')}" + msg += f"📁 {file.get('name')}
(folder)

" + furl = short_url(furl) + msg += f"Drive Link" + if INDEX_URLS[index] is not None: + if isRecur: + url_path = "/".join([rquote(n, safe='') for n in self.__get_recursive_list(file, parent_id)]) + else: + url_path = rquote(f'{file.get("name")}', safe='') + url = f'{INDEX_URLS[index]}/{url_path}/' + url = short_url(url) + msg += f' | Index Link' + elif mime_type == 'application/vnd.google-apps.shortcut': + msg += f"⁍{file.get('name')}" \ + f" (shortcut)" + # Excluded index link as indexes cant download or open these shortcuts + else: + furl = f"https://drive.google.com/uc?id={file.get('id')}&export=download" + msg += f"📄 {file.get('name')}
({get_readable_file_size(int(file.get('size', 0)))})

" + furl = short_url(furl) + msg += f"Drive Link" + if INDEX_URLS[index] is not None: + if isRecur: + url_path = "/".join(rquote(n, safe='') for n in self.__get_recursive_list(file, parent_id)) + + else: + url_path = rquote(f'{file.get("name")}') + url = f'{INDEX_URLS[index]}/{url_path}' + url = short_url(url) + msg += f' | Index Link' + if VIEW_LINK: + urls = f'{INDEX_URLS[index]}/{url_path}?a=view' + urls = short_url(urls) + msg += f' | View Link' + msg += '

' + contents_count += 1 + if len(msg.encode('utf-8')) > 39000: + telegraph_content.append(msg) + msg = "" + if noMulti: + break + + if msg != '': + telegraph_content.append(msg) + + if len(telegraph_content) == 0: + return "", None + + for content in telegraph_content: + path.append( + telegraph.create_page( + title = f'{TITLE_NAME}', + content=content + )["path"] + ) + if len(path) > 1: + telegraph.edit_telegraph(path, telegraph_content) + + msg = f"Found {contents_count} result for {fileName}" + buttons = ButtonMaker() + buttons.buildbutton("🔎 VIEW", f"https://graph.org/{path[0]}") + + return msg, buttons.build_menu(1) + + else: + + msg = "" + fileName = self.__escapes(str(fileName)) + contents_count = 0 + Title = False + if len(DRIVES_IDS) > 1: + token_service = self.__alt_authorize() + if token_service is not None: + self.__service = token_service + for index, parent_id in enumerate(DRIVES_IDS): + isRecur = False if isRecursive and len(parent_id) > 23 else isRecursive + response = self.__drive_query(parent_id, fileName, stopDup, isRecur, itemType) + if not response["files"]: + if noMulti: + break + else: + continue + if not Title: + msg += '' \ + f'

Search Result For {fileName}

' + Title = True + if len(DRIVES_NAMES) > 1 and DRIVES_NAMES[index] is not None: + msg += '' \ + f'{DRIVES_NAMES[index]}' + for file in response.get('files', []): + mime_type = file.get('mimeType') + if mime_type == "application/vnd.google-apps.folder": + furl = f"https://drive.google.com/drive/folders/{file.get('id')}" + msg += '' \ + f"
📁 {file.get('name')} (folder)
" \ + '