diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54eb9a69bf4bb3aee67592c5dec4cf8efd118a6a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM anasty17/mltb:latest + +WORKDIR /app +RUN chmod 777 /app + +RUN python3 -m venv mltbenv + +COPY requirements.txt . +RUN mltbenv/bin/pip install --no-cache-dir -r requirements.txt + +COPY . . + +RUN sed -i 's/\r$//' *.sh + +CMD ["bash", "start.sh"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000000000000000000000000000000000000..ddeb671b60b62a185d59d29ba6f6253e0f7f7a6e --- /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 0000000000000000000000000000000000000000..fdab364be7d855a4a1bba11bf427a63baee61035 --- /dev/null +++ b/add_to_team_drive.py @@ -0,0 +1,104 @@ +from __future__ import print_function + +import argparse +import glob +import googleapiclient.discovery +import json +import os +import pickle +import progress.bar +import sys +import time +from google.auth.transport.requests import Request +from google_auth_oauthlib.flow import InstalledAppFlow + +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(f"{acc_dir}/*.json") +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)) diff --git a/aria-nox-nzb.sh b/aria-nox-nzb.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a7e7dc238f3c277345a8b5548c38d58b42ff8f7 --- /dev/null +++ b/aria-nox-nzb.sh @@ -0,0 +1,11 @@ +tracker_list=$(curl -Ns https://ngosang.github.io/trackerslist/trackers_all_http.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-tracker="[$tracker_list]" --bt-max-peers=0 --enable-rpc=true \ + --rpc-max-request-size=1024M --max-connection-per-server=10 --max-concurrent-downloads=1000 --split=10 \ + --seed-ratio=0 --check-integrity=true --continue=true --daemon=true --disk-cache=40M --force-save=true \ + --min-split-size=10M --follow-torrent=mem --check-certificate=false --optimize-concurrent-downloads=true \ + --http-accept-gzip=true --max-file-not-found=0 --max-tries=20 --peer-id-prefix=-qB4520- --reuse-uri=true \ + --content-disposition-default-utf8=true --user-agent=Wget/1.12 --peer-agent=qBittorrent/4.5.2 --quiet=true \ + --summary-interval=0 --max-upload-limit=1K +qbittorrent-nox -d --profile="$(pwd)" +sabnzbdplus -f sabnzbd/SABnzbd.ini -s :::8070 -b 0 -d -c -l 0 --console \ No newline at end of file diff --git a/bot/__init__.py b/bot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd89dcb501b253552196260a8d8b44b306abe21 --- /dev/null +++ b/bot/__init__.py @@ -0,0 +1,80 @@ +from uvloop import install + +install() +from apscheduler.schedulers.asyncio import AsyncIOScheduler +from asyncio import Lock, new_event_loop, set_event_loop +from logging import ( + getLogger, + FileHandler, + StreamHandler, + INFO, + basicConfig, + WARNING, + ERROR, +) +from sabnzbdapi import SabnzbdClient +from time import time +from os import cpu_count + +getLogger("requests").setLevel(WARNING) +getLogger("urllib3").setLevel(WARNING) +getLogger("pyrogram").setLevel(ERROR) +getLogger("httpx").setLevel(WARNING) +getLogger("pymongo").setLevel(WARNING) +getLogger("aiohttp").setLevel(WARNING) + +bot_start_time = time() + +bot_loop = new_event_loop() +set_event_loop(bot_loop) + +basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[FileHandler("log.txt"), StreamHandler()], + level=INFO, +) + +LOGGER = getLogger(__name__) +cpu_no = cpu_count() +threads = max(1, cpu_no // 2) +cores = ",".join(str(i) for i in reversed(range(threads))) + +DOWNLOAD_DIR = "/app/downloads/" +intervals = {"status": {}, "qb": "", "jd": "", "nzb": "", "stopAll": False} +qb_torrents = {} +jd_downloads = {} +nzb_jobs = {} +user_data = {} +aria2_options = {} +qbit_options = {} +nzb_options = {} +queued_dl = {} +queued_up = {} +status_dict = {} +task_dict = {} +rss_dict = {} +auth_chats = {} +excluded_extensions = ["aria2", "!qB"] +included_extensions = [] +drives_names = [] +drives_ids = [] +index_urls = [] +sudo_users = [] +non_queued_dl = set() +non_queued_up = set() +multi_tags = set() +task_dict_lock = Lock() +queue_dict_lock = Lock() +qb_listener_lock = Lock() +nzb_listener_lock = Lock() +jd_listener_lock = Lock() +cpu_eater_lock = Lock() +same_directory_lock = Lock() + +sabnzbd_client = SabnzbdClient( + host="http://localhost", + api_key="mltb", + port="8070", +) + +scheduler = AsyncIOScheduler(event_loop=bot_loop) diff --git a/bot/__main__.py b/bot/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..172aebc9d131fd3a12aea1f10a8f644a47156e8a --- /dev/null +++ b/bot/__main__.py @@ -0,0 +1,66 @@ +from . import LOGGER, bot_loop +from .core.telegram_manager import TgClient +from .core.config_manager import Config + +Config.load() + + +async def main(): + from asyncio import gather + from .core.startup import ( + load_settings, + load_configurations, + save_settings, + update_aria2_options, + update_nzb_options, + update_qb_options, + update_variables, + ) + + await load_settings() + + await gather(TgClient.start_bot(), TgClient.start_user()) + await gather(load_configurations(), update_variables()) + + from .core.torrent_manager import TorrentManager + + await TorrentManager.initiate() + await gather( + update_qb_options(), + update_aria2_options(), + update_nzb_options(), + ) + from .helper.ext_utils.files_utils import clean_all + from .core.jdownloader_booter import jdownloader + from .helper.ext_utils.telegraph_helper import telegraph + from .helper.mirror_leech_utils.rclone_utils.serve import rclone_serve_booter + from .modules import ( + initiate_search_tools, + get_packages_version, + restart_notification, + ) + + await gather( + save_settings(), + jdownloader.boot(), + clean_all(), + initiate_search_tools(), + get_packages_version(), + restart_notification(), + telegraph.create_account(), + rclone_serve_booter(), + ) + + +bot_loop.run_until_complete(main()) + +from .helper.ext_utils.bot_utils import create_help_buttons +from .helper.listeners.aria2_listener import add_aria2_callbacks +from .core.handlers import add_handlers + +add_aria2_callbacks() +create_help_buttons() +add_handlers() + +LOGGER.info("Bot Started!") +bot_loop.run_forever() diff --git a/bot/core/__init__.py b/bot/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/core/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/core/config_manager.py b/bot/core/config_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..4a17f660ce2962ba8a72edeea209b1b77c740c9c --- /dev/null +++ b/bot/core/config_manager.py @@ -0,0 +1,240 @@ +from importlib import import_module +from ast import literal_eval +from os import getenv + +from bot import LOGGER + + +class Config: + AS_DOCUMENT = False + AUTHORIZED_CHATS = "" + BASE_URL = "" + BASE_URL_PORT = 80 + BOT_TOKEN = "" + CMD_SUFFIX = "" + CLONE_DUMP_CHATS = "" + DATABASE_URL = "" + DATABASE_NAME = "mltb" + DEFAULT_UPLOAD = "rc" + EQUAL_SPLITS = False + EXCLUDED_EXTENSIONS = "" + INCLUDED_EXTENSIONS = "" + FFMPEG_CMDS = {} + FILELION_API = "" + FILES_LINKS = False + GDRIVE_ID = "" + INCOMPLETE_TASK_NOTIFIER = False + INDEX_URL = "" + IS_TEAM_DRIVE = False + JD_EMAIL = "" + JD_PASS = "" + LEECH_DUMP_CHAT = "" + LEECH_FILENAME_PREFIX = "" + LEECH_SPLIT_SIZE = 2097152000 + MEDIA_GROUP = False + HYBRID_LEECH = False + HYDRA_IP = "" + HYDRA_API_KEY = "" + NAME_SUBSTITUTE = r"" + OWNER_ID = 0 + QUEUE_ALL = 0 + QUEUE_DOWNLOAD = 0 + QUEUE_UPLOAD = 0 + RCLONE_FLAGS = "" + RCLONE_PATH = "" + RCLONE_SERVE_URL = "" + RCLONE_SERVE_USER = "" + RCLONE_SERVE_PASS = "" + RCLONE_SERVE_PORT = 8080 + RSS_CHAT = "" + RSS_DELAY = 600 + RSS_SIZE_LIMIT = 0 + SEARCH_API_LINK = "" + SEARCH_LIMIT = 0 + SEARCH_PLUGINS = [] + STATUS_LIMIT = 4 + STATUS_UPDATE_INTERVAL = 15 + STOP_DUPLICATE = False + STREAMWISH_API = "" + SUDO_USERS = "" + TELEGRAM_API = 0 + TELEGRAM_HASH = "" + TG_PROXY = {} + THUMBNAIL_LAYOUT = "" + TORRENT_TIMEOUT = 0 + UPLOAD_PATHS = {} + UPSTREAM_REPO = "" + UPSTREAM_BRANCH = "master" + USENET_SERVERS = [] + USER_SESSION_STRING = "" + USER_TRANSMISSION = False + USE_SERVICE_ACCOUNTS = False + WEB_PINCODE = False + YT_DLP_OPTIONS = {} + + @classmethod + def _convert(cls, key: str, value): + if not hasattr(cls, key): + raise KeyError(f"{key} is not a valid configuration key.") + + expected_type = type(getattr(cls, key)) + + if value is None: + return None + + if isinstance(value, expected_type): + return value + + if expected_type is bool: + return str(value).strip().lower() in {"true", "1", "yes"} + + if expected_type in [list, dict]: + if not isinstance(value, str): + raise TypeError( + f"{key} should be {expected_type.__name__}, got {type(value).__name__}" + ) + + if not value: + return expected_type() + + try: + evaluated = literal_eval(value) + if not isinstance(evaluated, expected_type): + raise TypeError( + f"Expected {expected_type.__name__}, got {type(evaluated).__name__}" + ) + return evaluated + except (ValueError, SyntaxError, TypeError) as e: + raise TypeError( + f"{key} should be {expected_type.__name__}, got invalid string: {value}" + ) from e + + try: + return expected_type(value) + except (ValueError, TypeError) as exc: + raise TypeError( + f"Invalid type for {key}: expected {expected_type}, got {type(value)}" + ) from exc + + @classmethod + def get(cls, key: str): + return getattr(cls, key, None) + + @classmethod + def set(cls, key: str, value) -> None: + if not hasattr(cls, key): + raise KeyError(f"{key} is not a valid configuration key.") + + converted_value = cls._convert(key, value) + setattr(cls, key, converted_value) + + @classmethod + def get_all(cls): + return { + key: getattr(cls, key) + for key in cls.__dict__.keys() + if not key.startswith("__") and not callable(getattr(cls, key)) + } + + @classmethod + def _is_valid_config_attr(cls, attr: str) -> bool: + if attr.startswith("__") or callable(getattr(cls, attr, None)): + return False + return hasattr(cls, attr) + + @classmethod + def _process_config_value(cls, attr: str, value): + if not value: + return None + + converted_value = cls._convert(attr, value) + + if isinstance(converted_value, str): + converted_value = converted_value.strip() + + if attr == "DEFAULT_UPLOAD" and converted_value != "gd": + return "rc" + + if attr in { + "BASE_URL", + "RCLONE_SERVE_URL", + "SEARCH_API_LINK", + }: + return converted_value.strip("/") if converted_value else "" + + if attr == "USENET_SERVERS" and ( + not converted_value or not converted_value[0].get("host") + ): + return None + + return converted_value + + @classmethod + def _load_from_module(cls) -> bool: + try: + settings = import_module("config") + except ModuleNotFoundError: + return False + + for attr in dir(settings): + if not cls._is_valid_config_attr(attr): + continue + + raw_value = getattr(settings, attr) + processed_value = cls._process_config_value(attr, raw_value) + + if processed_value is not None: + setattr(cls, attr, processed_value) + + return True + + @classmethod + def _load_from_env(cls) -> None: + for attr in dir(cls): + if not cls._is_valid_config_attr(attr): + continue + + env_value = getenv(attr) + if env_value is None: + continue + + processed_value = cls._process_config_value(attr, env_value) + if processed_value is not None: + setattr(cls, attr, processed_value) + + @classmethod + def _validate_required_config(cls) -> None: + required_keys = ["BOT_TOKEN", "OWNER_ID", "TELEGRAM_API", "TELEGRAM_HASH"] + + for key in required_keys: + value = getattr(cls, key) + if isinstance(value, str): + value = value.strip() + if not value: + raise ValueError(f"{key} variable is missing!") + + @classmethod + def load(cls) -> None: + if not cls._load_from_module(): + LOGGER.info( + "Config module not found, loading from environment variables..." + ) + cls._load_from_env() + + cls._validate_required_config() + + @classmethod + def load_dict(cls, config_dict) -> None: + for key, value in config_dict.items(): + if not hasattr(cls, key): + continue + + processed_value = cls._process_config_value(key, value) + + if key == "USENET_SERVERS" and processed_value is None: + processed_value = [] + + if processed_value is not None: + setattr(cls, key, processed_value) + + cls._validate_required_config() diff --git a/bot/core/handlers.py b/bot/core/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3c6bd00c664057be69f05a1fe7974c3ac63627 --- /dev/null +++ b/bot/core/handlers.py @@ -0,0 +1,321 @@ +from pyrogram.filters import command, regex +from pyrogram.handlers import MessageHandler, CallbackQueryHandler, EditedMessageHandler + +from ..modules import * +from ..helper.telegram_helper.bot_commands import BotCommands +from ..helper.telegram_helper.filters import CustomFilters +from .telegram_manager import TgClient + + +def add_handlers(): + TgClient.bot.add_handler( + MessageHandler( + authorize, + filters=command(BotCommands.AuthorizeCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + unauthorize, + filters=command(BotCommands.UnAuthorizeCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + add_sudo, + filters=command(BotCommands.AddSudoCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + remove_sudo, + filters=command(BotCommands.RmSudoCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + send_bot_settings, + filters=command(BotCommands.BotSetCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler( + edit_bot_settings, filters=regex("^botset") & CustomFilters.sudo + ) + ) + TgClient.bot.add_handler( + MessageHandler( + cancel, + filters=command(BotCommands.CancelTaskCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + cancel_all_buttons, + filters=command(BotCommands.CancelAllCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(cancel_all_update, filters=regex("^canall")) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(cancel_multi, filters=regex("^stopm")) + ) + TgClient.bot.add_handler( + MessageHandler( + clone_node, + filters=command(BotCommands.CloneCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + aioexecute, + filters=command(BotCommands.AExecCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + execute, + filters=command(BotCommands.ExecCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + clear, + filters=command(BotCommands.ClearLocalsCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + select, + filters=command(BotCommands.SelectCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(confirm_selection, filters=regex("^sel")) + ) + TgClient.bot.add_handler( + MessageHandler( + remove_from_queue, + filters=command(BotCommands.ForceStartCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + count_node, + filters=command(BotCommands.CountCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + delete_file, + filters=command(BotCommands.DeleteCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + gdrive_search, + filters=command(BotCommands.ListCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(select_type, filters=regex("^list_types")) + ) + TgClient.bot.add_handler(CallbackQueryHandler(arg_usage, filters=regex("^help"))) + TgClient.bot.add_handler( + MessageHandler( + mirror, + filters=command(BotCommands.MirrorCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + qb_mirror, + filters=command(BotCommands.QbMirrorCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + jd_mirror, + filters=command(BotCommands.JdMirrorCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + nzb_mirror, + filters=command(BotCommands.NzbMirrorCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + leech, + filters=command(BotCommands.LeechCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + qb_leech, + filters=command(BotCommands.QbLeechCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + jd_leech, + filters=command(BotCommands.JdLeechCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + nzb_leech, + filters=command(BotCommands.NzbLeechCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + get_rss_menu, + filters=command(BotCommands.RssCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler(CallbackQueryHandler(rss_listener, filters=regex("^rss"))) + TgClient.bot.add_handler( + MessageHandler( + run_shell, + filters=command(BotCommands.ShellCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + EditedMessageHandler( + run_shell, + filters=command(BotCommands.ShellCommand, case_sensitive=True) + & CustomFilters.owner, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + start, filters=command(BotCommands.StartCommand, case_sensitive=True) + ) + ) + TgClient.bot.add_handler( + MessageHandler( + log, + filters=command(BotCommands.LogCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + restart_bot, + filters=command(BotCommands.RestartCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler( + confirm_restart, filters=regex("^botrestart") & CustomFilters.sudo + ) + ) + TgClient.bot.add_handler( + MessageHandler( + ping, + filters=command(BotCommands.PingCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + bot_help, + filters=command(BotCommands.HelpCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + bot_stats, + filters=command(BotCommands.StatsCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + task_status, + filters=command(BotCommands.StatusCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(status_pages, filters=regex("^status")) + ) + TgClient.bot.add_handler( + MessageHandler( + torrent_search, + filters=command(BotCommands.SearchCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(torrent_search_update, filters=regex("^torser")) + ) + TgClient.bot.add_handler( + MessageHandler( + get_users_settings, + filters=command(BotCommands.UsersCommand, case_sensitive=True) + & CustomFilters.sudo, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + send_user_settings, + filters=command(BotCommands.UserSetCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + CallbackQueryHandler(edit_user_settings, filters=regex("^userset")) + ) + TgClient.bot.add_handler( + MessageHandler( + ytdl, + filters=command(BotCommands.YtdlCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + ytdl_leech, + filters=command(BotCommands.YtdlLeechCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) + TgClient.bot.add_handler( + MessageHandler( + hydra_search, + filters=command(BotCommands.NzbSearchCommand, case_sensitive=True) + & CustomFilters.authorized, + ) + ) diff --git a/bot/core/jdownloader_booter.py b/bot/core/jdownloader_booter.py new file mode 100644 index 0000000000000000000000000000000000000000..da4fac094523ab97c239a56d310242ab8937a2ef --- /dev/null +++ b/bot/core/jdownloader_booter.py @@ -0,0 +1,91 @@ +from aiofiles.os import path, makedirs, listdir, rename +from aioshutil import rmtree +from json import dump +from random import randint +from re import match + +from .. import LOGGER +from ..helper.ext_utils.bot_utils import cmd_exec, new_task +from .telegram_manager import TgClient +from .config_manager import Config +from myjd import MyJdApi + + +class JDownloader(MyJdApi): + def __init__(self): + super().__init__() + self._username = "" + self._password = "" + self._device_name = "" + self.is_connected = False + self.error = "JDownloader Credentials not provided!" + + @new_task + async def boot(self): + await cmd_exec(["pkill", "-9", "-f", "java"]) + if not Config.JD_EMAIL or not Config.JD_PASS: + self.is_connected = False + self.error = "JDownloader Credentials not provided!" + return + self.error = "Connecting... Try again after couple of seconds" + self._device_name = f"{randint(0, 1000)}@{TgClient.NAME}" + if await path.exists("/JDownloader/logs"): + LOGGER.info( + "Starting JDownloader... This might take up to 10 sec and might restart once if update available!" + ) + else: + LOGGER.info( + "Starting JDownloader... This might take up to 8 sec and might restart once after build!" + ) + jdata = { + "autoconnectenabledv2": True, + "password": Config.JD_PASS, + "devicename": f"{self._device_name}", + "email": Config.JD_EMAIL, + } + remote_data = { + "localapiserverheaderaccesscontrollalloworigin": "", + "deprecatedapiport": 3128, + "localapiserverheaderxcontenttypeoptions": "nosniff", + "localapiserverheaderxframeoptions": "DENY", + "externinterfaceenabled": True, + "deprecatedapilocalhostonly": True, + "localapiserverheaderreferrerpolicy": "no-referrer", + "deprecatedapienabled": True, + "localapiserverheadercontentsecuritypolicy": "default-src 'self'", + "jdanywhereapienabled": True, + "externinterfacelocalhostonly": False, + "localapiserverheaderxxssprotection": "1; mode=block", + } + await makedirs("/JDownloader/cfg", exist_ok=True) + with open( + "/JDownloader/cfg/org.jdownloader.api.myjdownloader.MyJDownloaderSettings.json", + "w", + ) as sf: + sf.truncate(0) + dump(jdata, sf) + with open( + "/JDownloader/cfg/org.jdownloader.api.RemoteAPIConfig.json", + "w", + ) as rf: + rf.truncate(0) + dump(remote_data, rf) + if not await path.exists("/JDownloader/JDownloader.jar"): + pattern = r"JDownloader\.jar\.backup.\d$" + for filename in await listdir("/JDownloader"): + if match(pattern, filename): + await rename( + f"/JDownloader/{filename}", "/JDownloader/JDownloader.jar" + ) + break + await rmtree("/JDownloader/update") + await rmtree("/JDownloader/tmp") + cmd = "java -Dsun.jnu.encoding=UTF-8 -Dfile.encoding=UTF-8 -Djava.awt.headless=true -jar /JDownloader/JDownloader.jar" + self.is_connected = True + _, __, code = await cmd_exec(cmd, shell=True) + self.is_connected = False + if code != -9: + await self.boot() + + +jdownloader = JDownloader() diff --git a/bot/core/startup.py b/bot/core/startup.py new file mode 100644 index 0000000000000000000000000000000000000000..160246b3398be5f10089828bb55b5f1e4ed9a9f9 --- /dev/null +++ b/bot/core/startup.py @@ -0,0 +1,288 @@ +from aiofiles.os import path as aiopath, remove, makedirs +from aiofiles import open as aiopen +from aioshutil import rmtree +from asyncio import create_subprocess_exec, create_subprocess_shell, sleep +from importlib import import_module + +from .. import ( + aria2_options, + qbit_options, + nzb_options, + drives_ids, + drives_names, + index_urls, + user_data, + excluded_extensions, + included_extensions, + LOGGER, + rss_dict, + sabnzbd_client, + auth_chats, + sudo_users, +) +from ..helper.ext_utils.db_handler import database +from .config_manager import Config +from .telegram_manager import TgClient +from .torrent_manager import TorrentManager + + +async def update_qb_options(): + LOGGER.info("Get qBittorrent options from server") + if not qbit_options: + opt = await TorrentManager.qbittorrent.app.preferences() + qbit_options.update(opt) + del qbit_options["listen_port"] + for k in list(qbit_options.keys()): + if k.startswith("rss"): + del qbit_options[k] + qbit_options["web_ui_password"] = "mltbmltb" + await TorrentManager.qbittorrent.app.set_preferences( + {"web_ui_password": "mltbmltb"} + ) + else: + await TorrentManager.qbittorrent.app.set_preferences(qbit_options) + + +async def update_aria2_options(): + LOGGER.info("Get aria2 options from server") + if not aria2_options: + op = await TorrentManager.aria2.getGlobalOption() + aria2_options.update(op) + else: + await TorrentManager.aria2.changeGlobalOption(aria2_options) + + +async def update_nzb_options(): + LOGGER.info("Get SABnzbd options from server") + while True: + try: + no = (await sabnzbd_client.get_config())["config"]["misc"] + nzb_options.update(no) + except: + await sleep(0.5) + continue + break + + +async def load_settings(): + if not Config.DATABASE_URL: + return + + for p in ["thumbnails", "tokens", "rclone"]: + if await aiopath.exists(p): + await rmtree(p, ignore_errors=True) + + await database.connect() + if database.db is None: + return + + BOT_ID = Config.BOT_TOKEN.split(":", 1)[0] + + try: + settings = import_module("config") + config_file = { + key: value.strip() if isinstance(value, str) else value + for key, value in vars(settings).items() + if not key.startswith("__") + } + except ModuleNotFoundError: + config_file = {} + + old_config = await database.db.settings.deployConfig.find_one( + {"_id": BOT_ID}, {"_id": 0} + ) + if old_config is None and config_file: + await database.db.settings.deployConfig.replace_one( + {"_id": BOT_ID}, config_file, upsert=True + ) + elif old_config and config_file and old_config != config_file: + LOGGER.info("Replacing existing deploy config in Database") + await database.db.settings.deployConfig.replace_one( + {"_id": BOT_ID}, config_file, upsert=True + ) + else: + config_dict = await database.db.settings.config.find_one( + {"_id": BOT_ID}, {"_id": 0} + ) + if config_dict: + Config.load_dict(config_dict) + + if pf_dict := await database.db.settings.files.find_one( + {"_id": BOT_ID}, {"_id": 0} + ): + for key, value in pf_dict.items(): + if value: + file_ = key.replace("__", ".") + async with aiopen(file_, "wb+") as f: + await f.write(value) + + if a2c_options := await database.db.settings.aria2c.find_one( + {"_id": BOT_ID}, {"_id": 0} + ): + aria2_options.update(a2c_options) + + if qbit_opt := await database.db.settings.qbittorrent.find_one( + {"_id": BOT_ID}, {"_id": 0} + ): + qbit_options.update(qbit_opt) + + if nzb_opt := await database.db.settings.nzb.find_one({"_id": BOT_ID}, {"_id": 0}): + if await aiopath.exists("sabnzbd/SABnzbd.ini.bak"): + await remove("sabnzbd/SABnzbd.ini.bak") + ((key, value),) = nzb_opt.items() + file_ = key.replace("__", ".") + async with aiopen(f"sabnzbd/{file_}", "wb+") as f: + await f.write(value) + + if await database.db.users.find_one(): + for p in ["thumbnails", "tokens", "rclone"]: + if not await aiopath.exists(p): + await makedirs(p) + rows = database.db.users.find({}) + async for row in rows: + uid = row["_id"] + del row["_id"] + thumb_path = f"thumbnails/{uid}.jpg" + rclone_config_path = f"rclone/{uid}.conf" + token_path = f"tokens/{uid}.pickle" + if row.get("THUMBNAIL"): + async with aiopen(thumb_path, "wb+") as f: + await f.write(row["THUMBNAIL"]) + row["THUMBNAIL"] = thumb_path + if row.get("RCLONE_CONFIG"): + async with aiopen(rclone_config_path, "wb+") as f: + await f.write(row["RCLONE_CONFIG"]) + row["RCLONE_CONFIG"] = rclone_config_path + if row.get("TOKEN_PICKLE"): + async with aiopen(token_path, "wb+") as f: + await f.write(row["TOKEN_PICKLE"]) + row["TOKEN_PICKLE"] = token_path + user_data[uid] = row + LOGGER.info("Users data has been imported from Database") + + if await database.db.rss[BOT_ID].find_one(): + rows = database.db.rss[BOT_ID].find({}) + async for row in rows: + user_id = row["_id"] + del row["_id"] + rss_dict[user_id] = row + LOGGER.info("Rss data has been imported from Database.") + + +async def save_settings(): + if database.db is None: + return + config_dict = Config.get_all() + await database.db.settings.config.replace_one( + {"_id": TgClient.ID}, config_dict, upsert=True + ) + if await database.db.settings.aria2c.find_one({"_id": TgClient.ID}) is None: + await database.db.settings.aria2c.update_one( + {"_id": TgClient.ID}, {"$set": aria2_options}, upsert=True + ) + if await database.db.settings.qbittorrent.find_one({"_id": TgClient.ID}) is None: + await database.save_qbit_settings() + if await database.db.settings.nzb.find_one({"_id": TgClient.ID}) is None: + async with aiopen("sabnzbd/SABnzbd.ini", "rb+") as pf: + nzb_conf = await pf.read() + await database.db.settings.nzb.update_one( + {"_id": TgClient.ID}, {"$set": {"SABnzbd__ini": nzb_conf}}, upsert=True + ) + + +async def update_variables(): + if ( + Config.LEECH_SPLIT_SIZE > TgClient.MAX_SPLIT_SIZE + or Config.LEECH_SPLIT_SIZE == 2097152000 + or not Config.LEECH_SPLIT_SIZE + ): + Config.LEECH_SPLIT_SIZE = TgClient.MAX_SPLIT_SIZE + + Config.HYBRID_LEECH = bool(Config.HYBRID_LEECH and TgClient.IS_PREMIUM_USER) + Config.USER_TRANSMISSION = bool( + Config.USER_TRANSMISSION and TgClient.IS_PREMIUM_USER + ) + + if Config.AUTHORIZED_CHATS: + aid = Config.AUTHORIZED_CHATS.split() + for id_ in aid: + chat_id, *thread_ids = id_.split("|") + chat_id = int(chat_id.strip()) + if thread_ids: + thread_ids = list(map(lambda x: int(x.strip()), thread_ids)) + auth_chats[chat_id] = thread_ids + else: + auth_chats[chat_id] = [] + + if Config.SUDO_USERS: + aid = Config.SUDO_USERS.split() + for id_ in aid: + sudo_users.append(int(id_.strip())) + + if Config.EXCLUDED_EXTENSIONS: + fx = Config.EXCLUDED_EXTENSIONS.split() + for x in fx: + x = x.lstrip(".") + excluded_extensions.append(x.strip().lower()) + + if Config.INCLUDED_EXTENSIONS: + fx = Config.INCLUDED_EXTENSIONS.split() + for x in fx: + x = x.lstrip(".") + included_extensions.append(x.strip().lower()) + + if Config.GDRIVE_ID: + drives_names.append("Main") + drives_ids.append(Config.GDRIVE_ID) + index_urls.append(Config.INDEX_URL) + + if await aiopath.exists("list_drives.txt"): + async with aiopen("list_drives.txt", "r+") as f: + lines = await f.readlines() + for line in lines: + temp = line.split() + drives_ids.append(temp[1]) + drives_names.append(temp[0].replace("_", " ")) + if len(temp) > 2: + index_urls.append(temp[2]) + else: + index_urls.append("") + + +async def load_configurations(): + + if not await aiopath.exists(".netrc"): + async with aiopen(".netrc", "w"): + pass + + await ( + await create_subprocess_shell( + "chmod 600 .netrc && cp .netrc /root/.netrc && chmod +x aria-nox-nzb.sh && ./aria-nox-nzb.sh" + ) + ).wait() + + if Config.BASE_URL: + await create_subprocess_shell( + f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{Config.BASE_URL_PORT}" + ) + + if await aiopath.exists("cfg.zip"): + if await aiopath.exists("/JDownloader/cfg"): + await rmtree("/JDownloader/cfg", ignore_errors=True) + await ( + await create_subprocess_exec("7z", "x", "cfg.zip", "-o/JDownloader") + ).wait() + + if await aiopath.exists("accounts.zip"): + if await aiopath.exists("accounts"): + await rmtree("accounts") + await ( + await create_subprocess_exec( + "7z", "x", "-o.", "-aoa", "accounts.zip", "accounts/*.json" + ) + ).wait() + await (await create_subprocess_exec("chmod", "-R", "777", "accounts")).wait() + await remove("accounts.zip") + + if not await aiopath.exists("accounts"): + Config.USE_SERVICE_ACCOUNTS = False diff --git a/bot/core/telegram_manager.py b/bot/core/telegram_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..ec74048feaa42301d65ebadd618f34c3006c58a7 --- /dev/null +++ b/bot/core/telegram_manager.py @@ -0,0 +1,82 @@ +from pyrogram import Client, enums +from pyrogram.types import LinkPreviewOptions +from asyncio import Lock + +from .. import LOGGER +from .config_manager import Config + + +class TgClient: + _lock = Lock() + bot = None + user = None + NAME = "" + ID = 0 + IS_PREMIUM_USER = False + MAX_SPLIT_SIZE = 2097152000 + + @classmethod + async def start_bot(cls): + LOGGER.info("Creating client from BOT_TOKEN") + cls.ID = Config.BOT_TOKEN.split(":", 1)[0] + cls.bot = Client( + cls.ID, + Config.TELEGRAM_API, + Config.TELEGRAM_HASH, + proxy=Config.TG_PROXY, + bot_token=Config.BOT_TOKEN, + workdir="/app", + parse_mode=enums.ParseMode.HTML, + max_concurrent_transmissions=10, + max_message_cache_size=15000, + max_topic_cache_size=15000, + sleep_threshold=0, + link_preview_options=LinkPreviewOptions(is_disabled=True), + ) + await cls.bot.start() + cls.NAME = cls.bot.me.username + + @classmethod + async def start_user(cls): + if Config.USER_SESSION_STRING: + LOGGER.info("Creating client from USER_SESSION_STRING") + try: + cls.user = Client( + "user", + Config.TELEGRAM_API, + Config.TELEGRAM_HASH, + proxy=Config.TG_PROXY, + session_string=Config.USER_SESSION_STRING, + workdir="/app", + parse_mode=enums.ParseMode.HTML, + sleep_threshold=60, + max_concurrent_transmissions=10, + max_message_cache_size=15000, + max_topic_cache_size=15000, + link_preview_options=LinkPreviewOptions(is_disabled=True), + ) + await cls.user.start() + cls.IS_PREMIUM_USER = cls.user.me.is_premium + if cls.IS_PREMIUM_USER: + cls.MAX_SPLIT_SIZE = 4194304000 + except Exception as e: + LOGGER.error(f"Failed to start client from USER_SESSION_STRING. {e}") + cls.IS_PREMIUM_USER = False + cls.user = None + + @classmethod + async def stop(cls): + async with cls._lock: + if cls.bot: + await cls.bot.stop() + if cls.user: + await cls.user.stop() + LOGGER.info("Client(s) stopped") + + @classmethod + async def reload(cls): + async with cls._lock: + await cls.bot.restart() + if cls.user: + await cls.user.restart() + LOGGER.info("Client(s) restarted") diff --git a/bot/core/torrent_manager.py b/bot/core/torrent_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..e25dd09c50db191e126d71187ba67a56a6c0542d --- /dev/null +++ b/bot/core/torrent_manager.py @@ -0,0 +1,134 @@ +from aioaria2 import Aria2WebsocketClient +from aioqbt.client import create_client +from asyncio import gather, TimeoutError +from aiohttp import ClientError +from pathlib import Path +from inspect import iscoroutinefunction +from tenacity import ( + retry, + stop_after_attempt, + wait_exponential, + retry_if_exception_type, +) + +from .. import LOGGER, aria2_options + + +def wrap_with_retry(obj, max_retries=3): + for attr_name in dir(obj): + if attr_name.startswith("_"): + continue + + attr = getattr(obj, attr_name) + if iscoroutinefunction(attr): + retry_policy = retry( + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=1, min=1, max=5), + retry=retry_if_exception_type( + (ClientError, TimeoutError, RuntimeError) + ), + ) + wrapped = retry_policy(attr) + setattr(obj, attr_name, wrapped) + return obj + + +class TorrentManager: + aria2 = None + qbittorrent = None + + @classmethod + async def initiate(cls): + cls.aria2, cls.qbittorrent = await gather( + Aria2WebsocketClient.new("http://localhost:6800/jsonrpc"), + create_client("http://localhost:8090/api/v2/"), + ) + cls.qbittorrent = wrap_with_retry(cls.qbittorrent) + + @classmethod + async def close_all(cls): + await gather(cls.aria2.close(), cls.qbittorrent.close()) + + @classmethod + async def aria2_remove(cls, download): + if download.get("status", "") in ["active", "paused", "waiting"]: + await cls.aria2.forceRemove(download.get("gid", "")) + else: + try: + await cls.aria2.removeDownloadResult(download.get("gid", "")) + except: + pass + + @classmethod + async def remove_all(cls): + await cls.pause_all() + await gather( + cls.qbittorrent.torrents.delete("all", False), + cls.aria2.purgeDownloadResult(), + ) + downloads = [] + results = await gather(cls.aria2.tellActive(), cls.aria2.tellWaiting(0, 1000)) + for res in results: + downloads.extend(res) + tasks = [] + tasks.extend( + cls.aria2.forceRemove(download.get("gid")) for download in downloads + ) + try: + await gather(*tasks) + except: + pass + + @classmethod + async def overall_speed(cls): + s1, s2 = await gather( + cls.qbittorrent.transfer.info(), cls.aria2.getGlobalStat() + ) + download_speed = s1.dl_info_speed + int(s2.get("downloadSpeed", "0")) + upload_speed = s1.up_info_speed + int(s2.get("uploadSpeed", "0")) + return download_speed, upload_speed + + @classmethod + async def pause_all(cls): + await gather(cls.aria2.forcePauseAll(), cls.qbittorrent.torrents.stop("all")) + + @classmethod + async def change_aria2_option(cls, key, value): + downloads = [] + results = await gather(cls.aria2.tellActive(), cls.aria2.tellWaiting(0, 1000)) + for res in results: + downloads.extend(res) + tasks = [] + for download in downloads: + if download.get("status", "") != "complete": + tasks.append(cls.aria2.changeOption(download.get("gid"), {key: value})) + if tasks: + try: + await gather(*tasks) + except Exception as e: + LOGGER.error(e) + if key not in ["checksum", "index-out", "out", "pause", "select-file"]: + await cls.aria2.changeGlobalOption({key: value}) + aria2_options[key] = value + + +def aria2_name(download_info): + if "bittorrent" in download_info and download_info["bittorrent"].get("info"): + return download_info["bittorrent"]["info"]["name"] + elif download_info.get("files"): + if download_info["files"][0]["path"].startswith("[METADATA]"): + return download_info["files"][0]["path"] + file_path = download_info["files"][0]["path"] + dir_path = download_info["dir"] + if file_path.startswith(dir_path): + return Path(file_path[len(dir_path) + 1 :]).parts[0] + else: + return "" + else: + return "" + + +def is_metadata(download_info): + return any( + f["path"].startswith("[METADATA]") for f in download_info.get("files", []) + ) diff --git a/bot/helper/__init__.py b/bot/helper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/common.py b/bot/helper/common.py new file mode 100644 index 0000000000000000000000000000000000000000..dea985ba81af93ccaabcb23d945cb0c6f89520fc --- /dev/null +++ b/bot/helper/common.py @@ -0,0 +1,1217 @@ +from aiofiles.os import path as aiopath, remove, makedirs, listdir +from aiofiles import open as aiopen +from asyncio import sleep, gather +from os import walk, path as ospath +from secrets import token_urlsafe +from aioshutil import move, rmtree +from pyrogram.enums import ChatAction +from re import sub, I, findall +from shlex import split +from collections import Counter +from copy import deepcopy +from natsort import natsorted + +from .. import ( + user_data, + multi_tags, + LOGGER, + task_dict_lock, + task_dict, + excluded_extensions, + included_extensions, + cpu_eater_lock, + intervals, + DOWNLOAD_DIR, + cores, +) +from ..core.config_manager import Config +from ..core.telegram_manager import TgClient +from .ext_utils.bot_utils import new_task, sync_to_async, get_size_bytes +from .ext_utils.bulk_links import extract_bulk_links +from .mirror_leech_utils.gdrive_utils.list import GoogleDriveList +from .mirror_leech_utils.rclone_utils.list import RcloneList +from .mirror_leech_utils.status_utils.sevenz_status import SevenZStatus +from .mirror_leech_utils.status_utils.ffmpeg_status import FFmpegStatus +from .telegram_helper.bot_commands import BotCommands +from .ext_utils.files_utils import ( + get_base_name, + is_first_archive_split, + is_archive, + is_archive_split, + get_path_size, + split_file, + SevenZ, +) +from .ext_utils.links_utils import ( + is_gdrive_id, + is_rclone_path, + is_gdrive_link, + is_telegram_link, +) +from .ext_utils.media_utils import ( + create_thumb, + take_ss, + get_document_type, + FFMpeg, + ffconcat_escape, +) +from .telegram_helper.message_utils import ( + send_message, + send_status_message, + get_tg_link_message, + temp_download, +) + + +class TaskConfig: + def __init__(self): + self.mid = self.message.id + self.user = self.message.from_user or self.message.sender_chat + self.user_id = self.user.id + self.user_dict = user_data.get(self.user_id, {}) + self.clone_dump_chats = {} + self.dir = f"{DOWNLOAD_DIR}{self.mid}" + self.up_dir = "" + self.link = "" + self.up_dest = "" + self.rc_flags = "" + self.tag = "" + self.name = "" + self.subname = "" + self.name_sub = "" + self.thumbnail_layout = "" + self.folder_name = "" + self.split_size = 0 + self.max_split_size = 0 + self.multi = 0 + self.size = 0 + self.subsize = 0 + self.proceed_count = 0 + self.is_leech = False + self.is_qbit = False + self.is_nzb = False + self.is_jd = False + self.is_clone = False + self.is_ytdlp = False + self.equal_splits = False + self.user_transmission = False + self.hybrid_leech = False + self.extract = False + self.compress = False + self.select = False + self.seed = False + self.compress = False + self.extract = False + self.join = False + self.private_link = False + self.stop_duplicate = False + self.sample_video = False + self.convert_audio = False + self.convert_video = False + self.screen_shots = False + self.is_cancelled = False + self.force_run = False + self.force_download = False + self.force_upload = False + self.is_torrent = False + self.as_med = False + self.as_doc = False + self.is_file = False + self.bot_trans = False + self.user_trans = False + self.is_rss = False + self.progress = True + self.ffmpeg_cmds = None + self.chat_thread_id = None + self.subproc = None + self.thumb = None + self.excluded_extensions = [] + self.included_extensions = [] + self.files_to_proceed = [] + self.is_super_chat = self.message.chat.type.name in [ + "SUPERGROUP", + "CHANNEL", + "FORUM", + ] + + def get_token_path(self, dest): + if dest.startswith("mtp:"): + return f"tokens/{self.user_id}.pickle" + elif ( + dest.startswith("sa:") + or Config.USE_SERVICE_ACCOUNTS + and not dest.startswith("tp:") + ): + return "accounts" + else: + return "token.pickle" + + def get_config_path(self, dest): + return ( + f"rclone/{self.user_id}.conf" if dest.startswith("mrcc:") else "rclone.conf" + ) + + async def is_token_exists(self, path, status): + if is_rclone_path(path): + config_path = self.get_config_path(path) + if config_path != "rclone.conf" and status == "up": + self.private_link = True + if not await aiopath.exists(config_path): + raise ValueError(f"Rclone Config: {config_path} not Exists!") + elif ( + status == "dl" + and is_gdrive_link(path) + or status == "up" + and is_gdrive_id(path) + ): + token_path = self.get_token_path(path) + if token_path.startswith("tokens/") and status == "up": + self.private_link = True + if not await aiopath.exists(token_path): + raise ValueError(f"NO TOKEN! {token_path} not Exists!") + + async def before_start(self): + self.name_sub = ( + self.name_sub + or self.user_dict.get("NAME_SUBSTITUTE", False) + or ( + Config.NAME_SUBSTITUTE + if "NAME_SUBSTITUTE" not in self.user_dict + else "" + ) + ) + if self.name_sub: + self.name_sub = [x.split("/") for x in self.name_sub.split(" | ")] + self.excluded_extensions = self.user_dict.get("EXCLUDED_EXTENSIONS") or ( + excluded_extensions + if "EXCLUDED_EXTENSIONS" not in self.user_dict + else ["aria2", "!qB"] + ) + self.included_extensions = self.user_dict.get("INCLUDED_EXTENSIONS") or ( + included_extensions if "INCLUDED_EXTENSIONS" not in self.user_dict else [] + ) + if not self.rc_flags: + if self.user_dict.get("RCLONE_FLAGS"): + self.rc_flags = self.user_dict["RCLONE_FLAGS"] + elif "RCLONE_FLAGS" not in self.user_dict and Config.RCLONE_FLAGS: + self.rc_flags = Config.RCLONE_FLAGS + if self.link not in ["rcl", "gdl"]: + if not self.is_jd: + if is_rclone_path(self.link): + if not self.link.startswith("mrcc:") and self.user_dict.get( + "USER_TOKENS", False + ): + self.link = f"mrcc:{self.link}" + await self.is_token_exists(self.link, "dl") + elif is_gdrive_link(self.link): + if not self.link.startswith( + ("mtp:", "tp:", "sa:") + ) and self.user_dict.get("USER_TOKENS", False): + self.link = f"mtp:{self.link}" + await self.is_token_exists(self.link, "dl") + elif self.link == "rcl": + if not self.is_ytdlp and not self.is_jd: + self.link = await RcloneList(self).get_rclone_path("rcd") + if not is_rclone_path(self.link): + raise ValueError(self.link) + elif self.link == "gdl": + if not self.is_ytdlp and not self.is_jd: + self.link = await GoogleDriveList(self).get_target_id("gdd") + if not is_gdrive_id(self.link): + raise ValueError(self.link) + + self.user_transmission = TgClient.IS_PREMIUM_USER and ( + self.user_dict.get("USER_TRANSMISSION") + or Config.USER_TRANSMISSION + and "USER_TRANSMISSION" not in self.user_dict + ) + + if self.user_dict.get("UPLOAD_PATHS", False): + if self.up_dest in self.user_dict["UPLOAD_PATHS"]: + self.up_dest = self.user_dict["UPLOAD_PATHS"][self.up_dest] + elif ( + "UPLOAD_PATHS" not in self.user_dict or not self.user_dict["UPLOAD_PATHS"] + ) and Config.UPLOAD_PATHS: + if self.up_dest in Config.UPLOAD_PATHS: + self.up_dest = Config.UPLOAD_PATHS[self.up_dest] + + if self.ffmpeg_cmds: + if self.user_dict.get("FFMPEG_CMDS", None): + ffmpeg_dict = deepcopy(self.user_dict["FFMPEG_CMDS"]) + elif ( + "FFMPEG_CMDS" not in self.user_dict or not self.user_dict["FFMPEG_CMDS"] + ) and Config.FFMPEG_CMDS: + ffmpeg_dict = deepcopy(Config.FFMPEG_CMDS) + else: + ffmpeg_dict = None + cmds = [] + for key in list(self.ffmpeg_cmds): + if isinstance(key, tuple): + cmds.extend(list(key)) + elif ffmpeg_dict is not None: + if key in ffmpeg_dict.keys(): + for ind, vl in enumerate(ffmpeg_dict[key]): + if variables := set(findall(r"\{(.*?)\}", vl)): + ff_values = ( + self.user_dict.get("FFMPEG_VARIABLES", {}) + .get(key, {}) + .get(str(ind), {}) + ) + if Counter(list(variables)) == Counter( + list(ff_values.keys()) + ): + cmds.append(vl.format(**ff_values)) + else: + cmds.append(vl) + self.ffmpeg_cmds = cmds + + if not self.is_leech: + self.stop_duplicate = ( + self.user_dict.get("STOP_DUPLICATE") + or "STOP_DUPLICATE" not in self.user_dict + and Config.STOP_DUPLICATE + ) + default_upload = ( + self.user_dict.get("DEFAULT_UPLOAD", "") or Config.DEFAULT_UPLOAD + ) + if (not self.up_dest and default_upload == "rc") or self.up_dest == "rc": + self.up_dest = self.user_dict.get("RCLONE_PATH") or Config.RCLONE_PATH + elif (not self.up_dest and default_upload == "gd") or self.up_dest == "gd": + self.up_dest = self.user_dict.get("GDRIVE_ID") or Config.GDRIVE_ID + if not self.up_dest: + raise ValueError("No Upload Destination!") + if self.up_dest not in ["rcl", "gdl"]: + if is_gdrive_id(self.up_dest): + if not self.up_dest.startswith( + ("mtp:", "tp:", "sa:") + ) and self.user_dict.get("USER_TOKENS", False): + self.up_dest = f"mtp:{self.up_dest}" + elif is_rclone_path(self.up_dest): + if not self.up_dest.startswith("mrcc:") and self.user_dict.get( + "USER_TOKENS", False + ): + self.up_dest = f"mrcc:{self.up_dest}" + self.up_dest = self.up_dest.strip("/") + else: + raise ValueError("Wrong Upload Destination!") + await self.is_token_exists(self.up_dest, "up") + + if self.up_dest == "rcl": + if self.is_clone: + if not is_rclone_path(self.link): + raise ValueError( + "You can't clone from different types of tools" + ) + config_path = self.get_config_path(self.link) + else: + config_path = None + self.up_dest = await RcloneList(self).get_rclone_path( + "rcu", config_path + ) + if not is_rclone_path(self.up_dest): + raise ValueError(self.up_dest) + elif self.up_dest == "gdl": + if self.is_clone: + if not is_gdrive_link(self.link): + raise ValueError( + "You can't clone from different types of tools" + ) + token_path = self.get_token_path(self.link) + else: + token_path = None + self.up_dest = await GoogleDriveList(self).get_target_id( + "gdu", token_path + ) + if not is_gdrive_id(self.up_dest): + raise ValueError(self.up_dest) + elif self.is_clone: + if is_gdrive_link(self.link) and self.get_token_path( + self.link + ) != self.get_token_path(self.up_dest): + raise ValueError("You must use the same token to clone!") + elif is_rclone_path(self.link) and self.get_config_path( + self.link + ) != self.get_config_path(self.up_dest): + raise ValueError("You must use the same config to clone!") + else: + self.up_dest = ( + self.up_dest + or self.user_dict.get("LEECH_DUMP_CHAT") + or ( + Config.LEECH_DUMP_CHAT + if "LEECH_DUMP_CHAT" not in self.user_dict + else None + ) + ) + self.hybrid_leech = TgClient.IS_PREMIUM_USER and ( + self.user_dict.get("HYBRID_LEECH") + or Config.HYBRID_LEECH + and "HYBRID_LEECH" not in self.user_dict + ) + if self.bot_trans: + self.user_transmission = False + self.hybrid_leech = False + if self.user_trans: + self.user_transmission = TgClient.IS_PREMIUM_USER + if self.up_dest: + if not isinstance(self.up_dest, int): + if self.up_dest.startswith("b:"): + self.up_dest = self.up_dest.replace("b:", "", 1) + self.user_transmission = False + self.hybrid_leech = False + elif self.up_dest.startswith("u:"): + self.up_dest = self.up_dest.replace("u:", "", 1) + self.user_transmission = TgClient.IS_PREMIUM_USER + elif self.up_dest.startswith("h:"): + self.up_dest = self.up_dest.replace("h:", "", 1) + self.user_transmission = TgClient.IS_PREMIUM_USER + self.hybrid_leech = self.user_transmission + if "|" in self.up_dest: + self.up_dest, self.chat_thread_id = list( + map( + lambda x: int(x) if x.lstrip("-").isdigit() else x, + self.up_dest.split("|", 1), + ) + ) + elif self.up_dest.lstrip("-").isdigit(): + self.up_dest = int(self.up_dest) + elif self.up_dest.lower() == "pm": + self.up_dest = self.user_id + + if self.user_transmission: + try: + chat = await TgClient.user.get_chat(self.up_dest) + except: + chat = None + if chat is None: + LOGGER.warning( + "Account of user session can't find the the destination chat!" + ) + self.user_transmission = False + self.hybrid_leech = False + else: + if chat.type.name not in [ + "SUPERGROUP", + "CHANNEL", + "GROUP", + "FORUM", + ]: + self.user_transmission = False + self.hybrid_leech = False + elif chat.is_admin: + member = await chat.get_member(TgClient.user.me.id) + if ( + not member.privileges.can_manage_chat + or not member.privileges.can_delete_messages + ): + self.user_transmission = False + self.hybrid_leech = False + LOGGER.warning( + "Enable manage chat and delete messages to account of the user session from administration settings!" + ) + else: + LOGGER.warning( + "Promote the account of the user session to admin in the chat to get the benefit of user transmission!" + ) + self.user_transmission = False + self.hybrid_leech = False + + if not self.user_transmission or self.hybrid_leech: + try: + chat = await self.client.get_chat(self.up_dest) + except: + chat = None + if chat is None: + if self.user_transmission: + self.hybrid_leech = False + else: + raise ValueError("Chat not found!") + else: + if chat.type.name in [ + "SUPERGROUP", + "CHANNEL", + "GROUP", + "FORUM", + ]: + if not chat.is_admin: + raise ValueError( + "Bot is not admin in the destination chat!" + ) + else: + member = await chat.get_member(self.client.me.id) + if ( + not member.privileges.can_manage_chat + or not member.privileges.can_delete_messages + ): + if not self.user_transmission: + raise ValueError( + "You don't have enough privileges in this chat! Enable manage chat and delete messages for this bot!" + ) + else: + self.hybrid_leech = False + else: + try: + await self.client.send_chat_action( + self.up_dest, ChatAction.TYPING + ) + except: + raise ValueError("Start the bot and try again!") + elif ( + self.user_transmission or self.hybrid_leech + ) and not self.is_super_chat: + self.user_transmission = False + self.hybrid_leech = False + if self.split_size: + if self.split_size.isdigit(): + self.split_size = int(self.split_size) + else: + self.split_size = get_size_bytes(self.split_size) + self.split_size = ( + self.split_size + or self.user_dict.get("LEECH_SPLIT_SIZE") + or Config.LEECH_SPLIT_SIZE + ) + self.equal_splits = ( + self.user_dict.get("EQUAL_SPLITS") + or Config.EQUAL_SPLITS + and "EQUAL_SPLITS" not in self.user_dict + ) + self.max_split_size = ( + TgClient.MAX_SPLIT_SIZE if self.user_transmission else 2097152000 + ) + self.split_size = min(self.split_size, self.max_split_size) + + if not self.as_doc: + self.as_doc = ( + not self.as_med + if self.as_med + else ( + self.user_dict.get("AS_DOCUMENT", False) + or Config.AS_DOCUMENT + and "AS_DOCUMENT" not in self.user_dict + ) + ) + + self.thumbnail_layout = ( + self.thumbnail_layout + or self.user_dict.get("THUMBNAIL_LAYOUT", False) + or ( + Config.THUMBNAIL_LAYOUT + if "THUMBNAIL_LAYOUT" not in self.user_dict + else "" + ) + ) + + self.clone_dump_chats = self.user_dict.get("CLONE_DUMP_CHATS", {}) or ( + Config.CLONE_DUMP_CHATS + if "CLONE_DUMP_CHATS" not in self.user_dict and Config.CLONE_DUMP_CHATS + else {} + ) + if self.clone_dump_chats: + if isinstance(self.clone_dump_chats, int): + self.clone_dump_chats = [self.clone_dump_chats] + elif isinstance(self.clone_dump_chats, str): + if self.clone_dump_chats.startswith( + "[" + ) and self.clone_dump_chats.endswith("]"): + self.clone_dump_chats = eval(self.clone_dump_chats) + else: + self.clone_dump_chats = [self.clone_dump_chats] + temp_dict = {} + for ch in self.clone_dump_chats: + if isinstance(ch, str) and "|" in ch: + ci, ti = map( + lambda x: int(x) if x.lstrip("-").isdigit() else x, + ch.split("|", 1), + ) + temp_dict[ci] = {"thread_id": ti, "last_sent_msg": None} + elif isinstance(ch, str): + if ch.lower() == "pm": + ci = self.user_id + else: + ci = int(ch) if ch.lstrip("-").isdigit() else ch + temp_dict[ci] = {"thread_id": None, "last_sent_msg": None} + else: + temp_dict[ch] = {"thread_id": None, "last_sent_msg": None} + self.clone_dump_chats = temp_dict + if self.thumb != "none" and is_telegram_link(self.thumb): + msg = (await get_tg_link_message(self.thumb))[0] + self.thumb = ( + await create_thumb(msg) if msg.photo or msg.document else "" + ) + + async def get_tag(self, text: list): + if len(text) > 1 and text[1].startswith("Tag: "): + self.is_rss = True + user_info = text[1].split("Tag: ") + if len(user_info) >= 3: + id_ = user_info[-1] + self.tag = " ".join(user_info[:-1]) + else: + self.tag, id_ = text[1].split("Tag: ")[1].split() + self.user = self.message.from_user = await self.client.get_users(int(id_)) + self.user_id = self.user.id + self.user_dict = user_data.get(self.user_id, {}) + try: + await self.message.unpin() + except: + pass + if self.user: + if username := self.user.username: + self.tag = f"@{username}" + elif hasattr(self.user, "mention"): + self.tag = self.user.mention + else: + self.tag = self.user.title + + @new_task + async def run_multi(self, input_list, obj): + await sleep(7) + if not self.multi_tag and self.multi > 1: + self.multi_tag = token_urlsafe(3) + multi_tags.add(self.multi_tag) + elif self.multi <= 1: + if self.multi_tag in multi_tags: + multi_tags.discard(self.multi_tag) + return + if self.multi_tag and self.multi_tag not in multi_tags: + await send_message( + self.message, f"{self.tag} Multi Task has been cancelled!" + ) + await send_status_message(self.message) + async with task_dict_lock: + for fd_name in self.same_dir: + self.same_dir[fd_name]["total"] -= self.multi + return + if len(self.bulk) != 0: + msg = input_list[:1] + msg.append(f"{self.bulk[0]} -i {self.multi - 1} {self.options}") + msgts = " ".join(msg) + if self.multi > 2: + msgts += f"\nCancel Multi: /{BotCommands.CancelTaskCommand[1]} {self.multi_tag}" + nextmsg = await send_message(self.message, msgts) + else: + msg = [s.strip() for s in input_list] + index = msg.index("-i") + msg[index + 1] = f"{self.multi - 1}" + nextmsg = await self.client.get_messages( + chat_id=self.message.chat.id, + message_ids=self.message.reply_to_message_id + 1, + ) + if nextmsg.empty: + await send_message( + self.message, + "Bot can't fetch old messages (older than 48H), forward those messages and try multi/bulk again!", + ) + await send_status_message(self.message) + return + msgts = " ".join(msg) + if self.multi > 2: + msgts += f"\nCancel Multi: /{BotCommands.CancelTaskCommand[1]} {self.multi_tag}" + nextmsg = await send_message(nextmsg, msgts) + if self.message.from_user: + nextmsg.from_user = self.user + else: + nextmsg.sender_chat = self.user + if intervals["stopAll"]: + return + await obj( + self.client, + nextmsg, + self.is_qbit, + self.is_leech, + self.is_jd, + self.is_nzb, + self.same_dir, + self.bulk, + self.multi_tag, + self.options, + ).new_event() + + async def init_bulk(self, input_list, bulk_start, bulk_end, obj): + try: + self.bulk = await extract_bulk_links(self.message, bulk_start, bulk_end) + if len(self.bulk) == 0: + raise ValueError("Bulk Empty!") + b_msg = input_list[:1] + self.options = input_list[1:] + index = self.options.index("-b") + del self.options[index] + if bulk_start or bulk_end: + del self.options[index] + self.options = " ".join(self.options) + b_msg.append(f"{self.bulk[0]} -i {len(self.bulk)} {self.options}") + msg = " ".join(b_msg) + if len(self.bulk) > 2: + self.multi_tag = token_urlsafe(3) + multi_tags.add(self.multi_tag) + msg += f"\nCancel Multi: /{BotCommands.CancelTaskCommand[1]} {self.multi_tag}" + nextmsg = await send_message(self.message, msg) + if self.message.from_user: + nextmsg.from_user = self.user + else: + nextmsg.sender_chat = self.user + await obj( + self.client, + nextmsg, + self.is_qbit, + self.is_leech, + self.is_jd, + self.is_nzb, + self.same_dir, + self.bulk, + self.multi_tag, + self.options, + ).new_event() + except Exception as e: + await send_message( + self.message, + f"Reply to text file or to telegram message that have links separated by new line! {e}", + ) + + async def proceed_extract(self, dl_path, gid): + pswd = self.extract if isinstance(self.extract, str) else "" + self.files_to_proceed = [] + if self.is_file and is_archive(dl_path): + self.files_to_proceed.append(dl_path) + else: + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + if ( + is_first_archive_split(file_) + or is_archive(file_) + and not file_.strip().lower().endswith(".rar") + ): + f_path = ospath.join(dirpath, file_) + self.files_to_proceed.append(f_path) + + if not self.files_to_proceed: + return dl_path + t_path = dl_path + sevenz = SevenZ(self) + LOGGER.info(f"Extracting: {self.name}") + async with task_dict_lock: + task_dict[self.mid] = SevenZStatus(self, sevenz, gid, "Extract") + for dirpath, _, files in await sync_to_async( + walk, self.up_dir or self.dir, topdown=False + ): + code = 0 + for file_ in files: + if self.is_cancelled: + return False + if ( + is_first_archive_split(file_) + or is_archive(file_) + and not file_.strip().lower().endswith(".rar") + ): + + self.proceed_count += 1 + f_path = ospath.join(dirpath, file_) + t_path = get_base_name(f_path) if self.is_file else dirpath + if not self.is_file: + self.subname = file_ + code = await sevenz.extract(f_path, t_path, pswd) + if self.is_cancelled: + return code + if code == 0: + for file_ in files: + if is_archive_split(file_) or is_archive(file_): + del_path = ospath.join(dirpath, file_) + try: + await remove(del_path) + except: + self.is_cancelled = True + if self.proceed_count == 0: + LOGGER.info("No files able to extract!") + return t_path if self.is_file and code == 0 else dl_path + + async def proceed_ffmpeg(self, dl_path, gid): + checked = False + inputs = {} + cmds = [ + [part.strip() for part in split(item) if part.strip()] + for item in self.ffmpeg_cmds + ] + try: + ffmpeg = FFMpeg(self) + for ffmpeg_cmd in cmds: + self.proceed_count = 0 + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + ] + ffmpeg_cmd + if "-del" in cmd: + cmd.remove("-del") + delete_files = True + else: + delete_files = False + input_indexes = [ + index for index, value in enumerate(cmd) if value == "-i" + ] + input_file = next( + ( + cmd[index + 1] + for index in input_indexes + if cmd[index + 1].startswith("mltb") + ), + "", + ) + if not input_file: + LOGGER.error("Wrong FFmpeg cmd!") + return dl_path + if input_file.strip().endswith(".video") or input_file.strip().endswith( + ".txt" + ): + ext = "video" + elif input_file.strip().endswith(".audio"): + ext = "audio" + elif "." not in input_file: + ext = "all" + else: + ext = ospath.splitext(input_file)[-1].lower() + if await aiopath.isfile(dl_path): + is_video, is_audio, _ = await get_document_type(dl_path) + if not is_video and not is_audio: + break + elif is_video and ext == "audio": + break + elif is_audio and not is_video and ext == "video": + break + elif ext not in [ + "all", + "audio", + "video", + ] and not dl_path.strip().lower().endswith(ext): + break + new_folder = ospath.splitext(dl_path)[0] + name = ospath.basename(dl_path) + await makedirs(new_folder, exist_ok=True) + file_path = f"{new_folder}/{name}" + await move(dl_path, file_path) + if not checked: + checked = True + async with task_dict_lock: + task_dict[self.mid] = FFmpegStatus( + self, ffmpeg, gid, "FFmpeg" + ) + self.progress = False + await cpu_eater_lock.acquire() + self.progress = True + LOGGER.info(f"Running ffmpeg cmd for: {file_path}") + var_cmd = cmd.copy() + for index in input_indexes: + if cmd[index + 1].startswith("mltb"): + var_cmd[index + 1] = file_path + elif is_telegram_link(cmd[index + 1]): + msg = (await get_tg_link_message(cmd[index + 1]))[0] + file_dir = await temp_download(msg) + inputs[index + 1] = file_dir + var_cmd[index + 1] = file_dir + self.subsize = self.size + res = await ffmpeg.ffmpeg_cmds(var_cmd, file_path) + if res: + if delete_files: + await remove(file_path) + if len(await listdir(new_folder)) == 1: + folder = new_folder.rsplit("/", 1)[0] + self.name = ospath.basename(res[0]) + if self.name.startswith("ffmpeg"): + self.name = self.name.split(".", 1)[-1] + dl_path = ospath.join(folder, self.name) + await move(res[0], dl_path) + await rmtree(new_folder) + else: + dl_path = new_folder + self.name = new_folder.rsplit("/", 1)[-1] + else: + dl_path = new_folder + self.name = new_folder.rsplit("/", 1)[-1] + else: + await move(file_path, dl_path) + await rmtree(new_folder) + else: + for dirpath, _, files in natsorted( + await sync_to_async(walk, dl_path, topdown=False) + ): + f_path = [] + for file_ in natsorted(files): + if ( + ospath.join(dirpath, file_) in f_path + or file_ == "mltb.txt" + ): + continue + var_cmd = cmd.copy() + if self.is_cancelled: + return False + if "concat" not in var_cmd: + f_path = ospath.join(dirpath, file_) + is_video, is_audio, _ = await get_document_type(f_path) + if not is_video and not is_audio: + continue + elif is_video and ext == "audio": + continue + elif is_audio and not is_video and ext == "video": + continue + elif ext not in [ + "all", + "audio", + "video", + ] and not f_path.strip().lower().endswith(ext): + continue + self.proceed_count += 1 + for index in input_indexes: + if cmd[index + 1].startswith("mltb"): + if cmd[index + 1].endswith("txt"): + txt = "" + for mf in natsorted(files): + df = ospath.join(dirpath, mf) + if (await get_document_type(df))[0]: + f_path.append(df) + txt += f"file '{ffconcat_escape(df)}'\n" + async with aiopen( + f"{dirpath}/mltb.txt", "w" + ) as f: + await f.write(txt) + var_cmd[index + 1] = f"{dirpath}/mltb.txt" + else: + var_cmd[index + 1] = f_path + elif is_telegram_link(cmd[index + 1]): + msg = (await get_tg_link_message(cmd[index + 1]))[0] + file_dir = await temp_download(msg) + inputs[index + 1] = file_dir + var_cmd[index + 1] = file_dir + if not checked: + checked = True + async with task_dict_lock: + task_dict[self.mid] = FFmpegStatus( + self, ffmpeg, gid, "FFmpeg" + ) + self.progress = False + await cpu_eater_lock.acquire() + self.progress = True + LOGGER.info(f"Running ffmpeg cmd for: {f_path}") + if isinstance(f_path, list): + self.subsize = 0 + for mf in f_path: + self.subsize += await get_path_size(mf) + else: + self.subsize = await get_path_size(f_path) + self.subname = file_ + res = await ffmpeg.ffmpeg_cmds(var_cmd, f_path) + if res and delete_files: + if isinstance(f_path, list): + for mf in f_path: + await remove(mf) + else: + await remove(f_path) + if len(res) == 1: + file_name = ospath.basename(res[0]) + if file_name.startswith("ffmpeg"): + newname = file_name.split(".", 1)[-1] + newres = ospath.join(dirpath, newname) + await move(res[0], newres) + if await aiopath.exists(f"{dirpath}/mltb.txt"): + await remove(f"{dirpath}/mltb.txt") + for inp in inputs.values(): + if "/temp/" in inp and await aiopath.exists(inp): + await remove(inp) + finally: + if checked: + cpu_eater_lock.release() + return dl_path + + async def substitute(self, dl_path): + def perform_substitution(name, substitutions): + for substitution in substitutions: + sen = False + pattern = substitution[0] + if pattern.startswith('"') and pattern.endswith('"'): + pattern = pattern.strip('"') + if len(substitution) > 1: + if len(substitution) > 2: + sen = substitution[2] == "s" + res = substitution[1] + elif len(substitution[1]) == 0: + res = " " + else: + res = substitution[1] + else: + res = "" + try: + name = sub(pattern, res, name, flags=I if sen else 0) + except Exception as e: + LOGGER.error( + f"Substitute Error: pattern: {pattern} res: {res}. Error: {e}" + ) + return False + if len(name.encode()) > 255: + LOGGER.error(f"Substitute: {name} is too long") + return False + return name + + if self.is_file: + up_dir, name = dl_path.rsplit("/", 1) + new_name = perform_substitution(name, self.name_sub) + if not new_name: + return dl_path + new_path = ospath.join(up_dir, new_name) + await move(dl_path, new_path) + return new_path + else: + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + f_path = ospath.join(dirpath, file_) + new_name = perform_substitution(file_, self.name_sub) + if not new_name: + continue + await move(f_path, ospath.join(dirpath, new_name)) + return dl_path + + async def generate_screenshots(self, dl_path): + ss_nb = int(self.screen_shots) if isinstance(self.screen_shots, str) else 10 + if self.is_file: + if (await get_document_type(dl_path))[0]: + LOGGER.info(f"Creating Screenshot for: {dl_path}") + res = await take_ss(dl_path, ss_nb) + if res: + new_folder = ospath.splitext(dl_path)[0] + name = ospath.basename(dl_path) + await makedirs(new_folder, exist_ok=True) + await gather( + move(dl_path, f"{new_folder}/{name}"), + move(res, new_folder), + ) + return new_folder + else: + LOGGER.info(f"Creating Screenshot for: {dl_path}") + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + f_path = ospath.join(dirpath, file_) + if (await get_document_type(f_path))[0]: + await take_ss(f_path, ss_nb) + return dl_path + + async def convert_media(self, dl_path, gid): + fvext = [] + if self.convert_video: + vdata = self.convert_video.split() + vext = vdata[0].lower() + if len(vdata) > 2: + if "+" in vdata[1].split(): + vstatus = "+" + elif "-" in vdata[1].split(): + vstatus = "-" + else: + vstatus = "" + fvext.extend(f".{ext.lower()}" for ext in vdata[2:]) + else: + vstatus = "" + else: + vext = "" + vstatus = "" + + faext = [] + if self.convert_audio: + adata = self.convert_audio.split() + aext = adata[0].lower() + if len(adata) > 2: + if "+" in adata[1].split(): + astatus = "+" + elif "-" in adata[1].split(): + astatus = "-" + else: + astatus = "" + faext.extend(f".{ext.lower()}" for ext in adata[2:]) + else: + astatus = "" + else: + aext = "" + astatus = "" + + self.files_to_proceed = {} + all_files = [] + if self.is_file: + all_files.append(dl_path) + else: + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + f_path = ospath.join(dirpath, file_) + all_files.append(f_path) + + for f_path in all_files: + is_video, is_audio, _ = await get_document_type(f_path) + if ( + is_video + and vext + and not f_path.strip().lower().endswith(f".{vext}") + and ( + vstatus == "+" + and f_path.strip().lower().endswith(tuple(fvext)) + or vstatus == "-" + and not f_path.strip().lower().endswith(tuple(fvext)) + or not vstatus + ) + ): + self.files_to_proceed[f_path] = "video" + elif ( + is_audio + and aext + and not is_video + and not f_path.strip().lower().endswith(f".{aext}") + and ( + astatus == "+" + and f_path.strip().lower().endswith(tuple(faext)) + or astatus == "-" + and not f_path.strip().lower().endswith(tuple(faext)) + or not astatus + ) + ): + self.files_to_proceed[f_path] = "audio" + del all_files + + if self.files_to_proceed: + ffmpeg = FFMpeg(self) + async with task_dict_lock: + task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Convert") + self.progress = False + async with cpu_eater_lock: + self.progress = True + for f_path, f_type in self.files_to_proceed.items(): + self.proceed_count += 1 + LOGGER.info(f"Converting: {f_path}") + if self.is_file: + self.subsize = self.size + else: + self.subsize = await get_path_size(f_path) + self.subname = ospath.basename(f_path) + if f_type == "video": + res = await ffmpeg.convert_video(f_path, vext) + else: + res = await ffmpeg.convert_audio(f_path, aext) + if res: + try: + await remove(f_path) + except: + self.is_cancelled = True + return False + if self.is_file: + return res + return dl_path + + async def generate_sample_video(self, dl_path, gid): + data = ( + self.sample_video.split(":") if isinstance(self.sample_video, str) else "" + ) + if data: + sample_duration = int(data[0]) if data[0] else 60 + part_duration = int(data[1]) if len(data) > 1 else 4 + else: + sample_duration = 60 + part_duration = 4 + + self.files_to_proceed = {} + if self.is_file and (await get_document_type(dl_path))[0]: + file_ = ospath.basename(dl_path) + self.files_to_proceed[dl_path] = file_ + else: + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + f_path = ospath.join(dirpath, file_) + if (await get_document_type(f_path))[0]: + self.files_to_proceed[f_path] = file_ + if self.files_to_proceed: + ffmpeg = FFMpeg(self) + async with task_dict_lock: + task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Sample Video") + self.progress = False + async with cpu_eater_lock: + self.progress = True + LOGGER.info(f"Creating Sample video: {self.name}") + for f_path, file_ in self.files_to_proceed.items(): + self.proceed_count += 1 + if self.is_file: + self.subsize = self.size + else: + self.subsize = await get_path_size(f_path) + self.subname = file_ + res = await ffmpeg.sample_video( + f_path, sample_duration, part_duration + ) + if res and self.is_file: + new_folder = ospath.splitext(f_path)[0] + await makedirs(new_folder, exist_ok=True) + await gather( + move(f_path, f"{new_folder}/{file_}"), + move(res, f"{new_folder}/SAMPLE.{file_}"), + ) + return new_folder + return dl_path + + async def proceed_compress(self, dl_path, gid): + pswd = self.compress if isinstance(self.compress, str) else "" + if self.is_leech and self.is_file: + new_folder = ospath.splitext(dl_path)[0] + name = ospath.basename(dl_path) + await makedirs(new_folder, exist_ok=True) + new_dl_path = f"{new_folder}/{name}" + await move(dl_path, new_dl_path) + dl_path = new_dl_path + up_path = f"{new_dl_path}.zip" + self.is_file = False + else: + up_path = f"{dl_path}.zip" + sevenz = SevenZ(self) + async with task_dict_lock: + task_dict[self.mid] = SevenZStatus(self, sevenz, gid, "Zip") + return await sevenz.zip(dl_path, up_path, pswd) + + async def proceed_split(self, dl_path, gid): + self.files_to_proceed = {} + if self.is_file: + f_size = await get_path_size(dl_path) + if f_size > self.split_size: + self.files_to_proceed[dl_path] = [f_size, ospath.basename(dl_path)] + else: + for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False): + for file_ in files: + f_path = ospath.join(dirpath, file_) + f_size = await get_path_size(f_path) + if f_size > self.split_size: + self.files_to_proceed[f_path] = [f_size, file_] + if self.files_to_proceed: + ffmpeg = FFMpeg(self) + async with task_dict_lock: + task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Split") + LOGGER.info(f"Splitting: {self.name}") + for f_path, (f_size, file_) in self.files_to_proceed.items(): + self.proceed_count += 1 + if self.is_file: + self.subsize = self.size + else: + self.subsize = f_size + self.subname = file_ + parts = -(-f_size // self.split_size) + if self.equal_splits: + split_size = (f_size // parts) + (f_size % parts) + else: + split_size = self.split_size + if not self.as_doc and (await get_document_type(f_path))[0]: + self.progress = True + res = await ffmpeg.split(f_path, file_, parts, split_size) + else: + self.progress = False + res = await split_file(f_path, split_size, self) + if self.is_cancelled: + return False + if res or f_size >= self.max_split_size: + try: + await remove(f_path) + except: + self.is_cancelled = True diff --git a/bot/helper/ext_utils/__init__.py b/bot/helper/ext_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /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 0000000000000000000000000000000000000000..73110eafb25882cab93a843361be7c87878bfe61 --- /dev/null +++ b/bot/helper/ext_utils/bot_utils.py @@ -0,0 +1,256 @@ +from httpx import AsyncClient +from asyncio.subprocess import PIPE +from functools import partial, wraps +from concurrent.futures import ThreadPoolExecutor +from asyncio import ( + create_subprocess_exec, + create_subprocess_shell, + run_coroutine_threadsafe, + sleep, +) + +from ... import user_data, bot_loop +from ...core.config_manager import Config +from ..telegram_helper.button_build import ButtonMaker +from .telegraph_helper import telegraph +from .help_messages import ( + YT_HELP_DICT, + MIRROR_HELP_DICT, + CLONE_HELP_DICT, +) + +COMMAND_USAGE = {} + +THREAD_POOL = ThreadPoolExecutor(max_workers=500) + + +class SetInterval: + def __init__(self, interval, action, *args, **kwargs): + self.interval = interval + self.action = action + self.task = bot_loop.create_task(self._set_interval(*args, **kwargs)) + + async def _set_interval(self, *args, **kwargs): + while True: + await sleep(self.interval) + await self.action(*args, **kwargs) + + def cancel(self): + self.task.cancel() + + +def _build_command_usage(help_dict, command_key): + buttons = ButtonMaker() + for name in list(help_dict.keys())[1:]: + buttons.data_button(name, f"help {command_key} {name}") + buttons.data_button("Close", "help close") + COMMAND_USAGE[command_key] = [help_dict["main"], buttons.build_menu(3)] + buttons.reset() + + +def create_help_buttons(): + _build_command_usage(MIRROR_HELP_DICT, "mirror") + _build_command_usage(YT_HELP_DICT, "yt") + _build_command_usage(CLONE_HELP_DICT, "clone") + + +def bt_selection_buttons(id_): + gid = id_[:12] if len(id_) > 25 else id_ + pin = "".join([n for n in id_ if n.isdigit()][:4]) + buttons = ButtonMaker() + if Config.WEB_PINCODE: + buttons.url_button("Select Files", f"{Config.BASE_URL}/app/files?gid={id_}") + buttons.data_button("Pincode", f"sel pin {gid} {pin}") + else: + buttons.url_button( + "Select Files", f"{Config.BASE_URL}/app/files?gid={id_}&pin={pin}" + ) + buttons.data_button("Done Selecting", f"sel done {gid} {id_}") + buttons.data_button("Cancel", f"sel cancel {gid}") + return buttons.build_menu(2) + + +async def get_telegraph_list(telegraph_content): + path = [ + ( + await telegraph.create_page( + title="Mirror-Leech-Bot Drive Search", content=content + ) + )["path"] + for content in telegraph_content + ] + if len(path) > 1: + await telegraph.edit_telegraph(path, telegraph_content) + buttons = ButtonMaker() + buttons.url_button("🔎 VIEW", f"https://telegra.ph/{path[0]}") + return buttons.build_menu(1) + + +def arg_parser(items, arg_base): + + if not items: + return + + arg_start = -1 + i = 0 + total = len(items) + + bool_arg_set = { + "-b", + "-e", + "-z", + "-s", + "-j", + "-d", + "-sv", + "-ss", + "-f", + "-fd", + "-fu", + "-sync", + "-hl", + "-doc", + "-med", + "-ut", + "-bt", + } + + while i < total: + part = items[i] + + if part in arg_base: + if arg_start == -1: + arg_start = i + + if ( + i + 1 == total + and part in bool_arg_set + or part + in [ + "-s", + "-j", + "-f", + "-fd", + "-fu", + "-sync", + "-hl", + "-doc", + "-med", + "-ut", + "-bt", + ] + ): + arg_base[part] = True + else: + sub_list = [] + for j in range(i + 1, total): + if items[j] in arg_base: + if part == "-c" and items[j] == "-c": + sub_list.append(items[j]) + continue + if part in bool_arg_set and not sub_list: + arg_base[part] = True + break + if not sub_list: + break + check = " ".join(sub_list).strip() + if part != "-ff": + break + if check.startswith("[") and check.endswith("]"): + break + elif not check.startswith("["): + break + sub_list.append(items[j]) + if sub_list: + value = " ".join(sub_list) + if part == "-ff": + if not value.strip().startswith("["): + arg_base[part].add(value) + else: + try: + arg_base[part].add(tuple(eval(value))) + except: + pass + else: + arg_base[part] = value + i += len(sub_list) + i += 1 + if "link" in arg_base: + link_items = items[:arg_start] if arg_start != -1 else items + if link_items: + arg_base["link"] = " ".join(link_items) + + +def get_size_bytes(size): + size = size.lower() + if "k" in size: + size = int(float(size.split("k")[0]) * 1024) + elif "m" in size: + size = int(float(size.split("m")[0]) * 1048576) + elif "g" in size: + size = int(float(size.split("g")[0]) * 1073741824) + elif "t" in size: + size = int(float(size.split("t")[0]) * 1099511627776) + else: + size = 0 + return size + + +async def get_content_type(url): + try: + async with AsyncClient() as client: + response = await client.get(url, allow_redirects=True, verify=False) + return response.headers.get("Content-Type") + except: + return None + + +def update_user_ldata(id_, key, value): + user_data.setdefault(id_, {}) + user_data[id_][key] = value + + +async def cmd_exec(cmd, shell=False): + if shell: + proc = await create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE) + else: + proc = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE) + stdout, stderr = await proc.communicate() + try: + stdout = stdout.decode().strip() + except: + stdout = "Unable to decode the response!" + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + return stdout, stderr, proc.returncode + + +def new_task(func): + @wraps(func) + async def wrapper(*args, **kwargs): + task = bot_loop.create_task(func(*args, **kwargs)) + return task + + return wrapper + + +async def sync_to_async(func, *args, wait=True, **kwargs): + pfunc = partial(func, *args, **kwargs) + future = bot_loop.run_in_executor(THREAD_POOL, pfunc) + return await future if wait else future + + +def async_to_sync(func, *args, wait=True, **kwargs): + future = run_coroutine_threadsafe(func(*args, **kwargs), bot_loop) + return future.result() if wait else future + + +def loop_thread(func): + @wraps(func) + def wrapper(*args, wait=False, **kwargs): + future = run_coroutine_threadsafe(func(*args, **kwargs), bot_loop) + return future.result() if wait else future + + return wrapper diff --git a/bot/helper/ext_utils/bulk_links.py b/bot/helper/ext_utils/bulk_links.py new file mode 100644 index 0000000000000000000000000000000000000000..8deb1bcc1d555ac72ea351ca7c77e63cd5935a53 --- /dev/null +++ b/bot/helper/ext_utils/bulk_links.py @@ -0,0 +1,35 @@ +from aiofiles import open as aiopen +from aiofiles.os import remove + + +def filter_links(links_list, bulk_start, bulk_end): + start = bulk_start if bulk_start > 0 else None + end = bulk_end if bulk_end > 0 else None + return links_list[start:end] + + +def get_links_from_message(text): + links_list = text.split("\n") + return [item.strip() for item in links_list if len(item) != 0] + + +async def get_links_from_file(message): + links_list = [] + text_file_dir = await message.download() + async with aiopen(text_file_dir, "r+") as f: + lines = await f.readlines() + links_list.extend(line.strip() for line in lines if len(line) != 0) + await remove(text_file_dir) + return links_list + + +async def extract_bulk_links(message, bulk_start, bulk_end): + bulk_start = int(bulk_start) + bulk_end = int(bulk_end) + links_list = [] + if reply_to := message.reply_to_message: + if (file_ := reply_to.document) and (file_.mime_type == "text/plain"): + links_list = await get_links_from_file(reply_to) + elif text := reply_to.text: + links_list = get_links_from_message(text) + return filter_links(links_list, bulk_start, bulk_end) if links_list else links_list diff --git a/bot/helper/ext_utils/db_handler.py b/bot/helper/ext_utils/db_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..bf78d3a02497fb540bb223f8a34229fd99110b60 --- /dev/null +++ b/bot/helper/ext_utils/db_handler.py @@ -0,0 +1,220 @@ +from aiofiles import open as aiopen +from aiofiles.os import path as aiopath +from importlib import import_module +from pymongo import AsyncMongoClient +from pymongo.server_api import ServerApi +from pymongo.errors import PyMongoError + +from ... import LOGGER, user_data, rss_dict, qbit_options +from ...core.telegram_manager import TgClient +from ...core.config_manager import Config + + +class DbManager: + def __init__(self): + self._return = True + self._conn = None + self.db = None + + async def connect(self): + try: + if self._conn is not None: + await self._conn.close() + self._conn = AsyncMongoClient( + Config.DATABASE_URL, + server_api=ServerApi("1"), + connectTimeoutMS=60000, + serverSelectionTimeoutMS=60000, + ) + self.db = self._conn[Config.DATABASE_NAME] + self._return = False + except PyMongoError as e: + LOGGER.error(f"Error in DB connection: {e}") + self.db = None + self._return = True + self._conn = None + + async def disconnect(self): + self._return = True + if self._conn is not None: + await self._conn.close() + self._conn = None + + async def update_deploy_config(self): + if self._return: + return + try: + settings = import_module("config") + config_file = { + key: value.strip() if isinstance(value, str) else value + for key, value in vars(settings).items() + if not key.startswith("__") + } + except ModuleNotFoundError: + return + await self.db.settings.deployConfig.replace_one( + {"_id": TgClient.ID}, config_file, upsert=True + ) + + async def update_config(self, dict_): + if self._return: + return + await self.db.settings.config.update_one( + {"_id": TgClient.ID}, {"$set": dict_}, upsert=True + ) + + async def update_aria2(self, key, value): + if self._return: + return + await self.db.settings.aria2c.update_one( + {"_id": TgClient.ID}, {"$set": {key: value}}, upsert=True + ) + + async def update_qbittorrent(self, key, value): + if self._return: + return + await self.db.settings.qbittorrent.update_one( + {"_id": TgClient.ID}, {"$set": {key: value}}, upsert=True + ) + + async def save_qbit_settings(self): + if self._return: + return + await self.db.settings.qbittorrent.update_one( + {"_id": TgClient.ID}, {"$set": qbit_options}, upsert=True + ) + + async def update_private_file(self, path): + if self._return: + return + db_path = path.replace(".", "__") + if await aiopath.exists(path): + async with aiopen(path, "rb+") as pf: + pf_bin = await pf.read() + await self.db.settings.files.update_one( + {"_id": TgClient.ID}, {"$set": {db_path: pf_bin}}, upsert=True + ) + if path == "config.py": + await self.update_deploy_config() + else: + await self.db.settings.files.update_one( + {"_id": TgClient.ID}, {"$unset": {db_path: ""}}, upsert=True + ) + + async def update_nzb_config(self): + if self._return: + return + async with aiopen("sabnzbd/SABnzbd.ini", "rb+") as pf: + nzb_conf = await pf.read() + await self.db.settings.nzb.replace_one( + {"_id": TgClient.ID}, {"SABnzbd__ini": nzb_conf}, upsert=True + ) + + async def update_user_data(self, user_id): + if self._return: + return + data = user_data.get(user_id, {}) + data = data.copy() + for key in ("THUMBNAIL", "RCLONE_CONFIG", "TOKEN_PICKLE"): + data.pop(key, None) + pipeline = [ + { + "$replaceRoot": { + "newRoot": { + "$mergeObjects": [ + data, + { + "$arrayToObject": { + "$filter": { + "input": {"$objectToArray": "$$ROOT"}, + "as": "field", + "cond": { + "$in": [ + "$$field.k", + [ + "THUMBNAIL", + "RCLONE_CONFIG", + "TOKEN_PICKLE", + ], + ] + }, + } + } + }, + ] + } + } + } + ] + await self.db.users.update_one({"_id": user_id}, pipeline, upsert=True) + + async def update_user_doc(self, user_id, key, path=""): + if self._return: + return + if path: + async with aiopen(path, "rb+") as doc: + doc_bin = await doc.read() + await self.db.users.update_one( + {"_id": user_id}, {"$set": {key: doc_bin}}, upsert=True + ) + else: + await self.db.users.update_one( + {"_id": user_id}, {"$unset": {key: ""}}, upsert=True + ) + + async def rss_update_all(self): + if self._return: + return + for user_id in list(rss_dict.keys()): + await self.db.rss[TgClient.ID].replace_one( + {"_id": user_id}, rss_dict[user_id], upsert=True + ) + + async def rss_update(self, user_id): + if self._return: + return + await self.db.rss[TgClient.ID].replace_one( + {"_id": user_id}, rss_dict[user_id], upsert=True + ) + + async def rss_delete(self, user_id): + if self._return: + return + await self.db.rss[TgClient.ID].delete_one({"_id": user_id}) + + async def add_incomplete_task(self, cid, link, tag): + if self._return: + return + await self.db.tasks[TgClient.ID].insert_one( + {"_id": link, "cid": cid, "tag": tag} + ) + + async def rm_complete_task(self, link): + if self._return: + return + await self.db.tasks[TgClient.ID].delete_one({"_id": link}) + + async def get_incomplete_tasks(self): + notifier_dict = {} + if self._return: + return notifier_dict + if await self.db.tasks[TgClient.ID].find_one(): + rows = self.db.tasks[TgClient.ID].find({}) + async for row in rows: + if row["cid"] in list(notifier_dict.keys()): + if row["tag"] in list(notifier_dict[row["cid"]]): + notifier_dict[row["cid"]][row["tag"]].append(row["_id"]) + else: + notifier_dict[row["cid"]][row["tag"]] = [row["_id"]] + else: + notifier_dict[row["cid"]] = {row["tag"]: [row["_id"]]} + await self.db.tasks[TgClient.ID].drop() + return notifier_dict + + async def trunc_table(self, name): + if self._return: + return + await self.db[name][TgClient.ID].drop() + + +database = DbManager() diff --git a/bot/helper/ext_utils/exceptions.py b/bot/helper/ext_utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..747607eb6d6c3b4c975595714aa9844384849236 --- /dev/null +++ b/bot/helper/ext_utils/exceptions.py @@ -0,0 +1,22 @@ +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 + + +class RssShutdownException(Exception): + """This exception should be raised when shutdown is called to stop the monitor""" + + pass + + +class TgLinkException(Exception): + """No Access granted for this chat""" + + pass diff --git a/bot/helper/ext_utils/files_utils.py b/bot/helper/ext_utils/files_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44d5910b8df18a476760042e7e8abb21607744ee --- /dev/null +++ b/bot/helper/ext_utils/files_utils.py @@ -0,0 +1,463 @@ +from aioshutil import rmtree as aiormtree, move +from asyncio import create_subprocess_exec, wait_for +from asyncio.subprocess import PIPE +from magic import Magic +from os import walk, path as ospath, readlink +from re import split as re_split, I, search as re_search, escape +from aiofiles.os import ( + remove, + path as aiopath, + listdir, + rmdir, + readlink as aioreadlink, + symlink, + makedirs as aiomakedirs, +) + +from ... import LOGGER, DOWNLOAD_DIR +from ...core.torrent_manager import TorrentManager +from .bot_utils import sync_to_async, cmd_exec +from .exceptions import NotSupportedExtractionArchive + +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", + ".zst", + ".zstd", + ".cbz", + ".apfs", + ".ar", + ".qcow", + ".macho", + ".exe", + ".dll", + ".sys", + ".pmd", + ".swf", + ".swfc", + ".simg", + ".vdi", + ".vhdx", + ".vmdk", + ".gzip", + ".lzma86", + ".sha256", + ".sha512", + ".sha224", + ".sha384", + ".sha1", + ".md5", + ".crc32", + ".crc64", +] + + +FIRST_SPLIT_REGEX = ( + r"\.part0*1\.rar$|\.7z\.0*1$|\.zip\.0*1$|^(?!.*\.part\d+\.rar$).*\.rar$" +) + +SPLIT_REGEX = r"\.r\d+$|\.7z\.\d+$|\.z\d+$|\.zip\.\d+$|\.part\d+\.rar$" + + +def is_first_archive_split(file): + return bool(re_search(FIRST_SPLIT_REGEX, file.lower(), I)) + + +def is_archive(file): + return file.strip().lower().endswith(tuple(ARCH_EXT)) + + +def is_archive_split(file): + return bool(re_search(SPLIT_REGEX, file.lower(), I)) + + +async def clean_target(opath): + if await aiopath.exists(opath): + LOGGER.info(f"Cleaning Target: {opath}") + try: + if await aiopath.isdir(opath): + await aiormtree(opath, ignore_errors=True) + else: + await remove(opath) + except Exception as e: + LOGGER.error(str(e)) + + +async def clean_download(opath): + if await aiopath.exists(opath): + LOGGER.info(f"Cleaning Download: {opath}") + try: + await aiormtree(opath, ignore_errors=True) + except Exception as e: + LOGGER.error(str(e)) + + +async def clean_all(): + await TorrentManager.remove_all() + LOGGER.info("Cleaning Download Directory") + await (await create_subprocess_exec("rm", "-rf", DOWNLOAD_DIR)).wait() + await aiomakedirs(DOWNLOAD_DIR, exist_ok=True) + + +async def clean_unwanted(opath): + LOGGER.info(f"Cleaning unwanted files/folders: {opath}") + for dirpath, _, files in await sync_to_async(walk, opath, topdown=False): + for filee in files: + f_path = ospath.join(dirpath, filee) + if filee.strip().endswith(".parts") and filee.startswith("."): + await remove(f_path) + if dirpath.strip().endswith(".unwanted"): + await aiormtree(dirpath, ignore_errors=True) + for dirpath, _, files in await sync_to_async(walk, opath, topdown=False): + if not await listdir(dirpath): + await rmdir(dirpath) + + +async def get_path_size(opath): + total_size = 0 + if await aiopath.isfile(opath): + if await aiopath.islink(opath): + opath = await aioreadlink(opath) + return await aiopath.getsize(opath) + for root, _, files in await sync_to_async(walk, opath): + for f in files: + abs_path = ospath.join(root, f) + if await aiopath.islink(abs_path): + abs_path = await aioreadlink(abs_path) + total_size += await aiopath.getsize(abs_path) + return total_size + + +async def count_files_and_folders(opath): + total_files = 0 + total_folders = 0 + for _, dirs, files in await sync_to_async(walk, opath): + total_files += len(files) + total_folders += len(dirs) + return total_folders, total_files + + +def get_base_name(orig_path): + extension = next( + (ext for ext in ARCH_EXT if orig_path.strip().lower().endswith(ext)), "" + ) + if extension != "": + return re_split(f"{extension}$", orig_path, maxsplit=1, flags=I)[0] + else: + raise NotSupportedExtractionArchive("File format not supported for extraction") + + +async def create_recursive_symlink(source, destination): + if ospath.isdir(source): + await aiomakedirs(destination, exist_ok=True) + for item in await listdir(source): + item_source = ospath.join(source, item) + item_dest = ospath.join(destination, item) + await create_recursive_symlink(item_source, item_dest) + elif ospath.isfile(source): + try: + await symlink(source, destination) + except FileExistsError: + LOGGER.error(f"Shortcut already exists: {destination}") + except Exception as e: + LOGGER.error(f"Error creating shortcut for {source}: {e}") + + +def get_mime_type(file_path): + if ospath.islink(file_path): + file_path = readlink(file_path) + mime = Magic(mime=True) + mime_type = mime.from_file(file_path) + mime_type = mime_type or "text/plain" + return mime_type + + +async def remove_excluded_files(fpath, ee): + for root, _, files in await sync_to_async(walk, fpath): + if root.strip().endswith("/yt-dlp-thumb"): + continue + for f in files: + if f.strip().lower().endswith(tuple(ee)): + await remove(ospath.join(root, f)) + + +async def remove_non_included_files(fpath, ie): + for root, _, files in await sync_to_async(walk, fpath): + if root.strip().endswith("/yt-dlp-thumb"): + continue + for f in files: + if f.strip().lower().endswith(tuple(ie)): + continue + await remove(ospath.join(root, f)) + + +async def move_and_merge(source, destination, mid): + if not await aiopath.exists(destination): + await aiomakedirs(destination, exist_ok=True) + for item in await listdir(source): + item = item.strip() + src_path = f"{source}/{item}" + dest_path = f"{destination}/{item}" + if await aiopath.isdir(src_path): + if await aiopath.exists(dest_path): + await move_and_merge(src_path, dest_path, mid) + else: + await move(src_path, dest_path) + else: + if item.endswith((".aria2", ".!qB")): + continue + if await aiopath.exists(dest_path): + dest_path = f"{destination}/{mid}-{item}" + await move(src_path, dest_path) + + +async def join_files(opath): + files = await listdir(opath) + results = [] + exists = False + for file_ in files: + if re_search(r"\.0+2$", file_) and await sync_to_async( + get_mime_type, f"{opath}/{file_}" + ) not in ["application/x-7z-compressed", "application/zip"]: + exists = True + final_name = file_.rsplit(".", 1)[0] + fpath = f"{opath}/{final_name}" + cmd = f'cat "{fpath}."* > "{fpath}"' + _, stderr, code = await cmd_exec(cmd, True) + if code != 0: + LOGGER.error(f"Failed to join {final_name}, stderr: {stderr}") + if await aiopath.isfile(fpath): + await remove(fpath) + else: + results.append(final_name) + + if not exists: + LOGGER.warning("No files to join!") + elif results: + LOGGER.info("Join Completed!") + for res in results: + for file_ in files: + if re_search(rf"{escape(res)}\.0[0-9]+$", file_): + await remove(f"{opath}/{file_}") + + +async def split_file(f_path, split_size, listener): + out_path = f"{f_path}." + if listener.is_cancelled: + return False + listener.subproc = await create_subprocess_exec( + "split", + "--numeric-suffixes=1", + "--suffix-length=3", + f"--bytes={split_size}", + f_path, + out_path, + stderr=PIPE, + ) + _, stderr = await listener.subproc.communicate() + code = listener.subproc.returncode + if listener.is_cancelled: + return False + if code == -9: + listener.is_cancelled = True + return False + elif code != 0: + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error(f"{stderr}. Split Document: {f_path}") + return True + + +class SevenZ: + def __init__(self, listener): + self._listener = listener + self._processed_bytes = 0 + self._percentage = "0%" + + @property + def processed_bytes(self): + return self._processed_bytes + + @property + def progress(self): + return self._percentage + + async def _sevenz_progress(self): + pattern = ( + r"(\d+)\s+bytes|Total Physical Size\s*=\s*(\d+)|Physical Size\s*=\s*(\d+)" + ) + while not ( + self._listener.subproc.returncode is not None + or self._listener.is_cancelled + or self._listener.subproc.stdout.at_eof() + ): + try: + line = await wait_for(self._listener.subproc.stdout.readline(), 2) + except: + break + line = line.decode().strip() + if "%" in line: + perc = line.split("%", 1)[0] + if perc.isdigit(): + self._percentage = f"{perc}%" + self._processed_bytes = (int(perc) / 100) * self._listener.subsize + else: + self._percentage = "0%" + continue + if match := re_search(pattern, line): + self._listener.subsize = int(match[1] or match[2] or match[3]) + s = b"" + while not ( + self._listener.is_cancelled + or self._listener.subproc.returncode is not None + or self._listener.subproc.stdout.at_eof() + ): + try: + char = await wait_for(self._listener.subproc.stdout.read(1), 60) + except: + break + if not char: + break + s += char + if char == b"%": + try: + self._percentage = s.decode().rsplit(" ", 1)[-1].strip() + self._processed_bytes = ( + int(self._percentage.strip("%")) / 100 + ) * self._listener.subsize + except: + self._processed_bytes = 0 + self._percentage = "0%" + s = b"" + + self._processed_bytes = 0 + self._percentage = "0%" + + async def extract(self, f_path, t_path, pswd): + cmd = [ + "7z", + "x", + f"-p{pswd}", + f_path, + f"-o{t_path}", + "-aot", + "-xr!@PaxHeader", + "-bsp1", + "-bse1", + "-bb3", + ] + if not pswd: + del cmd[2] + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, + stdout=PIPE, + stderr=PIPE, + ) + await self._sevenz_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == -9: + self._listener.is_cancelled = True + return False + elif code != 0: + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error(f"{stderr}. Unable to extract archive!. Path: {f_path}") + return code + + async def zip(self, dl_path, up_path, pswd): + size = await get_path_size(dl_path) + if self._listener.equal_splits: + parts = -(-size // self._listener.split_size) + split_size = (size // parts) + (size % parts) + else: + split_size = self._listener.split_size + cmd = [ + "7z", + f"-v{split_size}b", + "a", + "-mx=0", + f"-p{pswd}", + up_path, + dl_path, + "-bsp1", + "-bse1", + "-bb3", + ] + if self._listener.is_leech and int(size) > self._listener.split_size: + if not pswd: + del cmd[4] + LOGGER.info(f"Zip: orig_path: {dl_path}, zip_path: {up_path}.0*") + else: + del cmd[1] + if not pswd: + del cmd[3] + LOGGER.info(f"Zip: orig_path: {dl_path}, zip_path: {up_path}") + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, stdout=PIPE, stderr=PIPE + ) + await self._sevenz_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == -9: + self._listener.is_cancelled = True + return False + elif code == 0: + await clean_target(dl_path) + return up_path + else: + if await aiopath.exists(up_path): + await remove(up_path) + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error(f"{stderr}. Unable to zip this path: {dl_path}") + return dl_path diff --git a/bot/helper/ext_utils/help_messages.py b/bot/helper/ext_utils/help_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..156b798e93ce139928fb43f8e28bbf1f235f8ac2 --- /dev/null +++ b/bot/helper/ext_utils/help_messages.py @@ -0,0 +1,435 @@ +from ..telegram_helper.bot_commands import BotCommands +from ...core.telegram_manager import TgClient + +mirror = """Send link along with command line or + +/cmd link + +By replying to link/file: + +/cmd -n new name -e -up upload destination + +NOTE: +1. Commands that start with qb are ONLY for torrents.""" + +yt = """Send link along with command line: + +/cmd link +By replying to link: +/cmd -n new name -z password -opt x:y|x1:y1 + +Check here all supported SITES +Check all yt-dlp api options from this FILE or use this script to convert cli arguments to api options.""" + +clone = """Send Gdrive|Gdot|Filepress|Filebee|Appdrive|Gdflix link or rclone path along with command or by replying to the link/rc_path by command. +Use -sync to use sync method in rclone. Example: /cmd rcl/rclone_path -up rcl/rclone_path/rc -sync""" + +new_name = """New Name: -n + +/cmd link -n new name +Note: Doesn't work with torrents""" + +multi_link = """Multi links only by replying to first link/file: -i + +/cmd -i 10(number of links/files)""" + +same_dir = """Move file(s)/folder(s) to new folder: -m + +You can use this arg also to move multiple links/torrents contents to the same directory, so all links will be uploaded together as one task + +/cmd link -m new folder (only one link inside new folder) +/cmd -i 10(number of links/files) -m folder name (all links contents in one folder) +/cmd -b -m folder name (reply to batch of message/file(each link on new line)) + +While using bulk you can also use this arg with different folder name along with the links in message or file batch +Example: +link1 -m folder1 +link2 -m folder1 +link3 -m folder2 +link4 -m folder2 +link5 -m folder3 +link6 +so link1 and link2 content will be uploaded from same folder which is folder1 +link3 and link4 content will be uploaded from same folder also which is folder2 +link5 will uploaded alone inside new folder named folder3 +link6 will get uploaded normally alone +""" + +thumb = """Thumbnail for current task: -t + +/cmd link -t tg-message-link (doc or photo) or none (file without thumb)""" + +split_size = """Split size for current task: -sp + +/cmd link -sp (500mb or 2gb or 4000000000) +Note: Only mb and gb are supported or write in bytes without unit!""" + +upload = """Upload Destination: -up + +/cmd link -up rcl/gdl (rcl: to select rclone config, remote & path | gdl: To select token.pickle, gdrive id) using buttons +You can directly add the upload path: -up remote:dir/subdir or -up Gdrive_id or -up id/username (telegram) or -up id/username|topic_id (telegram) +If DEFAULT_UPLOAD is `rc` then you can pass up: `gd` to upload using gdrive tools to GDRIVE_ID. +If DEFAULT_UPLOAD is `gd` then you can pass up: `rc` to upload to RCLONE_PATH. + +If you want to add path or gdrive manually from your config/token (UPLOADED FROM USETTING) add mrcc: for rclone and mtp: before the path/gdrive_id without space. +/cmd link -up mrcc:main:dump or -up mtp:gdrive_id or you can simply edit upload using owner/user token/config from usetting without adding mtp: or mrcc: before the upload path/id + +To add leech destination: +-up id/@username/pm +-up b:id/@username/pm (b: means leech by bot) (id or username of the chat or write pm means private message so bot will send the files in private to you) +when you should use b:(leech by bot)? When your default settings is leech by user and you want to leech by bot for specific task. +-up u:id/@username(u: means leech by user) This incase OWNER added USER_STRING_SESSION. +-up h:id/@username(hybrid leech) h: to upload files by bot and user based on file size. +-up id/@username|topic_id(leech in specific chat and topic) add | without space and write topic id after chat id or username. + +In case you want to specify whether using token.pickle or service accounts you can add tp:gdrive_id (using token.pickle) or sa:gdrive_id (using service accounts) or mtp:gdrive_id (using token.pickle uploaded from usetting). +DEFAULT_UPLOAD doesn't affect on leech cmds. +""" + +user_download = """User Download: link + +/cmd tp:link to download using owner token.pickle incase service account enabled. +/cmd sa:link to download using service account incase service account disabled. +/cmd tp:gdrive_id to download using token.pickle and file_id incase service account enabled. +/cmd sa:gdrive_id to download using service account and file_id incase service account disabled. +/cmd mtp:gdrive_id or mtp:link to download using user token.pickle uploaded from usetting +/cmd mrcc:remote:path to download using user rclone config uploaded from usetting +you can simply edit upload using owner/user token/config from usetting without adding mtp: or mrcc: before the path/id""" + +rcf = """Rclone Flags: -rcf + +/cmd link|path|rcl -up path|rcl -rcf --buffer-size:8M|--drive-starred-only|key|key:value +This will override all other flags except --exclude +Check here all RcloneFlags.""" + +bulk = """Bulk Download: -b + +Bulk can be used only by replying to text message or text file contains links separated by new line. +Example: +link1 -n new name -up remote1:path1 -rcf |key:value|key:value +link2 -z -n new name -up remote2:path2 +link3 -e -n new name -up remote2:path2 +Reply to this example by this cmd -> /cmd -b(bulk) + +Note: Any arg along with the cmd will be setted to all links +/cmd -b -up remote: -z -m folder name (all links contents in one zipped folder uploaded to one destination) +so you can't set different upload destinations along with link incase you have added -m along with cmd +You can set start and end of the links from the bulk like seed, with -b start:end or only end by -b :end or only start by -b start. +The default start is from zero(first link) to inf.""" + +rlone_dl = """Rclone Download: + +Treat rclone paths exactly like links +/cmd main:dump/ubuntu.iso or rcl(To select config, remote and path) +Users can add their own rclone from user settings +If you want to add path manually from your config add mrcc: before the path without space +/cmd mrcc:main:dump/ubuntu.iso +You can simply edit using owner/user config from usetting without adding mrcc: before the path""" + +extract_zip = """Extract/Zip: -e -z + +/cmd link -e password (extract password protected) +/cmd link -z password (zip password protected) +/cmd link -z password -e (extract and zip password protected) +Note: When both extract and zip added with cmd it will extract first and then zip, so always extract first""" + +join = """Join Splitted Files: -j + +This option will only work before extract and zip, so mostly it will be used with -m argument (samedir) +By Reply: +/cmd -i 3 -j -m folder name +/cmd -b -j -m folder name +if u have link(folder) have splitted files: +/cmd link -j""" + +tg_links = """TG Links: + +Treat links like any direct link +Some links need user access so you must add USER_SESSION_STRING for it. +Three types of links: +Public: https://t.me/channel_name/message_id +Private: tg://openmessage?user_id=xxxxxx&message_id=xxxxx +Super: https://t.me/c/channel_id/message_id +Range: https://t.me/channel_name/first_message_id-last_message_id +Range Example: tg://openmessage?user_id=xxxxxx&message_id=555-560 or https://t.me/channel_name/100-150 +Note: Range link will work only by replying cmd to it""" + +sample_video = """Sample Video: -sv + +Create sample video for one video or folder of videos. +/cmd -sv (it will take the default values which 60sec sample duration and part duration is 4sec). +You can control those values. Example: /cmd -sv 70:5(sample-duration:part-duration) or /cmd -sv :5 or /cmd -sv 70.""" + +screenshot = """ScreenShots: -ss + +Create screenshots for one video or folder of videos. +/cmd -ss (it will take the default values which is 10 photos). +You can control this value. Example: /cmd -ss 6.""" + +seed = """Bittorrent seed: -d + +/cmd link -d ratio:seed_time or by replying to file/link +To specify ratio and seed time add -d ratio:time. +Example: -d 0.7:10 (ratio and time) or -d 0.7 (only ratio) or -d :10 (only time) where time in minutes""" + +zip_arg = """Zip: -z password + +/cmd link -z (zip) +/cmd link -z password (zip password protected)""" + +qual = """Quality Buttons: -s + +In case default quality added from yt-dlp options using format option and you need to select quality for specific link or links with multi links feature. +/cmd link -s""" + +yt_opt = """Options: -opt + +/cmd link -opt {"format": "bv*+mergeall[vcodec=none]", "nocheckcertificate": True, "playliststart": 10, "fragment_retries": float("inf"), "matchtitle": "S13", "writesubtitles": True, "live_from_start": True, "postprocessor_args": {"ffmpeg": ["-threads", "4"]}, "wait_for_video": (5, 100), "download_ranges": [{"start_time": 0, "end_time": 10}]} + +Check all yt-dlp api options from this FILE or use this script to convert cli arguments to api options.""" + +convert_media = """Convert Media: -ca -cv +/cmd link -ca mp3 -cv mp4 (convert all audios to mp3 and all videos to mp4) +/cmd link -ca mp3 (convert all audios to mp3) +/cmd link -cv mp4 (convert all videos to mp4) +/cmd link -ca mp3 + flac ogg (convert only flac and ogg audios to mp3) +/cmd link -cv mkv - webm flv (convert all videos to mp4 except webm and flv)""" + +force_start = """Force Start: -f -fd -fu +/cmd link -f (force download and upload) +/cmd link -fd (force download only) +/cmd link -fu (force upload directly after download finish)""" + +gdrive = """Gdrive: link +If DEFAULT_UPLOAD is `rc` then you can pass up: `gd` to upload using gdrive tools to GDRIVE_ID. +/cmd gdriveLink or gdl or gdriveId -up gdl or gdriveId or gd +/cmd tp:gdriveLink or tp:gdriveId -up tp:gdriveId or gdl or gd (to use token.pickle if service account enabled) +/cmd sa:gdriveLink or sa:gdriveId -p sa:gdriveId or gdl or gd (to use service account if service account disabled) +/cmd mtp:gdriveLink or mtp:gdriveId -up mtp:gdriveId or gdl or gd(if you have added upload gdriveId from usetting) (to use user token.pickle that uploaded by usetting) +You can simply edit using owner/user token from usetting without adding mtp: before the id""" + +rclone_cl = """Rclone: path +If DEFAULT_UPLOAD is `gd` then you can pass up: `rc` to upload to RCLONE_PATH. +/cmd rcl/rclone_path -up rcl/rclone_path/rc -rcf flagkey:flagvalue|flagkey|flagkey:flagvalue +/cmd rcl or rclone_path -up rclone_path or rc or rcl +/cmd mrcc:rclone_path -up rcl or rc(if you have add rclone path from usetting) (to use user config) +You can simply edit using owner/user config from usetting without adding mrcc: before the path""" + +name_sub = r"""Name Substitution: -ns +/cmd link -ns script/code/s | mirror/leech | tea/ /s | clone | cpu/ | \[mltb\]/mltb | \\text\\/text/s +This will affect on all files. Format: wordToReplace/wordToReplaceWith/sensitiveCase +Word Subtitions. You can add pattern instead of normal text. Timeout: 60 sec +NOTE: You must add \ before any character, those are the characters: \^$.|?*+()[]{}- +1. script will get replaced by code with sensitive case +2. mirror will get replaced by leech +4. tea will get replaced by space with sensitive case +5. clone will get removed +6. cpu will get replaced by space +7. [mltb] will get replaced by mltb +8. \text\ will get replaced by text with sensitive case +""" + +transmission = """Tg transmission: -hl -ut -bt +/cmd link -hl (leech by user and bot session with respect to size) (Hybrid Leech) +/cmd link -bt (leech by bot session) +/cmd link -ut (leech by user)""" + +thumbnail_layout = """Thumbnail Layout: -tl +/cmd link -tl 3x3 (widthxheight) 3 photos in row and 3 photos in column""" + +leech_as = """Leech as: -doc -med +/cmd link -doc (Leech as document) +/cmd link -med (Leech as media)""" + +ffmpeg_cmds = """FFmpeg Commands: -ff +list of lists of ffmpeg commands. You can set multiple ffmpeg commands for all files before upload. Don't write ffmpeg at beginning, start directly with the arguments. +Notes: +1. Add -del to the list(s) which you want from the bot to delete the original files after command run complete! +3. To execute one of pre-added lists in bot like: ({"subtitle": ["-i mltb.mkv -c copy -c:s srt mltb.mkv"]}), you must use -ff subtitle (list key) +Examples: ["-i mltb.mkv -c copy -c:s srt mltb.mkv", "-i mltb.video -c copy -c:s srt mltb", "-i mltb.m4a -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb.audio -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb -map 0:a -c copy mltb.mka -map 0:s -c copy mltb.srt", "-i mltb -i tg://openmessage?user_id=5272663208&message_id=322801 -filter_complex 'overlay=W-w-10:H-h-10' -c:a copy mltb"] +Here I will explain how to use mltb.* which is reference to files you want to work on. +1. First cmd: the input is mltb.mkv so this cmd will work only on mkv videos and the output is mltb.mkv also so all outputs is mkv. -del will delete the original media after complete run of the cmd. +2. Second cmd: the input is mltb.video so this cmd will work on all videos and the output is only mltb so the extension is same as input files. +3. Third cmd: the input in mltb.m4a so this cmd will work only on m4a audios and the output is mltb.mp3 so the output extension is mp3. +4. Fourth cmd: the input is mltb.audio so this cmd will work on all audios and the output is mltb.mp3 so the output extension is mp3. +5. Fifth cmd: You can add telegram link for small size input like photo to set watermark""" + +YT_HELP_DICT = { + "main": yt, + "New-Name": f"{new_name}\nNote: Don't add file extension", + "Zip": zip_arg, + "Quality": qual, + "Options": yt_opt, + "Multi-Link": multi_link, + "Same-Directory": same_dir, + "Thumb": thumb, + "Split-Size": split_size, + "Upload-Destination": upload, + "Rclone-Flags": rcf, + "Bulk": bulk, + "Sample-Video": sample_video, + "Screenshot": screenshot, + "Convert-Media": convert_media, + "Force-Start": force_start, + "Name-Substitute": name_sub, + "TG-Transmission": transmission, + "Thumb-Layout": thumbnail_layout, + "Leech-Type": leech_as, + "FFmpeg-Cmds": ffmpeg_cmds, +} + +MIRROR_HELP_DICT = { + "main": mirror, + "New-Name": new_name, + "DL-Auth": "Direct link authorization: -au -ap\n\n/cmd link -au username -ap password", + "Headers": "Direct link custom headers: -h\n\n/cmd link -h key:value|key1:value1", + "Extract/Zip": extract_zip, + "Select-Files": "Bittorrent/JDownloader/Sabnzbd File Selection: -s\n\n/cmd link -s or by replying to file/link", + "Torrent-Seed": seed, + "Multi-Link": multi_link, + "Same-Directory": same_dir, + "Thumb": thumb, + "Split-Size": split_size, + "Upload-Destination": upload, + "Rclone-Flags": rcf, + "Bulk": bulk, + "Join": join, + "Rclone-DL": rlone_dl, + "Tg-Links": tg_links, + "Sample-Video": sample_video, + "Screenshot": screenshot, + "Convert-Media": convert_media, + "Force-Start": force_start, + "User-Download": user_download, + "Name-Substitute": name_sub, + "TG-Transmission": transmission, + "Thumb-Layout": thumbnail_layout, + "Leech-Type": leech_as, + "FFmpeg-Cmds": ffmpeg_cmds, +} + +CLONE_HELP_DICT = { + "main": clone, + "Multi-Link": multi_link, + "Bulk": bulk, + "Gdrive": gdrive, + "Rclone": rclone_cl, +} + +RSS_HELP_MESSAGE = """ +Use this format to add feed url: +Title1 link (required) +Title2 link -c cmd -inf xx -exf xx +Title3 link -c cmd -d ratio:time -z password + +-c command -up mrcc:remote:path/subdir -rcf --buffer-size:8M|key|key:value +-inf For included words filter. +-exf For excluded words filter. +-stv true or false (sensitive filter) + +Example: Title https://www.rss-url.com -inf 1080 or 720 or 144p|mkv or mp4|hevc -exf flv or web|xxx +This filter will parse links that its titles contain `(1080 or 720 or 144p) and (mkv or mp4) and hevc` and doesn't contain (flv or web) and xxx words. You can add whatever you want. + +Another example: -inf 1080 or 720p|.web. or .webrip.|hvec or x264. This will parse titles that contain ( 1080 or 720p) and (.web. or .webrip.) and (hvec or x264). I have added space before and after 1080 to avoid wrong matching. If this `10805695` number in title it will match 1080 if added 1080 without spaces after it. + +Filter Notes: +1. | means and. +2. Add `or` between similar keys, you can add it between qualities or between extensions, so don't add filter like this f: 1080|mp4 or 720|web because this will parse 1080 and (mp4 or 720) and web ... not (1080 and mp4) or (720 and web). +3. You can add `or` and `|` as much as you want. +4. Take a look at the title if it has a static special character after or before the qualities or extensions or whatever and use them in the filter to avoid wrong match. +Timeout: 60 sec. +""" + +PASSWORD_ERROR_MESSAGE = """ +This link requires a password! +- Insert :: after the link and write the password after the sign. + +Example: link::my password +""" + +user_settings_text = { + "LEECH_SPLIT_SIZE": f"Send Leech split size in bytes or use gb or mb. Example: 40000000 or 2.5gb or 1000mb. IS_PREMIUM_USER: {TgClient.IS_PREMIUM_USER}. Timeout: 60 sec", + "LEECH_DUMP_CHAT": """Send leech destination ID/USERNAME/PM. +* b:id/@username/pm (b: means leech by bot) (id or username of the chat or write pm means private message so bot will send the files in private to you) when you should use b:(leech by bot)? When your default settings is leech by user and you want to leech by bot for specific task. +* u:id/@username(u: means leech by user) This incase OWNER added USER_STRING_SESSION. +* h:id/@username(hybrid leech) h: to upload files by bot and user based on file size. +* id/@username|topic_id(leech in specific chat and topic) add | without space and write topic id after chat id or username. Timeout: 60 sec""", + "LEECH_FILENAME_PREFIX": r"Send Leech Filename Prefix. You can add HTML tags. Example: @mychannel. Timeout: 60 sec", + "THUMBNAIL_LAYOUT": "Send thumbnail layout (widthxheight, 2x2, 3x3, 2x4, 4x4, ...). Example: 3x3. Timeout: 60 sec", + "RCLONE_PATH": "Send Rclone Path. If you want to use your rclone config edit using owner/user config from usetting or add mrcc: before rclone path. Example mrcc:remote:folder. Timeout: 60 sec", + "RCLONE_FLAGS": "key:value|key|key|key:value . Check here all RcloneFlags\nEx: --buffer-size:8M|--drive-starred-only", + "GDRIVE_ID": "Send Gdrive ID. If you want to use your token.pickle edit using owner/user token from usetting or add mtp: before the id. Example: mtp:F435RGGRDXXXXXX . Timeout: 60 sec", + "INDEX_URL": "Send Index URL. Timeout: 60 sec", + "UPLOAD_PATHS": "Send Dict of keys that have path values. Example: {'path 1': 'remote:rclonefolder', 'path 2': 'gdrive1 id', 'path 3': 'tg chat id', 'path 4': 'mrcc:remote:', 'path 5': b:@username} . Timeout: 60 sec", + "EXCLUDED_EXTENSIONS": "Send excluded extensions separated by space without dot at beginning. Timeout: 60 sec", + "INCLUDED_EXTENSIONS": "Send included extensions separated by space without dot at beginning. Timeout: 60 sec", + "NAME_SUBSTITUTE": r"""Word Subtitions. You can add pattern instead of normal text. Timeout: 60 sec +NOTE: You must add \ before any character, those are the characters: \^$.|?*+()[]{}- +Example: script/code/s | mirror/leech | tea/ /s | clone | cpu/ | \[mltb\]/mltb | \\text\\/text/s +1. script will get replaced by code with sensitive case +2. mirror will get replaced by leech +4. tea will get replaced by space with sensitive case +5. clone will get removed +6. cpu will get replaced by space +7. [mltb] will get replaced by mltb +8. \text\ will get replaced by text with sensitive case +""", + "YT_DLP_OPTIONS": """Send dict of YT-DLP Options. Timeout: 60 sec +Format: {key: value, key: value, key: value}. +Example: {"format": "bv*+mergeall[vcodec=none]", "nocheckcertificate": True, "playliststart": 10, "fragment_retries": float("inf"), "matchtitle": "S13", "writesubtitles": True, "live_from_start": True, "postprocessor_args": {"ffmpeg": ["-threads", "4"]}, "wait_for_video": (5, 100), "download_ranges": [{"start_time": 0, "end_time": 10}]} +Check all yt-dlp api options from this FILE or use this script to convert cli arguments to api options.""", + "FFMPEG_CMDS": """Dict of list values of ffmpeg commands. You can set multiple ffmpeg commands for all files before upload. Don't write ffmpeg at beginning, start directly with the arguments. +Examples: {"subtitle": ["-i mltb.mkv -c copy -c:s srt mltb.mkv", "-i mltb.video -c copy -c:s srt mltb"], "convert": ["-i mltb.m4a -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb.audio -c:a libmp3lame -q:a 2 mltb.mp3"], "extract": ["-i mltb -map 0:a -c copy mltb.mka -map 0:s -c copy mltb.srt"], "metadata": ["-i mltb.mkv -map 0 -map -0:v:1 -map -0:s -map 0:s:0 -map -0:v:m:attachment -c copy -metadata:s:v:0 title={title} -metadata:s:a:0 title={title} -metadata:s:a:1 title={title2} -metadata:s:a:2 title={title2} -c:s srt -metadata:s:s:0 title={title3} mltb -y -del"], "watermark": ["-i mltb -i tg://openmessage?user_id=5272663208&message_id=322801 -filter_complex 'overlay=W-w-10:H-h-10' -c:a copy mltb"]} +Notes: +- Add `-del` to the list which you want from the bot to delete the original files after command run complete! +- To execute one of those lists in bot for example, you must use -ff subtitle (list key) or -ff convert (list key) +Here I will explain how to use mltb.* which is reference to files you want to work on. +1. First cmd: the input is mltb.mkv so this cmd will work only on mkv videos and the output is mltb.mkv also so all outputs is mkv. -del will delete the original media after complete run of the cmd. +2. Second cmd: the input is mltb.video so this cmd will work on all videos and the output is only mltb so the extension is same as input files. +3. Third cmd: the input in mltb.m4a so this cmd will work only on m4a audios and the output is mltb.mp3 so the output extension is mp3. +4. Fourth cmd: the input is mltb.audio so this cmd will work on all audios and the output is mltb.mp3 so the output extension is mp3. +5. FFmpeg Variables in last cmd which is metadata ({title}, {title2}, etc...), you can edit them in usetting +6. Telegram link for small size inputs like photo to set watermark.""", + "CLONE_DUMP_CHATS": "Send List/Int/Str Chat_id/username|thread_id. Example: -100xxxx555|5 or @dumpchat|8 or @mltb_dump or pm or List like: [-100xxx885552|6, '@username', 65585541254, 'pm']", +} + + +help_string = f""" +NOTE: Try each command without any argument to see more detalis. +/{BotCommands.MirrorCommand[0]} or /{BotCommands.MirrorCommand[1]}: Start mirroring to cloud. +/{BotCommands.QbMirrorCommand[0]} or /{BotCommands.QbMirrorCommand[1]}: Start Mirroring to cloud using qBittorrent. +/{BotCommands.JdMirrorCommand[0]} or /{BotCommands.JdMirrorCommand[1]}: Start Mirroring to cloud using JDownloader. +/{BotCommands.NzbMirrorCommand[0]} or /{BotCommands.NzbMirrorCommand[1]}: Start Mirroring to cloud using Sabnzbd. +/{BotCommands.YtdlCommand[0]} or /{BotCommands.YtdlCommand[1]}: Mirror yt-dlp supported link. +/{BotCommands.LeechCommand[0]} or /{BotCommands.LeechCommand[1]}: Start leeching to Telegram. +/{BotCommands.QbLeechCommand[0]} or /{BotCommands.QbLeechCommand[1]}: Start leeching using qBittorrent. +/{BotCommands.JdLeechCommand[0]} or /{BotCommands.JdLeechCommand[1]}: Start leeching using JDownloader. +/{BotCommands.NzbLeechCommand[0]} or /{BotCommands.NzbLeechCommand[1]}: Start leeching using Sabnzbd. +/{BotCommands.YtdlLeechCommand[0]} or /{BotCommands.YtdlLeechCommand[1]}: Leech yt-dlp supported link. +/{BotCommands.CloneCommand} [drive_url]: Copy file/folder to Google Drive. +/{BotCommands.CountCommand} [drive_url]: Count file/folder of Google Drive. +/{BotCommands.DeleteCommand} [drive_url]: Delete file/folder from Google Drive (Only Owner & Sudo). +/{BotCommands.UserSetCommand[0]} or /{BotCommands.UserSetCommand[1]} [query]: Users settings. +/{BotCommands.BotSetCommand[0]} or /{BotCommands.BotSetCommand[1]} [query]: Bot settings. +/{BotCommands.SelectCommand}: Select files from torrents or nzb by gid or reply. +/{BotCommands.CancelTaskCommand[0]} or /{BotCommands.CancelTaskCommand[1]} [gid]: Cancel task by gid or reply. +/{BotCommands.ForceStartCommand[0]} or /{BotCommands.ForceStartCommand[1]} [gid]: Force start task by gid or reply. +/{BotCommands.CancelAllCommand} [query]: Cancel all [status] tasks. +/{BotCommands.ListCommand} [query]: Search in Google Drive(s). +/{BotCommands.SearchCommand} [query]: Search for torrents with API. +/{BotCommands.StatusCommand}: Shows a status of all the downloads. +/{BotCommands.StatsCommand}: Show stats of the machine where the bot is hosted in. +/{BotCommands.PingCommand}: Check how long it takes to Ping the Bot (Only Owner & Sudo). +/{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Only Owner & Sudo). +/{BotCommands.UnAuthorizeCommand}: Unauthorize a chat or a user to use the bot (Only Owner & Sudo). +/{BotCommands.UsersCommand}: show users settings (Only Owner & Sudo). +/{BotCommands.AddSudoCommand}: Add sudo user (Only Owner). +/{BotCommands.RmSudoCommand}: Remove sudo users (Only Owner). +/{BotCommands.RestartCommand}: Restart and update the bot (Only Owner & Sudo). +/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports (Only Owner & Sudo). +/{BotCommands.ShellCommand}: Run shell commands (Only Owner). +/{BotCommands.AExecCommand}: Exec async functions (Only Owner). +/{BotCommands.ExecCommand}: Exec sync functions (Only Owner). +/{BotCommands.ClearLocalsCommand}: Clear {BotCommands.AExecCommand} or {BotCommands.ExecCommand} locals (Only Owner). +/{BotCommands.RssCommand}: RSS Menu. +""" diff --git a/bot/helper/ext_utils/links_utils.py b/bot/helper/ext_utils/links_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f37280f3d4e058f245371b962a6a38bf0f2fe9f6 --- /dev/null +++ b/bot/helper/ext_utils/links_utils.py @@ -0,0 +1,49 @@ +from re import match as re_match + + +def is_magnet(url: str): + return bool(re_match(r"^magnet:\?.*xt=urn:(btih|btmh):([a-zA-Z0-9]{32,40}|[a-z2-7]{32}).*", url)) + + +def is_url(url: str): + return bool( + re_match( + r"^(?!\/)(rtmps?:\/\/|mms:\/\/|rtsp:\/\/|https?:\/\/|ftp:\/\/)?([^\/:]+:[^\/@]+@)?(www\.)?(?=[^\/:\s]+\.[^\/:\s]+)([^\/:\s]+\.[^\/:\s]+)(:\d+)?(\/[^#\s]*[\s\S]*)?(\?[^#\s]*)?(#.*)?$", + url, + ) + ) + + +def is_gdrive_link(url: str): + return "drive.google.com" in url or "drive.usercontent.google.com" in url + + +def is_telegram_link(url: str): + return url.startswith(("https://t.me/", "tg://openmessage?user_id=")) + + +def is_share_link(url: str): + return bool( + re_match( + r"https?:\/\/.+\.gdtot\.\S+|https?:\/\/(filepress|filebee|appdrive|gdflix)\.\S+", + url, + ) + ) + + +def is_rclone_path(path: str): + return bool( + re_match( + r"^(mrcc:)?(?!(magnet:|mtp:|sa:|tp:))(?![- ])[a-zA-Z0-9_\. -]+(? bool: + duration = (await get_media_info(video_file))[0] + if duration != 0: + dirpath, name = video_file.rsplit("/", 1) + name, _ = ospath.splitext(name) + dirpath = f"{dirpath}/{name}_mltbss" + await makedirs(dirpath, exist_ok=True) + interval = duration // (ss_nb + 1) + cap_time = interval + cmds = [] + for i in range(ss_nb): + output = f"{dirpath}/SS.{name}_{i:02}.png" + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-ss", + f"{cap_time}", + "-i", + video_file, + "-q:v", + "1", + "-frames:v", + "1", + "-threads", + f"{threads}", + output, + ] + cap_time += interval + cmds.append(cmd_exec(cmd)) + try: + resutls = await wait_for(gather(*cmds), timeout=60) + if resutls[0][2] != 0: + LOGGER.error( + f"Error while creating screenshots from video. Path: {video_file}. stderr: {resutls[0][1]}" + ) + await rmtree(dirpath, ignore_errors=True) + return False + except: + LOGGER.error( + f"Error while creating screenshots from video. Path: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!" + ) + await rmtree(dirpath, ignore_errors=True) + return False + return dirpath + else: + LOGGER.error("take_ss: Can't get the duration of video") + return False + + +async def get_audio_thumbnail(audio_file): + output_dir = f"{DOWNLOAD_DIR}thumbnails" + await makedirs(output_dir, exist_ok=True) + output = ospath.join(output_dir, f"{time()}.jpg") + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-i", + audio_file, + "-an", + "-vcodec", + "copy", + "-threads", + f"{threads}", + output, + ] + try: + _, err, code = await wait_for(cmd_exec(cmd), timeout=60) + if code != 0 or not await aiopath.exists(output): + LOGGER.error( + f"Error while extracting thumbnail from audio. Name: {audio_file} stderr: {err}" + ) + return None + except: + LOGGER.error( + f"Error while extracting thumbnail from audio. Name: {audio_file}. Error: Timeout some issues with ffmpeg with specific arch!" + ) + return None + return output + + +async def get_video_thumbnail(video_file, duration): + output_dir = f"{DOWNLOAD_DIR}thumbnails" + await makedirs(output_dir, exist_ok=True) + output = ospath.join(output_dir, f"{time()}.jpg") + if duration is None: + duration = (await get_media_info(video_file))[0] + if duration == 0: + duration = 3 + duration = duration // 2 + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-ss", + f"{duration}", + "-i", + video_file, + "-vf", + "thumbnail", + "-q:v", + "1", + "-frames:v", + "1", + "-threads", + f"{threads}", + output, + ] + try: + _, err, code = await wait_for(cmd_exec(cmd), timeout=60) + if code != 0 or not await aiopath.exists(output): + LOGGER.error( + f"Error while extracting thumbnail from video. Name: {video_file} stderr: {err}" + ) + return None + except: + LOGGER.error( + f"Error while extracting thumbnail from video. Name: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!" + ) + return None + return output + + +async def get_multiple_frames_thumbnail(video_file, layout, keep_screenshots): + ss_nb = layout.split("x") + ss_nb = int(ss_nb[0]) * int(ss_nb[1]) + dirpath = await take_ss(video_file, ss_nb) + if not dirpath: + return None + output_dir = f"{DOWNLOAD_DIR}thumbnails" + await makedirs(output_dir, exist_ok=True) + output = ospath.join(output_dir, f"{time()}.jpg") + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-pattern_type", + "glob", + "-i", + f"{escape(dirpath)}/*.png", + "-vf", + f"tile={layout}, thumbnail", + "-q:v", + "1", + "-frames:v", + "1", + "-f", + "mjpeg", + "-threads", + f"{threads}", + output, + ] + try: + _, err, code = await wait_for(cmd_exec(cmd), timeout=60) + if code != 0 or not await aiopath.exists(output): + LOGGER.error( + f"Error while combining thumbnails for video. Name: {video_file} stderr: {err}" + ) + return None + except: + LOGGER.error( + f"Error while combining thumbnails from video. Name: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!" + ) + return None + finally: + if not keep_screenshots: + await rmtree(dirpath, ignore_errors=True) + return output + + +class FFMpeg: + + def __init__(self, listener): + self._listener = listener + self._processed_bytes = 0 + self._last_processed_bytes = 0 + self._processed_time = 0 + self._last_processed_time = 0 + self._speed_raw = 0 + self._progress_raw = 0 + self._total_time = 0 + self._eta_raw = 0 + self._time_rate = 0.1 + self._start_time = 0 + + @property + def processed_bytes(self): + return self._processed_bytes + + @property + def speed_raw(self): + return self._speed_raw + + @property + def progress_raw(self): + return self._progress_raw + + @property + def eta_raw(self): + return self._eta_raw + + def clear(self): + self._start_time = time() + self._processed_bytes = 0 + self._processed_time = 0 + self._speed_raw = 0 + self._progress_raw = 0 + self._eta_raw = 0 + self._time_rate = 0.1 + self._last_processed_time = 0 + self._last_processed_bytes = 0 + + async def _ffmpeg_progress(self): + while not ( + self._listener.subproc.returncode is not None + or self._listener.is_cancelled + or self._listener.subproc.stdout.at_eof() + ): + try: + line = await wait_for(self._listener.subproc.stdout.readline(), 60) + except: + break + line = line.decode().strip() + if not line: + break + if "=" in line: + key, value = line.split("=", 1) + if value != "N/A": + if key == "total_size": + self._processed_bytes = int(value) + self._last_processed_bytes + self._speed_raw = self._processed_bytes / ( + time() - self._start_time + ) + elif key == "speed": + self._time_rate = max(0.1, float(value.strip("x"))) + elif key == "out_time": + self._processed_time = ( + time_to_seconds(value) + self._last_processed_time + ) + try: + self._progress_raw = ( + self._processed_time * 100 + ) / self._total_time + self._eta_raw = ( + self._total_time - self._processed_time + ) / self._time_rate + except: + self._progress_raw = 0 + self._eta_raw = 0 + + async def ffmpeg_cmds(self, ffmpeg, f_path): + self.clear() + if isinstance(f_path, list): + self._total_time = 0 + for f in f_path: + self._total_time += (await get_media_info(f))[0] + base_name = ospath.commonprefix(f_path) + ext = f_path[0].rsplit(".", 1)[-1] + else: + self._total_time = (await get_media_info(f_path))[0] + base_name, ext = ospath.splitext(f_path) + dir, base_name = base_name.rsplit("/", 1) + indices = [ + index + for index, item in enumerate(ffmpeg) + if (item.startswith("mltb") or item == "mltb") and item != "mltb.txt" + ] + outputs = [] + for index in indices: + output_file = ffmpeg[index] + if output_file != "mltb" and output_file.startswith("mltb"): + bo, oext = ospath.splitext(output_file) + if oext: + if isinstance(f_path, list) or ext != oext: + prefix = "" + else: + prefix = f"ffmpeg{index}." if bo == "mltb" else "" + ext = "" + else: + prefix = "" + else: + prefix = f"ffmpeg{index}." + output = f"{dir}/{prefix}{output_file.replace("mltb", base_name)}{ext}" + outputs.append(output) + ffmpeg[index] = output + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *ffmpeg, stdout=PIPE, stderr=PIPE + ) + await self._ffmpeg_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == 0: + return outputs + elif code == -9: + self._listener.is_cancelled = True + return False + else: + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error( + f"{stderr}. Something went wrong while running ffmpeg cmd, mostly file requires different/specific arguments. Path: {f_path}" + ) + for op in outputs: + if await aiopath.exists(op): + await remove(op) + return False + + async def convert_video(self, video_file, ext, retry=False): + self.clear() + self._total_time = (await get_media_info(video_file))[0] + base_name = ospath.splitext(video_file)[0] + output = f"{base_name}.{ext}" + if retry: + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + "-i", + video_file, + "-map", + "0", + "-c:v", + "libx264", + "-c:a", + "aac", + "-threads", + f"{threads}", + output, + ] + if ext == "mp4": + cmd[17:17] = ["-c:s", "mov_text"] + elif ext == "mkv": + cmd[17:17] = ["-c:s", "ass"] + else: + cmd[17:17] = ["-c:s", "copy"] + else: + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + "-i", + video_file, + "-map", + "0", + "-c", + "copy", + "-threads", + f"{threads}", + output, + ] + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, stdout=PIPE, stderr=PIPE + ) + await self._ffmpeg_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == 0: + return output + elif code == -9: + self._listener.is_cancelled = True + return False + else: + if await aiopath.exists(output): + await remove(output) + if not retry: + return await self.convert_video(video_file, ext, True) + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error( + f"{stderr}. Something went wrong while converting video, mostly file need specific codec. Path: {video_file}" + ) + return False + + async def convert_audio(self, audio_file, ext): + self.clear() + self._total_time = (await get_media_info(audio_file))[0] + base_name = ospath.splitext(audio_file)[0] + output = f"{base_name}.{ext}" + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + "-i", + audio_file, + "-threads", + f"{threads}", + output, + ] + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, stdout=PIPE, stderr=PIPE + ) + await self._ffmpeg_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == 0: + return output + elif code == -9: + self._listener.is_cancelled = True + return False + else: + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + LOGGER.error( + f"{stderr}. Something went wrong while converting audio, mostly file need specific codec. Path: {audio_file}" + ) + if await aiopath.exists(output): + await remove(output) + return False + + async def sample_video(self, video_file, sample_duration, part_duration): + self.clear() + self._total_time = sample_duration + dir, name = video_file.rsplit("/", 1) + output_file = f"{dir}/SAMPLE.{name}" + segments = [(0, part_duration)] + duration = (await get_media_info(video_file))[0] + remaining_duration = duration - (part_duration * 2) + parts = (sample_duration - (part_duration * 2)) // part_duration + time_interval = remaining_duration // parts + next_segment = time_interval + for _ in range(parts): + segments.append((next_segment, next_segment + part_duration)) + next_segment += time_interval + segments.append((duration - part_duration, duration)) + + filter_complex = "" + for i, (start, end) in enumerate(segments): + filter_complex += ( + f"[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS[v{i}]; " + ) + filter_complex += ( + f"[0:a]atrim=start={start}:end={end},asetpts=PTS-STARTPTS[a{i}]; " + ) + + for i in range(len(segments)): + filter_complex += f"[v{i}][a{i}]" + + filter_complex += f"concat=n={len(segments)}:v=1:a=1[vout][aout]" + + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + "-i", + video_file, + "-filter_complex", + filter_complex, + "-map", + "[vout]", + "-map", + "[aout]", + "-c:v", + "libx264", + "-c:a", + "aac", + "-threads", + f"{threads}", + output_file, + ] + + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, stdout=PIPE, stderr=PIPE + ) + await self._ffmpeg_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == -9: + self._listener.is_cancelled = True + return False + elif code == 0: + return output_file + else: + try: + stderr = stderr.decode().strip() + except Exception: + stderr = "Unable to decode the error!" + LOGGER.error( + f"{stderr}. Something went wrong while creating sample video, mostly file is corrupted. Path: {video_file}" + ) + if await aiopath.exists(output_file): + await remove(output_file) + return False + + async def split(self, f_path, file_, parts, split_size): + self.clear() + multi_streams = True + self._total_time = duration = (await get_media_info(f_path))[0] + base_name, extension = ospath.splitext(file_) + split_size -= 3000000 + start_time = 0 + i = 1 + while i <= parts or start_time < duration - 4: + out_path = f_path.replace(file_, f"{base_name}.part{i:03}{extension}") + cmd = [ + "taskset", + "-c", + f"{cores}", + "ffmpeg", + "-hide_banner", + "-loglevel", + "error", + "-progress", + "pipe:1", + "-ss", + str(start_time), + "-i", + f_path, + "-fs", + str(split_size), + "-map", + "0", + "-map_chapters", + "-1", + "-async", + "1", + "-strict", + "-2", + "-c", + "copy", + "-threads", + f"{threads}", + out_path, + ] + if not multi_streams: + del cmd[15] + del cmd[15] + if self._listener.is_cancelled: + return False + self._listener.subproc = await create_subprocess_exec( + *cmd, stdout=PIPE, stderr=PIPE + ) + await self._ffmpeg_progress() + _, stderr = await self._listener.subproc.communicate() + code = self._listener.subproc.returncode + if self._listener.is_cancelled: + return False + if code == -9: + self._listener.is_cancelled = True + return False + elif code != 0: + try: + stderr = stderr.decode().strip() + except: + stderr = "Unable to decode the error!" + try: + await remove(out_path) + except: + pass + if multi_streams: + LOGGER.warning( + f"{stderr}. Retrying without map, -map 0 not working in all situations. Path: {f_path}" + ) + multi_streams = False + continue + else: + LOGGER.warning( + f"{stderr}. Unable to split this video, if it's size less than {self._listener.max_split_size} will be uploaded as it is. Path: {f_path}" + ) + return False + out_size = await aiopath.getsize(out_path) + if out_size > self._listener.max_split_size: + split_size -= (out_size - self._listener.max_split_size) + 5000000 + LOGGER.warning( + f"Part size is {out_size}. Trying again with lower split size!. Path: {f_path}" + ) + await remove(out_path) + continue + lpd = (await get_media_info(out_path))[0] + if lpd == 0: + LOGGER.error( + f"Something went wrong while splitting, mostly file is corrupted. Path: {f_path}" + ) + break + elif duration == lpd: + LOGGER.warning( + f"This file has been splitted with default stream and audio, so you will only see one part with less size from original one because it doesn't have all streams and audios. This happens mostly with MKV videos. Path: {f_path}" + ) + break + elif lpd <= 3: + await remove(out_path) + break + self._last_processed_time += lpd + self._last_processed_bytes += out_size + start_time += lpd - 3 + i += 1 + return True diff --git a/bot/helper/ext_utils/status_utils.py b/bot/helper/ext_utils/status_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4259f4413855e2e4823f9d24aaae717c07c26e32 --- /dev/null +++ b/bot/helper/ext_utils/status_utils.py @@ -0,0 +1,254 @@ +from html import escape +from psutil import virtual_memory, cpu_percent, disk_usage +from time import time +from asyncio import iscoroutinefunction, gather + +from ... import task_dict, task_dict_lock, bot_start_time, status_dict, DOWNLOAD_DIR +from ...core.config_manager import Config +from ..telegram_helper.button_build import ButtonMaker +from ..telegram_helper.bot_commands import BotCommands + +SIZE_UNITS = ["B", "KB", "MB", "GB", "TB", "PB"] + + +class MirrorStatus: + STATUS_UPLOAD = "Upload" + STATUS_DOWNLOAD = "Download" + STATUS_CLONE = "Clone" + STATUS_QUEUEDL = "QueueDl" + STATUS_QUEUEUP = "QueueUp" + STATUS_PAUSED = "Pause" + STATUS_ARCHIVE = "Archive" + STATUS_EXTRACT = "Extract" + STATUS_SPLIT = "Split" + STATUS_CHECK = "CheckUp" + STATUS_SEED = "Seed" + STATUS_SAMVID = "SamVid" + STATUS_CONVERT = "Convert" + STATUS_FFMPEG = "FFmpeg" + + +STATUSES = { + "ALL": "All", + "DL": MirrorStatus.STATUS_DOWNLOAD, + "UP": MirrorStatus.STATUS_UPLOAD, + "QD": MirrorStatus.STATUS_QUEUEDL, + "QU": MirrorStatus.STATUS_QUEUEUP, + "AR": MirrorStatus.STATUS_ARCHIVE, + "EX": MirrorStatus.STATUS_EXTRACT, + "SD": MirrorStatus.STATUS_SEED, + "CL": MirrorStatus.STATUS_CLONE, + "CM": MirrorStatus.STATUS_CONVERT, + "SP": MirrorStatus.STATUS_SPLIT, + "SV": MirrorStatus.STATUS_SAMVID, + "FF": MirrorStatus.STATUS_FFMPEG, + "PA": MirrorStatus.STATUS_PAUSED, + "CK": MirrorStatus.STATUS_CHECK, +} + + +async def get_task_by_gid(gid: str): + async with task_dict_lock: + for tk in task_dict.values(): + if hasattr(tk, "seeding"): + await tk.update() + if tk.gid() == gid: + return tk + return None + + +async def get_specific_tasks(status, user_id): + if status == "All": + if user_id: + return [tk for tk in task_dict.values() if tk.listener.user_id == user_id] + else: + return list(task_dict.values()) + tasks_to_check = ( + [tk for tk in task_dict.values() if tk.listener.user_id == user_id] + if user_id + else list(task_dict.values()) + ) + coro_tasks = [] + coro_tasks.extend(tk for tk in tasks_to_check if iscoroutinefunction(tk.status)) + coro_statuses = await gather(*[tk.status() for tk in coro_tasks]) + result = [] + coro_index = 0 + for tk in tasks_to_check: + if tk in coro_tasks: + st = coro_statuses[coro_index] + coro_index += 1 + else: + st = tk.status() + if (st == status) or ( + status == MirrorStatus.STATUS_DOWNLOAD and st not in STATUSES.values() + ): + result.append(tk) + return result + + +async def get_all_tasks(req_status: str, user_id): + async with task_dict_lock: + return await get_specific_tasks(req_status, user_id) + + +def get_readable_file_size(size_in_bytes): + if not size_in_bytes: + return "0B" + + index = 0 + while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1: + size_in_bytes /= 1024 + index += 1 + + return f"{size_in_bytes:.2f}{SIZE_UNITS[index]}" + + +def get_readable_time(seconds: int): + periods = [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)] + result = "" + for period_name, period_seconds in periods: + if seconds >= period_seconds: + period_value, seconds = divmod(seconds, period_seconds) + result += f"{int(period_value)}{period_name}" + return result + + +def time_to_seconds(time_duration): + try: + parts = time_duration.split(":") + if len(parts) == 3: + hours, minutes, seconds = map(float, parts) + elif len(parts) == 2: + hours = 0 + minutes, seconds = map(float, parts) + elif len(parts) == 1: + hours = 0 + minutes = 0 + seconds = float(parts[0]) + else: + return 0 + return hours * 3600 + minutes * 60 + seconds + except: + return 0 + + +def speed_string_to_bytes(size_text: str): + size = 0 + size_text = size_text.lower() + if "k" in size_text: + size += float(size_text.split("k")[0]) * 1024 + elif "m" in size_text: + size += float(size_text.split("m")[0]) * 1048576 + elif "g" in size_text: + size += float(size_text.split("g")[0]) * 1073741824 + elif "t" in size_text: + size += float(size_text.split("t")[0]) * 1099511627776 + elif "b" in size_text: + size += float(size_text.split("b")[0]) + return size + + +def get_progress_bar_string(pct): + pct = float(pct.strip("%")) + p = min(max(pct, 0), 100) + cFull = int(p // 8) + p_str = "■" * cFull + p_str += "□" * (12 - cFull) + return f"[{p_str}]" + + +async def get_readable_message(sid, is_user, page_no=1, status="All", page_step=1): + msg = "" + button = None + + tasks = await get_specific_tasks(status, sid if is_user else None) + + STATUS_LIMIT = Config.STATUS_LIMIT + tasks_no = len(tasks) + pages = (max(tasks_no, 1) + STATUS_LIMIT - 1) // STATUS_LIMIT + if page_no > pages: + page_no = (page_no - 1) % pages + 1 + status_dict[sid]["page_no"] = page_no + elif page_no < 1: + page_no = pages - (abs(page_no) % pages) + status_dict[sid]["page_no"] = page_no + start_position = (page_no - 1) * STATUS_LIMIT + + for index, task in enumerate( + tasks[start_position : STATUS_LIMIT + start_position], start=1 + ): + if status != "All": + tstatus = status + elif iscoroutinefunction(task.status): + tstatus = await task.status() + else: + tstatus = task.status() + if task.listener.is_super_chat: + msg += f"{index + start_position}.{tstatus}: " + else: + msg += f"{index + start_position}.{tstatus}: " + msg += f"{escape(f'{task.name()}')}" + if task.listener.subname: + msg += f"\n{task.listener.subname}" + if ( + tstatus not in [MirrorStatus.STATUS_SEED, MirrorStatus.STATUS_QUEUEUP] + and task.listener.progress + ): + progress = task.progress() + msg += f"\n{get_progress_bar_string(progress)} {progress}" + if task.listener.subname: + subsize = f"/{get_readable_file_size(task.listener.subsize)}" + ac = len(task.listener.files_to_proceed) + count = f"{task.listener.proceed_count}/{ac or '?'}" + else: + subsize = "" + count = "" + msg += f"\nProcessed: {task.processed_bytes()}{subsize}" + if count: + msg += f"\nCount: {count}" + msg += f"\nSize: {task.size()}" + msg += f"\nSpeed: {task.speed()}" + msg += f"\nETA: {task.eta()}" + if ( + tstatus == MirrorStatus.STATUS_DOWNLOAD + and task.listener.is_torrent + or task.listener.is_qbit + ): + try: + msg += f"\nSeeders: {task.seeders_num()} | Leechers: {task.leechers_num()}" + except: + pass + elif tstatus == MirrorStatus.STATUS_SEED: + msg += f"\nSize: {task.size()}" + msg += f"\nSpeed: {task.seed_speed()}" + msg += f"\nUploaded: {task.uploaded_bytes()}" + msg += f"\nRatio: {task.ratio()}" + msg += f" | Time: {task.seeding_time()}" + else: + msg += f"\nSize: {task.size()}" + msg += f"\n/{BotCommands.CancelTaskCommand[1]} {task.gid()}\n\n" + + if len(msg) == 0: + if status == "All": + return None, None + else: + msg = f"No Active {status} Tasks!\n\n" + buttons = ButtonMaker() + if not is_user: + buttons.data_button("📜", f"status {sid} ov", position="header") + if len(tasks) > STATUS_LIMIT: + msg += f"Page: {page_no}/{pages} | Tasks: {tasks_no} | Step: {page_step}\n" + buttons.data_button("<<", f"status {sid} pre", position="header") + buttons.data_button(">>", f"status {sid} nex", position="header") + if tasks_no > 30: + for i in [1, 2, 4, 6, 8, 10, 15]: + buttons.data_button(i, f"status {sid} ps {i}", position="footer") + if status != "All" or tasks_no > 20: + for label, status_value in list(STATUSES.items()): + if status_value != status: + buttons.data_button(label, f"status {sid} st {status_value}") + buttons.data_button("♻️", f"status {sid} ref", position="header") + button = buttons.build_menu(8) + msg += f"CPU: {cpu_percent()}% | FREE: {get_readable_file_size(disk_usage(DOWNLOAD_DIR).free)}" + msg += f"\nRAM: {virtual_memory().percent}% | UPTIME: {get_readable_time(time() - bot_start_time)}" + return msg, button diff --git a/bot/helper/ext_utils/task_manager.py b/bot/helper/ext_utils/task_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..fdddbaa8ab3571aa141166773b64b7a981773aeb --- /dev/null +++ b/bot/helper/ext_utils/task_manager.py @@ -0,0 +1,154 @@ +from asyncio import Event + +from ... import ( + queued_dl, + queued_up, + non_queued_up, + non_queued_dl, + queue_dict_lock, + LOGGER, +) +from ...core.config_manager import Config +from ..mirror_leech_utils.gdrive_utils.search import GoogleDriveSearch +from .bot_utils import sync_to_async, get_telegraph_list +from .files_utils import get_base_name +from .links_utils import is_gdrive_id + + +async def stop_duplicate_check(listener): + if ( + listener.is_leech + or not listener.stop_duplicate + or listener.same_dir + or listener.select + or not is_gdrive_id(listener.up_dest) + ): + return False, None + + name = listener.name + LOGGER.info(f"Checking File/Folder if already in Drive: {name}") + + if listener.compress: + name = f"{name}.zip" + elif listener.extract: + try: + name = get_base_name(name) + except: + name = None + + if name is not None: + telegraph_content, contents_no = await sync_to_async( + GoogleDriveSearch(stop_dup=True, no_multi=listener.is_clone).drive_list, + name, + listener.up_dest, + listener.user_id, + ) + if telegraph_content: + msg = f"File/Folder is already available in Drive.\nHere are {contents_no} list results:" + button = await get_telegraph_list(telegraph_content) + return msg, button + + return False, None + + +async def check_running_tasks(listener, state="dl"): + all_limit = Config.QUEUE_ALL + state_limit = Config.QUEUE_DOWNLOAD if state == "dl" else Config.QUEUE_UPLOAD + event = None + is_over_limit = False + async with queue_dict_lock: + if state == "up" and listener.mid in non_queued_dl: + non_queued_dl.remove(listener.mid) + if ( + (all_limit or state_limit) + and not listener.force_run + and not (listener.force_upload and state == "up") + and not (listener.force_download and state == "dl") + ): + dl_count = len(non_queued_dl) + up_count = len(non_queued_up) + t_count = dl_count if state == "dl" else up_count + is_over_limit = ( + all_limit + and dl_count + up_count >= all_limit + and (not state_limit or t_count >= state_limit) + ) or (state_limit and t_count >= state_limit) + if is_over_limit: + event = Event() + if state == "dl": + queued_dl[listener.mid] = event + else: + queued_up[listener.mid] = event + if not is_over_limit: + if state == "up": + non_queued_up.add(listener.mid) + else: + non_queued_dl.add(listener.mid) + + return is_over_limit, event + + +async def start_dl_from_queued(mid: int): + queued_dl[mid].set() + del queued_dl[mid] + non_queued_dl.add(mid) + + +async def start_up_from_queued(mid: int): + queued_up[mid].set() + del queued_up[mid] + non_queued_up.add(mid) + + +async def start_from_queued(): + if all_limit := Config.QUEUE_ALL: + dl_limit = Config.QUEUE_DOWNLOAD + up_limit = Config.QUEUE_UPLOAD + async with queue_dict_lock: + dl = len(non_queued_dl) + up = len(non_queued_up) + all_ = dl + up + if all_ < all_limit: + f_tasks = all_limit - all_ + if queued_up and (not up_limit or up < up_limit): + for index, mid in enumerate(list(queued_up.keys()), start=1): + await start_up_from_queued(mid) + f_tasks -= 1 + if f_tasks == 0 or (up_limit and index >= up_limit - up): + break + if queued_dl and (not dl_limit or dl < dl_limit) and f_tasks != 0: + for index, mid in enumerate(list(queued_dl.keys()), start=1): + await start_dl_from_queued(mid) + if (dl_limit and index >= dl_limit - dl) or index == f_tasks: + break + return + + if up_limit := Config.QUEUE_UPLOAD: + async with queue_dict_lock: + up = len(non_queued_up) + if queued_up and up < up_limit: + f_tasks = up_limit - up + for index, mid in enumerate(list(queued_up.keys()), start=1): + await start_up_from_queued(mid) + if index == f_tasks: + break + else: + async with queue_dict_lock: + if queued_up: + for mid in list(queued_up.keys()): + await start_up_from_queued(mid) + + if dl_limit := Config.QUEUE_DOWNLOAD: + async with queue_dict_lock: + dl = len(non_queued_dl) + if queued_dl and dl < dl_limit: + f_tasks = dl_limit - dl + for index, mid in enumerate(list(queued_dl.keys()), start=1): + await start_dl_from_queued(mid) + if index == f_tasks: + break + else: + async with queue_dict_lock: + if queued_dl: + for mid in list(queued_dl.keys()): + await start_dl_from_queued(mid) diff --git a/bot/helper/ext_utils/telegraph_helper.py b/bot/helper/ext_utils/telegraph_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..e27ac0429853efacc07bfb1883025944233cdcdb --- /dev/null +++ b/bot/helper/ext_utils/telegraph_helper.py @@ -0,0 +1,86 @@ +from asyncio import sleep +from secrets import token_urlsafe +from telegraph.aio import Telegraph +from telegraph.exceptions import RetryAfterError + +from ... import LOGGER + + +class TelegraphHelper: + def __init__(self, author_name=None, author_url=None): + self._telegraph = Telegraph(domain="graph.org") + self._author_name = author_name + self._author_url = author_url + + async def create_account(self): + LOGGER.info("Creating Telegraph Account") + try: + await self._telegraph.create_account( + short_name=token_urlsafe(8), + author_name=self._author_name, + author_url=self._author_url, + ) + except Exception as e: + LOGGER.error(f"Failed to create Telegraph Account: {e}") + + async def create_page(self, title, content): + try: + return await 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." + ) + await sleep(st.retry_after) + return await self.create_page(title, content) + + async def edit_page(self, path, title, content): + try: + return await 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." + ) + await sleep(st.retry_after) + return await self.edit_page(path, title, content) + + async 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 + await self.edit_page( + path=path[prev_page], + title="Mirror-leech-bot Torrent Search", + content=content, + ) + return + + +telegraph = TelegraphHelper( + "Mirror-Leech-Telegram-Bot", "https://github.com/anasty17/mirror-leech-telegram-bot" +) + +print(__name__) diff --git a/bot/helper/listeners/__init__.py b/bot/helper/listeners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/listeners/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/listeners/aria2_listener.py b/bot/helper/listeners/aria2_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..cca6ef53a4fc43f0ece235f6a43fc5c5787886b9 --- /dev/null +++ b/bot/helper/listeners/aria2_listener.py @@ -0,0 +1,195 @@ +from aiofiles.os import remove, path as aiopath +from asyncio import sleep, TimeoutError +from time import time +from aiohttp.client_exceptions import ClientError + +from ... import task_dict_lock, task_dict, LOGGER, intervals +from ...core.config_manager import Config +from ...core.torrent_manager import TorrentManager, is_metadata, aria2_name +from ..ext_utils.bot_utils import bt_selection_buttons +from ..ext_utils.files_utils import clean_unwanted +from ..ext_utils.status_utils import get_task_by_gid +from ..ext_utils.task_manager import stop_duplicate_check +from ..mirror_leech_utils.status_utils.aria2_status import Aria2Status +from ..telegram_helper.message_utils import ( + send_message, + delete_message, + update_status_message, +) + + +async def _on_download_started(api, data): + gid = data["params"][0]["gid"] + download = await api.tellStatus(gid) + options = await api.getOption(gid) + if options.get("follow-torrent", "") == "false": + return + if is_metadata(download): + LOGGER.info(f"onDownloadStarted: {gid} METADATA") + await sleep(1) + if task := await get_task_by_gid(gid): + task.listener.is_torrent = True + if task.listener.select: + metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait." + meta = await send_message(task.listener.message, metamsg) + while True: + await sleep(0.5) + if download.get("status", "") == "removed" or download.get( + "followedBy", [] + ): + await delete_message(meta) + break + download = await api.tellStatus(gid) + return + else: + LOGGER.info(f"onDownloadStarted: {aria2_name(download)} - Gid: {gid}") + await sleep(1) + + await sleep(2) + if task := await get_task_by_gid(gid): + download = await api.tellStatus(gid) + if "bittorrent" in download: + task.listener.is_torrent = True + task.listener.name = aria2_name(download) + msg, button = await stop_duplicate_check(task.listener) + if msg: + await TorrentManager.aria2_remove(download) + await task.listener.on_download_error(msg, button) + + +async def _on_download_complete(api, data): + try: + gid = data["params"][0]["gid"] + download = await api.tellStatus(gid) + options = await api.getOption(gid) + except (TimeoutError, ClientError, Exception) as e: + LOGGER.error(f"onDownloadComplete: {e}") + return + if options.get("follow-torrent", "") == "false": + return + if download.get("followedBy", []): + new_gid = download.get("followedBy", [])[0] + LOGGER.info(f"Gid changed from {gid} to {new_gid}") + if task := await get_task_by_gid(new_gid): + task.listener.is_torrent = True + if Config.BASE_URL and task.listener.select: + if not task.queued: + await api.forcePause(new_gid) + SBUTTONS = bt_selection_buttons(new_gid) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + await send_message(task.listener.message, msg, SBUTTONS) + elif "bittorrent" in download: + if task := await get_task_by_gid(gid): + task.listener.is_torrent = True + if hasattr(task, "seeding") and task.seeding: + LOGGER.info( + f"Cancelling Seed: {aria2_name(download)} onDownloadComplete" + ) + await TorrentManager.aria2_remove(download) + await task.listener.on_upload_error( + f"Seeding stopped with Ratio: {task.ratio()} and Time: {task.seeding_time()}" + ) + else: + LOGGER.info(f"onDownloadComplete: {aria2_name(download)} - Gid: {gid}") + if task := await get_task_by_gid(gid): + await task.listener.on_download_complete() + if intervals["stopAll"]: + return + await TorrentManager.aria2_remove(download) + + +async def _on_bt_download_complete(api, data): + gid = data["params"][0]["gid"] + await sleep(1) + download = await api.tellStatus(gid) + LOGGER.info(f"onBtDownloadComplete: {aria2_name(download)} - Gid: {gid}") + if task := await get_task_by_gid(gid): + task.listener.is_torrent = True + if task.listener.select: + res = download.get("files", []) + for file_o in res: + f_path = file_o.get("path", "") + if file_o.get("selected", "") != "true" and await aiopath.exists( + f_path + ): + try: + await remove(f_path) + except: + pass + await clean_unwanted(download.get("dir", "")) + if task.listener.seed: + try: + await api.changeOption(gid, {"max-upload-limit": "0"}) + except (TimeoutError, ClientError, 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 GID: {gid}" + ) + else: + try: + await api.forcePause(gid) + except (TimeoutError, ClientError, Exception) as e: + LOGGER.error(f"onBtDownloadComplete: {e} GID: {gid}") + await task.listener.on_download_complete() + if intervals["stopAll"]: + return + download = await api.tellStatus(gid) + if ( + task.listener.seed + and download.get("status", "") == "complete" + and await get_task_by_gid(gid) + ): + LOGGER.info(f"Cancelling Seed: {aria2_name(download)}") + await TorrentManager.aria2_remove(download) + await task.listener.on_upload_error( + f"Seeding stopped with Ratio: {task.ratio()} and Time: {task.seeding_time()}" + ) + elif ( + task.listener.seed + and download.get("status", "") == "complete" + and not await get_task_by_gid(gid) + ): + pass + elif task.listener.seed and not task.listener.is_cancelled: + async with task_dict_lock: + if task.listener.mid not in task_dict: + await TorrentManager.aria2_remove(download) + return + task_dict[task.listener.mid] = Aria2Status(task.listener, gid, True) + task_dict[task.listener.mid].start_time = time() + LOGGER.info(f"Seeding started: {aria2_name(download)} - Gid: {gid}") + await update_status_message(task.listener.message.chat.id) + else: + await TorrentManager.aria2_remove(download) + + +async def _on_download_stopped(_, data): + gid = data["params"][0]["gid"] + await sleep(4) + if task := await get_task_by_gid(gid): + await task.listener.on_download_error("Dead torrent!") + + +async def _on_download_error(api, data): + gid = data["params"][0]["gid"] + await sleep(1) + LOGGER.info(f"onDownloadError: {gid}") + error = "None" + try: + download = await api.tellStatus(gid) + options = await api.getOption(gid) + error = download.get("errorMessage", "") + LOGGER.info(f"Download Error: {error}") + if options.get("follow-torrent", "") == "false": + return + except (TimeoutError, ClientError, Exception) as e: + return + if task := await get_task_by_gid(gid): + await task.listener.on_download_error(error) + + +def add_aria2_callbacks(): + TorrentManager.aria2.onBtDownloadComplete(_on_bt_download_complete) + TorrentManager.aria2.onDownloadComplete(_on_download_complete) + TorrentManager.aria2.onDownloadError(_on_download_error) + TorrentManager.aria2.onDownloadStart(_on_download_started) + TorrentManager.aria2.onDownloadStop(_on_download_stopped) diff --git a/bot/helper/listeners/direct_listener.py b/bot/helper/listeners/direct_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7ac06b7b455de457862804e6060d69ee77927d --- /dev/null +++ b/bot/helper/listeners/direct_listener.py @@ -0,0 +1,86 @@ +from asyncio import sleep, TimeoutError +from aiohttp.client_exceptions import ClientError + +from ... import LOGGER +from ...core.torrent_manager import TorrentManager, aria2_name + + +class DirectListener: + def __init__(self, path, listener, a2c_opt): + self.listener = listener + self._path = path + self._a2c_opt = a2c_opt + self._proc_bytes = 0 + self._failed = 0 + self.download_task = None + self.name = self.listener.name + + @property + def processed_bytes(self): + if self.download_task: + return self._proc_bytes + int( + self.download_task.get("completedLength", "0") + ) + return self._proc_bytes + + @property + def speed(self): + return ( + int(self.download_task.get("downloadSpeed", "0")) + if self.download_task + else 0 + ) + + async def download(self, contents): + self.is_downloading = True + for content in contents: + if self.listener.is_cancelled: + break + if content["path"]: + self._a2c_opt["dir"] = f"{self._path}/{content['path']}" + else: + self._a2c_opt["dir"] = self._path + filename = content["filename"] + self._a2c_opt["out"] = filename + try: + gid = await TorrentManager.aria2.addUri( + uris=[content["url"]], options=self._a2c_opt, position=0 + ) + except (TimeoutError, ClientError, Exception) as e: + self._failed += 1 + LOGGER.error(f"Unable to download {filename} due to: {e}") + continue + self.download_task = await TorrentManager.aria2.tellStatus(gid) + while True: + if self.listener.is_cancelled: + if self.download_task: + await TorrentManager.aria2_remove(self.download_task) + break + self.download_task = await TorrentManager.aria2.tellStatus(gid) + if error_message := self.download_task.get("errorMessage"): + self._failed += 1 + LOGGER.error( + f"Unable to download {aria2_name(self.download_task)} due to: {error_message}" + ) + await TorrentManager.aria2_remove(self.download_task) + break + elif self.download_task.get("status", "") == "complete": + self._proc_bytes += int(self.download_task.get("totalLength", "0")) + await TorrentManager.aria2_remove(self.download_task) + break + await sleep(1) + self.download_task = None + if self.listener.is_cancelled: + return + if self._failed == len(contents): + await self.listener.on_download_error("All files are failed to download!") + return + await self.listener.on_download_complete() + return + + async def cancel_task(self): + self.listener.is_cancelled = True + LOGGER.info(f"Cancelling Download: {self.listener.name}") + await self.listener.on_download_error("Download Cancelled by User!") + if self.download_task: + await TorrentManager.aria2_remove(self.download_task) diff --git a/bot/helper/listeners/jdownloader_listener.py b/bot/helper/listeners/jdownloader_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd52c5666a00db823edfc442c1aca24a637d753 --- /dev/null +++ b/bot/helper/listeners/jdownloader_listener.py @@ -0,0 +1,91 @@ +from asyncio import sleep + +from ... import intervals, jd_listener_lock, jd_downloads +from ..ext_utils.bot_utils import new_task +from ...core.jdownloader_booter import jdownloader +from ..ext_utils.status_utils import get_task_by_gid + + +@new_task +async def remove_download(gid): + if intervals["stopAll"]: + return + await jdownloader.device.downloads.remove_links( + package_ids=jd_downloads[gid]["ids"] + ) + if task := await get_task_by_gid(gid): + await task.listener.on_download_error("Download removed manually!") + async with jd_listener_lock: + del jd_downloads[gid] + + +@new_task +async def _on_download_complete(gid): + if task := await get_task_by_gid(gid): + if task.listener.select: + async with jd_listener_lock: + await jdownloader.device.downloads.cleanup( + "DELETE_DISABLED", + "REMOVE_LINKS_AND_DELETE_FILES", + "ALL", + package_ids=jd_downloads[gid]["ids"], + ) + await task.listener.on_download_complete() + if intervals["stopAll"]: + return + async with jd_listener_lock: + if gid in jd_downloads: + await jdownloader.device.downloads.remove_links( + package_ids=jd_downloads[gid]["ids"], + ) + del jd_downloads[gid] + + +@new_task +async def _jd_listener(): + while True: + await sleep(3) + async with jd_listener_lock: + if len(jd_downloads) == 0: + intervals["jd"] = "" + break + try: + packages = await jdownloader.device.downloads.query_packages( + [{"finished": True, "saveTo": True}] + ) + except: + continue + + all_packages = {pack["uuid"]: pack for pack in packages} + for d_gid, d_dict in list(jd_downloads.items()): + if d_dict["status"] == "down": + for index, pid in enumerate(d_dict["ids"]): + if pid not in all_packages: + del jd_downloads[d_gid]["ids"][index] + if len(jd_downloads[d_gid]["ids"]) == 0: + path = jd_downloads[d_gid]["path"] + jd_downloads[d_gid]["ids"] = [ + uid + for uid, pk in all_packages.items() + if pk["saveTo"].startswith(path) + ] + if len(jd_downloads[d_gid]["ids"]) == 0: + await remove_download(d_gid) + + if completed_packages := [ + pack["uuid"] for pack in packages if pack.get("finished", False) + ]: + for d_gid, d_dict in list(jd_downloads.items()): + if d_dict["status"] == "down": + is_finished = all( + did in completed_packages for did in d_dict["ids"] + ) + if is_finished: + jd_downloads[d_gid]["status"] = "done" + await _on_download_complete(d_gid) + + +async def on_download_start(): + async with jd_listener_lock: + if not intervals["jd"]: + intervals["jd"] = await _jd_listener() diff --git a/bot/helper/listeners/nzb_listener.py b/bot/helper/listeners/nzb_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f2757c0bad11609009dbffcd20bca4baa98fae --- /dev/null +++ b/bot/helper/listeners/nzb_listener.py @@ -0,0 +1,104 @@ +from asyncio import sleep, gather + +from ... import ( + intervals, + sabnzbd_client, + nzb_jobs, + nzb_listener_lock, + LOGGER, +) +from ..ext_utils.bot_utils import new_task +from ..ext_utils.status_utils import get_task_by_gid +from ..ext_utils.task_manager import stop_duplicate_check + + +async def _remove_job(nzo_id, mid): + res1, _ = await gather( + sabnzbd_client.delete_history(nzo_id, delete_files=True), + sabnzbd_client.delete_category(f"{mid}"), + ) + if not res1: + await sabnzbd_client.delete_job(nzo_id, True) + async with nzb_listener_lock: + if nzo_id in nzb_jobs: + del nzb_jobs[nzo_id] + + +@new_task +async def _on_download_error(err, nzo_id, button=None): + if task := await get_task_by_gid(nzo_id): + LOGGER.info(f"Cancelling Download: {task.name()}") + await gather( + task.listener.on_download_error(err, button), + _remove_job(nzo_id, task.listener.mid), + ) + + +@new_task +async def _stop_duplicate(nzo_id): + if task := await get_task_by_gid(nzo_id): + await task.update() + task.listener.name = task.name() + msg, button = await stop_duplicate_check(task.listener) + if msg: + _on_download_error(msg, nzo_id, button) + + +@new_task +async def _on_download_complete(nzo_id): + if task := await get_task_by_gid(nzo_id): + await task.listener.on_download_complete() + if intervals["stopAll"]: + return + await _remove_job(nzo_id, task.listener.mid) + + +@new_task +async def _nzb_listener(): + while not intervals["stopAll"]: + async with nzb_listener_lock: + try: + jobs = (await sabnzbd_client.get_history())["history"]["slots"] + downloads = (await sabnzbd_client.get_downloads())["queue"]["slots"] + if len(nzb_jobs) == 0: + intervals["nzb"] = "" + break + for job in jobs: + nzo_id = job["nzo_id"] + if nzo_id not in nzb_jobs: + continue + if job["status"] == "Completed": + if not nzb_jobs[nzo_id]["uploaded"]: + nzb_jobs[nzo_id]["uploaded"] = True + await _on_download_complete(nzo_id) + nzb_jobs[nzo_id]["status"] = "Completed" + elif job["status"] == "Failed": + await _on_download_error(job["fail_message"], nzo_id) + for dl in downloads: + nzo_id = dl["nzo_id"] + if nzo_id not in nzb_jobs: + continue + if dl["labels"] and dl["labels"][0] == "ALTERNATIVE": + await _on_download_error("Duplicated Job!", nzo_id) + continue + if ( + dl["status"] == "Downloading" + and not nzb_jobs[nzo_id]["stop_dup_check"] + and not dl["filename"].startswith("Trying") + ): + nzb_jobs[nzo_id]["stop_dup_check"] = True + await _stop_duplicate(nzo_id) + except Exception as e: + LOGGER.error(str(e)) + await sleep(3) + + +async def on_download_start(nzo_id): + async with nzb_listener_lock: + nzb_jobs[nzo_id] = { + "uploaded": False, + "stop_dup_check": False, + "status": "Downloading", + } + if not intervals["nzb"]: + intervals["nzb"] = await _nzb_listener() diff --git a/bot/helper/listeners/qbit_listener.py b/bot/helper/listeners/qbit_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca296a9a986fc5ce6d75638e2cd657404d3d785 --- /dev/null +++ b/bot/helper/listeners/qbit_listener.py @@ -0,0 +1,202 @@ +from aiofiles.os import remove, path as aiopath +from asyncio import sleep, TimeoutError +from time import time +from aiohttp.client_exceptions import ClientError +from aioqbt.exc import AQError + +from ... import ( + task_dict, + task_dict_lock, + intervals, + qb_torrents, + qb_listener_lock, + LOGGER, +) +from ...core.config_manager import Config +from ...core.torrent_manager import TorrentManager +from ..ext_utils.bot_utils import new_task +from ..ext_utils.files_utils import clean_unwanted +from ..ext_utils.status_utils import get_readable_time, get_task_by_gid +from ..ext_utils.task_manager import stop_duplicate_check +from ..mirror_leech_utils.status_utils.qbit_status import QbittorrentStatus +from ..telegram_helper.message_utils import update_status_message + + +async def _remove_torrent(hash_, tag): + await TorrentManager.qbittorrent.torrents.delete([hash_], True) + async with qb_listener_lock: + if tag in qb_torrents: + del qb_torrents[tag] + await TorrentManager.qbittorrent.torrents.delete_tags([tag]) + + +@new_task +async def _on_download_error(err, tor, button=None): + LOGGER.info(f"Cancelling Download: {tor.name}") + ext_hash = tor.hash + if task := await get_task_by_gid(ext_hash[:12]): + await task.listener.on_download_error(err, button) + await TorrentManager.qbittorrent.torrents.stop([ext_hash]) + await sleep(0.3) + await _remove_torrent(ext_hash, tor.tags[0]) + + +@new_task +async def _on_seed_finish(tor): + ext_hash = tor.hash + LOGGER.info(f"Cancelling Seed: {tor.name}") + if task := await get_task_by_gid(ext_hash[:12]): + msg = f"Seeding stopped with Ratio: {round(tor.ratio, 3)} and Time: {get_readable_time(int(tor.seeding_time.total_seconds() or "0"))}" + await task.listener.on_upload_error(msg) + await _remove_torrent(ext_hash, tor.tags[0]) + + +@new_task +async def _stop_duplicate(tor): + if task := await get_task_by_gid(tor.hash[:12]): + if task.listener.stop_duplicate: + task.listener.name = tor.content_path.rsplit("/", 1)[-1].rsplit(".!qB", 1)[ + 0 + ] + msg, button = await stop_duplicate_check(task.listener) + if msg: + _on_download_error(msg, tor, button) + + +@new_task +async def _on_download_complete(tor): + ext_hash = tor.hash + tag = tor.tags[0] + if task := await get_task_by_gid(ext_hash[:12]): + if not task.listener.seed: + await TorrentManager.qbittorrent.torrents.stop([ext_hash]) + if task.listener.select: + await clean_unwanted(task.listener.dir) + path = tor.content_path.rsplit("/", 1)[0] + res = await TorrentManager.qbittorrent.torrents.files(ext_hash) + for f in res: + if f.priority == 0 and await aiopath.exists(f"{path}/{f.name}"): + try: + await remove(f"{path}/{f.name}") + except: + pass + await task.listener.on_download_complete() + if intervals["stopAll"]: + return + if task.listener.seed and not task.listener.is_cancelled: + async with task_dict_lock: + if task.listener.mid in task_dict: + removed = False + task_dict[task.listener.mid] = QbittorrentStatus( + task.listener, True + ) + else: + removed = True + if removed: + await _remove_torrent(ext_hash, tag) + return + async with qb_listener_lock: + if tag in qb_torrents: + qb_torrents[tag]["seeding"] = True + else: + return + await update_status_message(task.listener.message.chat.id) + LOGGER.info(f"Seeding started: {tor.name} - Hash: {ext_hash}") + else: + await _remove_torrent(ext_hash, tag) + else: + await _remove_torrent(ext_hash, tag) + + +@new_task +async def _qb_listener(): + while True: + async with qb_listener_lock: + try: + torrents = await TorrentManager.qbittorrent.torrents.info() + if len(torrents) == 0: + intervals["qb"] = "" + break + for tor_info in torrents: + tag = tor_info.tags[0] + if tag not in qb_torrents: + continue + state = tor_info.state + if state == "metaDL": + qb_torrents[tag]["stalled_time"] = time() + if ( + Config.TORRENT_TIMEOUT + and time() - qb_torrents[tag]["start_time"] + >= Config.TORRENT_TIMEOUT + ): + await _on_download_error("Dead Torrent!", tor_info) + else: + await TorrentManager.qbittorrent.torrents.reannounce( + [tor_info.hash] + ) + elif state == "downloading": + qb_torrents[tag]["stalled_time"] = time() + if not qb_torrents[tag]["stop_dup_check"]: + qb_torrents[tag]["stop_dup_check"] = True + await _stop_duplicate(tor_info) + elif state == "stalledDL": + if ( + not qb_torrents[tag]["rechecked"] + and 0.99989999999999999 < tor_info.progress < 1 + ): + msg = f"Force recheck - Name: {tor_info.name} Hash: " + msg += f"{tor_info.hash} Downloaded Bytes: {tor_info.downloaded} " + msg += f"Size: {tor_info.size} Total Size: {tor_info.total_size}" + LOGGER.warning(msg) + await TorrentManager.qbittorrent.torrents.recheck( + [tor_info.hash] + ) + qb_torrents[tag]["rechecked"] = True + elif ( + Config.TORRENT_TIMEOUT + and time() - qb_torrents[tag]["stalled_time"] + >= Config.TORRENT_TIMEOUT + ): + await _on_download_error("Dead Torrent!", tor_info) + else: + await TorrentManager.qbittorrent.torrents.reannounce( + [tor_info.hash] + ) + elif state == "missingFiles": + await TorrentManager.qbittorrent.torrents.recheck( + [tor_info.hash] + ) + elif state == "error": + await _on_download_error( + "No enough space for this torrent on device", tor_info + ) + elif ( + int(tor_info.completion_on.timestamp()) != -1 + and not qb_torrents[tag]["uploaded"] + ): + qb_torrents[tag]["uploaded"] = True + await _on_download_complete(tor_info) + elif ( + state in ["stoppedUP", "stoppedDL"] + and qb_torrents[tag]["seeding"] + ): + qb_torrents[tag]["seeding"] = False + await _on_seed_finish(tor_info) + await sleep(0.5) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(str(e)) + await sleep(3) + + +async def on_download_start(tag): + async with qb_listener_lock: + qb_torrents[tag] = { + "start_time": time(), + "stalled_time": time(), + "stop_dup_check": False, + "rechecked": False, + "uploaded": False, + "seeding": False, + } + if not intervals["qb"]: + intervals["qb"] = await _qb_listener() diff --git a/bot/helper/listeners/task_listener.py b/bot/helper/listeners/task_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..e57cfba2351cf630dcf41b06f150a6b9959f54e5 --- /dev/null +++ b/bot/helper/listeners/task_listener.py @@ -0,0 +1,494 @@ +from aiofiles.os import path as aiopath, listdir, remove +from asyncio import sleep, gather +from html import escape +from requests import utils as rutils + +from ... import ( + intervals, + task_dict, + task_dict_lock, + LOGGER, + non_queued_up, + non_queued_dl, + queued_up, + queued_dl, + queue_dict_lock, + same_directory_lock, + DOWNLOAD_DIR, +) +from ...core.config_manager import Config +from ...core.torrent_manager import TorrentManager +from ..common import TaskConfig +from ..ext_utils.bot_utils import sync_to_async +from ..ext_utils.db_handler import database +from ..ext_utils.files_utils import ( + get_path_size, + clean_download, + clean_target, + join_files, + create_recursive_symlink, + remove_excluded_files, + remove_non_included_files, + move_and_merge, +) +from ..ext_utils.links_utils import is_gdrive_id +from ..ext_utils.status_utils import get_readable_file_size +from ..ext_utils.task_manager import start_from_queued, check_running_tasks +from ..mirror_leech_utils.gdrive_utils.upload import GoogleDriveUpload +from ..mirror_leech_utils.rclone_utils.transfer import RcloneTransferHelper +from ..mirror_leech_utils.status_utils.gdrive_status import GoogleDriveStatus +from ..mirror_leech_utils.status_utils.queue_status import QueueStatus +from ..mirror_leech_utils.status_utils.rclone_status import RcloneStatus +from ..mirror_leech_utils.status_utils.telegram_status import TelegramStatus +from ..mirror_leech_utils.telegram_uploader import TelegramUploader +from ..telegram_helper.button_build import ButtonMaker +from ..telegram_helper.message_utils import ( + send_message, + delete_status, + update_status_message, +) + + +class TaskListener(TaskConfig): + def __init__(self): + super().__init__() + + async def clean(self): + try: + if st := intervals["status"]: + for intvl in list(st.values()): + intvl.cancel() + intervals["status"].clear() + await gather(TorrentManager.aria2.purgeDownloadResult(), delete_status()) + except: + pass + + def clear(self): + self.subname = "" + self.subsize = 0 + self.files_to_proceed = [] + self.proceed_count = 0 + self.progress = True + + async def remove_from_same_dir(self): + async with task_dict_lock: + if ( + self.folder_name + and self.same_dir + and self.mid in self.same_dir[self.folder_name]["tasks"] + ): + self.same_dir[self.folder_name]["tasks"].remove(self.mid) + self.same_dir[self.folder_name]["total"] -= 1 + + async def on_download_start(self): + if ( + self.is_super_chat + and Config.INCOMPLETE_TASK_NOTIFIER + and Config.DATABASE_URL + ): + await database.add_incomplete_task( + self.message.chat.id, self.message.link, self.tag + ) + + async def on_download_complete(self): + await sleep(2) + if self.is_cancelled: + return + multi_links = False + if ( + self.folder_name + and self.same_dir + and self.mid in self.same_dir[self.folder_name]["tasks"] + ): + async with same_directory_lock: + while True: + async with task_dict_lock: + if self.mid not in self.same_dir[self.folder_name]["tasks"]: + return + if ( + self.same_dir[self.folder_name]["total"] <= 1 + or len(self.same_dir[self.folder_name]["tasks"]) > 1 + ): + if self.same_dir[self.folder_name]["total"] > 1: + self.same_dir[self.folder_name]["tasks"].remove( + self.mid + ) + self.same_dir[self.folder_name]["total"] -= 1 + spath = f"{self.dir}{self.folder_name}" + des_id = list(self.same_dir[self.folder_name]["tasks"])[ + 0 + ] + des_path = f"{DOWNLOAD_DIR}{des_id}{self.folder_name}" + LOGGER.info(f"Moving files from {self.mid} to {des_id}") + await move_and_merge(spath, des_path, self.mid) + multi_links = True + break + await sleep(1) + async with task_dict_lock: + if self.is_cancelled: + return + if self.mid not in task_dict: + return + download = task_dict[self.mid] + self.name = download.name() + gid = download.gid() + LOGGER.info(f"Download completed: {self.name}") + + if not (self.is_torrent or self.is_qbit): + self.seed = False + + if multi_links: + self.seed = False + await self.on_upload_error( + f"{self.name} Downloaded!\n\nWaiting for other tasks to finish..." + ) + return + elif self.same_dir: + self.seed = False + + if self.folder_name: + self.name = self.folder_name.strip("/").split("/", 1)[0] + + if not await aiopath.exists(f"{self.dir}/{self.name}"): + try: + files = await listdir(self.dir) + self.name = files[-1] + if self.name == "yt-dlp-thumb": + self.name = files[0] + except Exception as e: + await self.on_upload_error(str(e)) + return + + dl_path = f"{self.dir}/{self.name}" + self.size = await get_path_size(dl_path) + self.is_file = await aiopath.isfile(dl_path) + + if self.seed: + up_dir = self.up_dir = f"{self.dir}10000" + up_path = f"{self.up_dir}/{self.name}" + await create_recursive_symlink(self.dir, self.up_dir) + LOGGER.info(f"Shortcut created: {dl_path} -> {up_path}") + else: + up_dir = self.dir + up_path = dl_path + + if not self.included_extensions: + await remove_excluded_files( + self.up_dir or self.dir, self.excluded_extensions + ) + else: + await remove_non_included_files( + self.up_dir or self.dir, self.included_extensions + ) + + if not await aiopath.exists(up_path): + e = "No files to upload. In case you have filled EXCLUDED/INCLUDED EXTENSIONS, then check if all files have those extensions or not." + await self.on_upload_error(str(e)) + return + + if not Config.QUEUE_ALL: + async with queue_dict_lock: + if self.mid in non_queued_dl: + non_queued_dl.remove(self.mid) + await start_from_queued() + + if self.join and not self.is_file: + await join_files(up_path) + + if self.extract and not self.is_nzb: + up_path = await self.proceed_extract(up_path, gid) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + self.clear() + if not self.included_extensions: + await remove_excluded_files(up_dir, self.excluded_extensions) + else: + await remove_non_included_files(up_dir, self.included_extensions) + + if self.ffmpeg_cmds: + up_path = await self.proceed_ffmpeg( + up_path, + gid, + ) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + self.clear() + + if self.name_sub: + LOGGER.info(f"Start Name Substitution {up_path}") + up_path = await self.substitute(up_path) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + + if self.screen_shots: + up_path = await self.generate_screenshots(up_path) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + + if self.convert_audio or self.convert_video: + up_path = await self.convert_media( + up_path, + gid, + ) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + self.clear() + + if self.sample_video: + up_path = await self.generate_sample_video(up_path, gid) + if self.is_cancelled: + return + self.is_file = await aiopath.isfile(up_path) + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + self.clear() + + if self.compress: + up_path = await self.proceed_compress( + up_path, + gid, + ) + self.is_file = await aiopath.isfile(up_path) + if self.is_cancelled: + return + self.clear() + + self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0] + self.size = await get_path_size(up_dir) + + if self.is_leech and not self.compress: + await self.proceed_split(up_path, gid) + if self.is_cancelled: + return + self.clear() + + self.subproc = None + + add_to_queue, event = await check_running_tasks(self, "up") + await start_from_queued() + if add_to_queue: + LOGGER.info(f"Added to Queue/Upload: {self.name}") + async with task_dict_lock: + task_dict[self.mid] = QueueStatus(self, gid, "Up") + await event.wait() + if self.is_cancelled: + return + LOGGER.info(f"Start from Queued/Upload: {self.name}") + + self.size = await get_path_size(up_dir) + + if self.is_leech: + LOGGER.info(f"Leech Name: {self.name}") + tg = TelegramUploader(self, up_dir) + async with task_dict_lock: + task_dict[self.mid] = TelegramStatus(self, tg, gid, "up") + await gather( + update_status_message(self.message.chat.id), + tg.upload(), + ) + del tg + elif is_gdrive_id(self.up_dest): + LOGGER.info(f"Gdrive Upload Name: {self.name}") + drive = GoogleDriveUpload(self, up_path) + async with task_dict_lock: + task_dict[self.mid] = GoogleDriveStatus(self, drive, gid, "up") + await gather( + update_status_message(self.message.chat.id), + sync_to_async(drive.upload), + ) + del drive + else: + LOGGER.info(f"Rclone Upload Name: {self.name}") + RCTransfer = RcloneTransferHelper(self) + async with task_dict_lock: + task_dict[self.mid] = RcloneStatus(self, RCTransfer, gid, "up") + await gather( + update_status_message(self.message.chat.id), + RCTransfer.upload(up_path), + ) + del RCTransfer + return + + async def on_upload_complete( + self, link, files, folders, mime_type, rclone_path="", dir_id="" + ): + if ( + self.is_super_chat + and Config.INCOMPLETE_TASK_NOTIFIER + and Config.DATABASE_URL + ): + await database.rm_complete_task(self.message.link) + msg = f"Name: {escape(self.name)}\n\nSize: {get_readable_file_size(self.size)}" + LOGGER.info(f"Task Done: {self.name}") + if self.is_leech: + msg += f"\nTotal Files: {folders}" + if mime_type != 0: + msg += f"\nCorrupted Files: {mime_type}" + msg += f"\ncc: {self.tag}\n\n" + if not files: + await send_message(self.message, msg) + else: + fmsg = "" + for index, (link, name) in enumerate(files.items(), start=1): + fmsg += f"{index}. {name}\n" + if len(fmsg.encode() + msg.encode()) > 4000: + await send_message(self.message, msg + fmsg) + await sleep(1) + fmsg = "" + if fmsg != "": + await send_message(self.message, msg + fmsg) + else: + msg += f"\n\nType: {mime_type}" + if mime_type == "Folder": + msg += f"\nSubFolders: {folders}" + msg += f"\nFiles: {files}" + if ( + link + or rclone_path + and Config.RCLONE_SERVE_URL + and not self.private_link + ): + buttons = ButtonMaker() + if link: + buttons.url_button("☁️ Cloud Link", link) + else: + msg += f"\n\nPath: {rclone_path}" + if rclone_path and Config.RCLONE_SERVE_URL and not self.private_link: + remote, rpath = rclone_path.split(":", 1) + url_path = rutils.quote(f"{rpath}") + share_url = f"{Config.RCLONE_SERVE_URL}/{remote}/{url_path}" + if mime_type == "Folder": + share_url += "/" + buttons.url_button("🔗 Rclone Link", share_url) + if not rclone_path and dir_id: + INDEX_URL = "" + if self.private_link: + INDEX_URL = self.user_dict.get("INDEX_URL", "") or "" + elif Config.INDEX_URL: + INDEX_URL = Config.INDEX_URL + if INDEX_URL: + share_url = f"{INDEX_URL}findpath?id={dir_id}" + buttons.url_button("⚡ Index Link", share_url) + if mime_type.startswith(("image", "video", "audio")): + share_urls = f"{INDEX_URL}findpath?id={dir_id}&view=true" + buttons.url_button("🌐 View Link", share_urls) + button = buttons.build_menu(2) + else: + msg += f"\n\nPath: {rclone_path}" + button = None + msg += f"\n\ncc: {self.tag}" + await send_message(self.message, msg, button) + if self.seed: + await clean_target(self.up_dir) + async with queue_dict_lock: + if self.mid in non_queued_up: + non_queued_up.remove(self.mid) + await start_from_queued() + return + await clean_download(self.dir) + async with task_dict_lock: + if self.mid in task_dict: + del task_dict[self.mid] + count = len(task_dict) + if count == 0: + await self.clean() + else: + await update_status_message(self.message.chat.id) + + async with queue_dict_lock: + if self.mid in non_queued_up: + non_queued_up.remove(self.mid) + + await start_from_queued() + + async def on_download_error(self, error, button=None): + async with task_dict_lock: + if self.mid in task_dict: + del task_dict[self.mid] + count = len(task_dict) + await self.remove_from_same_dir() + msg = f"{self.tag} Download: {escape(str(error))}" + await send_message(self.message, msg, button) + if count == 0: + await self.clean() + else: + await update_status_message(self.message.chat.id) + + if ( + self.is_super_chat + and Config.INCOMPLETE_TASK_NOTIFIER + and Config.DATABASE_URL + ): + await database.rm_complete_task(self.message.link) + + async with queue_dict_lock: + if self.mid in queued_dl: + queued_dl[self.mid].set() + del queued_dl[self.mid] + if self.mid in queued_up: + queued_up[self.mid].set() + del queued_up[self.mid] + if self.mid in non_queued_dl: + non_queued_dl.remove(self.mid) + if self.mid in non_queued_up: + non_queued_up.remove(self.mid) + + await start_from_queued() + await sleep(3) + await clean_download(self.dir) + if self.up_dir: + await clean_download(self.up_dir) + if self.thumb and await aiopath.exists(self.thumb): + await remove(self.thumb) + + async def on_upload_error(self, error): + async with task_dict_lock: + if self.mid in task_dict: + del task_dict[self.mid] + count = len(task_dict) + await send_message(self.message, f"{self.tag} {escape(str(error))}") + if count == 0: + await self.clean() + else: + await update_status_message(self.message.chat.id) + + if ( + self.is_super_chat + and Config.INCOMPLETE_TASK_NOTIFIER + and Config.DATABASE_URL + ): + await database.rm_complete_task(self.message.link) + + async with queue_dict_lock: + if self.mid in queued_dl: + queued_dl[self.mid].set() + del queued_dl[self.mid] + if self.mid in queued_up: + queued_up[self.mid].set() + del queued_up[self.mid] + if self.mid in non_queued_dl: + non_queued_dl.remove(self.mid) + if self.mid in non_queued_up: + non_queued_up.remove(self.mid) + + await start_from_queued() + await sleep(3) + await clean_download(self.dir) + if self.up_dir: + await clean_download(self.up_dir) + if self.thumb and await aiopath.exists(self.thumb): + await remove(self.thumb) diff --git a/bot/helper/mirror_leech_utils/__init__.py b/bot/helper/mirror_leech_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/mirror_leech_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_leech_utils/download_utils/__init__.py b/bot/helper/mirror_leech_utils/download_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_leech_utils/download_utils/aria2_download.py b/bot/helper/mirror_leech_utils/download_utils/aria2_download.py new file mode 100644 index 0000000000000000000000000000000000000000..8be75a85c32984a79b0761325403a6cc6b5a8b2d --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/aria2_download.py @@ -0,0 +1,103 @@ +from aiofiles.os import remove, path as aiopath +from aiofiles import open as aiopen +from base64 import b64encode +from aiohttp.client_exceptions import ClientError +from asyncio import TimeoutError + +from .... import task_dict_lock, task_dict, LOGGER +from ....core.config_manager import Config +from ....core.torrent_manager import TorrentManager, is_metadata, aria2_name +from ...ext_utils.bot_utils import bt_selection_buttons +from ...ext_utils.task_manager import check_running_tasks +from ...mirror_leech_utils.status_utils.aria2_status import Aria2Status +from ...telegram_helper.message_utils import send_status_message, send_message + + +async def add_aria2_download(listener, dpath, header, ratio, seed_time): + a2c_opt = {"dir": dpath} + if listener.name: + a2c_opt["out"] = listener.name + if header: + a2c_opt["header"] = header + if ratio: + a2c_opt["seed-ratio"] = ratio + if seed_time: + a2c_opt["seed-time"] = seed_time + if TORRENT_TIMEOUT := Config.TORRENT_TIMEOUT: + a2c_opt["bt-stop-timeout"] = f"{TORRENT_TIMEOUT}" + + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + if listener.link.startswith("magnet:"): + a2c_opt["pause-metadata"] = "true" + else: + a2c_opt["pause"] = "true" + + try: + if await aiopath.exists(listener.link): + async with aiopen(listener.link, "rb") as tf: + torrent = await tf.read() + encoded = b64encode(torrent).decode() + params = [encoded, [], a2c_opt] + gid = await TorrentManager.aria2.jsonrpc("addTorrent", params) + """gid = await TorrentManager.aria2.add_torrent(path=listener.link, options=a2c_opt)""" + else: + gid = await TorrentManager.aria2.addUri( + uris=[listener.link], options=a2c_opt + ) + except (TimeoutError, ClientError, Exception) as e: + LOGGER.info(f"Aria2c Download Error: {e}") + await listener.on_download_error(f"{e}") + return + download = await TorrentManager.aria2.tellStatus(gid) + if download.get("errorMessage"): + error = str(download["errorMessage"]).replace("<", " ").replace(">", " ") + LOGGER.info(f"Aria2c Download Error: {error}") + await TorrentManager.aria2_remove(download) + await listener.on_download_error(error) + return + if await aiopath.exists(listener.link): + await remove(listener.link) + + name = aria2_name(download) + async with task_dict_lock: + task_dict[listener.mid] = Aria2Status(listener, gid, queued=add_to_queue) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {name}. Gid: {gid}") + if ( + (not listener.select or "bittorrent" not in download) + and listener.multi <= 1 + and not listener.is_rss + ): + await send_status_message(listener.message) + else: + LOGGER.info(f"Aria2Download started: {name}. Gid: {gid}") + + await listener.on_download_start() + + if ( + not add_to_queue + and (not listener.select or not Config.BASE_URL) + and listener.multi <= 1 + and not listener.is_rss + ): + await send_status_message(listener.message) + elif listener.select and "bittorrent" in download and not is_metadata(download): + if not add_to_queue: + await TorrentManager.aria2.forcePause(gid) + SBUTTONS = bt_selection_buttons(gid) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + await send_message(listener.message, msg, SBUTTONS) + + if add_to_queue: + await event.wait() + if listener.is_cancelled: + return + async with task_dict_lock: + task = task_dict[listener.mid] + task.queued = False + await task.update() + new_gid = task.gid() + + await TorrentManager.aria2.unpause(new_gid) + LOGGER.info(f"Start Queued Download from Aria2c: {name}. Gid: {new_gid}") diff --git a/bot/helper/mirror_leech_utils/download_utils/direct_downloader.py b/bot/helper/mirror_leech_utils/download_utils/direct_downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6d8099420c4e0b2c49e203b1098439a0a01b4 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/direct_downloader.py @@ -0,0 +1,60 @@ +from secrets import token_urlsafe + +from .... import ( + LOGGER, + task_dict, + task_dict_lock, +) +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...listeners.direct_listener import DirectListener +from ...mirror_leech_utils.status_utils.direct_status import DirectStatus +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...telegram_helper.message_utils import send_status_message + + +async def add_direct_download(listener, path): + details = listener.link + if not (contents := details.get("contents")): + await listener.on_download_error("There is nothing to download!") + return + listener.size = details["total_size"] + + if not listener.name: + listener.name = details["title"] + path = f"{path}/{listener.name}" + + msg, button = await stop_duplicate_check(listener) + if msg: + await listener.on_download_error(msg, button) + return + + gid = token_urlsafe(10) + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {listener.name}") + async with task_dict_lock: + task_dict[listener.mid] = QueueStatus(listener, gid, "dl") + await listener.on_download_start() + if listener.multi <= 1 and not listener.is_rss: + await send_status_message(listener.message) + await event.wait() + if listener.is_cancelled: + return + + a2c_opt = {"follow-torrent": "false", "follow-metalink": "false"} + if header := details.get("header"): + a2c_opt["header"] = header + directListener = DirectListener(path, listener, a2c_opt) + + async with task_dict_lock: + task_dict[listener.mid] = DirectStatus(listener, directListener, gid) + + if add_to_queue: + LOGGER.info(f"Start Queued Download from Direct Download: {listener.name}") + else: + LOGGER.info(f"Download from Direct Download: {listener.name}") + await listener.on_download_start() + if listener.multi <= 1 and not listener.is_rss: + await send_status_message(listener.message) + + await directListener.download(contents) diff --git a/bot/helper/mirror_leech_utils/download_utils/direct_link_generator.py b/bot/helper/mirror_leech_utils/download_utils/direct_link_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..b262bee8ac9771ff4c49d2c678ffc22b954da23f --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/direct_link_generator.py @@ -0,0 +1,1918 @@ +from cloudscraper import create_scraper +from hashlib import sha256 +from http.cookiejar import MozillaCookieJar +from json import loads +from lxml.etree import HTML +from os import path as ospath +from re import findall, match, search +from requests import Session, post, get +from requests.adapters import HTTPAdapter +from time import sleep +from urllib.parse import parse_qs, urlparse, quote +from urllib3.util.retry import Retry +from uuid import uuid4 +from base64 import b64decode, b64encode + +from ....core.config_manager import Config +from ...ext_utils.exceptions import DirectDownloadLinkException +from ...ext_utils.help_messages import PASSWORD_ERROR_MESSAGE +from ...ext_utils.links_utils import is_share_link +from ...ext_utils.status_utils import speed_string_to_bytes + +user_agent = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0" +) + + +def direct_link_generator(link): + """direct links generator""" + domain = urlparse(link).hostname + if not domain: + raise DirectDownloadLinkException("ERROR: Invalid URL") + elif "yadi.sk" in link or "disk.yandex." in link: + return yandex_disk(link) + elif "buzzheavier.com" in domain: + return buzzheavier(link) + elif "devuploads" in domain: + return devuploads(link) + elif "lulacloud.com" in domain: + return lulacloud(link) + elif "uploadhaven" in domain: + return uploadhaven(link) + elif "fuckingfast.co" in domain: + return fuckingfast_dl(link) + elif "mediafile.cc" in domain: + return mediafile(link) + elif "mediafire.com" in domain: + return mediafire(link) + elif "osdn.net" in domain: + return osdn(link) + elif "github.com" in domain: + return github(link) + elif "transfer.it" in domain: + return transfer_it(link) + elif "hxfile.co" in domain: + return hxfile(link) + elif "1drv.ms" in domain: + return onedrive(link) + elif any(x in domain for x in ["pixeldrain.com", "pixeldra.in"]): + return pixeldrain(link) + elif "racaty" in domain: + return racaty(link) + elif "1fichier.com" in domain: + return fichier(link) + elif "solidfiles.com" in domain: + return solidfiles(link) + elif "krakenfiles.com" in domain: + return krakenfiles(link) + elif "upload.ee" in domain: + return uploadee(link) + elif "gofile.io" in domain: + return gofile(link) + elif "send.cm" in domain: + return send_cm(link) + elif "tmpsend.com" in domain: + return tmpsend(link) + elif "easyupload.io" in domain: + return easyupload(link) + elif "streamvid.net" in domain: + return streamvid(link) + elif "shrdsk.me" in domain: + return shrdsk(link) + elif "u.pcloud.link" in domain: + return pcloud(link) + elif "qiwi.gg" in domain: + return qiwi(link) + elif "mp4upload.com" in domain: + return mp4upload(link) + elif "berkasdrive.com" in domain: + return berkasdrive(link) + elif "swisstransfer.com" in domain: + return swisstransfer(link) + elif any(x in domain for x in ["akmfiles.com", "akmfls.xyz"]): + return akmfiles(link) + elif any( + x in domain + for x in [ + "dood.watch", + "doodstream.com", + "dood.to", + "dood.so", + "dood.cx", + "dood.la", + "dood.ws", + "dood.sh", + "doodstream.co", + "dood.pm", + "dood.wf", + "dood.re", + "dood.video", + "dooood.com", + "dood.yt", + "doods.yt", + "dood.stream", + "doods.pro", + "ds2play.com", + "d0o0d.com", + "ds2video.com", + "do0od.com", + "d000d.com", + ] + ): + return doods(link) + elif any( + x in domain + for x in [ + "streamtape.com", + "streamtape.co", + "streamtape.cc", + "streamtape.to", + "streamtape.net", + "streamta.pe", + "streamtape.xyz", + ] + ): + return streamtape(link) + elif any(x in domain for x in ["wetransfer.com", "we.tl"]): + return wetransfer(link) + elif any( + x in domain + for x in [ + "terabox.com", + "nephobox.com", + "4funbox.com", + "mirrobox.com", + "momerybox.com", + "teraboxapp.com", + "1024tera.com", + "terabox.app", + "gibibox.com", + "goaibox.com", + "terasharelink.com", + "teraboxlink.com", + "freeterabox.com", + "1024terabox.com", + "teraboxshare.com", + "terafileshare.com", + "terabox.club", + ] + ): + return terabox(link) + elif any( + x in domain + for x in [ + "filelions.co", + "filelions.site", + "filelions.live", + "filelions.to", + "mycloudz.cc", + "cabecabean.lol", + "filelions.online", + "embedwish.com", + "kitabmarkaz.xyz", + "wishfast.top", + "streamwish.to", + "kissmovies.net", + ] + ): + return filelions_and_streamwish(link) + elif any(x in domain for x in ["streamhub.ink", "streamhub.to"]): + return streamhub(link) + elif any( + x in domain + for x in [ + "linkbox.to", + "lbx.to", + "teltobx.net", + "telbx.net", + "linkbox.cloud", + ] + ): + return linkBox(link) + elif is_share_link(link): + return filepress(link) if "filepress" in domain else sharer_scraper(link) + elif any( + x in domain + for x in [ + "anonfiles.com", + "zippyshare.com", + "letsupload.io", + "hotfile.io", + "bayfiles.com", + "megaupload.nz", + "letsupload.cc", + "filechan.org", + "myfile.is", + "vshare.is", + "rapidshare.nu", + "lolabits.se", + "openload.cc", + "share-online.is", + "upvid.cc", + "uptobox.com", + "uptobox.fr", + ] + ): + raise DirectDownloadLinkException(f"ERROR: R.I.P {domain}") + else: + raise DirectDownloadLinkException(f"No Direct link function found for {link}") + + +def get_captcha_token(session, params): + recaptcha_api = "https://www.google.com/recaptcha/api2" + res = session.get(f"{recaptcha_api}/anchor", params=params) + anchor_html = HTML(res.text) + if not (anchor_token := anchor_html.xpath('//input[@id="recaptcha-token"]/@value')): + return None + params["c"] = anchor_token[0] + params["reason"] = "q" + res = session.post(f"{recaptcha_api}/reload", params=params) + if token := findall(r'"rresp","(.*?)"', res.text): + return token[0] + + +def transfer_it(url): + resp = post("https://transfer-it-henna.vercel.app/post", json={"url": url}) + if resp.status_code == 200: + return resp.json()["url"] + else: + raise DirectDownloadLinkException("ERROR: File Expired or File Not Found") + + +def buzzheavier(url): + """ + Generate a direct download link for buzzheavier URLs. + @param link: URL from buzzheavier + @return: Direct download link + """ + pattern = r"^https?://buzzheavier\.com/[a-zA-Z0-9]+$" + if not match(pattern, url): + return url + + def _bhscraper(url, folder=False): + session = Session() + if "/download" not in url: + url += "/download" + url = url.strip() + session.headers.update( + { + "referer": url.split("/download")[0], + "hx-current-url": url.split("/download")[0], + "hx-request": "true", + "priority": "u=1, i", + } + ) + try: + response = session.get(url) + d_url = response.headers.get("Hx-Redirect") + if not d_url: + if not folder: + raise DirectDownloadLinkException("ERROR: Gagal mendapatkan data") + return + return d_url + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e + + with Session() as session: + tree = HTML(session.get(url).text) + if link := tree.xpath( + "//a[contains(@class, 'link-button') and contains(@class, 'gay-button')]/@hx-get" + ): + return _bhscraper(f"https://buzzheavier.com{link[0]}") + elif folders := tree.xpath("//tbody[@id='tbody']/tr"): + details = {"contents": [], "title": "", "total_size": 0} + for data in folders: + try: + filename = data.xpath(".//a")[0].text.strip() + _id = data.xpath(".//a")[0].attrib.get("href", "").strip() + size = data.xpath(".//td[@class='text-center']/text()")[0].strip() + url = _bhscraper(f"https://buzzheavier.com{_id}", True) + item = { + "path": "", + "filename": filename, + "url": url, + } + details["contents"].append(item) + size = speed_string_to_bytes(size) + details["total_size"] += size + except: + continue + details["title"] = tree.xpath("//span/text()")[0].strip() + return details + else: + raise DirectDownloadLinkException("ERROR: No download link found") + + +def fuckingfast_dl(url): + """ + Generate a direct download link for fuckingfast.co URLs. + @param url: URL from fuckingfast.co + @return: Direct download link + """ + url = url.strip() + + try: + response = get(url) + content = response.text + pattern = r'window\.open\((["\'])(https://fuckingfast\.co/dl/[^"\']+)\1' + if match := search(pattern, content): + return match.group(2) + else: + raise DirectDownloadLinkException( + "ERROR: Could not find download link in page" + ) + + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e + + +def lulacloud(url): + """ + Generate a direct download link for www.lulacloud.com URLs. + @param url: URL from www.lulacloud.com + @return: Direct download link + """ + try: + res = post(url, headers={"Referer": url}, allow_redirects=False) + return res.headers["location"] + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e + + +def devuploads(url): + """ + Generate a direct download link for devuploads.com URLs. + @param url: URL from devuploads.com + @return: Direct download link + """ + with Session() as session: + res = session.get(url) + html = HTML(res.text) + if not html.xpath("//input[@name]"): + raise DirectDownloadLinkException("ERROR: Unable to find link data") + data = {i.get("name"): i.get("value") for i in html.xpath("//input[@name]")} + res = session.post("https://gujjukhabar.in/", data=data) + html = HTML(res.text) + if not html.xpath("//input[@name]"): + raise DirectDownloadLinkException("ERROR: Unable to find link data") + data = {i.get("name"): i.get("value") for i in html.xpath("//input[@name]")} + resp = session.get( + "https://du2.devuploads.com/dlhash.php", + headers={ + "Origin": "https://gujjukhabar.in", + "Referer": "https://gujjukhabar.in/", + }, + ) + if not resp.text: + raise DirectDownloadLinkException("ERROR: Unable to find ipp value") + data["ipp"] = resp.text.strip() + if not data.get("rand"): + raise DirectDownloadLinkException("ERROR: Unable to find rand value") + randpost = session.post( + "https://devuploads.com/token/token.php", + data={"rand": data["rand"], "msg": ""}, + headers={ + "Origin": "https://gujjukhabar.in", + "Referer": "https://gujjukhabar.in/", + }, + ) + if not randpost: + raise DirectDownloadLinkException("ERROR: Unable to find xd value") + data["xd"] = randpost.text.strip() + res = session.post(url, data=data) + html = HTML(res.text) + if not html.xpath("//input[@name='orilink']/@value"): + raise DirectDownloadLinkException("ERROR: Unable to find Direct Link") + direct_link = html.xpath("//input[@name='orilink']/@value") + return direct_link[0] + + +def uploadhaven(url): + """ + Generate a direct download link for uploadhaven.com URLs. + @param url: URL from uploadhaven.com + @return: Direct download link + """ + try: + res = get(url, headers={"Referer": "http://steamunlocked.net/"}) + html = HTML(res.text) + if not html.xpath('//form[@method="POST"]//input'): + raise DirectDownloadLinkException("ERROR: Unable to find link data") + data = { + i.get("name"): i.get("value") + for i in html.xpath('//form[@method="POST"]//input') + } + sleep(15) + res = post(url, data=data, headers={"Referer": url}, cookies=res.cookies) + html = HTML(res.text) + if not html.xpath('//div[@class="alert alert-success mb-0"]//a'): + raise DirectDownloadLinkException("ERROR: Unable to find link data") + a = html.xpath('//div[@class="alert alert-success mb-0"]//a')[0] + return a.get("href") + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e + + +def mediafile(url): + """ + Generate a direct download link for mediafile.cc URLs. + @param url: URL from mediafile.cc + @return: Direct download link + """ + try: + res = get(url, allow_redirects=True) + match = search(r"href='([^']+)'", res.text) + if not match: + raise DirectDownloadLinkException("ERROR: Unable to find link data") + download_url = match[1] + sleep(60) + res = get(download_url, headers={"Referer": url}, cookies=res.cookies) + postvalue = search(r"showFileInformation(.*);", res.text) + if not postvalue: + raise DirectDownloadLinkException("ERROR: Unable to find post value") + postid = postvalue[1].replace("(", "").replace(")", "") + response = post( + "https://mediafile.cc/account/ajax/file_details", + data={"u": postid}, + headers={"X-Requested-With": "XMLHttpRequest"}, + ) + html = response.json()["html"] + return [ + i for i in findall(r'https://[^\s"\']+', html) if "download_token" in i + ][1] + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e + + +def mediafire(url, session=None): + if "/folder/" in url: + return mediafireFolder(url) + if "::" in url: + _password = url.split("::")[-1] + url = url.split("::")[-2] + else: + _password = "" + if final_link := findall( + r"https?:\/\/download\d+\.mediafire\.com\/\S+\/\S+\/\S+", url + ): + return final_link[0] + + def _repair_download(url, session): + try: + html = HTML(session.get(url).text) + if new_link := html.xpath('//a[@id="continue-btn"]/@href'): + return mediafire(f"https://mediafire.com/{new_link[0]}") + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + + if session is None: + session = create_scraper() + parsed_url = urlparse(url) + url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}" + try: + html = HTML(session.get(url).text) + except Exception as e: + session.close() + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if error := html.xpath('//p[@class="notranslate"]/text()'): + session.close() + raise DirectDownloadLinkException(f"ERROR: {error[0]}") + if html.xpath("//div[@class='passwordPrompt']"): + if not _password: + session.close() + raise DirectDownloadLinkException( + f"ERROR: {PASSWORD_ERROR_MESSAGE}".format(url) + ) + try: + html = HTML(session.post(url, data={"downloadp": _password}).text) + except Exception as e: + session.close() + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if html.xpath("//div[@class='passwordPrompt']"): + session.close() + raise DirectDownloadLinkException("ERROR: Wrong password.") + if not (final_link := html.xpath('//a[@aria-label="Download file"]/@href')): + if repair_link := html.xpath("//a[@class='retry']/@href"): + return _repair_download(repair_link[0], session) + raise DirectDownloadLinkException( + "ERROR: No links found in this page Try Again" + ) + if final_link[0].startswith("//"): + final_url = f"https://{final_link[0][2:]}" + if _password: + final_url += f"::{_password}" + return mediafire(final_url, session) + session.close() + return final_link[0] + + +def osdn(url): + with create_scraper() as session: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if not (direct_link := html.xapth('//a[@class="mirror_link"]/@href')): + raise DirectDownloadLinkException("ERROR: Direct link not found") + return f"https://osdn.net{direct_link[0]}" + + +def yandex_disk(url: str) -> str: + """Yandex.Disk direct link generator + Based on https://github.com/wldhx/yadisk-direct""" + try: + link = findall(r"\b(https?://(yadi\.sk|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 get(api.format(link)).json()["href"] + except KeyError as e: + raise DirectDownloadLinkException( + "ERROR: File not found/Download limit reached" + ) from e + + +def github(url): + """GitHub direct links generator""" + try: + findall(r"\bhttps?://.*github\.com.*releases\S+", url)[0] + except IndexError as e: + raise DirectDownloadLinkException("No GitHub Releases links found") from e + with create_scraper() as session: + _res = session.get(url, stream=True, allow_redirects=False) + if "location" in _res.headers: + return _res.headers["location"] + raise DirectDownloadLinkException("ERROR: Can't extract the link") + + +def hxfile(url): + if not ospath.isfile("hxfile.txt"): + raise DirectDownloadLinkException("ERROR: hxfile.txt (cookies) Not Found!") + try: + jar = MozillaCookieJar() + jar.load("hxfile.txt") + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + cookies = {cookie.name: cookie.value for cookie in jar} + try: + if url.strip().endswith(".html"): + url = url[:-5] + file_code = url.split("/")[-1] + html = HTML( + post( + url, + data={"op": "download2", "id": file_code}, + cookies=cookies, + ).text + ) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if direct_link := html.xpath("//a[@class='btn btn-dow']/@href"): + header = [f"Referer: {url}"] + return direct_link[0], header + raise DirectDownloadLinkException("ERROR: Direct download link not found") + + +def onedrive(link): + """Onedrive direct link generator + By https://github.com/junedkh""" + with create_scraper() as session: + try: + link = session.get(link).url + parsed_link = urlparse(link) + link_data = parse_qs(parsed_link.query) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if not link_data: + raise DirectDownloadLinkException("ERROR: Unable to find link_data") + folder_id = link_data.get("resid") + if not folder_id: + raise DirectDownloadLinkException("ERROR: folder id not found") + folder_id = folder_id[0] + authkey = link_data.get("authkey") + if not authkey: + raise DirectDownloadLinkException("ERROR: authkey not found") + authkey = authkey[0] + boundary = uuid4() + headers = {"content-type": f"multipart/form-data;boundary={boundary}"} + data = f"--{boundary}\r\nContent-Disposition: form-data;name=data\r\nPrefer: Migration=EnableRedirect;FailOnMigratedFiles\r\nX-HTTP-Method-Override: GET\r\nContent-Type: application/json\r\n\r\n--{boundary}--" + try: + resp = session.get( + f'https://api.onedrive.com/v1.0/drives/{folder_id.split("!", 1)[0]}/items/{folder_id}?$select=id,@content.downloadUrl&ump=1&authKey={authkey}', + headers=headers, + data=data, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if "@content.downloadUrl" not in resp: + raise DirectDownloadLinkException("ERROR: Direct link not found") + return resp["@content.downloadUrl"] + + +def pixeldrain(url): + try: + url = url.rstrip("/") + code = url.split("/")[-1].split("?", 1)[0] + response = get("https://pd.cybar.xyz/", allow_redirects=True) + return response.url + code + except Exception as e: + raise DirectDownloadLinkException("ERROR: Direct link not found") + + +def streamtape(url): + splitted_url = url.split("/") + _id = splitted_url[4] if len(splitted_url) >= 6 else splitted_url[-1] + try: + html = HTML(get(url).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + script = html.xpath( + "//script[contains(text(),'ideoooolink')]/text()" + ) or html.xpath("//script[contains(text(),'ideoolink')]/text()") + if not script: + raise DirectDownloadLinkException("ERROR: requeries script not found") + if not (link := findall(r"(&expires\S+)'", script[0])): + raise DirectDownloadLinkException("ERROR: Download link not found") + return f"https://streamtape.com/get_video?id={_id}{link[-1]}" + + +def racaty(url): + with create_scraper() as session: + try: + url = session.get(url).url + json_data = {"op": "download2", "id": url.split("/")[-1]} + html = HTML(session.post(url, data=json_data).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if direct_link := html.xpath("//a[@id='uniqueExpirylink']/@href"): + return direct_link[0] + else: + raise DirectDownloadLinkException("ERROR: Direct link not found") + + +def fichier(link): + """1Fichier direct link generator + Based on https://github.com/Maujar + """ + regex = r"^([http:\/\/|https:\/\/]+)?.*1fichier\.com\/\?.+" + gan = 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 + cget = create_scraper().request + try: + if pswd is None: + req = cget("post", url) + else: + pw = {"pass": pswd} + req = cget("post", url, data=pw) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if req.status_code == 404: + raise DirectDownloadLinkException( + "ERROR: File not found/The link you entered is wrong!" + ) + html = HTML(req.text) + if dl_url := html.xpath('//a[@class="ok btn-general btn-orange"]/@href'): + return dl_url[0] + if not (ct_warn := html.xpath('//div[@class="ct_warn"]')): + raise DirectDownloadLinkException( + "ERROR: Error trying to generate Direct Link from 1fichier!" + ) + if len(ct_warn) == 3: + str_2 = ct_warn[-1].text + if "you must wait" in str_2.lower(): + if numbers := [int(word) for word in str_2.split() if word.isdigit()]: + raise DirectDownloadLinkException( + f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute." + ) + else: + raise DirectDownloadLinkException( + "ERROR: 1fichier is on a limit. Please wait a few minutes/hour." + ) + elif "protect access" in str_2.lower(): + raise DirectDownloadLinkException( + f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(link)}" + ) + else: + raise DirectDownloadLinkException( + "ERROR: Failed to generate Direct Link from 1fichier!" + ) + elif len(ct_warn) == 4: + str_1 = ct_warn[-2].text + str_3 = ct_warn[-1].text + if "you must wait" in str_1.lower(): + if numbers := [int(word) for word in str_1.split() if word.isdigit()]: + raise DirectDownloadLinkException( + f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute." + ) + else: + raise DirectDownloadLinkException( + "ERROR: 1fichier is on a limit. Please wait a few minutes/hour." + ) + elif "bad password" in str_3.lower(): + raise DirectDownloadLinkException( + "ERROR: The password you entered is wrong!" + ) + raise DirectDownloadLinkException( + "ERROR: Error trying to generate Direct Link from 1fichier!" + ) + + +def solidfiles(url): + """Solidfiles direct link generator + Based on https://github.com/Xonshiz/SolidFiles-Downloader + By https://github.com/Jusidama18""" + with create_scraper() as session: + try: + 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 = session.get(url, headers=headers).text + mainOptions = str( + search(r"viewerOptions\'\,\ (.*?)\)\;", pageSource).group(1) + ) + return loads(mainOptions)["downloadUrl"] + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + + +def krakenfiles(url): + with Session() as session: + try: + _res = session.get(url) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + html = HTML(_res.text) + if post_url := html.xpath('//form[@id="dl-form"]/@action'): + post_url = f"https://krakenfiles.com{post_url[0]}" + else: + raise DirectDownloadLinkException("ERROR: Unable to find post link.") + if token := html.xpath('//input[@id="dl-token"]/@value'): + data = {"token": token[0]} + else: + raise DirectDownloadLinkException("ERROR: Unable to find token for post.") + try: + _json = session.post(post_url, data=data).json() + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While send post request" + ) from e + if _json["status"] != "ok": + raise DirectDownloadLinkException( + "ERROR: Unable to find download after post request" + ) + return _json["url"] + + +def uploadee(url): + with create_scraper() as session: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if link := html.xpath("//a[@id='d_l']/@href"): + return link[0] + else: + raise DirectDownloadLinkException("ERROR: Direct Link not found") + + +def terabox(url): + if "/file/" in url: + return url + api_url = f"https://wdzone-terabox-api.vercel.app/api?url={quote(url)}" + try: + with Session() as session: + req = session.get(api_url, headers={"User-Agent": user_agent}).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + + details = {"contents": [], "title": "", "total_size": 0} + if "✅ Status" not in req: + raise DirectDownloadLinkException("ERROR: File not found!") + for data in req["📜 Extracted Info"]: + item = { + "path": "", + "filename": data["📂 Title"], + "url": data["🔽 Direct Download Link"], + } + details["contents"].append(item) + size = (data["📏 Size"]).replace(" ", "") + size = speed_string_to_bytes(size) + details["total_size"] += size + details["title"] = req["📜 Extracted Info"][0]["📂 Title"] + if len(details["contents"]) == 1: + return details["contents"][0]["url"] + return details + + +def filepress(url): + try: + url = get(f"https://filebee.xyz/file/{url.split('/')[-1]}").url + raw = urlparse(url) + json_data = { + "id": raw.path.split("/")[-1], + "method": "publicDownlaod", + } + api = f"{raw.scheme}://{raw.hostname}/api/file/downlaod/" + res2 = post( + api, + headers={"Referer": f"{raw.scheme}://{raw.hostname}"}, + json=json_data, + ).json() + json_data2 = { + "id": res2["data"], + "method": "publicDownlaod", + } + api2 = f"{raw.scheme}://{raw.hostname}/api/file/downlaod2/" + res = post( + api2, + headers={"Referer": f"{raw.scheme}://{raw.hostname}"}, + json=json_data2, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + + if "data" not in res: + raise DirectDownloadLinkException(f'ERROR: {res["statusText"]}') + return f'https://drive.google.com/uc?id={res["data"]}&export=download' + + +def sharer_scraper(url): + cget = create_scraper().request + try: + url = cget("GET", url).url + raw = urlparse(url) + header = { + "useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.548.0 Safari/534.10" + } + res = cget("GET", url, headers=header) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + key = findall(r'"key",\s+"(.*?)"', res.text) + if not key: + raise DirectDownloadLinkException("ERROR: Key not found!") + key = key[0] + if not HTML(res.text).xpath("//button[@id='drc']"): + raise DirectDownloadLinkException( + "ERROR: This link don't have direct download button" + ) + boundary = uuid4() + headers = { + "Content-Type": f"multipart/form-data; boundary=----WebKitFormBoundary{boundary}", + "x-token": raw.hostname, + "useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.548.0 Safari/534.10", + } + + data = ( + f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="action"\r\n\r\ndirect\r\n' + f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="key"\r\n\r\n{key}\r\n' + f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="action_token"\r\n\r\n\r\n' + f"------WebKitFormBoundary{boundary}--\r\n" + ) + try: + res = cget("POST", url, cookies=res.cookies, headers=headers, data=data).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if "url" not in res: + raise DirectDownloadLinkException( + "ERROR: Drive Link not found, Try in your browser" + ) + if "drive.google.com" in res["url"] or "drive.usercontent.google.com" in res["url"]: + return res["url"] + try: + res = cget("GET", res["url"]) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if (drive_link := HTML(res.text).xpath("//a[contains(@class,'btn')]/@href")) and ( + "drive.google.com" in drive_link[0] + or "drive.usercontent.google.com" in drive_link[0] + ): + return drive_link[0] + else: + raise DirectDownloadLinkException( + "ERROR: Drive Link not found, Try in your browser" + ) + + +def wetransfer(url): + with create_scraper() as session: + try: + url = session.get(url).url + splited_url = url.split("/") + json_data = {"security_hash": splited_url[-1], "intent": "entire_transfer"} + res = session.post( + f"https://wetransfer.com/api/v4/transfers/{splited_url[-2]}/download", + json=json_data, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if "direct_link" in res: + return res["direct_link"] + elif "message" in res: + raise DirectDownloadLinkException(f"ERROR: {res['message']}") + elif "error" in res: + raise DirectDownloadLinkException(f"ERROR: {res['error']}") + else: + raise DirectDownloadLinkException("ERROR: cannot find direct link") + + +def akmfiles(url): + with create_scraper() as session: + try: + html = HTML( + session.post( + url, + data={"op": "download2", "id": url.split("/")[-1]}, + ).text + ) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if direct_link := html.xpath("//a[contains(@class,'btn btn-dow')]/@href"): + return direct_link[0] + else: + raise DirectDownloadLinkException("ERROR: Direct link not found") + + +def shrdsk(url): + with create_scraper() as session: + try: + _json = session.get( + f'https://us-central1-affiliate2apk.cloudfunctions.net/get_data?shortid={url.split("/")[-1]}', + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if "download_data" not in _json: + raise DirectDownloadLinkException("ERROR: Download data not found") + try: + _res = session.get( + f"https://shrdsk.me/download/{_json['download_data']}", + allow_redirects=False, + ) + if "Location" in _res.headers: + return _res.headers["Location"] + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + raise DirectDownloadLinkException("ERROR: cannot find direct link in headers") + + +def linkBox(url: str): + parsed_url = urlparse(url) + try: + shareToken = parsed_url.path.split("/")[-1] + except: + raise DirectDownloadLinkException("ERROR: invalid URL") + + details = {"contents": [], "title": "", "total_size": 0} + + def __singleItem(session, itemId): + try: + _json = session.get( + "https://www.linkbox.to/api/file/detail", + params={"itemId": itemId}, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + data = _json["data"] + if not data: + if "msg" in _json: + raise DirectDownloadLinkException(f"ERROR: {_json['msg']}") + raise DirectDownloadLinkException("ERROR: data not found") + itemInfo = data["itemInfo"] + if not itemInfo: + raise DirectDownloadLinkException("ERROR: itemInfo not found") + filename = itemInfo["name"] + sub_type = itemInfo.get("sub_type") + if sub_type and not filename.strip().endswith(sub_type): + filename += f".{sub_type}" + if not details["title"]: + details["title"] = filename + item = { + "path": "", + "filename": filename, + "url": itemInfo["url"], + } + if "size" in itemInfo: + size = itemInfo["size"] + if isinstance(size, str) and size.isdigit(): + size = float(size) + details["total_size"] += size + details["contents"].append(item) + + def __fetch_links(session, _id=0, folderPath=""): + params = { + "shareToken": shareToken, + "pageSize": 1000, + "pid": _id, + } + try: + _json = session.get( + "https://www.linkbox.to/api/file/share_out_list", + params=params, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + data = _json["data"] + if not data: + if "msg" in _json: + raise DirectDownloadLinkException(f"ERROR: {_json['msg']}") + raise DirectDownloadLinkException("ERROR: data not found") + try: + if data["shareType"] == "singleItem": + return __singleItem(session, data["itemId"]) + except: + pass + if not details["title"]: + details["title"] = data["dirName"] + contents = data["list"] + if not contents: + return None + for content in contents: + if content["type"] == "dir" and "url" not in content: + if not folderPath: + newFolderPath = ospath.join(details["title"], content["name"]) + else: + newFolderPath = ospath.join(folderPath, content["name"]) + if not details["title"]: + details["title"] = content["name"] + __fetch_links(session, content["id"], newFolderPath) + elif "url" in content: + if not folderPath: + folderPath = details["title"] + filename = content["name"] + if ( + sub_type := content.get("sub_type") + ) and not filename.strip().endswith(sub_type): + filename += f".{sub_type}" + item = { + "path": ospath.join(folderPath), + "filename": filename, + "url": content["url"], + } + if "size" in content: + size = content["size"] + if isinstance(size, str) and size.isdigit(): + size = float(size) + details["total_size"] += size + details["contents"].append(item) + + try: + with Session() as session: + __fetch_links(session) + except DirectDownloadLinkException as e: + raise e + return details + + +def gofile(url): + try: + if "::" in url: + _password = url.split("::")[-1] + _password = sha256(_password.encode("utf-8")).hexdigest() + url = url.split("::")[-2] + else: + _password = "" + _id = url.split("/")[-1] + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") + + def __get_token(session): + headers = { + "User-Agent": user_agent, + "Accept-Encoding": "gzip, deflate, br", + "Accept": "*/*", + "Connection": "keep-alive", + } + __url = "https://api.gofile.io/accounts" + try: + __res = session.post(__url, headers=headers).json() + if __res["status"] != "ok": + raise DirectDownloadLinkException("ERROR: Failed to get token.") + return __res["data"]["token"] + except Exception as e: + raise e + + def __fetch_links(session, _id, folderPath=""): + _url = f"https://api.gofile.io/contents/{_id}?cache=true" + headers = { + "User-Agent": user_agent, + "Accept-Encoding": "gzip, deflate, br", + "Accept": "*/*", + "Connection": "keep-alive", + "Authorization": "Bearer" + " " + token, + "X-Website-Token": "4fd6sg89d7s6", + } + if _password: + _url += f"&password={_password}" + try: + _json = session.get(_url, headers=headers).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") + if _json["status"] in "error-passwordRequired": + raise DirectDownloadLinkException( + f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}" + ) + if _json["status"] in "error-passwordWrong": + raise DirectDownloadLinkException("ERROR: This password is wrong !") + if _json["status"] in "error-notFound": + raise DirectDownloadLinkException( + "ERROR: File not found on gofile's server" + ) + if _json["status"] in "error-notPublic": + raise DirectDownloadLinkException("ERROR: This folder is not public") + + data = _json["data"] + + if not details["title"]: + details["title"] = data["name"] if data["type"] == "folder" else _id + + contents = data["children"] + for content in contents.values(): + if content["type"] == "folder": + if not content["public"]: + continue + if not folderPath: + newFolderPath = ospath.join(details["title"], content["name"]) + else: + newFolderPath = ospath.join(folderPath, content["name"]) + __fetch_links(session, content["id"], newFolderPath) + else: + if not folderPath: + folderPath = details["title"] + item = { + "path": ospath.join(folderPath), + "filename": content["name"], + "url": content["link"], + } + if "size" in content: + size = content["size"] + if isinstance(size, str) and size.isdigit(): + size = float(size) + details["total_size"] += size + details["contents"].append(item) + + details = {"contents": [], "title": "", "total_size": 0} + with Session() as session: + try: + token = __get_token(session) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") + details["header"] = f"Cookie: accountToken={token}" + try: + __fetch_links(session, _id) + except Exception as e: + raise DirectDownloadLinkException(e) + + if len(details["contents"]) == 1: + return (details["contents"][0]["url"], details["header"]) + return details + + +def mediafireFolder(url): + if "::" in url: + _password = url.split("::")[-1] + url = url.split("::")[-2] + else: + _password = "" + try: + raw = url.split("/", 4)[-1] + folderkey = raw.split("/", 1)[0] + folderkey = folderkey.split(",") + except: + raise DirectDownloadLinkException("ERROR: Could not parse ") + if len(folderkey) == 1: + folderkey = folderkey[0] + details = {"contents": [], "title": "", "total_size": 0, "header": ""} + + session = create_scraper() + adapter = HTTPAdapter( + max_retries=Retry(total=10, read=10, connect=10, backoff_factor=0.3) + ) + session.mount("http://", adapter) + session.mount("https://", adapter) + session = create_scraper( + browser={"browser": "firefox", "platform": "windows", "mobile": False}, + delay=10, + sess=session, + ) + folder_infos = [] + + def __get_info(folderkey): + try: + if isinstance(folderkey, list): + folderkey = ",".join(folderkey) + _json = session.post( + "https://www.mediafire.com/api/1.5/folder/get_info.php", + data={ + "recursive": "yes", + "folder_key": folderkey, + "response_format": "json", + }, + ).json() + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While getting info" + ) + _res = _json["response"] + if "folder_infos" in _res: + folder_infos.extend(_res["folder_infos"]) + elif "folder_info" in _res: + folder_infos.append(_res["folder_info"]) + elif "message" in _res: + raise DirectDownloadLinkException(f"ERROR: {_res['message']}") + else: + raise DirectDownloadLinkException("ERROR: something went wrong!") + + try: + __get_info(folderkey) + except Exception as e: + raise DirectDownloadLinkException(e) + + details["title"] = folder_infos[0]["name"] + + def __scraper(url): + session = create_scraper() + parsed_url = urlparse(url) + url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}" + + try: + html = HTML(session.get(url).text) + except: + return None + if html.xpath("//div[@class='passwordPrompt']"): + if not _password: + raise DirectDownloadLinkException( + f"ERROR: {PASSWORD_ERROR_MESSAGE}".format(url) + ) + try: + html = HTML(session.post(url, data={"downloadp": _password}).text) + except: + return None + if html.xpath("//div[@class='passwordPrompt']"): + return None + try: + final_link = __decode_url(html) + except: + return None + return final_link + + def __decode_url(html): + enc_url = html.xpath('//a[@id="downloadButton"]') + if enc_url: + final_link = enc_url[0].attrib.get("href") + scrambled = enc_url[0].attrib.get("data-scrambled-url") + if final_link and scrambled: + try: + final_link = b64decode(scrambled).decode("utf-8") + return final_link + except: + return None + elif final_link.startswith("http"): + return final_link + elif final_link.startswith("//"): + return __scraper(f"https:{final_link}") + else: + return None + else: + return None + + def __get_content(folderKey, folderPath="", content_type="folders"): + try: + params = { + "content_type": content_type, + "folder_key": folderKey, + "response_format": "json", + } + _json = session.get( + "https://www.mediafire.com/api/1.5/folder/get_content.php", + params=params, + ).json() + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While getting content" + ) + _res = _json["response"] + if "message" in _res: + raise DirectDownloadLinkException(f"ERROR: {_res['message']}") + _folder_content = _res["folder_content"] + if content_type == "folders": + folders = _folder_content["folders"] + for folder in folders: + if folderPath: + newFolderPath = ospath.join(folderPath, folder["name"]) + else: + newFolderPath = ospath.join(folder["name"]) + __get_content(folder["folderkey"], newFolderPath) + __get_content(folderKey, folderPath, "files") + else: + files = _folder_content["files"] + for file in files: + item = {} + if not (_url := __scraper(file["links"]["normal_download"])): + continue + item["filename"] = file["filename"] + if not folderPath: + folderPath = details["title"] + item["path"] = ospath.join(folderPath) + item["url"] = _url + if "size" in file: + size = file["size"] + if isinstance(size, str) and size.isdigit(): + size = float(size) + details["total_size"] += size + details["contents"].append(item) + + try: + for folder in folder_infos: + __get_content(folder["folderkey"], folder["name"]) + except Exception as e: + raise DirectDownloadLinkException(e) + finally: + session.close() + if len(details["contents"]) == 1: + return (details["contents"][0]["url"], [details["header"]]) + return details + + +def cf_bypass(url): + "DO NOT ABUSE THIS" + try: + data = {"cmd": "request.get", "url": url, "maxTimeout": 60000} + _json = post( + "https://cf.jmdkh.eu.org/v1", + headers={"Content-Type": "application/json"}, + json=data, + ).json() + if _json["status"] == "ok": + return _json["solution"]["response"] + except Exception as e: + e + raise DirectDownloadLinkException("ERROR: Con't bypass cloudflare") + + +def send_cm_file(url, file_id=None): + if "::" in url: + _password = url.split("::")[-1] + url = url.split("::")[-2] + else: + _password = "" + _passwordNeed = False + with create_scraper() as session: + if file_id is None: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__}" + ) from e + if html.xpath("//input[@name='password']"): + _passwordNeed = True + if not (file_id := html.xpath("//input[@name='id']/@value")): + raise DirectDownloadLinkException("ERROR: file_id not found") + try: + data = {"op": "download2", "id": file_id} + if _password and _passwordNeed: + data["password"] = _password + _res = session.post("https://send.cm/", data=data, allow_redirects=False) + if "Location" in _res.headers: + return (_res.headers["Location"], ["Referer: https://send.cm/"]) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if _passwordNeed: + raise DirectDownloadLinkException( + f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}" + ) + raise DirectDownloadLinkException("ERROR: Direct link not found") + + +def send_cm(url): + if "/d/" in url: + return send_cm_file(url) + elif "/s/" not in url: + file_id = url.split("/")[-1] + return send_cm_file(url, file_id) + splitted_url = url.split("/") + details = { + "contents": [], + "title": "", + "total_size": 0, + "header": "Referer: https://send.cm/", + } + if len(splitted_url) == 5: + url += "/" + splitted_url = url.split("/") + if len(splitted_url) >= 7: + details["title"] = splitted_url[5] + else: + details["title"] = splitted_url[-1] + session = Session() + + def __collectFolders(html): + folders = [] + folders_urls = html.xpath("//h6/a/@href") + folders_names = html.xpath("//h6/a/text()") + for folders_url, folders_name in zip(folders_urls, folders_names): + folders.append( + { + "folder_link": folders_url.strip(), + "folder_name": folders_name.strip(), + } + ) + return folders + + def __getFile_link(file_id): + try: + _res = session.post( + "https://send.cm/", + data={"op": "download2", "id": file_id}, + allow_redirects=False, + ) + if "Location" in _res.headers: + return _res.headers["Location"] + except: + pass + + def __getFiles(html): + files = [] + hrefs = html.xpath('//tr[@class="selectable"]//a/@href') + file_names = html.xpath('//tr[@class="selectable"]//a/text()') + sizes = html.xpath('//tr[@class="selectable"]//span/text()') + for href, file_name, size_text in zip(hrefs, file_names, sizes): + files.append( + { + "file_id": href.split("/")[-1], + "file_name": file_name.strip(), + "size": speed_string_to_bytes(size_text.strip()), + } + ) + return files + + def __writeContents(html_text, folderPath=""): + folders = __collectFolders(html_text) + for folder in folders: + _html = HTML(cf_bypass(folder["folder_link"])) + __writeContents(_html, ospath.join(folderPath, folder["folder_name"])) + files = __getFiles(html_text) + for file in files: + if not (link := __getFile_link(file["file_id"])): + continue + item = {"url": link, "filename": file["filename"], "path": folderPath} + details["total_size"] += file["size"] + details["contents"].append(item) + + try: + mainHtml = HTML(cf_bypass(url)) + except DirectDownloadLinkException as e: + raise e + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While getting mainHtml" + ) + + try: + __writeContents(mainHtml, details["title"]) + except DirectDownloadLinkException as e: + raise e + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While writing Contents" + ) + finally: + session.close() + if len(details["contents"]) == 1: + return (details["contents"][0]["url"], [details["header"]]) + return details + + +def doods(url): + if "/e/" in url: + url = url.replace("/e/", "/d/") + parsed_url = urlparse(url) + with create_scraper() as session: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While fetching token link" + ) from e + if not (link := html.xpath("//div[@class='download-content']//a/@href")): + raise DirectDownloadLinkException( + "ERROR: Token Link not found or maybe not allow to download! open in browser." + ) + link = f"{parsed_url.scheme}://{parsed_url.hostname}{link[0]}" + sleep(2) + try: + _res = session.get(link) + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__} While fetching download link" + ) from e + if not (link := search(r"window\.open\('(\S+)'", _res.text)): + raise DirectDownloadLinkException("ERROR: Download link not found try again") + return (link.group(1), [f"Referer: {parsed_url.scheme}://{parsed_url.hostname}/"]) + + +def easyupload(url): + if "::" in url: + _password = url.split("::")[-1] + url = url.split("::")[-2] + else: + _password = "" + file_id = url.split("/")[-1] + with create_scraper() as session: + try: + _res = session.get(url) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") + first_page_html = HTML(_res.text) + if ( + first_page_html.xpath("//h6[contains(text(),'Password Protected')]") + and not _password + ): + raise DirectDownloadLinkException( + f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}" + ) + if not ( + match := search( + r"https://eu(?:[1-9][0-9]?|100)\.easyupload\.io/action\.php", _res.text + ) + ): + raise DirectDownloadLinkException( + "ERROR: Failed to get server for EasyUpload Link" + ) + action_url = match.group() + session.headers.update({"referer": "https://easyupload.io/"}) + recaptcha_params = { + "k": "6LfWajMdAAAAAGLXz_nxz2tHnuqa-abQqC97DIZ3", + "ar": "1", + "co": "aHR0cHM6Ly9lYXN5dXBsb2FkLmlvOjQ0Mw..", + "hl": "en", + "v": "0hCdE87LyjzAkFO5Ff-v7Hj1", + "size": "invisible", + "cb": "c3o1vbaxbmwe", + } + if not (captcha_token := get_captcha_token(session, recaptcha_params)): + raise DirectDownloadLinkException("ERROR: Captcha token not found") + try: + data = { + "type": "download-token", + "url": file_id, + "value": _password, + "captchatoken": captcha_token, + "method": "regular", + } + json_resp = session.post(url=action_url, data=data).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if "download_link" in json_resp: + return json_resp["download_link"] + elif "data" in json_resp: + raise DirectDownloadLinkException( + f"ERROR: Failed to generate direct link due to {json_resp['data']}" + ) + raise DirectDownloadLinkException( + "ERROR: Failed to generate direct link from EasyUpload." + ) + + +def filelions_and_streamwish(url): + parsed_url = urlparse(url) + hostname = parsed_url.hostname + scheme = parsed_url.scheme + if any( + x in hostname + for x in [ + "filelions.co", + "filelions.live", + "filelions.to", + "filelions.site", + "cabecabean.lol", + "filelions.online", + "mycloudz.cc", + ] + ): + apiKey = Config.FILELION_API + apiUrl = "https://vidhideapi.com" + elif any( + x in hostname + for x in [ + "embedwish.com", + "kissmovies.net", + "kitabmarkaz.xyz", + "wishfast.top", + "streamwish.to", + ] + ): + apiKey = Config.STREAMWISH_API + apiUrl = "https://api.streamwish.com" + if not apiKey: + raise DirectDownloadLinkException( + f"ERROR: API is not provided get it from {scheme}://{hostname}" + ) + file_code = url.split("/")[-1] + quality = "" + if bool(file_code.strip().endswith(("_o", "_h", "_n", "_l"))): + spited_file_code = file_code.rsplit("_", 1) + quality = spited_file_code[1] + file_code = spited_file_code[0] + url = f"{scheme}://{hostname}/{file_code}" + try: + _res = get( + f"{apiUrl}/api/file/direct_link", + params={"key": apiKey, "file_code": file_code, "hls": "1"}, + ).json() + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if _res["status"] != 200: + raise DirectDownloadLinkException(f"ERROR: {_res['msg']}") + result = _res["result"] + if not result["versions"]: + raise DirectDownloadLinkException("ERROR: File Not Found") + error = "\nProvide a quality to download the video\nAvailable Quality:" + for version in result["versions"]: + if quality == version["name"]: + return version["url"] + elif version["name"] == "l": + error += "\nLow" + elif version["name"] == "n": + error += "\nNormal" + elif version["name"] == "o": + error += "\nOriginal" + elif version["name"] == "h": + error += "\nHD" + error += f" {url}_{version['name']}" + raise DirectDownloadLinkException(f"ERROR: {error}") + + +def streamvid(url: str): + file_code = url.split("/")[-1] + parsed_url = urlparse(url) + url = f"{parsed_url.scheme}://{parsed_url.hostname}/d/{file_code}" + quality_defined = bool(url.strip().endswith(("_o", "_h", "_n", "_l"))) + with create_scraper() as session: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if quality_defined: + data = {} + if not (inputs := html.xpath('//form[@id="F1"]//input')): + raise DirectDownloadLinkException("ERROR: No inputs found") + for i in inputs: + if key := i.get("name"): + data[key] = i.get("value") + try: + html = HTML(session.post(url, data=data).text) + except Exception as e: + raise DirectDownloadLinkException( + f"ERROR: {e.__class__.__name__}" + ) from e + if not ( + script := html.xpath( + '//script[contains(text(),"document.location.href")]/text()' + ) + ): + if error := html.xpath( + '//div[@class="alert alert-danger"][1]/text()[2]' + ): + raise DirectDownloadLinkException(f"ERROR: {error[0]}") + raise DirectDownloadLinkException( + "ERROR: direct link script not found!" + ) + if directLink := findall(r'document\.location\.href="(.*)"', script[0]): + return directLink[0] + raise DirectDownloadLinkException( + "ERROR: direct link not found! in the script" + ) + elif (qualities_urls := html.xpath('//div[@id="dl_versions"]/a/@href')) and ( + qualities := html.xpath('//div[@id="dl_versions"]/a/text()[2]') + ): + error = "\nProvide a quality to download the video\nAvailable Quality:" + for quality_url, quality in zip(qualities_urls, qualities): + error += f"\n{quality.strip()} {quality_url}" + raise DirectDownloadLinkException(f"ERROR: {error}") + elif error := html.xpath('//div[@class="not-found-text"]/text()'): + raise DirectDownloadLinkException(f"ERROR: {error[0]}") + raise DirectDownloadLinkException("ERROR: Something went wrong") + + +def streamhub(url): + file_code = url.split("/")[-1] + parsed_url = urlparse(url) + url = f"{parsed_url.scheme}://{parsed_url.hostname}/d/{file_code}" + with create_scraper() as session: + try: + html = HTML(session.get(url).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if not (inputs := html.xpath('//form[@name="F1"]//input')): + raise DirectDownloadLinkException("ERROR: No inputs found") + data = {} + for i in inputs: + if key := i.get("name"): + data[key] = i.get("value") + session.headers.update({"referer": url}) + sleep(1) + try: + html = HTML(session.post(url, data=data).text) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if directLink := html.xpath( + '//a[@class="btn btn-primary btn-go downloadbtn"]/@href' + ): + return directLink[0] + if error := html.xpath('//div[@class="alert alert-danger"]/text()[2]'): + raise DirectDownloadLinkException(f"ERROR: {error[0]}") + raise DirectDownloadLinkException("ERROR: direct link not found!") + + +def pcloud(url): + with create_scraper() as session: + try: + res = session.get(url) + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + if link := findall(r".downloadlink.:..(https:.*)..", res.text): + return link[0].replace(r"\/", "/") + raise DirectDownloadLinkException("ERROR: Direct link not found") + + +def tmpsend(url): + parsed_url = urlparse(url) + if any(x in parsed_url.path for x in ["thank-you", "download"]): + query_params = parse_qs(parsed_url.query) + if file_id := query_params.get("d"): + file_id = file_id[0] + elif not (file_id := parsed_url.path.strip("/")): + raise DirectDownloadLinkException("ERROR: Invalid URL format") + referer_url = f"https://tmpsend.com/thank-you?d={file_id}" + header = [f"Referer: {referer_url}"] + download_link = f"https://tmpsend.com/download?d={file_id}" + return download_link, header + + +def qiwi(url): + """qiwi.gg link generator + based on https://github.com/aenulrofik""" + file_id = url.split("/")[-1] + try: + res = get(url).text + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + tree = HTML(res) + if name := tree.xpath('//h1[@class="page_TextHeading__VsM7r"]/text()'): + ext = name[0].split(".")[-1] + return f"https://spyderrock.com/{file_id}.{ext}" + else: + raise DirectDownloadLinkException("ERROR: File not found") + + +def mp4upload(url): + with Session() as session: + try: + url = url.replace("embed-", "") + req = session.get(url).text + tree = HTML(req) + inputs = tree.xpath("//input") + header = ["Referer: https://www.mp4upload.com/"] + data = {input.get("name"): input.get("value") for input in inputs} + if not data: + raise DirectDownloadLinkException("ERROR: File Not Found!") + post = session.post( + url, + data=data, + headers={ + "User-Agent": user_agent, + "Referer": "https://www.mp4upload.com/", + }, + ).text + tree = HTML(post) + inputs = tree.xpath('//form[@name="F1"]//input') + data = { + input.get("name"): input.get("value").replace(" ", "") + for input in inputs + } + if not data: + raise DirectDownloadLinkException("ERROR: File Not Found!") + data["referer"] = url + direct_link = session.post(url, data=data).url + return direct_link, header + except: + raise DirectDownloadLinkException("ERROR: File Not Found!") + + +def berkasdrive(url): + """berkasdrive.com link generator + by https://github.com/aenulrofik""" + try: + sesi = get(url).text + except Exception as e: + raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e + html = HTML(sesi) + if link := html.xpath("//script")[0].text.split('"')[1]: + return b64decode(link).decode("utf-8") + else: + raise DirectDownloadLinkException("ERROR: File Not Found!") + + +def swisstransfer(link): + matched_link = match( + r"https://www\.swisstransfer\.com/d/([\w-]+)(?:\:\:(\w+))?", link + ) + if not matched_link: + raise DirectDownloadLinkException( + f"ERROR: Invalid SwissTransfer link format {link}" + ) + + transfer_id, password = matched_link.groups() + password = password or "" + + def encode_password(password): + return b64encode(password.encode("utf-8")).decode("utf-8") if password else "" + + def getfile(transfer_id, password): + url = f"https://www.swisstransfer.com/api/links/{transfer_id}" + headers = { + "User-Agent": "Mozilla/5.0", + "Authorization": encode_password(password) if password else "", + "Content-Type": "" if password else "application/json", + } + response = get(url, headers=headers) + + if response.status_code == 200: + try: + return response.json(), [f"{k}: {v}" for k, v in headers.items() if v] + except ValueError: + raise DirectDownloadLinkException( + f"ERROR: Error parsing JSON response {response.text}" + ) + raise DirectDownloadLinkException( + f"ERROR: Error fetching file details {response.status_code}, {response.text}" + ) + + def gettoken(password, containerUUID, fileUUID): + url = "https://www.swisstransfer.com/api/generateDownloadToken" + headers = { + "User-Agent": "Mozilla/5.0", + "Content-Type": "application/json", + } + body = { + "password": password, + "containerUUID": containerUUID, + "fileUUID": fileUUID, + } + + response = post(url, headers=headers, json=body) + + if response.status_code == 200: + return response.text.strip().replace('"', "") + raise DirectDownloadLinkException( + f"ERROR: Error generating download token {response.status_code}, {response.text}" + ) + + data, _ = getfile(transfer_id, password) + if not data: + return None + + try: + container_uuid = data["data"]["containerUUID"] + download_host = data["data"]["downloadHost"] + files = data["data"]["container"]["files"] + folder_name = data["data"]["container"]["message"] or "unknown" + except (KeyError, IndexError, TypeError) as e: + raise DirectDownloadLinkException(f"ERROR: Error parsing file details {e}") + + total_size = sum(file["fileSizeInBytes"] for file in files) + + if len(files) == 1: + file = files[0] + file_uuid = file["UUID"] + token = gettoken(password, container_uuid, file_uuid) + download_url = f"https://{download_host}/api/download/{transfer_id}/{file_uuid}?token={token}" + return download_url, ["User-Agent:Mozilla/5.0"] + + contents = [] + for file in files: + file_uuid = file["UUID"] + file_name = file["fileName"] + file_size = file["fileSizeInBytes"] + + token = gettoken(password, container_uuid, file_uuid) + if not token: + continue + + download_url = f"https://{download_host}/api/download/{transfer_id}/{file_uuid}?token={token}" + contents.append({"filename": file_name, "path": "", "url": download_url}) + + return { + "contents": contents, + "title": folder_name, + "total_size": total_size, + "header": "User-Agent:Mozilla/5.0", + } diff --git a/bot/helper/mirror_leech_utils/download_utils/direct_link_generator_license.md b/bot/helper/mirror_leech_utils/download_utils/direct_link_generator_license.md new file mode 100644 index 0000000000000000000000000000000000000000..3e1d62680a10b00270573fb4dfda9925742a274e --- /dev/null +++ b/bot/helper/mirror_leech_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 diff --git a/bot/helper/mirror_leech_utils/download_utils/gd_download.py b/bot/helper/mirror_leech_utils/download_utils/gd_download.py new file mode 100644 index 0000000000000000000000000000000000000000..74934d893299fe6ac3cb26670efb6943e668681e --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/gd_download.py @@ -0,0 +1,54 @@ +from secrets import token_urlsafe + +from .... import task_dict, task_dict_lock, LOGGER +from ...ext_utils.bot_utils import sync_to_async +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...mirror_leech_utils.gdrive_utils.count import GoogleDriveCount +from ...mirror_leech_utils.gdrive_utils.download import GoogleDriveDownload +from ...mirror_leech_utils.status_utils.gdrive_status import GoogleDriveStatus +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...telegram_helper.message_utils import send_status_message + + +async def add_gd_download(listener, path): + drive = GoogleDriveCount() + name, mime_type, listener.size, _, _ = await sync_to_async( + drive.count, listener.link, listener.user_id + ) + if mime_type is None: + await listener.on_download_error(name) + return + + listener.name = listener.name or name + gid = token_urlsafe(12) + + msg, button = await stop_duplicate_check(listener) + if msg: + await listener.on_download_error(msg, button) + return + + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {listener.name}") + async with task_dict_lock: + task_dict[listener.mid] = QueueStatus(listener, gid, "dl") + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + await event.wait() + if listener.is_cancelled: + return + + drive = GoogleDriveDownload(listener, path) + async with task_dict_lock: + task_dict[listener.mid] = GoogleDriveStatus(listener, drive, gid, "dl") + + if add_to_queue: + LOGGER.info(f"Start Queued Download from GDrive: {listener.name}") + else: + LOGGER.info(f"Download from GDrive: {listener.name}") + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + + await sync_to_async(drive.download) diff --git a/bot/helper/mirror_leech_utils/download_utils/jd_download.py b/bot/helper/mirror_leech_utils/download_utils/jd_download.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf3ca68bbdd613569f04cc19756f514302931c7 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/jd_download.py @@ -0,0 +1,374 @@ +from asyncio import wait_for, Event, sleep +from functools import partial +from pyrogram.filters import regex, user +from pyrogram.handlers import CallbackQueryHandler +from time import time +from aiofiles.os import path as aiopath, remove +from aiofiles import open as aiopen +from base64 import b64encode +from secrets import token_urlsafe +from myjd.exception import MYJDException + +from .... import ( + task_dict, + task_dict_lock, + LOGGER, + jd_listener_lock, + jd_downloads, +) +from ...ext_utils.bot_utils import new_task +from ....core.jdownloader_booter import jdownloader +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...listeners.jdownloader_listener import on_download_start +from ...mirror_leech_utils.status_utils.jdownloader_status import JDownloaderStatus +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...telegram_helper.button_build import ButtonMaker +from ...telegram_helper.message_utils import ( + send_message, + send_status_message, + edit_message, + delete_message, +) + + +@new_task +async def configureDownload(_, query, obj): + data = query.data.split() + message = query.message + await query.answer() + if data[1] == "sdone": + obj.event.set() + elif data[1] == "cancel": + await edit_message(message, "Task has been cancelled.") + obj.listener.is_cancelled = True + obj.event.set() + + +class JDownloaderHelper: + def __init__(self, listener): + self._timeout = 600 + self._reply_to = "" + self.listener = listener + self.event = Event() + + async def _event_handler(self): + pfunc = partial(configureDownload, obj=self) + handler = self.listener.client.add_handler( + CallbackQueryHandler( + pfunc, filters=regex("^jdq") & user(self.listener.user_id) + ), + group=-1, + ) + try: + await wait_for(self.event.wait(), timeout=self._timeout) + except: + await edit_message(self._reply_to, "Timed Out. Task has been cancelled!") + self.listener.is_cancelled = True + self.event.set() + finally: + self.listener.client.remove_handler(*handler) + + async def wait_for_configurations(self): + buttons = ButtonMaker() + buttons.url_button("Select", "https://my.jdownloader.org") + buttons.data_button("Done Selecting", "jdq sdone") + buttons.data_button("Cancel", "jdq cancel") + button = buttons.build_menu(2) + msg = f"Remove the unwanted files or change variants or edit files names from myJdownloader site for {self.listener.name}.\nDon't start it manually!\n\nAfter finish press Done Selecting!\nTimeout: 10 min" + self._reply_to = await send_message(self.listener.message, msg, button) + await self._event_handler() + if not self.listener.is_cancelled: + await delete_message(self._reply_to) + return not self.listener.is_cancelled + + +async def get_online_packages(path, state="grabbing"): + if state == "grabbing": + queued_downloads = await jdownloader.device.linkgrabber.query_packages( + [{"saveTo": True}] + ) + return [qd["uuid"] for qd in queued_downloads if qd["saveTo"].startswith(path)] + else: + download_packages = await jdownloader.device.downloads.query_packages( + [{"saveTo": True}] + ) + return [dl["uuid"] for dl in download_packages if dl["saveTo"].startswith(path)] + + +def trim_path(path): + path_components = path.split("/") + + trimmed_components = [ + component[:255] if len(component) > 255 else component + for component in path_components + ] + + return "/".join(trimmed_components) + + +async def get_jd_download_directory(): + res = await jdownloader.device.config.get( + "org.jdownloader.settings.GeneralSettings", None, "DefaultDownloadFolder" + ) + return f'/{res.strip("/")}/' + + +async def add_jd_download(listener, path): + try: + async with jd_listener_lock: + gid = token_urlsafe(12) + if not jdownloader.is_connected: + raise MYJDException(jdownloader.error) + + default_path = await get_jd_download_directory() + if not jd_downloads: + await jdownloader.device.linkgrabber.clear_list() + if odl := await jdownloader.device.downloads.query_packages([{}]): + odl_list = [od["uuid"] for od in odl] + await jdownloader.device.downloads.remove_links( + package_ids=odl_list + ) + elif odl := await jdownloader.device.linkgrabber.query_packages([{}]): + if odl_list := [ + od["uuid"] + for od in odl + if od.get("saveTo", "").startswith(default_path) + ]: + await jdownloader.device.linkgrabber.remove_links( + package_ids=odl_list + ) + + jd_downloads[gid] = {"status": "collect", "path": path} + + if await aiopath.exists(listener.link): + async with aiopen(listener.link, "rb") as dlc: + content = await dlc.read() + content = b64encode(content) + await jdownloader.device.linkgrabber.add_container( + "DLC", f"data:;base64,{content.decode()}" + ) + else: + await jdownloader.device.linkgrabber.add_links( + [ + { + "autoExtract": False, + "links": listener.link, + "deepDecrypt": True, + "overwritePackagizerRules": listener.join, + } + ], + ) + await sleep(1) + LOGGER.info(f"JDownloader Collecting Data: {listener.link}") + while await jdownloader.device.linkgrabber.is_collecting(): + await sleep(0.5) + LOGGER.info(f"JDownloader Finished Collecting Data: {listener.link}") + start_time = time() + online_packages = [] + corrupted_packages = [] + remove_unknown = False + name = "" + error = "" + while (time() - start_time) < 90: + queued_downloads = await jdownloader.device.linkgrabber.query_packages( + [ + { + "bytesTotal": True, + "saveTo": True, + "availableOnlineCount": True, + "availableOfflineCount": True, + "availableTempUnknownCount": True, + "availableUnknownCount": True, + } + ], + ) + + if not online_packages and corrupted_packages and error: + await jdownloader.device.linkgrabber.remove_links( + package_ids=corrupted_packages, + ) + raise MYJDException(error) + + for pack in queued_downloads: + if pack.get("onlineCount", 1) == 0: + error = f"{pack.get('name', '')}" + LOGGER.error(error) + corrupted_packages.append(pack["uuid"]) + continue + + if ( + pack.get("tempUnknownCount", 0) > 0 + or pack.get("unknownCount", 0) > 0 + or pack.get("offlineCount", 0) > 0 + ): + remove_unknown = True + + listener.size += pack.get("bytesTotal", 0) + online_packages.append(pack["uuid"]) + if not name: + name = pack.get("name", "").replace("/", "").split("/")[0] + save_to = pack["saveTo"] + if save_to.startswith(default_path): + save_to = trim_path(save_to) + await jdownloader.device.linkgrabber.set_download_directory( + save_to.replace(default_path, f"{path}/", 1), + [pack["uuid"]], + ) + + if online_packages: + break + else: + error = ( + name + or "Download Not Added! Maybe some issues in jdownloader or site!" + ) + if corrupted_packages or online_packages: + packages_to_remove = corrupted_packages + online_packages + await jdownloader.device.linkgrabber.remove_links( + package_ids=packages_to_remove, + ) + raise MYJDException(error) + + jd_downloads[gid]["ids"] = online_packages + + corrupted_links = [] + if remove_unknown: + links = await jdownloader.device.linkgrabber.query_links( + [{"packageUUIDs": online_packages, "availability": True}], + ) + corrupted_links = [ + link["uuid"] + for link in links + if link["availability"].lower() != "online" + ] + if corrupted_packages or corrupted_links: + await jdownloader.device.linkgrabber.remove_links( + corrupted_links, + corrupted_packages, + ) + + listener.name = listener.name or name + + msg, button = await stop_duplicate_check(listener) + if msg: + await jdownloader.device.linkgrabber.remove_links( + package_ids=online_packages + ) + await listener.on_download_error(msg, button) + async with jd_listener_lock: + del jd_downloads[gid] + return + + if listener.select: + if not await JDownloaderHelper(listener).wait_for_configurations(): + await jdownloader.device.linkgrabber.remove_links( + package_ids=online_packages + ) + await listener.remove_from_same_dir() + async with jd_listener_lock: + del jd_downloads[gid] + return + else: + online_packages = await get_online_packages(path) + if not online_packages: + raise MYJDException( + "Select: This Download have been removed manually!" + ) + async with jd_listener_lock: + jd_downloads[gid]["ids"] = online_packages + + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {listener.name}") + async with task_dict_lock: + task_dict[listener.mid] = QueueStatus(listener, gid, "dl") + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + await event.wait() + if listener.is_cancelled: + return + + online_packages = await get_online_packages(path) + if not online_packages: + raise MYJDException("Queue: This Download have been removed manually!") + async with jd_listener_lock: + jd_downloads[gid]["ids"] = online_packages + + await jdownloader.device.linkgrabber.move_to_downloadlist( + package_ids=online_packages + ) + + await sleep(0.5) + + online_packages = await get_online_packages(path, "down") + if not online_packages: + online_packages = await get_online_packages(path) + if not online_packages: + raise MYJDException( + "Linkgrabber: This Download have been removed manually!" + ) + await jdownloader.device.linkgrabber.move_to_downloadlist( + package_ids=online_packages + ) + await sleep(0.5) + online_packages = await get_online_packages(path, "down") + if not online_packages: + raise MYJDException( + "Download List: This Download have been removed manually!" + ) + + async with jd_listener_lock: + jd_downloads[gid]["status"] = "down" + jd_downloads[gid]["ids"] = online_packages + + await jdownloader.device.downloads.force_download(package_ids=online_packages) + + async with task_dict_lock: + task_dict[listener.mid] = JDownloaderStatus(listener, gid) + + await on_download_start() + + if add_to_queue: + LOGGER.info(f"Start Queued Download from JDownloader: {listener.name}") + else: + LOGGER.info(f"Download with JDownloader: {listener.name}") + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + except (Exception, MYJDException) as e: + await listener.on_download_error(f"{e}".strip()) + async with jd_listener_lock: + if gid in jd_downloads: + del jd_downloads[gid] + return + finally: + if await aiopath.exists(listener.link): + await remove(listener.link) + + await sleep(2) + + links = await jdownloader.device.downloads.query_links( + [ + { + "packageUUIDs": online_packages, + "status": True, + } + ], + ) + links_to_remove = [] + force_download = False + for dlink in links: + if dlink.get("status", "") == "Invalid download directory": + force_download = True + new_name, ext = dlink["name"].rsplit(".", 1) + new_name = new_name[: 250 - len(f".{ext}".encode())] + new_name = f"{new_name}.{ext}" + await jdownloader.device.downloads.rename_link(dlink["uuid"], new_name) + elif dlink.get("status", "") == "HLS stream broken?": + links_to_remove.append(dlink["uuid"]) + + if links_to_remove: + await jdownloader.device.downloads.remove_links(links_to_remove) + if force_download: + await jdownloader.device.downloads.force_download(package_ids=online_packages) diff --git a/bot/helper/mirror_leech_utils/download_utils/nzb_downloader.py b/bot/helper/mirror_leech_utils/download_utils/nzb_downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..31df922d55e05054d08c45d2442a25f566164ca0 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/nzb_downloader.py @@ -0,0 +1,167 @@ +from aiofiles.os import remove, path as aiopath +from asyncio import gather, sleep +from sabnzbdapi.exception import NotLoggedIn, LoginFailed + +from .... import ( + task_dict, + task_dict_lock, + sabnzbd_client, + LOGGER, +) +from ....core.config_manager import Config +from ...ext_utils.task_manager import check_running_tasks +from ...listeners.nzb_listener import on_download_start +from ...ext_utils.db_handler import database +from ...ext_utils.bot_utils import bt_selection_buttons +from ...mirror_leech_utils.status_utils.nzb_status import SabnzbdStatus +from ...telegram_helper.message_utils import ( + send_status_message, + send_message, + delete_message, +) + + +async def add_servers(): + res = await sabnzbd_client.check_login() + if res and (servers := res["servers"]): + sabnzbd_client.LOGGED_IN = True + tasks = [] + servers_hosts = [x["host"] for x in servers] + for server in list(Config.USENET_SERVERS): + if server["host"] not in servers_hosts: + tasks.append(sabnzbd_client.add_server(server)) + Config.USENET_SERVERS.append(server) + if Config.DATABASE_URL: + tasks.append( + database.update_config({"USENET_SERVERS": Config.USENET_SERVERS}) + ) + if tasks: + try: + await gather(*tasks) + except LoginFailed as e: + raise e + elif not res and ( + Config.USENET_SERVERS + and ( + not Config.USENET_SERVERS[0]["host"] + or not Config.USENET_SERVERS[0]["username"] + or not Config.USENET_SERVERS[0]["password"] + ) + or not Config.USENET_SERVERS + ): + sabnzbd_client.LOGGED_IN = False + raise NotLoggedIn("Set USENET_SERVERS in bsetting or config!") + else: + if tasks := [ + sabnzbd_client.add_server(server) for server in Config.USENET_SERVERS + ]: + try: + await gather(*tasks) + sabnzbd_client.LOGGED_IN = True + except LoginFailed as e: + if len(tasks) == 1: + sabnzbd_client.LOGGED_IN = False + raise e + + +async def add_nzb(listener, path): + if not sabnzbd_client.LOGGED_IN: + try: + await add_servers() + except Exception as e: + await listener.on_download_error(str(e)) + return + try: + await sabnzbd_client.create_category(f"{listener.mid}", path) + url = listener.link + nzbpath = None + if await aiopath.exists(listener.link): + url = None + nzbpath = listener.link + add_to_queue, event = await check_running_tasks(listener) + res = await sabnzbd_client.add_uri( + url, + nzbpath, + listener.name, + listener.extract if isinstance(listener.extract, str) else "", + f"{listener.mid}", + priority=-2 if add_to_queue else 0, + pp=3 if listener.extract else 1, + ) + if not res["status"]: + await listener.on_download_error( + "Not added! Mostly issue in the link", + ) + return + + job_id = res["nzo_ids"][0] + + await sleep(0.5) + + downloads = await sabnzbd_client.get_downloads(nzo_ids=job_id) + if not downloads["queue"]["slots"]: + await sleep(1) + history = await sabnzbd_client.get_history(nzo_ids=job_id) + if err := history["history"]["slots"][0]["fail_message"]: + await gather( + listener.on_download_error(err), + sabnzbd_client.delete_history(job_id, delete_files=True), + ) + return + name = history["history"]["slots"][0]["name"] + else: + name = downloads["queue"]["slots"][0]["filename"] + + async with task_dict_lock: + task_dict[listener.mid] = SabnzbdStatus( + listener, job_id, queued=add_to_queue + ) + await on_download_start(job_id) + + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {name} - Job_id: {job_id}") + else: + LOGGER.info(f"NzbDownload started: {name} - Job_id: {job_id}") + + await listener.on_download_start() + + if Config.BASE_URL and listener.select: + if url and name.startswith("Trying"): + metamsg = "Fetching URL, wait then you can select files. Use nzb file to avoid this wait." + meta = await send_message(listener.message, metamsg) + while True: + nzb_info = await sabnzbd_client.get_downloads(nzo_ids=job_id) + if nzb_info["queue"]["slots"]: + if not nzb_info["queue"]["slots"][0]["filename"].startswith( + "Trying" + ): + await delete_message(meta) + break + else: + await delete_message(meta) + return + await sleep(1) + if not add_to_queue: + await sabnzbd_client.pause_job(job_id) + SBUTTONS = bt_selection_buttons(job_id) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + await send_message(listener.message, msg, SBUTTONS) + elif listener.multi <= 1: + await send_status_message(listener.message) + + if add_to_queue: + await event.wait() + if listener.is_cancelled: + return + async with task_dict_lock: + task_dict[listener.mid].queued = False + + await sabnzbd_client.resume_job(job_id) + LOGGER.info( + f"Start Queued Download from Sabnzbd: {name} - Job_id: {job_id}" + ) + except Exception as e: + await listener.on_download_error(f"{e}") + finally: + if nzbpath and await aiopath.exists(listener.link): + await remove(listener.link) diff --git a/bot/helper/mirror_leech_utils/download_utils/qbit_download.py b/bot/helper/mirror_leech_utils/download_utils/qbit_download.py new file mode 100644 index 0000000000000000000000000000000000000000..733837ac7a1881dc20ddac66ba50ac1274e80ac0 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/qbit_download.py @@ -0,0 +1,149 @@ +from aiofiles.os import remove, path as aiopath +from aiofiles import open as aiopen +from asyncio import sleep, TimeoutError +from aioqbt.api import AddFormBuilder +from aioqbt.exc import AQError +from aiohttp.client_exceptions import ClientError + +from .... import ( + task_dict, + task_dict_lock, + LOGGER, + qb_torrents, +) +from ....core.config_manager import Config +from ....core.torrent_manager import TorrentManager +from ...ext_utils.bot_utils import bt_selection_buttons +from ...ext_utils.task_manager import check_running_tasks +from ...listeners.qbit_listener import on_download_start +from ...mirror_leech_utils.status_utils.qbit_status import QbittorrentStatus +from ...telegram_helper.message_utils import ( + send_message, + delete_message, + send_status_message, +) + +""" +Only v1 torrents +#from hashlib import sha1 +#from base64 import b16encode, b32decode +#from bencoding import bencode, bdecode +#from re import search as re_search +def _get_hash_magnet(mgt: str): + hash_ = re_search(r'(?<=xt=urn:btih:)[a-zA-Z0-9]+', mgt).group(0) + if len(hash_) == 32: + hash_ = b16encode(b32decode(hash_.upper())).decode() + return hash_ + +def _get_hash_file(fpath): + with open(fpath, "rb") as f: + decodedDict = bdecode(f.read()) + return sha1(bencode(decodedDict[b'info'])).hexdigest() +""" + + +async def add_qb_torrent(listener, path, ratio, seed_time): + try: + form = AddFormBuilder.with_client(TorrentManager.qbittorrent) + if await aiopath.exists(listener.link): + async with aiopen(listener.link, "rb") as f: + data = await f.read() + form = form.include_file(data) + else: + form = form.include_url(listener.link) + form = form.savepath(path).tags([f"{listener.mid}"]) + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + form = form.stopped(add_to_queue) + if ratio: + form = form.ratio_limit(ratio) + if seed_time: + form = form.seeding_time_limit(int(seed_time)) + try: + await TorrentManager.qbittorrent.torrents.add(form.build()) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error( + f"{e}. {listener.mid}. Already added torrent or unsupported link/file type!" + ) + await listener.on_download_error( + f"{e}. {listener.mid}. Already added torrent or unsupported link/file type!" + ) + return + tor_info = await TorrentManager.qbittorrent.torrents.info(tag=f"{listener.mid}") + if len(tor_info) == 0: + while True: + if add_to_queue and event.is_set(): + add_to_queue = False + tor_info = await TorrentManager.qbittorrent.torrents.info( + tag=f"{listener.mid}" + ) + if len(tor_info) > 0: + break + await sleep(1) + tor_info = tor_info[0] + listener.name = tor_info.name + ext_hash = tor_info.hash + + async with task_dict_lock: + task_dict[listener.mid] = QbittorrentStatus(listener, queued=add_to_queue) + await on_download_start(f"{listener.mid}") + + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {tor_info.name} - Hash: {ext_hash}") + else: + LOGGER.info(f"QbitDownload started: {tor_info.name} - Hash: {ext_hash}") + + await listener.on_download_start() + + if Config.BASE_URL and listener.select: + if listener.link.startswith("magnet:"): + metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait." + meta = await send_message(listener.message, metamsg) + while True: + tor_info = await TorrentManager.qbittorrent.torrents.info( + tag=f"{listener.mid}" + ) + if len(tor_info) == 0: + await delete_message(meta) + return + try: + tor_info = tor_info[0] + if tor_info.state not in [ + "metaDL", + "checkingResumeData", + "stoppedDL", + ]: + await delete_message(meta) + break + except: + await delete_message(meta) + return + + ext_hash = tor_info.hash + if not add_to_queue: + await TorrentManager.qbittorrent.torrents.stop([ext_hash]) + SBUTTONS = bt_selection_buttons(ext_hash) + msg = "Your download paused. Choose files then press Done Selecting button to start downloading." + await send_message(listener.message, msg, SBUTTONS) + elif listener.multi <= 1 and not listener.is_rss: + await send_status_message(listener.message) + + if event is not None: + if not event.is_set(): + await event.wait() + if listener.is_cancelled: + return + async with task_dict_lock: + task_dict[listener.mid].queued = False + LOGGER.info( + f"Start Queued Download from Qbittorrent: {tor_info.name} - Hash: {ext_hash}" + ) + await on_download_start(f"{listener.mid}") + await TorrentManager.qbittorrent.torrents.start([ext_hash]) + except (ClientError, TimeoutError, Exception, AQError) as e: + if f"{listener.mid}" in qb_torrents: + del qb_torrents[f"{listener.mid}"] + await listener.on_download_error(f"{e}") + finally: + if await aiopath.exists(listener.link): + await remove(listener.link) diff --git a/bot/helper/mirror_leech_utils/download_utils/rclone_download.py b/bot/helper/mirror_leech_utils/download_utils/rclone_download.py new file mode 100644 index 0000000000000000000000000000000000000000..a162d908eb3daf0525aec80db9eb0a227923d672 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/rclone_download.py @@ -0,0 +1,124 @@ +from asyncio import gather +from json import loads +from secrets import token_urlsafe +from aiofiles.os import remove + +from .... import task_dict, task_dict_lock, LOGGER +from ...ext_utils.bot_utils import cmd_exec +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...mirror_leech_utils.rclone_utils.transfer import RcloneTransferHelper +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...mirror_leech_utils.status_utils.rclone_status import RcloneStatus +from ...telegram_helper.message_utils import send_status_message + + +async def add_rclone_download(listener, path): + if listener.link.startswith("mrcc:"): + listener.link = listener.link.split("mrcc:", 1)[1] + config_path = f"rclone/{listener.user_id}.conf" + else: + config_path = "rclone.conf" + + remote, listener.link = listener.link.split(":", 1) + listener.link = listener.link.strip("/") + rclone_select = False + if listener.link.startswith("rclone_select"): + rclone_select = True + rpath = "" + else: + rpath = listener.link + + cmd1 = [ + "rclone", + "lsjson", + "--fast-list", + "--stat", + "--no-mimetype", + "--no-modtime", + "--config", + config_path, + f"{remote}:{rpath}", + ] + cmd2 = [ + "rclone", + "size", + "--fast-list", + "--json", + "--config", + config_path, + f"{remote}:{rpath}", + ] + if rclone_select: + cmd2.extend(("--files-from", listener.link)) + res = await cmd_exec(cmd2) + if res[2] != 0: + if res[2] != -9: + msg = f"Error: While getting rclone stat/size. Path: {remote}:{listener.link}. Stderr: {res[1][:4000]}" + await listener.on_download_error(msg) + return + try: + rsize = loads(res[0]) + except Exception as err: + await listener.on_download_error(f"RcloneDownload JsonLoad: {err}") + return + if not listener.name: + listener.name = listener.link + path += listener.name + else: + res1, res2 = await gather(cmd_exec(cmd1), cmd_exec(cmd2)) + if res1[2] != 0 or res2[2] != 0: + if res1[2] != -9: + err = res1[1] or res2[1] + msg = f"Error: While getting rclone stat/size. Path: {remote}:{listener.link}. Stderr: {err[:4000]}" + await listener.on_download_error(msg) + return + try: + rstat = loads(res1[0]) + rsize = loads(res2[0]) + except Exception as err: + await listener.on_download_error(f"RcloneDownload JsonLoad: {err}") + return + if rstat["IsDir"]: + if not listener.name: + listener.name = ( + listener.link.rsplit("/", 1)[-1] if listener.link else remote + ) + path += listener.name + else: + listener.name = listener.link.rsplit("/", 1)[-1] + listener.size = rsize["bytes"] + gid = token_urlsafe(12) + + if not rclone_select: + msg, button = await stop_duplicate_check(listener) + if msg: + await listener.on_download_error(msg, button) + return + + add_to_queue, event = await check_running_tasks(listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {listener.name}") + async with task_dict_lock: + task_dict[listener.mid] = QueueStatus(listener, gid, "dl") + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + await event.wait() + if listener.is_cancelled: + return + + RCTransfer = RcloneTransferHelper(listener) + async with task_dict_lock: + task_dict[listener.mid] = RcloneStatus(listener, RCTransfer, gid, "dl") + + if add_to_queue: + LOGGER.info(f"Start Queued Download with rclone: {listener.link}") + else: + await listener.on_download_start() + if listener.multi <= 1: + await send_status_message(listener.message) + LOGGER.info(f"Download with rclone: {listener.link}") + + await RCTransfer.download(remote, config_path, path) + if rclone_select: + await remove(listener.link) diff --git a/bot/helper/mirror_leech_utils/download_utils/telegram_download.py b/bot/helper/mirror_leech_utils/download_utils/telegram_download.py new file mode 100644 index 0000000000000000000000000000000000000000..80e4af1111cc623813c16cb5fbcb9ee27f827ac6 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/telegram_download.py @@ -0,0 +1,178 @@ +from asyncio import Lock, sleep +from time import time +from pyrogram.errors import FloodWait, FloodPremiumWait + +from .... import ( + LOGGER, + task_dict, + task_dict_lock, +) +from ....core.telegram_manager import TgClient +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...mirror_leech_utils.status_utils.telegram_status import TelegramStatus +from ...telegram_helper.message_utils import send_status_message + +global_lock = Lock() +GLOBAL_GID = set() + + +class TelegramDownloadHelper: + def __init__(self, listener): + self._processed_bytes = 0 + self._start_time = 1 + self._listener = listener + self._id = "" + self.session = "" + + @property + def speed(self): + return self._processed_bytes / (time() - self._start_time) + + @property + def processed_bytes(self): + return self._processed_bytes + + async def _on_download_start(self, file_id, from_queue): + async with global_lock: + GLOBAL_GID.add(file_id) + self._id = file_id + async with task_dict_lock: + task_dict[self._listener.mid] = TelegramStatus( + self._listener, self, file_id[:12], "dl" + ) + if not from_queue: + await self._listener.on_download_start() + if self._listener.multi <= 1: + await send_status_message(self._listener.message) + LOGGER.info(f"Download from Telegram: {self._listener.name}") + else: + LOGGER.info(f"Start Queued Download from Telegram: {self._listener.name}") + + async def _on_download_progress(self, current, _): + if self._listener.is_cancelled: + if self.session == "user": + TgClient.user.stop_transmission() + else: + TgClient.bot.stop_transmission() + self._processed_bytes = current + + async def _on_download_error(self, error): + async with global_lock: + if self._id in GLOBAL_GID: + GLOBAL_GID.remove(self._id) + await self._listener.on_download_error(error) + + async def _on_download_complete(self): + async with global_lock: + if self._id in GLOBAL_GID: + GLOBAL_GID.remove(self._id) + await self._listener.on_download_complete() + + async def _download(self, message, path): + try: + download = await message.download( + file_name=path, progress=self._on_download_progress + ) + if self._listener.is_cancelled: + return + except (FloodWait, FloodPremiumWait) as f: + LOGGER.warning(str(f)) + await sleep(f.value) + await self._download(message, path) + return + except Exception as e: + LOGGER.error(str(e)) + await self._on_download_error(str(e)) + return + if download is not None: + await self._on_download_complete() + elif not self._listener.is_cancelled: + await self._on_download_error("Internal error occurred") + + async def add_download(self, message, path, session): + self.session = session + if not self.session: + if self._listener.user_transmission and self._listener.is_super_chat: + self.session = "user" + message = await TgClient.user.get_messages( + chat_id=message.chat.id, message_ids=message.id + ) + else: + self.session = "bot" + media = ( + message.document + or message.photo + or message.video + or message.audio + or message.voice + or message.video_note + or message.sticker + or message.animation + or None + ) + + if media is not None: + async with global_lock: + download = media.file_unique_id not in GLOBAL_GID + + if download: + if not self._listener.name: + if hasattr(media, "file_name") and media.file_name: + if "/" in media.file_name: + self._listener.name = media.file_name.rsplit("/", 1)[-1] + path = path + self._listener.name + else: + self._listener.name = media.file_name + else: + self._listener.name = "None" + else: + path = path + self._listener.name + self._listener.size = media.file_size + gid = media.file_unique_id + + msg, button = await stop_duplicate_check(self._listener) + if msg: + await self._listener.on_download_error(msg, button) + return + + add_to_queue, event = await check_running_tasks(self._listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {self._listener.name}") + async with task_dict_lock: + task_dict[self._listener.mid] = QueueStatus( + self._listener, gid, "dl" + ) + await self._listener.on_download_start() + if self._listener.multi <= 1: + await send_status_message(self._listener.message) + await event.wait() + if self.session == "bot": + message = await self._listener.client.get_messages( + chat_id=message.chat.id, message_ids=message.id + ) + else: + message = await TgClient.user.get_messages( + chat_id=message.chat.id, message_ids=message.id + ) + if self._listener.is_cancelled: + async with global_lock: + if self._id in GLOBAL_GID: + GLOBAL_GID.remove(self._id) + return + self._start_time = time() + await self._on_download_start(gid, add_to_queue) + await self._download(message, path) + else: + await self._on_download_error("File already being downloaded!") + else: + await self._on_download_error( + "No document in the replied message! Use SuperGroup incase you are trying to download with User session!" + ) + + async def cancel_task(self): + self._listener.is_cancelled = True + LOGGER.info( + f"Cancelling download on user request: name: {self._listener.name} id: {self._id}" + ) + await self._on_download_error("Stopped by user!") diff --git a/bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py b/bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py new file mode 100644 index 0000000000000000000000000000000000000000..a231402c728658ca39bb04d1a086b4eba0630084 --- /dev/null +++ b/bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py @@ -0,0 +1,358 @@ +from logging import getLogger +from os import path as ospath, listdir +from re import search as re_search +from secrets import token_urlsafe +from yt_dlp import YoutubeDL, DownloadError + + +from .... import task_dict_lock, task_dict +from ...ext_utils.bot_utils import sync_to_async, async_to_sync +from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from ...mirror_leech_utils.status_utils.queue_status import QueueStatus +from ...telegram_helper.message_utils import send_status_message +from ..status_utils.yt_dlp_status import YtDlpStatus + +LOGGER = getLogger(__name__) + + +class MyLogger: + def __init__(self, obj, listener): + self._obj = obj + self._listener = listener + + 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._listener.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._last_downloaded = 0 + self._progress = 0 + self._downloaded_bytes = 0 + self._download_speed = 0 + self._eta = "-" + self._listener = listener + self._gid = "" + self._ext = "" + self.is_playlist = False + self.keep_thumb = False + self.opts = { + "progress_hooks": [self._on_download_progress], + "logger": MyLogger(self, self._listener), + "usenetrc": True, + "cookiefile": "cookies.txt", + "allow_multiple_video_streams": True, + "allow_multiple_audio_streams": True, + "noprogress": True, + "allow_playlist_files": True, + "overwrites": True, + "writethumbnail": True, + "trim_file_name": 220, + "fragment_retries": 10, + "retries": 10, + "retry_sleep_functions": { + "http": lambda n: 3, + "fragment": lambda n: 3, + "file_access": lambda n: 3, + "extractor": lambda n: 3, + }, + } + + @property + def download_speed(self): + return self._download_speed + + @property + def downloaded_bytes(self): + return self._downloaded_bytes + + @property + def size(self): + return self._listener.size + + @property + def progress(self): + return self._progress + + @property + def eta(self): + return self._eta + + def _on_download_progress(self, d): + if self._listener.is_cancelled: + raise ValueError("Cancelling...") + if d["status"] == "finished": + if self.is_playlist: + self._last_downloaded = 0 + elif d["status"] == "downloading": + self._download_speed = d["speed"] or 0 + if self.is_playlist: + downloadedBytes = d["downloaded_bytes"] or 0 + chunk_size = downloadedBytes - self._last_downloaded + self._last_downloaded = downloadedBytes + self._downloaded_bytes += chunk_size + else: + if d.get("total_bytes"): + self._listener.size = d["total_bytes"] or 0 + elif d.get("total_bytes_estimate"): + self._listener.size = d["total_bytes_estimate"] or 0 + self._downloaded_bytes = d["downloaded_bytes"] or 0 + self._eta = d.get("eta", "-") or "-" + try: + self._progress = (self._downloaded_bytes / self._listener.size) * 100 + except: + pass + + async def _on_download_start(self, from_queue=False): + async with task_dict_lock: + task_dict[self._listener.mid] = YtDlpStatus(self._listener, self, self._gid) + if not from_queue: + await self._listener.on_download_start() + if self._listener.multi <= 1 and not self._listener.is_rss: + await send_status_message(self._listener.message) + + def _on_download_error(self, error): + self._listener.is_cancelled = True + async_to_sync(self._listener.on_download_error, error) + + def _extract_meta_data(self): + if self._listener.link.startswith(("rtmp", "mms", "rstp", "rtmps")): + self.opts["external_downloader"] = "ffmpeg" + with YoutubeDL(self.opts) as ydl: + try: + result = ydl.extract_info(self._listener.link, download=False) + if result is None: + raise ValueError("Info result is None") + except Exception as e: + return self._on_download_error(str(e)) + if "entries" in result: + for entry in result["entries"]: + if not entry: + continue + elif "filesize_approx" in entry: + self._listener.size += entry.get("filesize_approx", 0) or 0 + elif "filesize" in entry: + self._listener.size += entry.get("filesize", 0) or 0 + if not self._listener.name: + outtmpl_ = "%(series,playlist_title,channel)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d.%(ext)s" + self._listener.name, ext = ospath.splitext( + ydl.prepare_filename(entry, outtmpl=outtmpl_) + ) + if not self._ext: + self._ext = ext + else: + outtmpl_ = "%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s" + realName = ydl.prepare_filename(result, outtmpl=outtmpl_) + ext = ospath.splitext(realName)[-1] + self._listener.name = ( + f"{self._listener.name}{ext}" if self._listener.name else realName + ) + if not self._ext: + self._ext = ext + + def _download(self, path): + try: + with YoutubeDL(self.opts) as ydl: + try: + ydl.download([self._listener.link]) + except DownloadError as e: + if not self._listener.is_cancelled: + self._on_download_error(str(e)) + return + if self.is_playlist and ( + not ospath.exists(path) or len(listdir(path)) == 0 + ): + self._on_download_error( + "No video available to download from this playlist. Check logs for more details" + ) + return + if self._listener.is_cancelled: + return + async_to_sync(self._listener.on_download_complete) + except: + pass + return + + async def add_download(self, path, qual, playlist, options): + if playlist: + self.opts["ignoreerrors"] = True + self.is_playlist = True + + self._gid = token_urlsafe(10) + + await self._on_download_start() + + self.opts["postprocessors"] = [ + { + "add_chapters": True, + "add_infojson": "if_exists", + "add_metadata": True, + "key": "FFmpegMetadata", + } + ] + + if qual.startswith("ba/b-"): + audio_info = qual.split("-") + qual = audio_info[0] + audio_format = audio_info[1] + rate = audio_info[2] + self.opts["postprocessors"].append( + { + "key": "FFmpegExtractAudio", + "preferredcodec": audio_format, + "preferredquality": rate, + } + ) + if audio_format == "vorbis": + self._ext = ".ogg" + elif audio_format == "alac": + self._ext = ".m4a" + else: + self._ext = f".{audio_format}" + + if not self._listener.is_leech or self._listener.thumbnail_layout: + self.opts["writethumbnail"] = False + + if options: + self._set_options(options) + + self.opts["format"] = qual + + await sync_to_async(self._extract_meta_data) + if self._listener.is_cancelled: + return + + base_name, ext = ospath.splitext(self._listener.name) + trim_name = self._listener.name if self.is_playlist else base_name + if len(trim_name.encode()) > 200: + self._listener.name = ( + self._listener.name[:200] + if self.is_playlist + else f"{base_name[:200]}{ext}" + ) + base_name = ospath.splitext(self._listener.name)[0] + + start_path = path if self.keep_thumb else f"{path}/yt-dlp-thumb" + if self.is_playlist: + self.opts["outtmpl"] = { + "default": f"{path}/{self._listener.name}/%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s", + "thumbnail": f"{start_path}/%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s", + } + elif "download_ranges" in options: + self.opts["outtmpl"] = { + "default": f"{path}/{base_name}/%(section_number|)s%(section_number&.|)s%(section_title|)s%(section_title&-|)s%(title,fulltitle,alt_title)s %(section_start)s to %(section_end)s.%(ext)s", + "thumbnail": f"{start_path}/%(section_number|)s%(section_number&.|)s%(section_title|)s%(section_title&-|)s%(title,fulltitle,alt_title)s %(section_start)s to %(section_end)s.%(ext)s", + } + elif any( + key in options + for key in [ + "writedescription", + "writeinfojson", + "writeannotations", + "writedesktoplink", + "writewebloclink", + "writelink", + "writeurllink", + "writesubtitles", + "write_all_thumbnails", + ] + ): + self.opts["outtmpl"] = { + "default": f"{path}/{base_name}/{self._listener.name}", + "thumbnail": f"{start_path}/{base_name}.%(ext)s", + } + else: + self.opts["outtmpl"] = { + "default": f"{path}/{self._listener.name}", + "thumbnail": f"{start_path}/{base_name}.%(ext)s", + } + + if qual.startswith("ba/b"): + self._listener.name = f"{base_name}{self._ext}" + + if self.opts["writethumbnail"]: + self.opts["postprocessors"].append( + { + "format": "jpg", + "key": "FFmpegThumbnailsConvertor", + "when": "before_dl", + } + ) + if self._ext in [ + ".mp3", + ".mkv", + ".mka", + ".ogg", + ".opus", + ".flac", + ".m4a", + ".mp4", + ".mov", + ".m4v", + ]: + self.opts["postprocessors"].append( + { + "already_have_thumbnail": self.opts["writethumbnail"], + "key": "EmbedThumbnail", + } + ) + + msg, button = await stop_duplicate_check(self._listener) + if msg: + await self._listener.on_download_error(msg, button) + return + + add_to_queue, event = await check_running_tasks(self._listener) + if add_to_queue: + LOGGER.info(f"Added to Queue/Download: {self._listener.name}") + async with task_dict_lock: + task_dict[self._listener.mid] = QueueStatus( + self._listener, self._gid, "dl" + ) + await event.wait() + if self._listener.is_cancelled: + return + LOGGER.info(f"Start Queued Download from YT_DLP: {self._listener.name}") + await self._on_download_start(True) + + if not add_to_queue: + LOGGER.info(f"Download with YT_DLP: {self._listener.name}") + + await sync_to_async(self._download, path) + + async def cancel_task(self): + self._listener.is_cancelled = True + LOGGER.info(f"Cancelling Download: {self._listener.name}") + await self._listener.on_download_error("Stopped by User!") + + def _set_options(self, options): + for key, value in options.items(): + if key == "postprocessors": + if isinstance(value, list): + self.opts[key].extend(tuple(value)) + elif isinstance(value, dict): + self.opts[key].append(value) + elif key == "download_ranges": + if isinstance(value, list): + self.opts[key] = lambda info, ytdl: value + else: + if key == "writethumbnail" and value is True: + self.keep_thumb = True + self.opts[key] = value diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/__init__.py b/bot/helper/mirror_leech_utils/gdrive_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/clone.py b/bot/helper/mirror_leech_utils/gdrive_utils/clone.py new file mode 100644 index 0000000000000000000000000000000000000000..61faf4d73ba7b65353c9e2aba7f4be6bd10f68cb --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/clone.py @@ -0,0 +1,169 @@ +from googleapiclient.errors import HttpError +from logging import getLogger +from os import path as ospath +from tenacity import ( + retry, + wait_exponential, + stop_after_attempt, + retry_if_exception_type, + RetryError, +) +from time import time + +from ...ext_utils.bot_utils import async_to_sync +from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveClone(GoogleDriveHelper): + def __init__(self, listener): + self.listener = listener + self._start_time = time() + super().__init__() + self.is_cloning = True + self.user_setting() + + def user_setting(self): + if self.listener.up_dest.startswith("mtp:") or self.listener.link.startswith( + "mtp:" + ): + self.token_path = f"tokens/{self.listener.user_id}.pickle" + self.listener.up_dest = self.listener.up_dest.replace("mtp:", "", 1) + self.use_sa = False + elif self.listener.up_dest.startswith("tp:"): + self.listener.up_dest = self.listener.up_dest.replace("tp:", "", 1) + self.use_sa = False + elif self.listener.up_dest.startswith("sa:") or self.listener.link.startswith( + "sa:" + ): + self.listener.up_dest = self.listener.up_dest.replace("sa:", "", 1) + self.use_sa = True + + def clone(self): + try: + file_id = self.get_id_from_url(self.listener.link) + except (KeyError, IndexError): + return ( + "Google Drive ID could not be found in the provided link", + None, + None, + None, + None, + ) + self.service = self.authorize() + msg = "" + LOGGER.info(f"File ID: {file_id}") + try: + meta = self.get_file_metadata(file_id) + mime_type = meta.get("mimeType") + if mime_type == self.G_DRIVE_DIR_MIME_TYPE: + dir_id = self.create_directory(meta.get("name"), self.listener.up_dest) + self._clone_folder(meta.get("name"), meta.get("id"), dir_id) + durl = self.G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id) + if self.listener.is_cancelled: + LOGGER.info("Deleting cloned data from Drive...") + self.service.files().delete( + fileId=dir_id, supportsAllDrives=True + ).execute() + return None, None, None, None, None + mime_type = "Folder" + self.listener.size = self.proc_bytes + else: + file = self._copy_file(meta.get("id"), self.listener.up_dest) + msg += f'Name: {file.get("name")}' + durl = self.G_DRIVE_BASE_DOWNLOAD_URL.format(file.get("id")) + if mime_type is None: + mime_type = "File" + self.listener.size = int(meta.get("size", 0)) + return ( + durl, + mime_type, + self.total_files, + self.total_folders, + self.get_id_from_url(durl), + ) + 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: + if not self.alt_auth and self.use_sa: + self.alt_auth = True + self.use_sa = False + LOGGER.error("File not found. Trying with token.pickle...") + return self.clone() + msg = "File not found." + else: + msg = f"Error.\n{err}" + async_to_sync(self.listener.on_upload_error, msg) + return None, None, None, None, None + + def _clone_folder(self, folder_name, folder_id, dest_id): + LOGGER.info(f"Syncing: {folder_name}") + files = self.get_files_by_folder_id(folder_id) + if len(files) == 0: + return dest_id + for file in files: + if file.get("mimeType") == self.G_DRIVE_DIR_MIME_TYPE: + self.total_folders += 1 + file_path = ospath.join(folder_name, file.get("name")) + current_dir_id = self.create_directory(file.get("name"), dest_id) + self._clone_folder(file_path, file.get("id"), current_dir_id) + elif self.listener.included_extensions and not file.get( + "name" + ).strip().lower().endswith(tuple(self.listener.included_extensions)): + continue + elif not self.listener.included_extensions and file.get( + "name" + ).strip().lower().endswith(tuple(self.listener.excluded_extensions)): + continue + else: + self.total_files += 1 + self._copy_file(file.get("id"), dest_id) + self.proc_bytes += int(file.get("size", 0)) + self.total_time = int(time() - self._start_time) + if self.listener.is_cancelled: + break + + @retry( + wait=wait_exponential(multiplier=2, min=3, max=6), + stop=stop_after_attempt(3), + retry=retry_if_exception_type(Exception), + ) + def _copy_file(self, file_id, dest_id): + body = {"parents": [dest_id]} + try: + return ( + self.service.files() + .copy(fileId=file_id, body=body, supportsAllDrives=True) + .execute() + ) + except HttpError as err: + if err.resp.get("content-type", "").startswith("application/json"): + reason = eval(err.content).get("error").get("errors")[0].get("reason") + if reason not in [ + "userRateLimitExceeded", + "dailyLimitExceeded", + "cannotCopyFile", + ]: + raise err + if reason == "cannotCopyFile": + LOGGER.error(err) + elif self.use_sa: + if self.sa_count >= self.sa_number: + LOGGER.info( + f"Reached maximum number of service accounts switching, which is {self.sa_count}" + ) + raise err + else: + if self.listener.is_cancelled: + return + self.switch_service_account() + return self._copy_file(file_id, dest_id) + else: + LOGGER.error(f"Got: {reason}") + raise err diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/count.py b/bot/helper/mirror_leech_utils/gdrive_utils/count.py new file mode 100644 index 0000000000000000000000000000000000000000..69c7b8f9d595b648ec269ab8a4844ab659d385ac --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/count.py @@ -0,0 +1,80 @@ +from logging import getLogger +from tenacity import RetryError + +from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveCount(GoogleDriveHelper): + def __init__(self): + super().__init__() + + def count(self, link, user_id): + try: + file_id = self.get_id_from_url(link, user_id) + except (KeyError, IndexError): + return ( + "Google Drive ID could not be found in the provided link", + None, + None, + None, + None, + ) + self.service = self.authorize() + LOGGER.info(f"File ID: {file_id}") + try: + return self._proceed_count(file_id) + 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 "File not found" in err: + if not self.alt_auth and self.use_sa: + self.alt_auth = True + self.use_sa = False + LOGGER.error("File not found. Trying with token.pickle...") + return self.count(link, user_id) + msg = "File not found." + else: + msg = f"Error.\n{err}" + return msg, None, None, None, None + + def _proceed_count(self, file_id): + meta = self.get_file_metadata(file_id) + name = meta["name"] + LOGGER.info(f"Counting: {name}") + mime_type = meta.get("mimeType") + if mime_type == self.G_DRIVE_DIR_MIME_TYPE: + self._gdrive_directory(meta) + mime_type = "Folder" + else: + if mime_type is None: + mime_type = "File" + self.total_files += 1 + self._gdrive_file(meta) + return name, mime_type, self.proc_bytes, self.total_files, self.total_folders + + def _gdrive_file(self, filee): + size = int(filee.get("size", 0)) + self.proc_bytes += size + + def _gdrive_directory(self, drive_folder): + files = self.get_files_by_folder_id(drive_folder["id"]) + if len(files) == 0: + return + for filee in files: + shortcut_details = filee.get("shortcutDetails") + if shortcut_details is not None: + mime_type = shortcut_details["targetMimeType"] + file_id = shortcut_details["targetId"] + filee = self.get_file_metadata(file_id) + else: + mime_type = filee.get("mimeType") + if mime_type == self.G_DRIVE_DIR_MIME_TYPE: + self.total_folders += 1 + self._gdrive_directory(filee) + else: + self.total_files += 1 + self._gdrive_file(filee) diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/delete.py b/bot/helper/mirror_leech_utils/gdrive_utils/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..d3ee5e7787b391266af23876161472c7dde3812f --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/delete.py @@ -0,0 +1,38 @@ +from googleapiclient.errors import HttpError +from logging import getLogger + +from ....helper.mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveDelete(GoogleDriveHelper): + def __init__(self): + super().__init__() + + def deletefile(self, link, user_id): + try: + file_id = self.get_id_from_url(link, user_id) + except (KeyError, IndexError): + return "Google Drive ID could not be found in the provided link" + self.service = self.authorize() + msg = "" + try: + self.service.files().delete( + fileId=file_id, supportsAllDrives=True + ).execute() + msg = "Successfully deleted" + LOGGER.info(f"Delete Result: {msg}") + except HttpError as err: + if "File not found" in str(err) or "insufficientFilePermissions" in str( + err + ): + if not self.alt_auth and self.use_sa: + self.alt_auth = True + self.use_sa = False + LOGGER.error("File not found. Trying with token.pickle...") + return self.deletefile(link, user_id) + err = "File not found or insufficientFilePermissions!" + LOGGER.error(f"Delete Result: {err}") + msg = str(err) + return msg diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/download.py b/bot/helper/mirror_leech_utils/gdrive_utils/download.py new file mode 100644 index 0000000000000000000000000000000000000000..4046a43832b74421577ae5947b08cc5a7fd5924d --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/download.py @@ -0,0 +1,177 @@ +from googleapiclient.errors import HttpError +from googleapiclient.http import MediaIoBaseDownload +from io import FileIO +from logging import getLogger +from os import makedirs, path as ospath +from tenacity import ( + retry, + wait_exponential, + stop_after_attempt, + retry_if_exception_type, + RetryError, +) + +from ...ext_utils.bot_utils import async_to_sync +from ...ext_utils.bot_utils import SetInterval +from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveDownload(GoogleDriveHelper): + def __init__(self, listener, path): + self.listener = listener + self._updater = None + self._path = path + super().__init__() + self.is_downloading = True + + def download(self): + file_id = self.get_id_from_url(self.listener.link, self.listener.user_id) + self.service = self.authorize() + self._updater = SetInterval(self.update_interval, self.progress) + try: + meta = self.get_file_metadata(file_id) + if meta.get("mimeType") == self.G_DRIVE_DIR_MIME_TYPE: + self._download_folder(file_id, self._path, self.listener.name) + else: + makedirs(self._path, exist_ok=True) + self._download_file( + file_id, self._path, self.listener.name, meta.get("mimeType") + ) + 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 "downloadQuotaExceeded" in err: + err = "Download Quota Exceeded." + elif "File not found" in err: + if not self.alt_auth and self.use_sa: + self.alt_auth = True + self.use_sa = False + LOGGER.error("File not found. Trying with token.pickle...") + self._updater.cancel() + return self.download() + err = "File not found!" + async_to_sync(self.listener.on_download_error, err) + self.listener.is_cancelled = True + finally: + self._updater.cancel() + if self.listener.is_cancelled: + return + async_to_sync(self.listener.on_download_complete) + return + + def _download_folder(self, folder_id, path, folder_name): + folder_name = folder_name.replace("/", "") + if not ospath.exists(f"{path}/{folder_name}"): + makedirs(f"{path}/{folder_name}") + path += f"/{folder_name}" + result = self.get_files_by_folder_id(folder_id) + if len(result) == 0: + return + result = sorted(result, key=lambda k: k["name"]) + for item in result: + file_id = item["id"] + filename = item["name"] + shortcut_details = item.get("shortcutDetails") + if shortcut_details is not None: + file_id = shortcut_details["targetId"] + mime_type = shortcut_details["targetMimeType"] + else: + mime_type = item.get("mimeType") + if mime_type == self.G_DRIVE_DIR_MIME_TYPE: + self._download_folder(file_id, path, filename) + elif ospath.isfile(f"{path}{filename}"): + continue + elif ( + self.listener.included_extensions + and not filename.strip() + .lower() + .endswith(tuple(self.listener.included_extensions)) + ): + continue + elif ( + not self.listener.included_extensions + and filename.strip() + .lower() + .endswith(tuple(self.listener.excluded_extensions)) + ): + continue + else: + self._download_file(file_id, path, filename, mime_type) + if self.listener.is_cancelled: + break + + @retry( + wait=wait_exponential(multiplier=2, min=3, max=6), + stop=stop_after_attempt(3), + retry=retry_if_exception_type(Exception), + ) + def _download_file(self, file_id, path, filename, mime_type, export=False): + if export: + request = self.service.files().export_media( + fileId=file_id, mimeType="application/pdf" + ) + else: + request = self.service.files().get_media( + fileId=file_id, supportsAllDrives=True, acknowledgeAbuse=True + ) + filename = filename.replace("/", "") + if export: + filename = f"{filename}.pdf" + if len(filename.encode()) > 255: + ext = ospath.splitext(filename)[1] + filename = f"{filename[:245]}{ext}" + + if self.listener.name.strip().endswith(ext): + self.listener.name = filename + if self.listener.is_cancelled: + return + fh = FileIO(f"{path}/{filename}", "wb") + downloader = MediaIoBaseDownload(fh, request, chunksize=100 * 1024 * 1024) + done = False + retries = 0 + while not done: + if self.listener.is_cancelled: + fh.close() + break + try: + self.status, done = downloader.next_chunk() + except HttpError as err: + LOGGER.error(err) + if err.resp.status in [500, 502, 503, 504, 429] and retries < 10: + retries += 1 + continue + if err.resp.get("content-type", "").startswith("application/json"): + reason = ( + eval(err.content).get("error").get("errors")[0].get("reason") + ) + if "fileNotDownloadable" in reason and "document" in mime_type: + return self._download_file( + file_id, path, filename, mime_type, True + ) + if reason not in [ + "downloadQuotaExceeded", + "dailyLimitExceeded", + ]: + raise err + if self.use_sa: + if self.sa_count >= self.sa_number: + LOGGER.info( + f"Reached maximum number of service accounts switching, which is {self.sa_count}" + ) + raise err + else: + if self.listener.is_cancelled: + return + self.switch_service_account() + LOGGER.info(f"Got: {reason}, Trying Again...") + return self._download_file( + file_id, path, filename, mime_type + ) + else: + LOGGER.error(f"Got: {reason}") + raise err + self.file_processed_bytes = 0 diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/helper.py b/bot/helper/mirror_leech_utils/gdrive_utils/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8eb528e18bfb159183c554c5308b850d0d9c2f --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/helper.py @@ -0,0 +1,256 @@ +from google.oauth2 import service_account +from googleapiclient.discovery import build +from google_auth_httplib2 import AuthorizedHttp +from googleapiclient.http import build_http +from logging import getLogger, ERROR +from os import path as ospath, listdir +from pickle import load as pload +from random import randrange +from re import search as re_search +from urllib.parse import parse_qs, urlparse +from tenacity import ( + retry, + wait_exponential, + stop_after_attempt, + retry_if_exception_type, +) + +from ....core.config_manager import Config +from ...ext_utils.links_utils import is_gdrive_id + +LOGGER = getLogger(__name__) +getLogger("googleapiclient.discovery").setLevel(ERROR) + + +class GoogleDriveHelper: + def __init__(self): + self._OAUTH_SCOPE = ["https://www.googleapis.com/auth/drive"] + self.token_path = "token.pickle" + 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.is_uploading = False + self.is_downloading = False + self.is_cloning = False + self.sa_index = 0 + self.sa_count = 1 + self.sa_number = 100 + self.alt_auth = False + self.service = None + self.total_files = 0 + self.total_folders = 0 + self.file_processed_bytes = 0 + self.proc_bytes = 0 + self.total_time = 0 + self.status = None + self.update_interval = 3 + self.use_sa = Config.USE_SERVICE_ACCOUNTS + + @property + def speed(self): + try: + return self.proc_bytes / self.total_time + except: + return 0 + + @property + def processed_bytes(self): + return self.proc_bytes + + async 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.proc_bytes += chunk_size + self.total_time += self.update_interval + + def authorize(self): + credentials = None + if self.use_sa: + json_files = listdir("accounts") + self.sa_number = len(json_files) + self.sa_index = randrange(self.sa_number) + LOGGER.info(f"Authorizing with {json_files[self.sa_index]} service account") + credentials = service_account.Credentials.from_service_account_file( + f"accounts/{json_files[self.sa_index]}", scopes=self._OAUTH_SCOPE + ) + elif ospath.exists(self.token_path): + LOGGER.info(f"Authorize with {self.token_path}") + with open(self.token_path, "rb") as f: + credentials = pload(f) + else: + LOGGER.error("token.pickle not found!") + authorized_http = AuthorizedHttp(credentials, http=build_http()) + authorized_http.http.disable_ssl_certificate_validation = True + return build("drive", "v3", http=authorized_http, cache_discovery=False) + + def switch_service_account(self): + if self.sa_index == self.sa_number - 1: + self.sa_index = 0 + else: + self.sa_index += 1 + self.sa_count += 1 + LOGGER.info(f"Switching to {self.sa_index} index") + self.service = self.authorize() + + def get_id_from_url(self, link, user_id=""): + if user_id and link.startswith("mtp:"): + self.use_sa = False + self.token_path = f"tokens/{user_id}.pickle" + link = link.replace("mtp:", "", 1) + elif link.startswith("sa:"): + self.use_sa = True + link = link.replace("sa:", "", 1) + elif link.startswith("tp:"): + self.use_sa = False + link = link.replace("tp:", "", 1) + if is_gdrive_id(link): + return link + 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(Exception), + ) + def set_permission(self, file_id): + permissions = { + "role": "reader", + "type": "anyone", + "value": None, + "withLink": True, + } + return ( + self.service.permissions() + .create(fileId=file_id, body=permissions, supportsAllDrives=True) + .execute() + ) + + @retry( + wait=wait_exponential(multiplier=2, min=3, max=6), + stop=stop_after_attempt(3), + retry=retry_if_exception_type(Exception), + ) + def get_file_metadata(self, file_id): + return ( + self.service.files() + .get( + fileId=file_id, + supportsAllDrives=True, + 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(Exception), + ) + def get_files_by_folder_id(self, folder_id, item_type=""): + page_token = None + files = [] + if not item_type: + q = f"'{folder_id}' in parents and trashed = false" + elif item_type == "folders": + q = f"'{folder_id}' in parents and mimeType = '{self.G_DRIVE_DIR_MIME_TYPE}' and trashed = false" + else: + q = f"'{folder_id}' in parents and mimeType != '{self.G_DRIVE_DIR_MIME_TYPE}' and trashed = false" + while True: + response = ( + self.service.files() + .list( + supportsAllDrives=True, + includeItemsFromAllDrives=True, + q=q, + 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 + + @retry( + wait=wait_exponential(multiplier=2, min=3, max=6), + stop=stop_after_attempt(3), + retry=retry_if_exception_type(Exception), + ) + def create_directory(self, directory_name, dest_id): + file_metadata = { + "name": directory_name, + "description": "Uploaded by Mirror-leech-telegram-bot", + "mimeType": self.G_DRIVE_DIR_MIME_TYPE, + } + if dest_id is not None: + file_metadata["parents"] = [dest_id] + file = ( + self.service.files() + .create(body=file_metadata, supportsAllDrives=True) + .execute() + ) + file_id = file.get("id") + if not Config.IS_TEAM_DRIVE: + self.set_permission(file_id) + LOGGER.info(f'Created G-Drive Folder:\nName: {file.get("name")}\nID: {file_id}') + return file_id + + 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 + """ + + async def cancel_task(self): + self.listener.is_cancelled = True + if self.is_downloading: + LOGGER.info(f"Cancelling Download: {self.listener.name}") + await self.listener.on_download_error("Stopped by user!") + elif self.is_cloning: + LOGGER.info(f"Cancelling Clone: {self.listener.name}") + await self.listener.on_upload_error( + "your clone has been stopped and cloned data has been deleted!" + ) + elif self.is_uploading: + LOGGER.info(f"Cancelling Upload: {self.listener.name}") + await self.listener.on_upload_error( + "your upload has been stopped and uploaded data has been deleted!" + ) diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/list.py b/bot/helper/mirror_leech_utils/gdrive_utils/list.py new file mode 100644 index 0000000000000000000000000000000000000000..109629f6597c55f2a4df9d22e5a325058c56aa21 --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/list.py @@ -0,0 +1,375 @@ +from aiofiles.os import path as aiopath +from asyncio import wait_for, Event, gather +from functools import partial +from logging import getLogger +from natsort import natsorted +from pyrogram.filters import regex, user +from pyrogram.handlers import CallbackQueryHandler +from tenacity import RetryError +from time import time + +from ....core.config_manager import Config +from ...ext_utils.bot_utils import update_user_ldata, new_task +from ...ext_utils.db_handler import database +from ...ext_utils.status_utils import get_readable_file_size, get_readable_time +from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper +from ...telegram_helper.button_build import ButtonMaker +from ...telegram_helper.message_utils import ( + send_message, + edit_message, + delete_message, +) + +LOGGER = getLogger(__name__) + +LIST_LIMIT = 6 + + +@new_task +async def id_updates(_, query, obj): + await query.answer() + message = query.message + data = query.data.split() + if data[1] == "cancel": + obj.id = "Task has been cancelled!" + obj.listener.is_cancelled = True + obj.event.set() + await delete_message(message) + return + if obj.query_proc: + return + obj.query_proc = True + if data[1] == "pre": + obj.iter_start -= LIST_LIMIT * obj.page_step + await obj.get_items_buttons() + elif data[1] == "nex": + obj.iter_start += LIST_LIMIT * obj.page_step + await obj.get_items_buttons() + elif data[1] == "back": + if data[2] == "dr": + await obj.choose_token() + else: + await obj.get_pevious_id() + elif data[1] == "dr": + index = int(data[2]) + i = obj.drives[index] + obj.id = i["id"] + obj.parents = [{"id": i["id"], "name": i["name"]}] + await obj.get_items() + elif data[1] == "pa": + index = int(data[3]) + i = obj.items_list[index] + obj.id = i["id"] + if data[2] == "fo": + obj.parents.append({"id": i["id"], "name": i["name"]}) + await obj.get_items() + else: + await delete_message(message) + obj.event.set() + elif data[1] == "ps": + if obj.page_step == int(data[2]): + obj.query_proc = False + return + obj.page_step = int(data[2]) + await obj.get_items_buttons() + elif data[1] == "root": + obj.id = obj.parents[0]["id"] + obj.parents = [obj.parents[0]] + await obj.get_items() + elif data[1] == "itype": + obj.item_type = data[2] + await obj.get_items() + elif data[1] == "cur": + await delete_message(message) + obj.event.set() + elif data[1] == "def": + if obj.token_path != obj.user_token_path: + id_ = f"sa:{obj.id}" if obj.use_sa else f"tp:{obj.id}" + else: + id_ = f"mtp:{obj.id}" + if id_ != obj.listener.user_dict.get("GDRIVE_ID"): + update_user_ldata(obj.listener.user_id, "GDRIVE_ID", id_) + await obj.get_items_buttons() + if Config.DATABASE_URL: + await database.update_user_data(obj.listener.user_id) + elif data[1] == "owner": + obj.token_path = "token.pickle" + obj.use_sa = False + obj.id = "" + obj.parents = [] + await obj.list_drives() + elif data[1] == "user": + obj.token_path = obj.user_token_path + obj.use_sa = False + obj.id = "" + obj.parents = [] + await obj.list_drives() + elif data[1] == "sa": + obj.token_path = "accounts" + obj.use_sa = True + obj.id = "" + obj.parents = [] + await obj.list_drives() + obj.query_proc = False + + +class GoogleDriveList(GoogleDriveHelper): + def __init__(self, listener): + self.listener = listener + self._token_user = False + self._token_owner = False + self._sa_owner = False + self._reply_to = None + self._time = time() + self._timeout = 240 + self.drives = [] + self.query_proc = False + self.item_type = "folders" + self.event = Event() + self.user_token_path = f"tokens/{self.listener.user_id}.pickle" + self.id = "" + self.parents = [] + self.list_status = "" + self.items_list = [] + self.iter_start = 0 + self.page_step = 1 + super().__init__() + + async def _event_handler(self): + pfunc = partial(id_updates, obj=self) + handler = self.listener.client.add_handler( + CallbackQueryHandler( + pfunc, filters=regex("^gdq") & user(self.listener.user_id) + ), + group=-1, + ) + try: + await wait_for(self.event.wait(), timeout=self._timeout) + except: + self.id = "Timed Out. Task has been cancelled!" + self.listener.is_cancelled = True + self.event.set() + finally: + self.listener.client.remove_handler(*handler) + + async def _send_list_message(self, msg, button): + if not self.listener.is_cancelled: + if self._reply_to is None: + self._reply_to = await send_message(self.listener.message, msg, button) + else: + await edit_message(self._reply_to, msg, button) + + async def get_items_buttons(self): + items_no = len(self.items_list) + pages = (items_no + LIST_LIMIT - 1) // LIST_LIMIT + if items_no <= self.iter_start: + self.iter_start = 0 + elif self.iter_start < 0 or self.iter_start > items_no: + self.iter_start = LIST_LIMIT * (pages - 1) + page = (self.iter_start / LIST_LIMIT) + 1 if self.iter_start != 0 else 1 + buttons = ButtonMaker() + for index, item in enumerate( + self.items_list[self.iter_start : LIST_LIMIT + self.iter_start] + ): + orig_index = index + self.iter_start + if item["mimeType"] == self.G_DRIVE_DIR_MIME_TYPE: + ptype = "fo" + name = item["name"] + else: + ptype = "fi" + name = f"[{get_readable_file_size(float(item['size']))}] {item['name']}" + buttons.data_button(name, f"gdq pa {ptype} {orig_index}") + if items_no > LIST_LIMIT: + for i in [1, 2, 4, 6, 10, 30, 50, 100]: + buttons.data_button(i, f"gdq ps {i}", position="header") + buttons.data_button("Previous", "gdq pre", position="footer") + buttons.data_button("Next", "gdq nex", position="footer") + if self.list_status == "gdd": + if self.item_type == "folders": + buttons.data_button("Files", "gdq itype files", position="footer") + else: + buttons.data_button("Folders", "gdq itype folders", position="footer") + if self.list_status == "gdu" or len(self.items_list) > 0: + buttons.data_button("Choose Current Path", "gdq cur", position="footer") + if self.list_status == "gdu": + buttons.data_button("Set as Default Path", "gdq def", position="footer") + if ( + len(self.parents) > 1 + and len(self.drives) > 1 + or self._token_user + and self._token_owner + ): + buttons.data_button("Back", "gdq back pa", position="footer") + if len(self.parents) > 1: + buttons.data_button("Back To Root", "gdq root", position="footer") + buttons.data_button("Cancel", "gdq cancel", position="footer") + button = buttons.build_menu(f_cols=2) + msg = "Choose Path:" + ( + "\nTransfer Type: Download" + if self.list_status == "gdd" + else "\nTransfer Type: Upload" + ) + if self.list_status == "gdu": + default_id = self.listener.user_dict.get("GDRIVE_ID") or Config.GDRIVE_ID + msg += f"\nDefault Gdrive ID: {default_id}" if default_id else "" + msg += f"\n\nItems: {items_no}" + if items_no > LIST_LIMIT: + msg += f" | Page: {int(page)}/{pages} | Page Step: {self.page_step}" + msg += f"\n\nItem Type: {self.item_type}\nToken Path: {self.token_path}" + msg += f"\n\nCurrent ID: {self.id}" + msg += f"\nCurrent Path: {('/').join(i['name'] for i in self.parents)}" + msg += f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await self._send_list_message(msg, button) + + async def get_items(self, itype=""): + if self.list_status == "gdu": + self.item_type = "folders" + elif itype: + self.item_type = itype + try: + files = self.get_files_by_folder_id(self.id, self.item_type) + if self.listener.is_cancelled: + return + except Exception as err: + if isinstance(err, RetryError): + LOGGER.info(f"Total Attempts: {err.last_attempt.attempt_number}") + err = err.last_attempt.exception() + self.id = str(err).replace(">", "").replace("<", "") + self.event.set() + return + if len(files) == 0 and itype != self.item_type and self.list_status == "gdd": + itype = "folders" if self.item_type == "files" else "files" + self.item_type = itype + await self.get_items(itype) + else: + self.items_list = natsorted(files) + self.iter_start = 0 + await self.get_items_buttons() + + async def list_drives(self): + self.service = self.authorize() + try: + result = self.service.drives().list(pageSize="100").execute() + except Exception as e: + self.id = str(e) + self.event.set() + return + drives = result["drives"] + if len(drives) == 0 and not self.use_sa: + self.drives = [{"id": "root", "name": "root"}] + self.parents = [{"id": "root", "name": "root"}] + self.id = "root" + await self.get_items() + elif len(drives) == 0: + msg = "Service accounts Doesn't have access to any drive!" + buttons = ButtonMaker() + if self._token_user and self._token_owner: + buttons.data_button("Back", "gdq back dr", position="footer") + buttons.data_button("Cancel", "gdq cancel", position="footer") + button = buttons.build_menu(2) + await self._send_list_message(msg, button) + elif self.use_sa and len(drives) == 1: + self.id = drives[0]["id"] + self.drives = [{"id": self.id, "name": drives[0]["name"]}] + self.parents = [{"id": self.id, "name": drives[0]["name"]}] + await self.get_items() + else: + msg = "Choose Drive:" + ( + "\nTransfer Type: Download" + if self.list_status == "gdd" + else "\nTransfer Type: Upload" + ) + msg += f"\nToken Path: {self.token_path}" + msg += ( + f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + ) + buttons = ButtonMaker() + self.drives.clear() + self.parents.clear() + if not self.use_sa: + buttons.data_button("root", "gdq dr 0") + self.drives = [{"id": "root", "name": "root"}] + for index, item in enumerate(drives, start=1): + self.drives.append({"id": item["id"], "name": item["name"]}) + buttons.data_button(item["name"], f"gdq dr {index}") + if self._token_user and self._token_owner: + buttons.data_button("Back", "gdq back dr", position="footer") + buttons.data_button("Cancel", "gdq cancel", position="footer") + button = buttons.build_menu(2) + await self._send_list_message(msg, button) + + async def choose_token(self): + if ( + self._token_user + and self._token_owner + or self._sa_owner + and self._token_owner + or self._sa_owner + and self._token_user + ): + msg = "Choose Token:" + ( + "\nTransfer Type: Download" + if self.list_status == "gdd" + else "\nTransfer Type: Upload" + ) + msg += ( + f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + ) + buttons = ButtonMaker() + if self._token_owner: + buttons.data_button("Owner Token", "gdq owner") + if self._sa_owner: + buttons.data_button("Service Accounts", "gdq sa") + if self._token_user: + buttons.data_button("My Token", "gdq user") + buttons.data_button("Cancel", "gdq cancel") + button = buttons.build_menu(2) + await self._send_list_message(msg, button) + else: + if self._token_owner: + self.token_path = "token.pickle" + self.use_sa = False + elif self._token_user: + self.token_path = self.user_token_path + self.use_sa = False + else: + self.token_path = "accounts" + self.use_sa = True + await self.list_drives() + + async def get_pevious_id(self): + if self.parents: + self.parents.pop() + if self.parents: + self.id = self.parents[-1]["id"] + await self.get_items() + else: + await self.list_drives() + else: + await self.list_drives() + + async def get_target_id(self, status, token_path=None): + self.list_status = status + if token_path is None: + self._token_user, self._token_owner, self._sa_owner = await gather( + aiopath.exists(self.user_token_path), + aiopath.exists("token.pickle"), + aiopath.exists("accounts"), + ) + if not self._token_owner and not self._token_user and not self._sa_owner: + self.event.set() + return "token.pickle or service accounts are not Exists!" + await self.choose_token() + else: + self.token_path = token_path + self.use_sa = self.token_path == "accounts" + await self.list_drives() + await self._event_handler() + if self._reply_to: + await delete_message(self._reply_to) + if not self.listener.is_cancelled: + if self.token_path == self.user_token_path: + return f"mtp:{self.id}" + else: + return f"sa:{self.id}" if self.use_sa else f"tp:{self.id}" + return self.id diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/search.py b/bot/helper/mirror_leech_utils/gdrive_utils/search.py new file mode 100644 index 0000000000000000000000000000000000000000..3e41bec1c66c2d88b00a71e0ca987fe45b3e5aea --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/search.py @@ -0,0 +1,183 @@ +from logging import getLogger + +from .... import drives_names, drives_ids, index_urls, user_data +from ....helper.ext_utils.status_utils import get_readable_file_size +from ....helper.mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveSearch(GoogleDriveHelper): + + def __init__(self, stop_dup=False, no_multi=False, is_recursive=True, item_type=""): + super().__init__() + self._stop_dup = stop_dup + self._no_multi = no_multi + self._is_recursive = is_recursive + self._item_type = item_type + + def _drive_query(self, dir_id, file_name, is_recursive): + try: + if is_recursive: + if self._stop_dup: + query = f"name = '{file_name}' and " + else: + file_name = file_name.split() + query = "".join( + f"name contains '{name}' and " + for name in file_name + if name != "" + ) + if self._item_type == "files": + query += f"mimeType != '{self.G_DRIVE_DIR_MIME_TYPE}' and " + elif self._item_type == "folders": + query += f"mimeType = '{self.G_DRIVE_DIR_MIME_TYPE}' and " + query += "trashed = false" + if dir_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( + supportsAllDrives=True, + includeItemsFromAllDrives=True, + driveId=dir_id, + q=query, + spaces="drive", + pageSize=150, + fields="files(id, name, mimeType, size, teamDriveId, parents)", + corpora="drive", + orderBy="folder, name asc", + ) + .execute() + ) + else: + if self._stop_dup: + query = f"'{dir_id}' in parents and name = '{file_name}' and " + else: + query = f"'{dir_id}' in parents and " + file_name = file_name.split() + for name in file_name: + if name != "": + query += f"name contains '{name}' and " + if self._item_type == "files": + query += f"mimeType != '{self.G_DRIVE_DIR_MIME_TYPE}' and " + elif self._item_type == "folders": + query += f"mimeType = '{self.G_DRIVE_DIR_MIME_TYPE}' and " + query += "trashed = false" + return ( + self.service.files() + .list( + supportsAllDrives=True, + includeItemsFromAllDrives=True, + q=query, + spaces="drive", + pageSize=150, + 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, file_name, target_id="", user_id=""): + msg = "" + file_name = self.escapes(str(file_name)) + contents_no = 0 + telegraph_content = [] + Title = False + + if target_id.startswith("mtp:"): + drives = self.get_user_drive(target_id, user_id) + elif target_id: + drives = [ + ( + "From Owner", + target_id.replace("tp:", "", 1), + index_urls[0] if index_urls else "", + ) + ] + else: + drives = zip(drives_names, drives_ids, index_urls) + if ( + target_id.startswith("mtp:") + or (not target_id.startswith("mtp:") and len(drives_ids) > 1) + or target_id.startswith("tp:") + ): + self.use_sa = False + + self.service = self.authorize() + + for drive_name, dir_id, index_url in drives: + isRecur = ( + False if self._is_recursive and len(dir_id) > 23 else self._is_recursive + ) + response = self._drive_query(dir_id, file_name, isRecur) + if not response["files"]: + if self._no_multi: + break + else: + continue + if not Title: + msg += f"

Search Result For {file_name}

" + Title = True + if drive_name: + msg += f"╾────────────╼
{drive_name}
╾────────────╼
" + for file in response.get("files", []): + mime_type = file.get("mimeType") + if mime_type == self.G_DRIVE_DIR_MIME_TYPE: + furl = self.G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(file.get("id")) + msg += f"📁 {file.get('name')}
(folder)

" + msg += f"Drive Link" + if index_url: + url = f'{index_url}findpath?id={file.get("id")}' + msg += f' | Index Link' + elif mime_type == "application/vnd.google-apps.shortcut": + furl = self.G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(file.get("id")) + msg += ( + f"⁍{file.get('name')}" + f" (shortcut)" + ) + else: + furl = self.G_DRIVE_BASE_DOWNLOAD_URL.format(file.get("id")) + msg += f"📄 {file.get('name')}
({get_readable_file_size(int(file.get('size', 0)))})

" + msg += f"Drive Link" + if index_url: + url = f'{index_url}findpath?id={file.get("id")}' + msg += f' | Index Link' + if mime_type.startswith(("image", "video", "audio")): + urlv = f'{index_url}findpath?id={file.get("id")}&view=true' + msg += f' | View Link' + msg += "

" + contents_no += 1 + if len(msg.encode("utf-8")) > 39000: + telegraph_content.append(msg) + msg = "" + if self._no_multi: + break + + if msg != "": + telegraph_content.append(msg) + + return telegraph_content, contents_no + + def get_user_drive(self, target_id, user_id): + dest_id = target_id.replace("mtp:", "", 1) + self.token_path = f"tokens/{user_id}.pickle" + self.use_sa = False + user_dict = user_data.get(user_id, {}) + INDEX = user_dict["index_url"] if user_dict.get("index_url") else "" + return [("User Choice", dest_id, INDEX)] diff --git a/bot/helper/mirror_leech_utils/gdrive_utils/upload.py b/bot/helper/mirror_leech_utils/gdrive_utils/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..8d527c14e16551c25009869aff9a541672ff07b5 --- /dev/null +++ b/bot/helper/mirror_leech_utils/gdrive_utils/upload.py @@ -0,0 +1,225 @@ +from googleapiclient.errors import HttpError +from googleapiclient.http import MediaFileUpload +from logging import getLogger +from os import path as ospath, listdir, remove +from tenacity import ( + retry, + wait_exponential, + stop_after_attempt, + retry_if_exception_type, + RetryError, +) + +from .... import intervals +from ....core.config_manager import Config +from ...ext_utils.bot_utils import async_to_sync, SetInterval +from ...ext_utils.files_utils import get_mime_type +from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper + +LOGGER = getLogger(__name__) + + +class GoogleDriveUpload(GoogleDriveHelper): + def __init__(self, listener, path): + self.listener = listener + self._updater = None + self._path = path + self._is_errored = False + super().__init__() + self.is_uploading = True + + def user_setting(self): + if self.listener.up_dest.startswith("mtp:"): + self.token_path = f"tokens/{self.listener.user_id}.pickle" + self.listener.up_dest = self.listener.up_dest.replace("mtp:", "", 1) + self.use_sa = False + elif self.listener.up_dest.startswith("tp:"): + self.listener.up_dest = self.listener.up_dest.replace("tp:", "", 1) + self.use_sa = False + elif self.listener.up_dest.startswith("sa:"): + self.listener.up_dest = self.listener.up_dest.replace("sa:", "", 1) + self.use_sa = True + + def upload(self): + self.user_setting() + self.service = self.authorize() + LOGGER.info(f"Uploading: {self._path}") + self._updater = SetInterval(self.update_interval, self.progress) + try: + if ospath.isfile(self._path): + mime_type = get_mime_type(self._path) + link = self._upload_file( + self._path, + self.listener.name, + mime_type, + self.listener.up_dest, + in_dir=False, + ) + if self.listener.is_cancelled: + return + if link is None: + raise ValueError("Upload has been manually cancelled") + LOGGER.info(f"Uploaded To G-Drive: {self._path}") + else: + mime_type = "Folder" + dir_id = self.create_directory( + ospath.basename(ospath.abspath(self.listener.name)), + self.listener.up_dest, + ) + result = self._upload_dir(self._path, dir_id) + if result is None: + raise ValueError("Upload has been manually cancelled!") + link = self.G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id) + if self.listener.is_cancelled: + return + LOGGER.info(f"Uploaded To G-Drive: {self.listener.name}") + 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("<", "") + LOGGER.error(err) + async_to_sync(self.listener.on_upload_error, err) + self._is_errored = True + finally: + self._updater.cancel() + if self.listener.is_cancelled and not self._is_errored: + if mime_type == "Folder" and dir_id: + LOGGER.info("Deleting uploaded data from Drive...") + self.service.files().delete( + fileId=dir_id, supportsAllDrives=True + ).execute() + return + elif self._is_errored: + return + async_to_sync( + self.listener.on_upload_complete, + link, + self.total_files, + self.total_folders, + mime_type, + dir_id=self.get_id_from_url(link), + ) + return + + def _upload_dir(self, input_directory, dest_id): + list_dirs = listdir(input_directory) + if len(list_dirs) == 0: + return dest_id + new_id = None + for item in list_dirs: + current_file_name = ospath.join(input_directory, item) + if not ospath.exists(current_file_name): + if intervals["stopAll"]: + return + LOGGER.error(f"{current_file_name} not exists! Continue uploading!") + continue + if ospath.isdir(current_file_name): + current_dir_id = self.create_directory(item, dest_id) + new_id = self._upload_dir(current_file_name, current_dir_id) + self.total_folders += 1 + else: + mime_type = get_mime_type(current_file_name) + file_name = current_file_name.split("/")[-1] + self._upload_file(current_file_name, file_name, mime_type, dest_id) + self.total_files += 1 + new_id = dest_id + if self.listener.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(Exception), + ) + def _upload_file(self, file_path, file_name, mime_type, dest_id, in_dir=True): + file_metadata = { + "name": file_name, + "description": "Uploaded by Mirror-leech-telegram-bot", + "mimeType": mime_type, + } + if dest_id is not None: + file_metadata["parents"] = [dest_id] + + if ospath.getsize(file_path) == 0: + media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=False) + response = ( + self.service.files() + .create( + body=file_metadata, media_body=media_body, supportsAllDrives=True + ) + .execute() + ) + if not Config.IS_TEAM_DRIVE: + self.set_permission(response["id"]) + + drive_file = ( + self.service.files() + .get(fileId=response["id"], supportsAllDrives=True) + .execute() + ) + return self.G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get("id")) + media_body = MediaFileUpload( + file_path, mimetype=mime_type, resumable=True, chunksize=100 * 1024 * 1024 + ) + + drive_file = self.service.files().create( + body=file_metadata, media_body=media_body, supportsAllDrives=True + ) + response = None + retries = 0 + while response is None and not self.listener.is_cancelled: + try: + self.status, response = drive_file.next_chunk() + except HttpError as err: + if err.resp.status in [500, 502, 503, 504, 429] and retries < 10: + retries += 1 + continue + if err.resp.get("content-type", "").startswith("application/json"): + reason = ( + eval(err.content).get("error").get("errors")[0].get("reason") + ) + if reason not in [ + "userRateLimitExceeded", + "dailyLimitExceeded", + ]: + raise err + if self.use_sa: + if self.sa_count >= self.sa_number: + LOGGER.info( + f"Reached maximum number of service accounts switching, which is {self.sa_count}" + ) + raise err + else: + if self.listener.is_cancelled: + return + self.switch_service_account() + LOGGER.info(f"Got: {reason}, Trying Again...") + return self._upload_file( + file_path, + file_name, + mime_type, + dest_id, + in_dir, + ) + else: + LOGGER.error(f"Got: {reason}") + raise err + if self.listener.is_cancelled: + return + try: + remove(file_path) + except: + pass + self.file_processed_bytes = 0 + if not Config.IS_TEAM_DRIVE: + self.set_permission(response["id"]) + if not in_dir: + drive_file = ( + self.service.files() + .get(fileId=response["id"], supportsAllDrives=True) + .execute() + ) + return self.G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get("id")) + return diff --git a/bot/helper/mirror_leech_utils/rclone_utils/__init__.py b/bot/helper/mirror_leech_utils/rclone_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/mirror_leech_utils/rclone_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_leech_utils/rclone_utils/list.py b/bot/helper/mirror_leech_utils/rclone_utils/list.py new file mode 100644 index 0000000000000000000000000000000000000000..820cc43aa2b936a1ea073dff610cc871ba521c1d --- /dev/null +++ b/bot/helper/mirror_leech_utils/rclone_utils/list.py @@ -0,0 +1,377 @@ +from aiofiles import open as aiopen +from aiofiles.os import path as aiopath +from asyncio import wait_for, Event, gather +from configparser import RawConfigParser +from functools import partial +from json import loads +from pyrogram.filters import regex, user +from pyrogram.handlers import CallbackQueryHandler +from time import time + +from .... import LOGGER +from ....core.config_manager import Config +from ...ext_utils.bot_utils import cmd_exec, update_user_ldata, new_task +from ...ext_utils.db_handler import database +from ...ext_utils.status_utils import get_readable_file_size, get_readable_time +from ...telegram_helper.button_build import ButtonMaker +from ...telegram_helper.message_utils import ( + send_message, + edit_message, + delete_message, +) + +LIST_LIMIT = 6 + + +@new_task +async def path_updates(_, query, obj): + await query.answer() + message = query.message + data = query.data.split() + if data[1] == "cancel": + obj.remote = "Task has been cancelled!" + obj.path = "" + obj.listener.is_cancelled = True + obj.event.set() + await delete_message(message) + return + if obj.query_proc: + return + obj.query_proc = True + if data[1] == "pre": + obj.iter_start -= LIST_LIMIT * obj.page_step + await obj.get_path_buttons() + elif data[1] == "nex": + obj.iter_start += LIST_LIMIT * obj.page_step + await obj.get_path_buttons() + elif data[1] == "select": + obj.select = not obj.select + await obj.get_path_buttons() + elif data[1] == "back": + if data[2] == "re": + await obj.list_config() + else: + await obj.back_from_path() + elif data[1] == "re": + # some remotes has space + data = query.data.split(maxsplit=2) + obj.remote = data[2] + await obj.get_path() + elif data[1] == "clear": + obj.selected_pathes = set() + await obj.get_path_buttons() + elif data[1] == "ds": + obj.path = f"rclone_select_{time()}.txt" + async with aiopen(obj.path, "w") as txt_file: + for f in obj.selected_pathes: + await txt_file.write(f"{f}\n") + await delete_message(message) + obj.event.set() + elif data[1] == "pa": + index = int(data[3]) + if obj.select: + path = obj.path + ( + f"/{obj.path_list[index]['Path']}" + if obj.path + else obj.path_list[index]["Path"] + ) + if path in obj.selected_pathes: + obj.selected_pathes.remove(path) + else: + obj.selected_pathes.add(path) + await obj.get_path_buttons() + obj.query_proc = False + return + obj.path += ( + f"/{obj.path_list[index]['Path']}" + if obj.path + else obj.path_list[index]["Path"] + ) + if data[2] == "fo": + await obj.get_path() + else: + await delete_message(message) + obj.event.set() + elif data[1] == "ps": + if obj.page_step == int(data[2]): + obj.query_proc = False + return + obj.page_step = int(data[2]) + await obj.get_path_buttons() + elif data[1] == "root": + obj.path = "" + await obj.get_path() + elif data[1] == "itype": + obj.item_type = data[2] + await obj.get_path() + elif data[1] == "cur": + await delete_message(message) + obj.event.set() + elif data[1] == "def": + path = ( + f"{obj.remote}{obj.path}" + if obj.config_path == "rclone.conf" + else f"mrcc:{obj.remote}{obj.path}" + ) + if path != obj.listener.user_dict.get("RCLONE_PATH"): + update_user_ldata(obj.listener.user_id, "RCLONE_PATH", path) + await obj.get_path_buttons() + if Config.DATABASE_URL: + await database.update_user_data(obj.listener.user_id) + elif data[1] == "owner": + obj.config_path = "rclone.conf" + obj.path = "" + obj.remote = "" + await obj.list_remotes() + elif data[1] == "user": + obj.config_path = obj.user_rcc_path + obj.path = "" + obj.remote = "" + await obj.list_remotes() + obj.query_proc = False + + +class RcloneList: + def __init__(self, listener): + self._rc_user = False + self._rc_owner = False + self._sections = [] + self._reply_to = None + self._time = time() + self._timeout = 240 + self.listener = listener + self.remote = "" + self.query_proc = False + self.item_type = "--dirs-only" + self.event = Event() + self.user_rcc_path = f"rclone/{self.listener.user_id}.conf" + self.config_path = "" + self.path = "" + self.list_status = "" + self.path_list = [] + self.iter_start = 0 + self.page_step = 1 + self.select = False + self.selected_pathes = set() + + async def _event_handler(self): + pfunc = partial(path_updates, obj=self) + handler = self.listener.client.add_handler( + CallbackQueryHandler( + pfunc, filters=regex("^rcq") & user(self.listener.user_id) + ), + group=-1, + ) + try: + await wait_for(self.event.wait(), timeout=self._timeout) + except: + self.path = "" + self.remote = "Timed Out. Task has been cancelled!" + self.listener.is_cancelled = True + self.event.set() + finally: + self.listener.client.remove_handler(*handler) + + async def _send_list_message(self, msg, button): + if not self.listener.is_cancelled: + if self._reply_to is None: + self._reply_to = await send_message(self.listener.message, msg, button) + else: + await edit_message(self._reply_to, msg, button) + + async def get_path_buttons(self): + items_no = len(self.path_list) + pages = (items_no + LIST_LIMIT - 1) // LIST_LIMIT + if items_no <= self.iter_start: + self.iter_start = 0 + elif self.iter_start < 0 or self.iter_start > items_no: + self.iter_start = LIST_LIMIT * (pages - 1) + page = (self.iter_start / LIST_LIMIT) + 1 if self.iter_start != 0 else 1 + buttons = ButtonMaker() + for index, idict in enumerate( + self.path_list[self.iter_start : LIST_LIMIT + self.iter_start] + ): + orig_index = index + self.iter_start + name = idict["Path"] + if name in self.selected_pathes or any( + p.strip().endswith(f"/{name}") for p in self.selected_pathes + ): + name = f"✅ {name}" + if idict["IsDir"]: + ptype = "fo" + else: + ptype = "fi" + name = f"[{get_readable_file_size(idict['Size'])}] {name}" + buttons.data_button(name, f"rcq pa {ptype} {orig_index}") + if items_no > LIST_LIMIT: + for i in [1, 2, 4, 6, 10, 30, 50, 100]: + buttons.data_button(i, f"rcq ps {i}", position="header") + buttons.data_button("Previous", "rcq pre", position="footer") + buttons.data_button("Next", "rcq nex", position="footer") + if self.list_status == "rcd": + if self.item_type == "--dirs-only": + buttons.data_button( + "Files", "rcq itype --files-only", position="footer" + ) + else: + buttons.data_button( + "Folders", "rcq itype --dirs-only", position="footer" + ) + if self.list_status == "rcu" or len(self.path_list) > 0: + buttons.data_button("Choose Current Path", "rcq cur", position="footer") + if self.list_status == "rcd": + buttons.data_button( + f"Select: {'Enabled' if self.select else 'Disabled'}", + "rcq select", + position="footer", + ) + if len(self.selected_pathes) > 1: + buttons.data_button("Done With Selection", "rcq ds", position="footer") + buttons.data_button("Clear Selection", "rcq clear", position="footer") + if self.list_status == "rcu": + buttons.data_button("Set as Default Path", "rcq def", position="footer") + if self.path or len(self._sections) > 1 or self._rc_user and self._rc_owner: + buttons.data_button("Back", "rcq back pa", position="footer") + if self.path: + buttons.data_button("Back To Root", "rcq root", position="footer") + buttons.data_button("Cancel", "rcq cancel", position="footer") + button = buttons.build_menu(f_cols=2) + msg = "Choose Path:" + ( + "\nTransfer Type: Download" + if self.list_status == "rcd" + else "\nTransfer Type: Upload" + ) + if self.list_status == "rcu": + default_path = Config.RCLONE_PATH + msg += f"\nDefault Rclone Path: {default_path}" if default_path else "" + msg += f"\n\nItems: {items_no}" + if items_no > LIST_LIMIT: + msg += f" | Page: {int(page)}/{pages} | Page Step: {self.page_step}" + msg += f"\n\nItem Type: {self.item_type}\nConfig Path: {self.config_path}" + msg += f"\nCurrent Path: {self.remote}{self.path}" + msg += f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await self._send_list_message(msg, button) + + async def get_path(self, itype=""): + if self.list_status == "rcu": + self.item_type = "--dirs-only" + elif itype: + self.item_type = itype + cmd = [ + "rclone", + "lsjson", + self.item_type, + "--fast-list", + "--no-mimetype", + "--no-modtime", + "--config", + self.config_path, + f"{self.remote}{self.path}", + ] + if self.listener.is_cancelled: + return + res, err, code = await cmd_exec(cmd) + if code in [0, -9]: + result = loads(res) + if ( + len(result) == 0 + and itype != self.item_type + and self.list_status == "rcd" + ): + itype = ( + "--dirs-only" + if self.item_type == "--files-only" + else "--files-only" + ) + self.item_type = itype + await self.get_path(itype) + else: + self.path_list = sorted(result, key=lambda x: x["Path"]) + self.iter_start = 0 + await self.get_path_buttons() + else: + LOGGER.error( + f"While rclone listing. Path: {self.remote}{self.path}. Stderr: {err}" + ) + self.remote = err[:4000] + self.path = "" + self.event.set() + + async def list_remotes(self): + config = RawConfigParser() + async with aiopen(self.config_path, "r") as f: + contents = await f.read() + config.read_string(contents) + if config.has_section("combine"): + config.remove_section("combine") + self._sections = config.sections() + if len(self._sections) == 1: + self.remote = f"{self._sections[0]}:" + await self.get_path() + else: + msg = "Choose Rclone remote:" + ( + "\nTransfer Type: Download" + if self.list_status == "rcd" + else "\nTransfer Type: Upload" + ) + msg += f"\nConfig Path: {self.config_path}" + msg += ( + f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + ) + buttons = ButtonMaker() + for remote in self._sections: + buttons.data_button(remote, f"rcq re {remote}:") + if self._rc_user and self._rc_owner: + buttons.data_button("Back", "rcq back re", position="footer") + buttons.data_button("Cancel", "rcq cancel", position="footer") + button = buttons.build_menu(2) + await self._send_list_message(msg, button) + + async def list_config(self): + if self._rc_user and self._rc_owner: + msg = "Choose Rclone config:" + ( + "\nTransfer Type: Download" + if self.list_status == "rcd" + else "\nTransfer Type: Upload" + ) + msg += ( + f"\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + ) + buttons = ButtonMaker() + buttons.data_button("Owner Config", "rcq owner") + buttons.data_button("My Config", "rcq user") + buttons.data_button("Cancel", "rcq cancel") + button = buttons.build_menu(2) + await self._send_list_message(msg, button) + else: + self.config_path = "rclone.conf" if self._rc_owner else self.user_rcc_path + await self.list_remotes() + + async def back_from_path(self): + if self.path: + path = self.path.rsplit("/", 1) + self.path = path[0] if len(path) > 1 else "" + await self.get_path() + elif len(self._sections) > 1: + await self.list_remotes() + else: + await self.list_config() + + async def get_rclone_path(self, status, config_path=None): + self.list_status = status + if config_path is None: + self._rc_user, self._rc_owner = await gather( + aiopath.exists(self.user_rcc_path), aiopath.exists("rclone.conf") + ) + if not self._rc_owner and not self._rc_user: + self.event.set() + return "Rclone Config not Exists!" + await self.list_config() + else: + self.config_path = config_path + await self.list_remotes() + await self._event_handler() + await delete_message(self._reply_to) + if self.config_path != "rclone.conf" and not self.listener.is_cancelled: + return f"mrcc:{self.remote}{self.path}" + return f"{self.remote}{self.path}" diff --git a/bot/helper/mirror_leech_utils/rclone_utils/serve.py b/bot/helper/mirror_leech_utils/rclone_utils/serve.py new file mode 100644 index 0000000000000000000000000000000000000000..06440fbefc7b7369a0761175ef23bc7358e69ce6 --- /dev/null +++ b/bot/helper/mirror_leech_utils/rclone_utils/serve.py @@ -0,0 +1,60 @@ +from aiofiles import open as aiopen +from aiofiles.os import path as aiopath +from asyncio import create_subprocess_exec +from configparser import RawConfigParser + +from ....core.config_manager import Config + +RcloneServe = [] + + +async def rclone_serve_booter(): + if not Config.RCLONE_SERVE_URL or not await aiopath.exists("rclone.conf"): + if RcloneServe: + try: + RcloneServe[0].kill() + RcloneServe.clear() + except: + pass + return + config = RawConfigParser() + async with aiopen("rclone.conf", "r") as f: + contents = await f.read() + config.read_string(contents) + if not config.has_section("combine"): + upstreams = " ".join(f"{remote}={remote}:" for remote in config.sections()) + config.add_section("combine") + config.set("combine", "type", "combine") + config.set("combine", "upstreams", upstreams) + with open("rclone.conf", "w") as f: + config.write(f, space_around_delimiters=False) + if RcloneServe: + try: + RcloneServe[0].kill() + RcloneServe.clear() + except: + pass + cmd = [ + "rclone", + "serve", + "http", + "--config", + "rclone.conf", + "--no-modtime", + "combine:", + "--addr", + f":{Config.RCLONE_SERVE_PORT}", + "--vfs-cache-mode", + "full", + "--vfs-cache-max-age", + "1m0s", + "--buffer-size", + "64M", + "-v", + "--log-file", + "rlog.txt", + ] + if (user := Config.RCLONE_SERVE_USER) and (pswd := Config.RCLONE_SERVE_PASS): + cmd.extend(("--user", user, "--pass", pswd)) + rcs = await create_subprocess_exec(*cmd) + RcloneServe.append(rcs) diff --git a/bot/helper/mirror_leech_utils/rclone_utils/transfer.py b/bot/helper/mirror_leech_utils/rclone_utils/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..47f22d7a57e248bfe9ef6894fe6fcf39798eab85 --- /dev/null +++ b/bot/helper/mirror_leech_utils/rclone_utils/transfer.py @@ -0,0 +1,511 @@ +from aiofiles import open as aiopen +from aiofiles.os import path as aiopath, makedirs, listdir +from asyncio import create_subprocess_exec, gather, wait_for +from asyncio.subprocess import PIPE +from configparser import RawConfigParser +from json import loads +from logging import getLogger +from random import randrange +from re import findall as re_findall + +from ....core.config_manager import Config +from ...ext_utils.bot_utils import cmd_exec, sync_to_async +from ...ext_utils.files_utils import ( + get_mime_type, + count_files_and_folders, +) + +LOGGER = getLogger(__name__) + + +class RcloneTransferHelper: + def __init__(self, listener): + self._listener = listener + self._proc = None + self._transferred_size = "0 B" + self._eta = "-" + self._percentage = "0%" + self._speed = "0 B/s" + self._size = "0 B" + self._is_download = False + self._is_upload = False + self._sa_count = 1 + self._sa_index = 0 + self._sa_number = 0 + self._use_service_accounts = Config.USE_SERVICE_ACCOUNTS + + @property + def transferred_size(self): + return self._transferred_size + + @property + def percentage(self): + return self._percentage + + @property + def speed(self): + return self._speed + + @property + def eta(self): + return self._eta + + @property + def size(self): + return self._size + + async def _progress(self): + while not ( + self._proc.returncode is not None + or self._proc.stdout.at_eof() + or self._listener.is_cancelled + ): + try: + data = await wait_for(self._proc.stdout.readline(), 60) + except: + break + if not data: + break + data = data.decode().strip() + if data := re_findall( + r"Transferred:\s+([\d.]+\s*\w+)\s+/\s+([\d.]+\s*\w+),\s+([\d.]+%)\s*,\s+([\d.]+\s*\w+/s),\s+ETA\s+([\dwdhms]+)", + data, + ): + ( + self._transferred_size, + self._size, + self._percentage, + self._speed, + self._eta, + ) = data[0] + + def _switch_service_account(self): + if self._sa_index == self._sa_number - 1: + self._sa_index = 0 + else: + self._sa_index += 1 + self._sa_count += 1 + remote = f"sa{self._sa_index:03}" + LOGGER.info(f"Switching to {remote} remote") + return remote + + async def _create_rc_sa(self, remote, remote_opts): + sa_conf_dir = "rclone_sa" + sa_conf_file = f"{sa_conf_dir}/{remote}.conf" + if await aiopath.isfile(sa_conf_file): + return sa_conf_file + await makedirs(sa_conf_dir, exist_ok=True) + + if gd_id := remote_opts.get("team_drive"): + option = "team_drive" + elif gd_id := remote_opts.get("root_folder_id"): + option = "root_folder_id" + else: + self._use_service_accounts = False + return "rclone.conf" + + files = await listdir("accounts") + text = "".join( + f"[sa{i:03}]\ntype = drive\nscope = drive\nservice_account_file = accounts/{sa}\n{option} = {gd_id}\n\n" + for i, sa in enumerate(files) + ) + + async with aiopen(sa_conf_file, "w") as f: + await f.write(text) + return sa_conf_file + + async def _start_download(self, cmd, remote_type): + self._proc = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE) + await self._progress() + _, stderr = await self._proc.communicate() + return_code = self._proc.returncode + if self._listener.is_cancelled: + return + + if return_code == 0: + await self._listener.on_download_complete() + elif return_code != -9: + error = stderr.decode().strip() + if not error and remote_type == "drive" and self._use_service_accounts: + error = "Mostly your service accounts don't have access to this drive!" + LOGGER.error(error) + + if ( + self._sa_number != 0 + and remote_type == "drive" + and "RATE_LIMIT_EXCEEDED" in error + and self._use_service_accounts + ): + if self._sa_count < self._sa_number: + remote = self._switch_service_account() + cmd[6] = f"{remote}:{cmd[6].split(':', 1)[1]}" + if self._listener.is_cancelled: + return + return await self._start_download(cmd, remote_type) + else: + LOGGER.info( + f"Reached maximum number of service accounts switching, which is {self._sa_count}" + ) + + await self._listener.on_download_error(error[:4000]) + return + + async def download(self, remote, config_path, path): + self._is_download = True + try: + remote_opts = await self._get_remote_options(config_path, remote) + except Exception as err: + await self._listener.on_download_error(str(err)) + return + remote_type = remote_opts["type"] + + if ( + remote_type == "drive" + and self._use_service_accounts + and config_path == "rclone.conf" + and await aiopath.isdir("accounts") + and not remote_opts.get("service_account_file") + ): + config_path = await self._create_rc_sa(remote, remote_opts) + if config_path != "rclone.conf": + sa_files = await listdir("accounts") + self._sa_number = len(sa_files) + self._sa_index = randrange(self._sa_number) + remote = f"sa{self._sa_index:03}" + LOGGER.info(f"Download with service account {remote}") + + cmd = self._get_updated_command( + config_path, f"{remote}:{self._listener.link}", path, "copy" + ) + + if remote_type == "drive" and not self._listener.rc_flags: + cmd.extend( + ( + "--drive-acknowledge-abuse", + "--drive-chunk-size", + "128M", + "--tpslimit", + "1", + "--tpslimit-burst", + "1", + "--transfers", + "1", + ) + ) + + await self._start_download(cmd, remote_type) + + async def _get_gdrive_link(self, config_path, destination, mime_type): + epath = destination.rsplit("/", 1)[0] if mime_type == "Folder" else destination + cmd = [ + "rclone", + "lsjson", + "--fast-list", + "--no-mimetype", + "--no-modtime", + "--config", + config_path, + epath, + ] + res, err, code = await cmd_exec(cmd) + + if code == 0: + result = loads(res) + fid = next( + (r["ID"] for r in result if r["Path"] == self._listener.name), "err" + ) + link = ( + f"https://drive.google.com/drive/folders/{fid}" + if mime_type == "Folder" + else f"https://drive.google.com/uc?id={fid}&export=download" + ) + elif code != -9: + LOGGER.error( + f"while getting drive link. Path: {destination}. Stderr: {err}" + ) + link = "" + return link + + async def _start_upload(self, cmd, remote_type): + self._proc = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE) + await self._progress() + _, stderr = await self._proc.communicate() + return_code = self._proc.returncode + + if self._listener.is_cancelled: + return False + if return_code == -9: + return False + elif return_code == 0: + return True + else: + error = stderr.decode().strip() + LOGGER.error(error) + if ( + self._sa_number != 0 + and remote_type == "drive" + and "RATE_LIMIT_EXCEEDED" in error + and self._use_service_accounts + ): + if self._sa_count < self._sa_number: + remote = self._switch_service_account() + cmd[7] = f"{remote}:{cmd[7].split(':', 1)[1]}" + return ( + False + if self._listener.is_cancelled + else await self._start_upload(cmd, remote_type) + ) + else: + LOGGER.info( + f"Reached maximum number of service accounts switching, which is {self._sa_count}" + ) + await self._listener.on_upload_error(error[:4000]) + return False + + async def upload(self, path): + self._is_upload = True + rc_path = self._listener.up_dest + if rc_path.startswith("mrcc:"): + rc_path = rc_path.split("mrcc:", 1)[1] + oconfig_path = f"rclone/{self._listener.user_id}.conf" + else: + oconfig_path = "rclone.conf" + + oremote, rc_path = rc_path.split(":", 1) + + if await aiopath.isdir(path): + mime_type = "Folder" + folders, files = await count_files_and_folders(path) + rc_path += f"/{self._listener.name}" if rc_path else self._listener.name + else: + mime_type = await sync_to_async(get_mime_type, path) + folders = 0 + files = 1 + + try: + remote_opts = await self._get_remote_options(oconfig_path, oremote) + except Exception as err: + await self._listener.on_upload_error(str(err)) + return + remote_type = remote_opts["type"] + + fremote = oremote + fconfig_path = oconfig_path + if ( + remote_type == "drive" + and self._use_service_accounts + and fconfig_path == "rclone.conf" + and await aiopath.isdir("accounts") + and not remote_opts.get("service_account_file") + ): + fconfig_path = await self._create_rc_sa(oremote, remote_opts) + if fconfig_path != "rclone.conf": + sa_files = await listdir("accounts") + self._sa_number = len(sa_files) + self._sa_index = randrange(self._sa_number) + fremote = f"sa{self._sa_index:03}" + LOGGER.info(f"Upload with service account {fremote}") + + cmd = self._get_updated_command( + fconfig_path, path, f"{fremote}:{rc_path}", "move" + ) + if remote_type == "drive" and not self._listener.rc_flags: + cmd.extend( + ( + "--tpslimit", + "1", + "--tpslimit-burst", + "1", + "--transfers", + "1", + ) + ) + + result = await self._start_upload(cmd, remote_type) + if not result: + return + + if mime_type == "Folder": + destination = f"{oremote}:{rc_path}" + elif rc_path: + destination = f"{oremote}:{rc_path}/{self._listener.name}" + else: + destination = f"{oremote}:{self._listener.name}" + + if remote_type == "drive": + link = await self._get_gdrive_link(oconfig_path, destination, mime_type) + else: + cmd = [ + "rclone", + "link", + "--config", + oconfig_path, + destination, + ] + res, err, code = await cmd_exec(cmd) + + if code == 0: + link = res + elif code != -9: + LOGGER.error(f"while getting link. Path: {destination} | Stderr: {err}") + link = "" + if self._listener.is_cancelled: + return + LOGGER.info(f"Upload Done. Path: {destination}") + await self._listener.on_upload_complete( + link, files, folders, mime_type, destination + ) + return + + async def clone(self, config_path, src_remote, src_path, mime_type, method): + destination = self._listener.up_dest + dst_remote, dst_path = destination.split(":", 1) + + try: + src_remote_opts, dst_remote_opt = await gather( + self._get_remote_options(config_path, src_remote), + self._get_remote_options(config_path, dst_remote), + ) + except Exception as err: + await self._listener.on_upload_error(str(err)) + return None, None + + src_remote_type, dst_remote_type = ( + src_remote_opts["type"], + dst_remote_opt["type"], + ) + + cmd = self._get_updated_command( + config_path, f"{src_remote}:{src_path}", destination, method + ) + if not self._listener.rc_flags and src_remote_type == "drive": + cmd.extend( + ( + "--drive-acknowledge-abuse", + "--tpslimit", + "3", + "--tpslimit-burst", + "1", + "--transfers", + "3", + ) + ) + + self._proc = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE) + await self._progress() + _, stderr = await self._proc.communicate() + return_code = self._proc.returncode + + if self._listener.is_cancelled: + return None, None + + if return_code == -9: + return None, None + elif return_code == 0: + if mime_type != "Folder": + destination += ( + f"/{self._listener.name}" if dst_path else self._listener.name + ) + if dst_remote_type == "drive": + link = await self._get_gdrive_link(config_path, destination, mime_type) + return ( + (None, None) if self._listener.is_cancelled else (link, destination) + ) + else: + cmd = [ + "rclone", + "link", + "--config", + config_path, + destination, + ] + res, err, code = await cmd_exec(cmd) + + if self._listener.is_cancelled: + return None, None + + if code == 0: + return res, destination + elif code != -9: + LOGGER.error( + f"while getting link. Path: {destination} | Stderr: {err}" + ) + return None, destination + + else: + error = stderr.decode().strip() + LOGGER.error(error) + await self._listener.on_upload_error(error[:4000]) + return None, None + + def _get_updated_command( + self, + config_path, + source, + destination, + method, + ): + rclone_select = False + if source.split(":")[-1].startswith("rclone_select"): + source = f"{source.split(":")[0]}:" + rclone_select = True + cmd = [ + "rclone", + method, + "--fast-list", + "--config", + config_path, + "-P", + source, + destination, + "-L", + "--retries-sleep", + "3s", + "--ignore-case", + "--low-level-retries", + "1", + "-M", + ] + if rclone_select: + cmd.extend(("--files-from", self._listener.link)) + elif self._listener.included_extensions: + ext = "*.{" + ",".join(self._listener.included_extensions) + "}" + cmd.extend(("--include", ext)) + else: + ext = "*.{" + ",".join(self._listener.excluded_extensions) + "}" + cmd.extend(("--exclude", ext)) + if rcflags := self._listener.rc_flags: + rcflags = rcflags.split("|") + for flag in rcflags: + if ":" in flag: + key, value = map(str.strip, flag.split(":", 1)) + cmd.extend((key, value)) + elif len(flag) > 0: + cmd.append(flag.strip()) + return cmd + + @staticmethod + async def _get_remote_options(config_path, remote): + config = RawConfigParser() + async with aiopen(config_path, "r") as f: + contents = await f.read() + config.read_string(contents) + options = config.options(remote) + return {opt: config.get(remote, opt) for opt in options} + + async def cancel_task(self): + self._listener.is_cancelled = True + if self._proc is not None: + try: + self._proc.kill() + except: + pass + if self._is_download: + LOGGER.info(f"Cancelling Download: {self._listener.name}") + await self._listener.on_download_error("Stopped by user!") + elif self._is_upload: + LOGGER.info(f"Cancelling Upload: {self._listener.name}") + await self._listener.on_upload_error("your upload has been stopped!") + else: + LOGGER.info(f"Cancelling Clone: {self._listener.name}") + await self._listener.on_upload_error("your clone has been stopped!") diff --git a/bot/helper/mirror_leech_utils/status_utils/__init__.py b/bot/helper/mirror_leech_utils/status_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/mirror_leech_utils/status_utils/aria2_status.py b/bot/helper/mirror_leech_utils/status_utils/aria2_status.py new file mode 100644 index 0000000000000000000000000000000000000000..618eccec202394b2c15565de8ab8e0ac6863f042 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/aria2_status.py @@ -0,0 +1,132 @@ +from time import time + +from .... import LOGGER +from ....core.torrent_manager import TorrentManager, aria2_name +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_time, + get_readable_file_size, +) + + +async def get_download(gid, old_info=None): + try: + res = await TorrentManager.aria2.tellStatus(gid) + return res or old_info + except Exception as e: + LOGGER.error(f"{e}: Aria2c, Error while getting torrent info") + return old_info + + +class Aria2Status: + def __init__(self, listener, gid, seeding=False, queued=False): + self._gid = gid + self._download = {} + self.listener = listener + self.queued = queued + self.start_time = 0 + self.seeding = seeding + self.tool = "aria2" + + async def update(self): + self._download = await get_download(self._gid, self._download) + if self._download.get("followedBy", []): + self._gid = self._download["followedBy"][0] + self._download = await get_download(self._gid) + + def progress(self): + try: + return f"{round(int(self._download.get("completedLength", "0")) / int(self._download.get("totalLength", "0")) * 100, 2)}%" + except: + return "0%" + + def processed_bytes(self): + return get_readable_file_size(int(self._download.get("completedLength", "0"))) + + def speed(self): + return ( + f"{get_readable_file_size(int(self._download.get("downloadSpeed", "0")))}/s" + ) + + def name(self): + return aria2_name(self._download) + + def size(self): + return get_readable_file_size(int(self._download.get("totalLength", "0"))) + + def eta(self): + try: + return get_readable_time( + ( + int(self._download.get("totalLength", "0")) + - int(self._download.get("completedLength", "0")) + ) + / int(self._download.get("downloadSpeed", "0")) + ) + except: + return "-" + + async def status(self): + await self.update() + if self._download.get("status", "") == "waiting" or self.queued: + if self.seeding: + return MirrorStatus.STATUS_QUEUEUP + else: + return MirrorStatus.STATUS_QUEUEDL + elif self._download.get("status", "") == "paused": + return MirrorStatus.STATUS_PAUSED + elif self._download.get("seeder", "") == "true" and self.seeding: + return MirrorStatus.STATUS_SEED + else: + return MirrorStatus.STATUS_DOWNLOAD + + def seeders_num(self): + return self._download.get("numSeeders", 0) + + def leechers_num(self): + return self._download.get("connections", 0) + + def uploaded_bytes(self): + return get_readable_file_size(int(self._download.get("uploadLength", "0"))) + + def seed_speed(self): + return ( + f"{get_readable_file_size(int(self._download.get("uploadSpeed", "0")))}/s" + ) + + def ratio(self): + try: + return round( + int(self._download.get("uploadLength", "0")) + / int(self._download.get("completedLength", "0")), + 3, + ) + except: + return 0 + + def seeding_time(self): + return get_readable_time(time() - self.start_time) + + def task(self): + return self + + def gid(self): + return self._gid + + async def cancel_task(self): + self.listener.is_cancelled = True + await self.update() + await TorrentManager.aria2_remove(self._download) + if self._download.get("seeder", "") == "true" and self.seeding: + LOGGER.info(f"Cancelling Seed: {self.name()}") + await self.listener.on_upload_error( + f"Seeding stopped with Ratio: {self.ratio()} and Time: {self.seeding_time()}" + ) + else: + if self.queued: + LOGGER.info(f"Cancelling QueueDl: {self.name()}") + msg = "task have been removed from queue/download" + else: + LOGGER.info(f"Cancelling Download: {self.name()}") + msg = "Stopped by user!" + await self.listener.on_download_error(msg) diff --git a/bot/helper/mirror_leech_utils/status_utils/direct_status.py b/bot/helper/mirror_leech_utils/status_utils/direct_status.py new file mode 100644 index 0000000000000000000000000000000000000000..c04dcb8ddf5fe151c5939837640c6d1a88140f0f --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/direct_status.py @@ -0,0 +1,55 @@ +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +class DirectStatus: + def __init__(self, listener, obj, gid): + self._gid = gid + self._obj = obj + self.listener = listener + self.tool = "aria2" + + def gid(self): + return self._gid + + def progress_raw(self): + try: + return self._obj.processed_bytes / self.listener.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._obj.speed)}/s" + + def name(self): + return self.listener.name + + def size(self): + return get_readable_file_size(self.listener.size) + + def eta(self): + try: + seconds = (self.listener.size - self._obj.processed_bytes) / self._obj.speed + return get_readable_time(seconds) + except: + return "-" + + def status(self): + if ( + self._obj.download_task + and self._obj.download_task.get("status", "") == "waiting" + ): + return MirrorStatus.STATUS_QUEUEDL + return MirrorStatus.STATUS_DOWNLOAD + + def processed_bytes(self): + return get_readable_file_size(self._obj.processed_bytes) + + def task(self): + return self._obj diff --git a/bot/helper/mirror_leech_utils/status_utils/ffmpeg_status.py b/bot/helper/mirror_leech_utils/status_utils/ffmpeg_status.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce025ec0ae02c5a2c6d6ffc1a191c20c282e5f3 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/ffmpeg_status.py @@ -0,0 +1,62 @@ +from .... import LOGGER +from ...ext_utils.status_utils import ( + get_readable_file_size, + MirrorStatus, + get_readable_time, +) + + +class FFmpegStatus: + def __init__(self, listener, obj, gid, status=""): + self.listener = listener + self._obj = obj + self._gid = gid + self._cstatus = status + self.tool = "ffmpeg" + + def speed(self): + return f"{get_readable_file_size(self._obj.speed_raw)}/s" + + def processed_bytes(self): + return get_readable_file_size(self._obj.processed_bytes) + + def progress(self): + return f"{round(self._obj.progress_raw, 2)}%" + + def gid(self): + return self._gid + + def name(self): + return self.listener.name + + def size(self): + return get_readable_file_size(self.listener.size) + + def eta(self): + return get_readable_time(self._obj.eta_raw) if self._obj.eta_raw else "-" + + def status(self): + if self._cstatus == "Convert": + return MirrorStatus.STATUS_CONVERT + elif self._cstatus == "Split": + return MirrorStatus.STATUS_SPLIT + elif self._cstatus == "Sample Video": + return MirrorStatus.STATUS_SAMVID + else: + return MirrorStatus.STATUS_FFMPEG + + def task(self): + return self + + async def cancel_task(self): + LOGGER.info(f"Cancelling {self._cstatus}: {self.listener.name}") + self.listener.is_cancelled = True + if ( + self.listener.subproc is not None + and self.listener.subproc.returncode is None + ): + try: + self.listener.subproc.kill() + except: + pass + await self.listener.on_upload_error(f"{self._cstatus} stopped by user!") diff --git a/bot/helper/mirror_leech_utils/status_utils/gdrive_status.py b/bot/helper/mirror_leech_utils/status_utils/gdrive_status.py new file mode 100644 index 0000000000000000000000000000000000000000..c6ce731cfa1e6c39224311a657aa2ab9f87f9266 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/gdrive_status.py @@ -0,0 +1,57 @@ +from ....helper.ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +class GoogleDriveStatus: + def __init__(self, listener, obj, gid, status): + self.listener = listener + self._obj = obj + self._size = self.listener.size + self._gid = gid + self._status = status + self.tool = "gDriveApi" + + def processed_bytes(self): + return get_readable_file_size(self._obj.processed_bytes) + + def size(self): + return get_readable_file_size(self._size) + + def status(self): + if self._status == "up": + return MirrorStatus.STATUS_UPLOAD + elif self._status == "dl": + return MirrorStatus.STATUS_DOWNLOAD + else: + return MirrorStatus.STATUS_CLONE + + def name(self): + return self.listener.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(self): + return f"{get_readable_file_size(self._obj.speed)}/s" + + def eta(self): + try: + seconds = (self._size - self._obj.processed_bytes) / self._obj.speed + return get_readable_time(seconds) + except: + return "-" + + def task(self): + return self._obj diff --git a/bot/helper/mirror_leech_utils/status_utils/jdownloader_status.py b/bot/helper/mirror_leech_utils/status_utils/jdownloader_status.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b37fde17ab1b12ab3c22143d60dc9849b666c6 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/jdownloader_status.py @@ -0,0 +1,129 @@ +from time import time + +from .... import LOGGER, jd_listener_lock, jd_downloads +from ....core.jdownloader_booter import jdownloader +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +def _get_combined_info(result, old_info): + name = result[0].get("name") + hosts = result[0].get("hosts") + bytesLoaded = 0 + bytesTotal = 0 + speed = 0 + status = "" + for res in result: + if res.get("enabled"): + st = res.get("status", "") + if st and st.lower() != "finished": + status = st + bytesLoaded += res.get("bytesLoaded", 0) + bytesTotal += res.get("bytesTotal", 0) + speed += res.get("speed", 0) + try: + if not speed: + speed = (bytesLoaded - old_info.get("bytesLoaded", 0)) / ( + time() - old_info.get("last_update", 0) + ) + eta = (bytesTotal - bytesLoaded) / speed + except: + eta = 0 + return { + "name": name, + "status": status, + "speed": speed, + "eta": eta, + "hosts": hosts, + "bytesLoaded": bytesLoaded, + "bytesTotal": bytesTotal, + "last_update": time(), + } + + +async def get_download(gid, old_info): + try: + result = await jdownloader.device.downloads.query_packages( + [ + { + "bytesLoaded": True, + "bytesTotal": True, + "enabled": True, + "packageUUIDs": jd_downloads[gid]["ids"], + "maxResults": -1, + "running": True, + "speed": True, + "eta": True, + "status": True, + "hosts": True, + } + ] + ) + return _get_combined_info(result, old_info) if len(result) > 1 else result[0] + except: + return old_info + + +class JDownloaderStatus: + def __init__(self, listener, gid): + self.listener = listener + self._gid = gid + self._info = {} + self.tool = "jdownloader" + + async def _update(self): + self._info = await get_download(self._gid, self._info) + + def progress(self): + try: + return f"{round((self._info.get('bytesLoaded', 0) / self._info.get('bytesTotal', 0)) * 100, 2)}%" + except: + return "0%" + + def processed_bytes(self): + return get_readable_file_size(self._info.get("bytesLoaded", 0)) + + def speed(self): + return f"{get_readable_file_size(self._info.get('speed', 0))}/s" + + def name(self): + return ( + self._info.get("name").strip("/").split("/")[0] + if self._info.get("name") + else self.listener.name + ) + + def size(self): + return get_readable_file_size(self._info.get("bytesTotal", 0)) + + def eta(self): + return get_readable_time(eta) if (eta := self._info.get("eta", False)) else "-" + + async def status(self): + await self._update() + state = self._info.get("status", "jdlimit").capitalize() + if len(state) == 0: + if self._info.get("bytesLoaded", 0) == 0: + return MirrorStatus.STATUS_QUEUEDL + else: + return MirrorStatus.STATUS_DOWNLOAD + return MirrorStatus.STATUS_QUEUEDL if state == "Jdlimit" else state + + def task(self): + return self + + def gid(self): + return self._gid + + async def cancel_task(self): + self.listener.is_cancelled = True + LOGGER.info(f"Cancelling Download: {self.name()}") + await jdownloader.device.downloads.remove_links( + package_ids=jd_downloads[self._gid]["ids"] + ) + async with jd_listener_lock: + del jd_downloads[self._gid] + await self.listener.on_download_error("Cancelled by user!") diff --git a/bot/helper/mirror_leech_utils/status_utils/nzb_status.py b/bot/helper/mirror_leech_utils/status_utils/nzb_status.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9e6d700353fae0642f8b1708781d26a3e1b29a --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/nzb_status.py @@ -0,0 +1,141 @@ +from asyncio import gather + +from .... import LOGGER, sabnzbd_client, nzb_jobs, nzb_listener_lock +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, + time_to_seconds, +) + + +async def get_download(nzo_id, old_info=None): + if old_info is None: + old_info = {} + try: + queue = await sabnzbd_client.get_downloads(nzo_ids=nzo_id) + if res := queue["queue"]["slots"]: + slot = res[0] + if msg := slot["labels"]: + LOGGER.warning(" | ".join(msg)) + return slot + else: + history = await sabnzbd_client.get_history(nzo_ids=nzo_id) + if res := history["history"]["slots"]: + slot = res[0] + if slot["status"] == "Verifying": + percentage = slot["action_line"].split("Verifying: ")[-1].split("/") + percentage = round( + (int(float(percentage[0])) / int(float(percentage[1]))) * 100, 2 + ) + old_info["percentage"] = percentage + elif slot["status"] == "Repairing": + action = slot["action_line"].split("Repairing: ")[-1].split() + percentage = action[0].strip("%") + eta = action[2] + old_info["percentage"] = percentage + old_info["timeleft"] = eta + elif slot["status"] == "Extracting": + if "Unpacking" in slot["action_line"]: + action = slot["action_line"].split("Unpacking: ")[-1].split() + else: + action = ( + slot["action_line"].split("Direct Unpack: ")[-1].split() + ) + percentage = action[0].split("/") + percentage = round( + (int(float(percentage[0])) / int(float(percentage[1]))) * 100, 2 + ) + eta = action[2] + old_info["percentage"] = percentage + old_info["timeleft"] = eta + old_info["status"] = slot["status"] + return old_info + except Exception as e: + LOGGER.error(f"{e}: Sabnzbd, while getting job info. ID: {nzo_id}") + return old_info + + +class SabnzbdStatus: + def __init__(self, listener, gid, queued=False): + self.queued = queued + self.listener = listener + self._gid = gid + self._info = {} + self.tool = "sabnzbd" + + async def update(self): + self._info = await get_download(self._gid, self._info) + + def progress(self): + return f"{self._info.get('percentage', "0")}%" + + def processed_raw(self): + return ( + float(self._info.get("mb", "0")) - float(self._info.get("mbleft", "0")) + ) * 1048576 + + def processed_bytes(self): + return get_readable_file_size(self.processed_raw()) + + def speed_raw(self): + if self._info.get("mb", "0") == self._info.get("mbleft", "0"): + return 0 + try: + return int(float(self._info.get("mbleft", "0")) * 1048576) / self.eta_raw() + except: + return 0 + + def speed(self): + return f"{get_readable_file_size(self.speed_raw())}/s" + + def name(self): + return self._info.get("filename", "") + + def size(self): + return self._info.get("size", 0) + + def eta_raw(self): + return int(time_to_seconds(self._info.get("timeleft", "0"))) + + def eta(self): + return get_readable_time(self.eta_raw()) + + async def status(self): + await self.update() + if self._info.get("mb", "0") == self._info.get("mbleft", "0"): + return MirrorStatus.STATUS_QUEUEDL + state = self._info.get("status") + if state == "Paused" and self.queued: + return MirrorStatus.STATUS_QUEUEDL + elif state in [ + "QuickCheck", + "Verifying", + "Repairing", + "Fetching", + "Moving", + "Extracting", + ]: + return state + else: + return MirrorStatus.STATUS_DOWNLOAD + + def task(self): + return self + + def gid(self): + return self._gid + + async def cancel_task(self): + self.listener.is_cancelled = True + await self.update() + LOGGER.info(f"Cancelling Download: {self.name()}") + await gather( + self.listener.on_download_error("Stopped by user!"), + sabnzbd_client.delete_job(self._gid, delete_files=True), + sabnzbd_client.delete_category(f"{self.listener.mid}"), + sabnzbd_client.delete_history(self._gid, delete_files=True), + ) + async with nzb_listener_lock: + if self._gid in nzb_jobs: + del nzb_jobs[self._gid] diff --git a/bot/helper/mirror_leech_utils/status_utils/qbit_status.py b/bot/helper/mirror_leech_utils/status_utils/qbit_status.py new file mode 100644 index 0000000000000000000000000000000000000000..a421162349a2038a2ef3b261f683297696e68500 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/qbit_status.py @@ -0,0 +1,117 @@ +from asyncio import sleep, gather + +from .... import LOGGER, qb_torrents, qb_listener_lock +from ....core.torrent_manager import TorrentManager +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +async def get_download(tag, old_info=None): + try: + res = (await TorrentManager.qbittorrent.torrents.info(tag=tag))[0] + return res or old_info + except Exception as e: + LOGGER.error(f"{e}: Qbittorrent, while getting torrent info. Tag: {tag}") + return old_info + + +class QbittorrentStatus: + def __init__(self, listener, seeding=False, queued=False): + self.queued = queued + self.seeding = seeding + self.listener = listener + self._info = None + self.tool = "qbittorrent" + + async def update(self): + self._info = await get_download(f"{self.listener.mid}", self._info) + + def progress(self): + return f"{round(self._info.progress * 100, 2)}%" + + def processed_bytes(self): + return get_readable_file_size(self._info.downloaded) + + def speed(self): + return f"{get_readable_file_size(self._info.dlspeed)}/s" + + def name(self): + if self._info.state in ["metaDL", "checkingResumeData"]: + return f"[METADATA]{self.listener.name}" + else: + return self.listener.name + + def size(self): + return get_readable_file_size(self._info.size) + + def eta(self): + return get_readable_time(self._info.eta.total_seconds()) + + async def status(self): + await self.update() + state = self._info.state + if state == "queuedDL" or self.queued: + return MirrorStatus.STATUS_QUEUEDL + elif state == "queuedUP": + return MirrorStatus.STATUS_QUEUEUP + elif state in ["stoppedDL", "stoppedUP"]: + return MirrorStatus.STATUS_PAUSED + elif state in ["checkingUP", "checkingDL"]: + return MirrorStatus.STATUS_CHECK + elif state in ["stalledUP", "uploading"] and self.seeding: + return MirrorStatus.STATUS_SEED + else: + return MirrorStatus.STATUS_DOWNLOAD + + def seeders_num(self): + return self._info.num_seeds + + def leechers_num(self): + return self._info.num_leechs + + def uploaded_bytes(self): + return get_readable_file_size(self._info.uploaded) + + def seed_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 get_readable_time(int(self._info.seeding_time.total_seconds())) + + def task(self): + return self + + def gid(self): + return self.hash()[:12] + + def hash(self): + return self._info.hash + + async def cancel_task(self): + self.listener.is_cancelled = True + await self.update() + await TorrentManager.qbittorrent.torrents.stop([self._info.hash]) + if not self.seeding: + if self.queued: + LOGGER.info(f"Cancelling QueueDL: {self.name()}") + msg = "task have been removed from queue/download" + else: + LOGGER.info(f"Cancelling Download: {self._info.name}") + msg = "Stopped by user!" + await sleep(0.3) + await gather( + self.listener.on_download_error(msg), + TorrentManager.qbittorrent.torrents.delete([self._info.hash], True), + TorrentManager.qbittorrent.torrents.delete_tags( + tags=[self._info.tags[0]] + ), + ) + async with qb_listener_lock: + if self._info.tags[0] in qb_torrents: + del qb_torrents[self._info.tags[0]] diff --git a/bot/helper/mirror_leech_utils/status_utils/queue_status.py b/bot/helper/mirror_leech_utils/status_utils/queue_status.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0810b7ee0ba8f1d1f2d370a22027cb2781b3af --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/queue_status.py @@ -0,0 +1,52 @@ +from .... import LOGGER +from ...ext_utils.status_utils import get_readable_file_size, MirrorStatus + + +class QueueStatus: + def __init__(self, listener, gid, status): + self.listener = listener + self._size = self.listener.size + self._gid = gid + self._status = status + self.tool = "system" + + def gid(self): + return self._gid + + def name(self): + return self.listener.name + + def size(self): + return get_readable_file_size(self._size) + + def status(self): + if self._status == "dl": + return MirrorStatus.STATUS_QUEUEDL + return MirrorStatus.STATUS_QUEUEUP + + def processed_bytes(self): + return 0 + + def progress(self): + return "0%" + + def speed(self): + return "0B/s" + + def eta(self): + return "-" + + def task(self): + return self + + async def cancel_task(self): + self.listener.is_cancelled = True + LOGGER.info(f"Cancelling Queue{self._status}: {self.listener.name}") + if self._status == "dl": + await self.listener.on_download_error( + "task have been removed from queue/download" + ) + else: + await self.listener.on_upload_error( + "task have been removed from queue/upload" + ) diff --git a/bot/helper/mirror_leech_utils/status_utils/rclone_status.py b/bot/helper/mirror_leech_utils/status_utils/rclone_status.py new file mode 100644 index 0000000000000000000000000000000000000000..17f40dd8c51065b1c523364e18199dc9492b7d8a --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/rclone_status.py @@ -0,0 +1,42 @@ +from ...ext_utils.status_utils import MirrorStatus + + +class RcloneStatus: + def __init__(self, listener, obj, gid, status): + self._obj = obj + self._gid = gid + self._status = status + self.listener = listener + self.tool = "rclone" + + def gid(self): + return self._gid + + def progress(self): + return self._obj.percentage + + def speed(self): + return self._obj.speed + + def name(self): + return self.listener.name + + def size(self): + return self._obj.size + + def eta(self): + return self._obj.eta + + def status(self): + if self._status == "dl": + return MirrorStatus.STATUS_DOWNLOAD + elif self._status == "up": + return MirrorStatus.STATUS_UPLOAD + else: + return MirrorStatus.STATUS_CLONE + + def processed_bytes(self): + return self._obj.transferred_size + + def task(self): + return self._obj diff --git a/bot/helper/mirror_leech_utils/status_utils/sevenz_status.py b/bot/helper/mirror_leech_utils/status_utils/sevenz_status.py new file mode 100644 index 0000000000000000000000000000000000000000..661a5f58838d529d0f0675776995635c4cafb3b5 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/sevenz_status.py @@ -0,0 +1,70 @@ +from time import time + +from .... import LOGGER +from ...ext_utils.status_utils import ( + get_readable_file_size, + MirrorStatus, + get_readable_time, +) + + +class SevenZStatus: + def __init__(self, listener, obj, gid, status=""): + self.listener = listener + self._obj = obj + self._gid = gid + self._start_time = time() + self._cstatus = status + self.tool = "7z" + + def gid(self): + return self._gid + + def _speed_raw(self): + return self._obj.processed_bytes / (time() - self._start_time) + + def progress(self): + return self._obj.progress + + def speed(self): + return f"{get_readable_file_size(self._speed_raw())}/s" + + def processed_bytes(self): + return get_readable_file_size(self._obj.processed_bytes) + + def name(self): + return self.listener.name + + def size(self): + return get_readable_file_size(self.listener.size) + + def eta(self): + try: + seconds = ( + self.listener.subsize - self._obj.processed_bytes + ) / self._speed_raw() + return get_readable_time(seconds) + except: + return "-" + + def status(self): + if self._cstatus == "Extract": + return MirrorStatus.STATUS_EXTRACT + else: + return MirrorStatus.STATUS_ARCHIVE + + def task(self): + return self + + async def cancel_task(self): + LOGGER.info(f"Cancelling {self._cstatus}: {self.listener.name}") + self.listener.is_cancelled = True + if ( + self.listener.subproc is not None + and self.listener.subproc.returncode is None + ): + try: + self.listener.subproc.kill() + except: + pass + await self.listener.on_upload_error(f"{self._cstatus} stopped by user!") diff --git a/bot/helper/mirror_leech_utils/status_utils/telegram_status.py b/bot/helper/mirror_leech_utils/status_utils/telegram_status.py new file mode 100644 index 0000000000000000000000000000000000000000..21ec5bafc937a7be7c975b4c986048073f6ce499 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/telegram_status.py @@ -0,0 +1,52 @@ +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +class TelegramStatus: + def __init__(self, listener, obj, gid, status): + self.listener = listener + self._obj = obj + self._size = self.listener.size + self._gid = gid + self._status = status + self.tool = "telegram" + + def processed_bytes(self): + return get_readable_file_size(self._obj.processed_bytes) + + def size(self): + return get_readable_file_size(self._size) + + def status(self): + if self._status == "up": + return MirrorStatus.STATUS_UPLOAD + return MirrorStatus.STATUS_DOWNLOAD + + def name(self): + return self.listener.name + + def progress(self): + try: + progress_raw = self._obj.processed_bytes / self._size * 100 + except: + progress_raw = 0 + return f"{round(progress_raw, 2)}%" + + def speed(self): + return f"{get_readable_file_size(self._obj.speed)}/s" + + def eta(self): + try: + seconds = (self._size - self._obj.processed_bytes) / self._obj.speed + return get_readable_time(seconds) + except: + return "-" + + def gid(self): + return self._gid + + def task(self): + return self._obj diff --git a/bot/helper/mirror_leech_utils/status_utils/yt_dlp_status.py b/bot/helper/mirror_leech_utils/status_utils/yt_dlp_status.py new file mode 100644 index 0000000000000000000000000000000000000000..8c31a7d9eb9c0bb680fe4bbd03579a74bdc0e762 --- /dev/null +++ b/bot/helper/mirror_leech_utils/status_utils/yt_dlp_status.py @@ -0,0 +1,48 @@ +from ...ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, +) + + +class YtDlpStatus: + def __init__(self, listener, obj, gid): + self._obj = obj + self._gid = gid + self.listener = listener + self.tool = "yt-dlp" + + def gid(self): + return self._gid + + def processed_bytes(self): + return get_readable_file_size(self._obj.downloaded_bytes) + + def size(self): + return get_readable_file_size(self._obj.size) + + def status(self): + return MirrorStatus.STATUS_DOWNLOAD + + def name(self): + return self.listener.name + + def progress(self): + return f"{round(self._obj.progress, 2)}%" + + def speed(self): + return f"{get_readable_file_size(self._obj.download_speed)}/s" + + def eta(self): + if self._obj.eta != "-": + return get_readable_time(self._obj.eta) + try: + seconds = ( + self._obj.size - self._obj.downloaded_bytes + ) / self._obj.download_speed + return get_readable_time(seconds) + except: + return "-" + + def task(self): + return self._obj diff --git a/bot/helper/mirror_leech_utils/telegram_uploader.py b/bot/helper/mirror_leech_utils/telegram_uploader.py new file mode 100644 index 0000000000000000000000000000000000000000..2518275a132e3f47b19c2cc065599f1adbb22821 --- /dev/null +++ b/bot/helper/mirror_leech_utils/telegram_uploader.py @@ -0,0 +1,536 @@ +from PIL import Image +from aioshutil import rmtree +from asyncio import sleep +from logging import getLogger +from natsort import natsorted +from os import walk, path as ospath +from time import time +from re import match as re_match, sub as re_sub +from pyrogram.errors import FloodWait, RPCError, FloodPremiumWait, BadRequest +from pyrogram.types import ( + InputMediaVideo, + InputMediaDocument, + InputMediaPhoto, +) +from aiofiles.os import ( + remove, + path as aiopath, + rename, +) +from tenacity import ( + retry, + wait_exponential, + stop_after_attempt, + retry_if_exception_type, + RetryError, +) + +from ... import intervals +from ...core.config_manager import Config +from ...core.telegram_manager import TgClient +from ..ext_utils.bot_utils import sync_to_async +from ..ext_utils.files_utils import is_archive, get_base_name +from ..telegram_helper.message_utils import delete_message +from ..ext_utils.media_utils import ( + get_media_info, + get_document_type, + get_video_thumbnail, + get_audio_thumbnail, + get_multiple_frames_thumbnail, +) + +LOGGER = getLogger(__name__) + + +class TelegramUploader: + def __init__(self, listener, path): + self._last_uploaded = 0 + self._processed_bytes = 0 + self._listener = listener + self._path = path + self._start_time = time() + self._total_files = 0 + self._thumb = self._listener.thumb or f"thumbnails/{listener.user_id}.jpg" + self._msgs_dict = {} + self._corrupted = 0 + self._is_corrupted = False + self._media_dict = {"videos": {}, "documents": {}} + self._last_msg_in_group = False + self._up_path = "" + self._lprefix = "" + self._media_group = False + self._is_private = False + self._sent_msg = None + self._user_session = self._listener.user_transmission + self._error = "" + self._base_msg = None + self._files_links = False + + async def _upload_progress(self, current, _): + if self._listener.is_cancelled: + if self._user_session: + TgClient.user.stop_transmission() + else: + self._listener.client.stop_transmission() + chunk_size = current - self._last_uploaded + self._last_uploaded = current + self._processed_bytes += chunk_size + + async def _user_settings(self): + self._media_group = self._listener.user_dict.get("MEDIA_GROUP", False) or ( + Config.MEDIA_GROUP + if "MEDIA_GROUP" not in self._listener.user_dict + else False + ) + self._lprefix = self._listener.user_dict.get("LEECH_FILENAME_PREFIX") or ( + Config.LEECH_FILENAME_PREFIX + if "LEECH_FILENAME_PREFIX" not in self._listener.user_dict + else "" + ) + self._files_links = self._listener.user_dict.get("FILES_LINKS", False) or ( + Config.FILES_LINKS + if "FILES_LINKS" not in self._listener.user_dict + else False + ) + if self._thumb != "none" and not await aiopath.exists(self._thumb): + self._thumb = None + + async def _msg_to_reply(self): + if self._listener.up_dest: + msg = ( + self._listener.message.link + if self._listener.is_super_chat + else self._listener.message.text.lstrip("/") + ) + try: + if self._user_session: + self._sent_msg = await TgClient.user.send_message( + chat_id=self._listener.up_dest, + text=msg, + message_thread_id=self._listener.chat_thread_id, + disable_notification=True, + ) + else: + self._sent_msg = await self._listener.client.send_message( + chat_id=self._listener.up_dest, + text=msg, + message_thread_id=self._listener.chat_thread_id, + disable_notification=True, + ) + self._is_private = self._sent_msg.chat.type.name == "PRIVATE" + except Exception as e: + await self._listener.on_upload_error(str(e)) + return False + finally: + self._base_msg = self._sent_msg + elif self._user_session: + self._sent_msg = await TgClient.user.get_messages( + chat_id=self._listener.message.chat.id, message_ids=self._listener.mid + ) + if self._sent_msg is None: + self._sent_msg = await TgClient.user.send_message( + chat_id=self._listener.message.chat.id, + text="Deleted Cmd Message! Don't delete the cmd message again!", + disable_notification=True, + ) + else: + self._sent_msg = self._listener.message + return True + + async def _prepare_file(self, file_, dirpath): + if self._lprefix: + cap_mono = f"{self._lprefix} {file_}" + self._lprefix = re_sub("<.*?>", "", self._lprefix) + new_path = ospath.join(dirpath, f"{self._lprefix} {file_}") + await rename(self._up_path, new_path) + self._up_path = new_path + else: + cap_mono = f"{file_}" + if len(file_) > 60: + if is_archive(file_): + name = get_base_name(file_) + ext = file_.split(name, 1)[1] + elif match := re_match(r".+(?=\..+\.0*\d+$)|.+(?=\.part\d+\..+$)", file_): + name = match.group(0) + ext = file_.split(name, 1)[1] + elif len(fsplit := ospath.splitext(file_)) > 1: + name = fsplit[0] + ext = fsplit[1] + else: + name = file_ + ext = "" + extn = len(ext) + remain = 60 - extn + name = name[:remain] + new_path = ospath.join(dirpath, f"{name}{ext}") + await rename(self._up_path, new_path) + self._up_path = new_path + return cap_mono + + def _get_input_media(self, subkey, key): + rlist = [] + for msg in self._media_dict[key][subkey]: + if key == "videos": + input_media = InputMediaVideo( + media=msg.video.file_id, caption=msg.caption + ) + else: + input_media = InputMediaDocument( + media=msg.document.file_id, caption=msg.caption + ) + rlist.append(input_media) + return rlist + + async def _send_screenshots(self, dirpath, outputs): + inputs = [ + InputMediaPhoto(ospath.join(dirpath, p), p.rsplit("/", 1)[-1]) + for p in outputs + ] + for i in range(0, len(inputs), 10): + batch = inputs[i : i + 10] + self._sent_msg = ( + await self._sent_msg.reply_media_group( + media=batch, + disable_notification=True, + ) + )[-1] + + async def _send_media_group(self, subkey, key, msgs): + for index, msg in enumerate(msgs): + if self._listener.hybrid_leech or not self._user_session: + msgs[index] = await self._listener.client.get_messages( + chat_id=msg[0], message_ids=msg[1] + ) + else: + msgs[index] = await TgClient.user.get_messages( + chat_id=msg[0], message_ids=msg[1] + ) + msgs_list = await msgs[0].reply_to_message.reply_media_group( + media=self._get_input_media(subkey, key), + disable_notification=True, + ) + for msg in msgs: + if msg.link in self._msgs_dict: + del self._msgs_dict[msg.link] + await delete_message(msg) + del self._media_dict[key][subkey] + if self._files_links and ( + self._listener.is_super_chat or self._listener.up_dest + ): + for m in msgs_list: + self._msgs_dict[m.link] = m.caption + self._sent_msg = msgs_list[-1] + if self._base_msg: + await delete_message(self._base_msg) + self._base_msg = None + + async def upload(self): + await self._user_settings() + res = await self._msg_to_reply() + if not res: + return + for dirpath, _, files in natsorted(await sync_to_async(walk, self._path)): + if dirpath.strip().endswith("/yt-dlp-thumb"): + continue + if dirpath.strip().endswith("_mltbss"): + await self._send_screenshots(dirpath, files) + await rmtree(dirpath, ignore_errors=True) + continue + for file_ in natsorted(files): + self._error = "" + self._up_path = f_path = ospath.join(dirpath, file_) + if not await aiopath.exists(self._up_path): + if intervals["stopAll"]: + return + LOGGER.error(f"{self._up_path} not exists! Continue uploading!") + continue + try: + f_size = await aiopath.getsize(self._up_path) + self._total_files += 1 + if f_size == 0: + LOGGER.error( + f"{self._up_path} size is zero, telegram don't upload zero size files" + ) + self._corrupted += 1 + continue + if self._listener.is_cancelled: + return + cap_mono = await self._prepare_file(file_, dirpath) + if self._last_msg_in_group: + group_lists = [ + x for v in self._media_dict.values() for x in v.keys() + ] + match = re_match(r".+(?=\.0*\d+$)|.+(?=\.part\d+\..+$)", f_path) + if not match or match and match.group(0) not in group_lists: + for key, value in list(self._media_dict.items()): + for subkey, msgs in list(value.items()): + if len(msgs) > 1: + await self._send_media_group(subkey, key, msgs) + if self._listener.hybrid_leech and self._listener.user_transmission: + self._user_session = f_size > 2097152000 + if self._user_session: + self._sent_msg = await TgClient.user.get_messages( + chat_id=self._sent_msg.chat.id, + message_ids=self._sent_msg.id, + ) + else: + self._sent_msg = await self._listener.client.get_messages( + chat_id=self._sent_msg.chat.id, + message_ids=self._sent_msg.id, + ) + self._last_msg_in_group = False + self._last_uploaded = 0 + await self._upload_file(cap_mono, file_, f_path) + if self._sent_msg and self._sent_msg.media_group_id: + for ch, ch_data in list( + self._listener.clone_dump_chats.items() + ): + try: + res = await TgClient.bot.copy_message( + chat_id=ch, + from_chat_id=self._sent_msg.chat.id, + message_id=self._sent_msg.id, + message_thread_id=ch_data["thread_id"], + disable_notification=True, + reply_to_message_id=ch_data["last_sent_msg"], + ) + self._listener.clone_dump_chats[ch][ + "last_sent_msg" + ] = res.id + except Exception as e: + LOGGER.error( + f"Can't forward message to clone dump chat: {ch}. Error: {e}" + ) + if self._listener.is_cancelled: + return + if ( + self._files_links + and not self._is_corrupted + and (self._listener.is_super_chat or self._listener.up_dest) + and not self._is_private + ): + self._msgs_dict[self._sent_msg.link] = file_ + await sleep(1) + except Exception as err: + if isinstance(err, RetryError): + LOGGER.info( + f"Total Attempts: {err.last_attempt.attempt_number}" + ) + err = err.last_attempt.exception() + LOGGER.error(f"{err}. Path: {self._up_path}") + self._error = str(err) + self._corrupted += 1 + if self._listener.is_cancelled: + return + if not self._listener.is_cancelled and await aiopath.exists( + self._up_path + ): + await remove(self._up_path) + for key, value in list(self._media_dict.items()): + for subkey, msgs in list(value.items()): + if len(msgs) > 1: + try: + await self._send_media_group(subkey, key, msgs) + except Exception as e: + LOGGER.info( + f"While sending media group at the end of task. Error: {e}" + ) + if self._base_msg: + await delete_message(self._base_msg) + self._base_msg = None + if self._listener.is_cancelled: + return + if self._total_files == 0: + await self._listener.on_upload_error( + "No files to upload. In case you have filled EXCLUDED/INCLUDED EXTENSIONS, then check if all files have those extensions or not." + ) + return + if self._total_files <= self._corrupted: + await self._listener.on_upload_error( + f"Files Corrupted or unable to upload. {self._error or 'Check logs!'}" + ) + return + LOGGER.info(f"Leech Completed: {self._listener.name}") + await self._listener.on_upload_complete( + None, self._msgs_dict, self._total_files, self._corrupted + ) + return + + @retry( + wait=wait_exponential(multiplier=2, min=4, max=8), + stop=stop_after_attempt(3), + retry=retry_if_exception_type(Exception), + ) + async def _upload_file(self, cap_mono, file, o_path, force_document=False): + if ( + self._thumb is not None + and not await aiopath.exists(self._thumb) + and self._thumb != "none" + ): + self._thumb = None + thumb = self._thumb + self._is_corrupted = False + try: + is_video, is_audio, is_image = await get_document_type(self._up_path) + + if not is_image and thumb is None: + file_name = ospath.splitext(file)[0] + thumb_path = f"{self._path}/yt-dlp-thumb/{file_name}.jpg" + if await aiopath.isfile(thumb_path): + thumb = thumb_path + elif await aiopath.isfile(thumb_path.replace("/yt-dlp-thumb", "")): + thumb = thumb_path.replace("/yt-dlp-thumb", "") + elif is_audio and not is_video: + thumb = await get_audio_thumbnail(self._up_path) + + if ( + self._listener.as_doc + or force_document + or (not is_video and not is_audio and not is_image) + ): + key = "documents" + if is_video and thumb is None: + thumb = await get_video_thumbnail(self._up_path, None) + + if self._listener.is_cancelled: + return + if thumb == "none": + thumb = None + self._sent_msg = await self._sent_msg.reply_document( + document=self._up_path, + thumb=thumb, + caption=cap_mono, + force_document=True, + disable_notification=True, + progress=self._upload_progress, + ) + elif is_video: + key = "videos" + duration = (await get_media_info(self._up_path))[0] + if thumb is None and self._listener.thumbnail_layout: + thumb = await get_multiple_frames_thumbnail( + self._up_path, + self._listener.thumbnail_layout, + self._listener.screen_shots, + ) + if thumb is None: + thumb = await get_video_thumbnail(self._up_path, duration) + if thumb is not None and thumb != "none": + with Image.open(thumb) as img: + width, height = img.size + else: + width = 480 + height = 320 + if self._listener.is_cancelled: + return + if thumb == "none": + thumb = None + self._sent_msg = await self._sent_msg.reply_video( + video=self._up_path, + caption=cap_mono, + duration=duration, + width=width, + height=height, + thumb=thumb, + supports_streaming=True, + disable_notification=True, + progress=self._upload_progress, + ) + elif is_audio: + key = "audios" + duration, artist, title = await get_media_info(self._up_path) + if self._listener.is_cancelled: + return + if thumb == "none": + thumb = None + self._sent_msg = await self._sent_msg.reply_audio( + audio=self._up_path, + caption=cap_mono, + duration=duration, + performer=artist, + title=title, + thumb=thumb, + disable_notification=True, + progress=self._upload_progress, + ) + else: + key = "photos" + if self._listener.is_cancelled: + return + self._sent_msg = await self._sent_msg.reply_photo( + photo=self._up_path, + caption=cap_mono, + disable_notification=True, + progress=self._upload_progress, + ) + + if ( + not self._listener.is_cancelled + and self._media_group + and (self._sent_msg.video or self._sent_msg.document) + ): + key = "documents" if self._sent_msg.document else "videos" + if match := re_match(r".+(?=\.0*\d+$)|.+(?=\.part\d+\..+$)", o_path): + + pname = match.group(0) + if pname in self._media_dict[key].keys(): + self._media_dict[key][pname].append( + [self._sent_msg.chat.id, self._sent_msg.id] + ) + else: + self._media_dict[key][pname] = [ + [self._sent_msg.chat.id, self._sent_msg.id] + ] + msgs = self._media_dict[key][pname] + if len(msgs) == 10: + await self._send_media_group(pname, key, msgs) + else: + self._last_msg_in_group = True + if ( + self._thumb is None + and thumb is not None + and await aiopath.exists(thumb) + ): + await remove(thumb) + if self._base_msg and not self._last_msg_in_group: + await delete_message(self._base_msg) + self._base_msg = None + except (FloodWait, FloodPremiumWait) as f: + LOGGER.warning(str(f)) + await sleep(f.value * 1.3) + if ( + self._thumb is None + and thumb is not None + and await aiopath.exists(thumb) + ): + await remove(thumb) + return await self._upload_file(cap_mono, file, o_path) + except Exception as err: + if ( + self._thumb is None + and thumb is not None + and await aiopath.exists(thumb) + ): + await remove(thumb) + err_type = "RPCError: " if isinstance(err, RPCError) else "" + LOGGER.error(f"{err_type}{err}. Path: {self._up_path}") + if isinstance(err, BadRequest) and key != "documents": + LOGGER.error(f"Retrying As Document. Path: {self._up_path}") + return await self._upload_file(cap_mono, file, o_path, True) + raise err + + @property + def speed(self): + try: + return self._processed_bytes / (time() - self._start_time) + except: + return 0 + + @property + def processed_bytes(self): + return self._processed_bytes + + async def cancel_task(self): + self._listener.is_cancelled = True + LOGGER.info(f"Cancelling Upload: {self._listener.name}") + await self._listener.on_upload_error("your upload has been stopped!") diff --git a/bot/helper/telegram_helper/__init__.py b/bot/helper/telegram_helper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/bot/helper/telegram_helper/__init__.py @@ -0,0 +1 @@ + diff --git a/bot/helper/telegram_helper/bot_commands.py b/bot/helper/telegram_helper/bot_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad704238d67588d5960ea9c5f0b23db2eaaf642 --- /dev/null +++ b/bot/helper/telegram_helper/bot_commands.py @@ -0,0 +1,44 @@ +from ...core.config_manager import Config + +i = Config.CMD_SUFFIX + +class BotCommands: + StartCommand = f"start{i}" + MirrorCommand = [f"mirror{i}", f"m{i}"] + QbMirrorCommand = [f"qbmirror{i}", f"qm{i}"] + JdMirrorCommand = [f"jdmirror{i}", f"jm{i}"] + YtdlCommand = [f"ytdl{i}", f"y{i}"] + NzbMirrorCommand = [f"nzbmirror{i}", f"nm{i}"] + LeechCommand = [f"leech{i}", f"l{i}"] + QbLeechCommand = [f"qbleech{i}", f"ql{i}"] + JdLeechCommand = [f"jdleech{i}", f"jl{i}"] + YtdlLeechCommand = [f"ytdlleech{i}", f"yl{i}"] + NzbLeechCommand = [f"nzbleech{i}", f"nl{i}"] + CloneCommand = f"clone{i}" + CountCommand = f"count{i}" + DeleteCommand = f"del{i}" + CancelTaskCommand = [f"cancel{i}", f"c{i}"] + CancelAllCommand = f"cancelall{i}" + ForceStartCommand = [f"forcestart{i}", f"fs{i}"] + ListCommand = f"list{i}" + SearchCommand = f"search{i}" + StatusCommand = f"status{i}" + UsersCommand = f"users{i}" + AuthorizeCommand = f"auth{i}" + UnAuthorizeCommand = f"unauth{i}" + AddSudoCommand = f"addsudo{i}" + RmSudoCommand = f"rmsudo{i}" + PingCommand = f"ping{i}" + RestartCommand = f"restart{i}" + StatsCommand = f"stats{i}" + HelpCommand = f"help{i}" + LogCommand = f"log{i}" + ShellCommand = f"shell{i}" + AExecCommand = f"aexec{i}" + ExecCommand = f"exec{i}" + ClearLocalsCommand = f"clearlocals{i}" + BotSetCommand = [f"bsetting{i}", f"bs{i}"] + UserSetCommand = [f"usetting{i}", f"us{i}"] + SelectCommand = f"sel{i}" + RssCommand = f"rss{i}" + NzbSearchCommand = f"nzbsearch{i}" diff --git a/bot/helper/telegram_helper/button_build.py b/bot/helper/telegram_helper/button_build.py new file mode 100644 index 0000000000000000000000000000000000000000..c7092a3dadeac641d36b13d5f523ec9ac8d8a042 --- /dev/null +++ b/bot/helper/telegram_helper/button_build.py @@ -0,0 +1,57 @@ +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton + + +class ButtonMaker: + def __init__(self): + self._button = [] + self._header_button = [] + self._footer_button = [] + + def url_button(self, key, link, position=None): + if not position: + self._button.append(InlineKeyboardButton(text=key, url=link)) + elif position == "header": + self._header_button.append(InlineKeyboardButton(text=key, url=link)) + elif position == "footer": + self._footer_button.append(InlineKeyboardButton(text=key, url=link)) + + def data_button(self, key, data, position=None): + if not position: + self._button.append(InlineKeyboardButton(text=key, callback_data=data)) + elif position == "header": + self._header_button.append( + InlineKeyboardButton(text=key, callback_data=data) + ) + elif position == "footer": + self._footer_button.append( + InlineKeyboardButton(text=key, callback_data=data) + ) + + def build_menu(self, b_cols=1, h_cols=8, f_cols=8): + menu = [ + self._button[i : i + b_cols] for i in range(0, len(self._button), b_cols) + ] + if self._header_button: + h_cnt = len(self._header_button) + if h_cnt > h_cols: + header_buttons = [ + self._header_button[i : i + h_cols] + for i in range(0, len(self._header_button), h_cols) + ] + menu = header_buttons + menu + else: + menu.insert(0, self._header_button) + if self._footer_button: + if len(self._footer_button) > f_cols: + [ + menu.append(self._footer_button[i : i + f_cols]) + for i in range(0, len(self._footer_button), f_cols) + ] + else: + menu.append(self._footer_button) + return InlineKeyboardMarkup(menu) + + def reset(self): + self._button = [] + self._header_button = [] + self._footer_button = [] diff --git a/bot/helper/telegram_helper/filters.py b/bot/helper/telegram_helper/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e22a23a764cf9192a74e9433656ca5ce1a0ff2cb --- /dev/null +++ b/bot/helper/telegram_helper/filters.py @@ -0,0 +1,59 @@ +from pyrogram.filters import create + +from ... import user_data, auth_chats, sudo_users +from ...core.config_manager import Config + + +class CustomFilters: + async def owner_filter(self, _, update): + user = update.from_user or update.sender_chat + return user.id == Config.OWNER_ID + + owner = create(owner_filter) + + async def authorized_user(self, _, update): + user = update.from_user or update.sender_chat + uid = user.id + chat_id = update.chat.id + thread_id = update.message_thread_id if update.topic_message else None + return bool( + uid == Config.OWNER_ID + or ( + uid in user_data + and ( + user_data[uid].get("AUTH", False) + or user_data[uid].get("SUDO", False) + ) + ) + or ( + chat_id in user_data + and user_data[chat_id].get("AUTH", False) + and ( + thread_id is None + or thread_id in user_data[chat_id].get("thread_ids", []) + ) + ) + or uid in sudo_users + or uid in auth_chats + or chat_id in auth_chats + and ( + auth_chats[chat_id] + and thread_id + and thread_id in auth_chats[chat_id] + or not auth_chats[chat_id] + ) + ) + + authorized = create(authorized_user) + + async def sudo_user(self, _, update): + user = update.from_user or update.sender_chat + uid = user.id + return bool( + uid == Config.OWNER_ID + or uid in user_data + and user_data[uid].get("SUDO") + or uid in sudo_users + ) + + sudo = create(sudo_user) diff --git a/bot/helper/telegram_helper/message_utils.py b/bot/helper/telegram_helper/message_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6fd1430738268921ca73310afff14d8021c979d --- /dev/null +++ b/bot/helper/telegram_helper/message_utils.py @@ -0,0 +1,278 @@ +from asyncio import sleep +from pyrogram.errors import FloodWait, FloodPremiumWait +from re import match as re_match +from time import time + +from ... import LOGGER, status_dict, task_dict_lock, intervals, DOWNLOAD_DIR +from ...core.config_manager import Config +from ...core.telegram_manager import TgClient +from ..ext_utils.bot_utils import SetInterval +from ..ext_utils.exceptions import TgLinkException +from ..ext_utils.status_utils import get_readable_message + + +async def send_message(message, text, buttons=None, block=True): + try: + return await message.reply( + text=text, + disable_notification=True, + reply_markup=buttons, + ) + except FloodWait as f: + LOGGER.warning(str(f)) + if not block: + return str(f) + await sleep(f.value * 1.2) + return await send_message(message, text, buttons, block) + except Exception as e: + LOGGER.error(str(e)) + return str(e) + + +async def edit_message(message, text, buttons=None, block=True): + try: + return await message.edit( + text=text, + reply_markup=buttons, + ) + except FloodWait as f: + LOGGER.warning(str(f)) + if not block: + return str(f) + await sleep(f.value * 1.2) + return await edit_message(message, text, buttons, block) + except Exception as e: + LOGGER.error(str(e)) + return str(e) + + +async def send_file(message, file, caption=""): + try: + return await message.reply_document( + document=file, caption=caption, disable_notification=True + ) + except FloodWait as f: + LOGGER.warning(str(f)) + await sleep(f.value * 1.2) + return await send_file(message, file, caption) + except Exception as e: + LOGGER.error(str(e)) + return str(e) + + +async def send_rss(text, chat_id, thread_id): + try: + app = TgClient.user or TgClient.bot + return await app.send_message( + chat_id=chat_id, + text=text, + message_thread_id=thread_id, + disable_notification=True, + ) + except (FloodWait, FloodPremiumWait) as f: + LOGGER.warning(str(f)) + await sleep(f.value * 1.2) + return await send_rss(text, chat_id, thread_id) + except Exception as e: + LOGGER.error(str(e)) + return str(e) + + +async def delete_message(message): + try: + await message.delete() + except Exception as e: + LOGGER.error(str(e)) + + +async def auto_delete_message(cmd_message=None, bot_message=None): + await sleep(60) + if cmd_message is not None: + await delete_message(cmd_message) + if bot_message is not None: + await delete_message(bot_message) + + +async def delete_status(): + async with task_dict_lock: + for key, data in list(status_dict.items()): + try: + await delete_message(data["message"]) + del status_dict[key] + except Exception as e: + LOGGER.error(str(e)) + + +async def get_tg_link_message(link): + message = None + links = [] + if link.startswith("https://t.me/"): + private = False + msg = re_match( + r"https:\/\/t\.me\/(?:c\/)?([^\/]+)\/(?:\d+\/)*([0-9-]+)", + link, + ) + else: + private = True + msg = re_match( + r"tg:\/\/openmessage\?user_id=([0-9]+)&message_id=([0-9-]+)", link + ) + if not TgClient.user: + raise TgLinkException("USER_SESSION_STRING required for this private link!") + if not msg: + raise TgLinkException("Wrong link format!") + chat = msg[1] + msg_id = msg[2] + if "-" in msg_id: + start_id, end_id = msg_id.split("-") + msg_id = start_id = int(start_id) + end_id = int(end_id) + btw = end_id - start_id + if private: + link = link.split("&message_id=")[0] + links.append(f"{link}&message_id={start_id}") + for _ in range(btw): + start_id += 1 + links.append(f"{link}&message_id={start_id}") + else: + link = link.rsplit("/", 1)[0] + links.append(f"{link}/{start_id}") + for _ in range(btw): + start_id += 1 + links.append(f"{link}/{start_id}") + else: + msg_id = int(msg_id) + + if chat.isdigit(): + chat = int(chat) if private else int(f"-100{chat}") + + if not private: + try: + message = await TgClient.bot.get_messages(chat_id=chat, message_ids=msg_id) + if message.empty: + private = True + except Exception as e: + private = True + if not TgClient.user: + raise e + + if not private: + return (links, "bot") if links else (message, "bot") + elif TgClient.user: + try: + user_message = await TgClient.user.get_messages( + chat_id=chat, message_ids=msg_id + ) + except Exception as e: + raise TgLinkException( + f"You don't have access to this chat!. ERROR: {e}" + ) from e + if not user_message.empty: + return (links, "user") if links else (user_message, "user") + else: + raise TgLinkException("Private: Can't get this message!") + else: + raise TgLinkException("Private: Can't get this message!") + + +async def temp_download(msg): + path = f"{DOWNLOAD_DIR}temp" + return await msg.download(file_name=f"{path}/") + + +async def update_status_message(sid, force=False): + if intervals["stopAll"]: + return + async with task_dict_lock: + if not status_dict.get(sid): + if obj := intervals["status"].get(sid): + obj.cancel() + del intervals["status"][sid] + return + if not force and time() - status_dict[sid]["time"] < 3: + return + status_dict[sid]["time"] = time() + page_no = status_dict[sid]["page_no"] + status = status_dict[sid]["status"] + is_user = status_dict[sid]["is_user"] + page_step = status_dict[sid]["page_step"] + text, buttons = await get_readable_message( + sid, is_user, page_no, status, page_step + ) + if text is None: + del status_dict[sid] + if obj := intervals["status"].get(sid): + obj.cancel() + del intervals["status"][sid] + return + if text != status_dict[sid]["message"].text: + message = await edit_message( + status_dict[sid]["message"], text, buttons, block=False + ) + if isinstance(message, str): + if message.startswith("Telegram says: [40"): + del status_dict[sid] + if obj := intervals["status"].get(sid): + obj.cancel() + del intervals["status"][sid] + else: + LOGGER.error( + f"Status with id: {sid} haven't been updated. Error: {message}" + ) + return + status_dict[sid]["message"].text = text + status_dict[sid]["time"] = time() + + +async def send_status_message(msg, user_id=0): + if intervals["stopAll"]: + return + sid = user_id or msg.chat.id + is_user = bool(user_id) + async with task_dict_lock: + if sid in status_dict: + page_no = status_dict[sid]["page_no"] + status = status_dict[sid]["status"] + page_step = status_dict[sid]["page_step"] + text, buttons = await get_readable_message( + sid, is_user, page_no, status, page_step + ) + if text is None: + del status_dict[sid] + if obj := intervals["status"].get(sid): + obj.cancel() + del intervals["status"][sid] + return + old_message = status_dict[sid]["message"] + message = await send_message(msg, text, buttons, block=False) + if isinstance(message, str): + LOGGER.error( + f"Status with id: {sid} haven't been sent. Error: {message}" + ) + return + await delete_message(old_message) + message.text = text + status_dict[sid].update({"message": message, "time": time()}) + else: + text, buttons = await get_readable_message(sid, is_user) + if text is None: + return + message = await send_message(msg, text, buttons, block=False) + if isinstance(message, str): + LOGGER.error( + f"Status with id: {sid} haven't been sent. Error: {message}" + ) + return + message.text = text + status_dict[sid] = { + "message": message, + "time": time(), + "page_no": 1, + "page_step": 1, + "status": "All", + "is_user": is_user, + } + if not intervals["status"].get(sid) and not is_user: + intervals["status"][sid] = SetInterval( + Config.STATUS_UPDATE_INTERVAL, update_status_message, sid + ) diff --git a/bot/modules/__init__.py b/bot/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cedf79408c78751ddd1f45c642b31bf638902f6 --- /dev/null +++ b/bot/modules/__init__.py @@ -0,0 +1,91 @@ +from .bot_settings import send_bot_settings, edit_bot_settings +from .cancel_task import cancel, cancel_multi, cancel_all_buttons, cancel_all_update +from .chat_permission import authorize, unauthorize, add_sudo, remove_sudo +from .clone import clone_node +from .exec import aioexecute, execute, clear +from .file_selector import select, confirm_selection +from .force_start import remove_from_queue +from .gd_count import count_node +from .gd_delete import delete_file +from .gd_search import gdrive_search, select_type +from .help import arg_usage, bot_help +from .mirror_leech import ( + mirror, + leech, + qb_leech, + qb_mirror, + jd_leech, + jd_mirror, + nzb_leech, + nzb_mirror, +) +from .restart import ( + restart_bot, + restart_notification, + confirm_restart, +) +from .rss import get_rss_menu, rss_listener +from .search import torrent_search, torrent_search_update, initiate_search_tools +from .nzb_search import hydra_search +from .services import start, ping, log +from .shell import run_shell +from .stats import bot_stats, get_packages_version +from .status import task_status, status_pages +from .users_settings import get_users_settings, edit_user_settings, send_user_settings +from .ytdlp import ytdl, ytdl_leech + +__all__ = [ + "send_bot_settings", + "edit_bot_settings", + "cancel", + "cancel_multi", + "cancel_all_buttons", + "cancel_all_update", + "authorize", + "unauthorize", + "add_sudo", + "remove_sudo", + "clone_node", + "aioexecute", + "execute", + "hydra_search", + "clear", + "select", + "confirm_selection", + "remove_from_queue", + "count_node", + "delete_file", + "gdrive_search", + "select_type", + "arg_usage", + "mirror", + "leech", + "qb_leech", + "qb_mirror", + "jd_leech", + "jd_mirror", + "nzb_leech", + "nzb_mirror", + "restart_bot", + "restart_notification", + "confirm_restart", + "get_rss_menu", + "rss_listener", + "torrent_search", + "torrent_search_update", + "initiate_search_tools", + "start", + "bot_help", + "ping", + "log", + "run_shell", + "bot_stats", + "get_packages_version", + "task_status", + "status_pages", + "get_users_settings", + "edit_user_settings", + "send_user_settings", + "ytdl", + "ytdl_leech", +] diff --git a/bot/modules/bot_settings.py b/bot/modules/bot_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..ca7f5dba23a07aab514a7264c21a1125826d21b6 --- /dev/null +++ b/bot/modules/bot_settings.py @@ -0,0 +1,893 @@ +from aiofiles import open as aiopen +from aiofiles.os import remove, rename, path as aiopath +from aioshutil import rmtree +from asyncio import ( + create_subprocess_exec, + create_subprocess_shell, + sleep, + gather, +) +from functools import partial +from io import BytesIO +from os import getcwd +from pyrogram.filters import create +from pyrogram.handlers import MessageHandler +from time import time + +from .. import ( + LOGGER, + drives_ids, + drives_names, + index_urls, + intervals, + aria2_options, + task_dict, + qbit_options, + sabnzbd_client, + nzb_options, + jd_listener_lock, + excluded_extensions, + included_extensions, + auth_chats, + sudo_users, +) +from ..helper.ext_utils.bot_utils import ( + SetInterval, + new_task, +) +from ..core.config_manager import Config +from ..core.telegram_manager import TgClient +from ..core.torrent_manager import TorrentManager +from ..core.startup import update_qb_options, update_nzb_options, update_variables +from ..helper.ext_utils.db_handler import database +from ..core.jdownloader_booter import jdownloader +from ..helper.ext_utils.task_manager import start_from_queued +from ..helper.mirror_leech_utils.rclone_utils.serve import rclone_serve_booter +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import ( + send_message, + send_file, + edit_message, + update_status_message, + delete_message, +) +from .rss import add_job +from .search import initiate_search_tools + +start = 0 +state = "view" +handler_dict = {} +DEFAULT_VALUES = { + "LEECH_SPLIT_SIZE": TgClient.MAX_SPLIT_SIZE, + "RSS_DELAY": 600, + "STATUS_UPDATE_INTERVAL": 15, + "SEARCH_LIMIT": 0, + "UPSTREAM_BRANCH": "master", + "DEFAULT_UPLOAD": "rc", +} + + +async def get_buttons(key=None, edit_type=None): + buttons = ButtonMaker() + if key is None: + buttons.data_button("Config Variables", "botset var") + buttons.data_button("Private Files", "botset private") + buttons.data_button("Qbit Settings", "botset qbit") + buttons.data_button("Aria2c Settings", "botset aria") + buttons.data_button("Sabnzbd Settings", "botset nzb") + buttons.data_button("JDownloader Sync", "botset syncjd") + buttons.data_button("Close", "botset close") + msg = "Bot Settings:" + elif edit_type is not None: + if edit_type == "botvar": + msg = "" + buttons.data_button("Back", "botset var") + if key not in ["TELEGRAM_HASH", "TELEGRAM_API", "OWNER_ID", "BOT_TOKEN"]: + buttons.data_button("Default", f"botset resetvar {key}") + buttons.data_button("Close", "botset close") + if key in [ + "CMD_SUFFIX", + "OWNER_ID", + "USER_SESSION_STRING", + "TELEGRAM_HASH", + "TELEGRAM_API", + "BOT_TOKEN", + "TG_PROXY", + ]: + msg += "Restart required for this edit to take effect! You will not see the changes in bot vars, the edit will be in database only!\n\n" + msg += f"Send a valid value for {key}. Current value is '{Config.get(key)}'. Timeout: 60 sec" + elif edit_type == "ariavar": + buttons.data_button("Back", "botset aria") + if key != "newkey": + buttons.data_button("Empty String", f"botset emptyaria {key}") + buttons.data_button("Close", "botset close") + msg = ( + "Send a key with value. Example: https-proxy-user:value. Timeout: 60 sec" + if key == "newkey" + else f"Send a valid value for {key}. Current value is '{aria2_options[key]}'. Timeout: 60 sec" + ) + elif edit_type == "qbitvar": + buttons.data_button("Back", "botset qbit") + buttons.data_button("Empty String", f"botset emptyqbit {key}") + buttons.data_button("Close", "botset close") + msg = f"Send a valid value for {key}. Current value is '{qbit_options[key]}'. Timeout: 60 sec" + elif edit_type == "nzbvar": + buttons.data_button("Back", "botset nzb") + buttons.data_button("Default", f"botset resetnzb {key}") + buttons.data_button("Empty String", f"botset emptynzb {key}") + buttons.data_button("Close", "botset close") + msg = f"Send a valid value for {key}. Current value is '{nzb_options[key]}'.\nIf the value is list then separate them by space or ,\nExample: .exe,info or .exe .info\nTimeout: 60 sec" + elif edit_type.startswith("nzbsevar"): + index = 0 if key == "newser" else int(edit_type.replace("nzbsevar", "")) + if key == "newser": + buttons.data_button("Back", "botset nzbserver") + msg = "Send one server as dictionary {}, like in config.py without []. Timeout: 60 sec" + else: + buttons.data_button("Empty", f"botset emptyserkey {index} {key}") + buttons.data_button("Back", f"botset nzbser{index}") + msg = f"Send a valid value for {key} in server {Config.USENET_SERVERS[index]['name']}. Current value is {Config.USENET_SERVERS[index][key]}. Timeout: 60 sec" + buttons.data_button("Close", "botset close") + elif key == "var": + conf_dict = Config.get_all() + for k in list(conf_dict.keys())[start : 10 + start]: + if k in ["DATABASE_URL", "DATABASE_NAME"] and state != "view": + continue + buttons.data_button(k, f"botset botvar {k}") + if state == "view": + buttons.data_button("Edit", "botset edit var") + else: + buttons.data_button("View", "botset view var") + buttons.data_button("Back", "botset back") + buttons.data_button("Close", "botset close") + for x in range(0, len(conf_dict), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start var {x}", position="footer" + ) + msg = f"Config Variables | Page: {int(start / 10)} | State: {state}" + elif key == "private": + buttons.data_button("Back", "botset back") + buttons.data_button("Close", "botset close") + msg = """Send private file: config.py, token.pickle, rclone.conf, accounts.zip, list_drives.txt, cookies.txt, .netrc or any other private file! +To delete private file send only the file name as text message. +Note: Changing .netrc will not take effect for aria2c until restart. +Timeout: 60 sec""" + elif key == "aria": + for k in list(aria2_options.keys())[start : 10 + start]: + if k not in ["checksum", "index-out", "out", "pause", "select-file"]: + buttons.data_button(k, f"botset ariavar {k}") + if state == "view": + buttons.data_button("Edit", "botset edit aria") + else: + buttons.data_button("View", "botset view aria") + buttons.data_button("Add new key", "botset ariavar newkey") + buttons.data_button("Back", "botset back") + buttons.data_button("Close", "botset close") + for x in range(0, len(aria2_options), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start aria {x}", position="footer" + ) + msg = f"Aria2c Options | Page: {int(start / 10)} | State: {state}" + elif key == "qbit": + for k in list(qbit_options.keys())[start : 10 + start]: + buttons.data_button(k, f"botset qbitvar {k}") + if state == "view": + buttons.data_button("Edit", "botset edit qbit") + else: + buttons.data_button("View", "botset view qbit") + buttons.data_button("Sync Qbittorrent", "botset syncqbit") + buttons.data_button("Back", "botset back") + buttons.data_button("Close", "botset close") + for x in range(0, len(qbit_options), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start qbit {x}", position="footer" + ) + msg = f"Qbittorrent Options | Page: {int(start / 10)} | State: {state}" + elif key == "nzb": + for k in list(nzb_options.keys())[start : 10 + start]: + buttons.data_button(k, f"botset nzbvar {k}") + if state == "view": + buttons.data_button("Edit", "botset edit nzb") + else: + buttons.data_button("View", "botset view nzb") + buttons.data_button("Servers", "botset nzbserver") + buttons.data_button("Sync Sabnzbd", "botset syncnzb") + buttons.data_button("Back", "botset back") + buttons.data_button("Close", "botset close") + for x in range(0, len(nzb_options), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start nzb {x}", position="footer" + ) + msg = f"Sabnzbd Options | Page: {int(start / 10)} | State: {state}" + elif key == "nzbserver": + if len(Config.USENET_SERVERS) > 0: + for index, k in enumerate(Config.USENET_SERVERS[start : 10 + start]): + buttons.data_button(k["name"], f"botset nzbser{index}") + buttons.data_button("Add New", "botset nzbsevar newser") + buttons.data_button("Back", "botset nzb") + buttons.data_button("Close", "botset close") + if len(Config.USENET_SERVERS) > 10: + for x in range(0, len(Config.USENET_SERVERS), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start nzbser {x}", position="footer" + ) + msg = f"Usenet Servers | Page: {int(start / 10)} | State: {state}" + elif key.startswith("nzbser"): + index = int(key.replace("nzbser", "")) + for k in list(Config.USENET_SERVERS[index].keys())[start : 10 + start]: + buttons.data_button(k, f"botset nzbsevar{index} {k}") + if state == "view": + buttons.data_button("Edit", f"botset edit {key}") + else: + buttons.data_button("View", f"botset view {key}") + buttons.data_button("Remove Server", f"botset remser {index}") + buttons.data_button("Back", "botset nzbserver") + buttons.data_button("Close", "botset close") + if len(Config.USENET_SERVERS[index].keys()) > 10: + for x in range(0, len(Config.USENET_SERVERS[index]), 10): + buttons.data_button( + f"{int(x / 10)}", f"botset start {key} {x}", position="footer" + ) + msg = f"Server Keys | Page: {int(start / 10)} | State: {state}" + + button = buttons.build_menu(1) if key is None else buttons.build_menu(2) + return msg, button + + +async def update_buttons(message, key=None, edit_type=None): + msg, button = await get_buttons(key, edit_type) + await edit_message(message, msg, button) + + +@new_task +async def edit_variable(_, message, pre_message, key): + handler_dict[message.chat.id] = False + value = str(message.text) + if value.lower() == "true": + value = True + elif value.lower() == "false": + value = False + if key == "INCOMPLETE_TASK_NOTIFIER" and Config.DATABASE_URL: + await database.trunc_table("tasks") + elif key == "STATUS_UPDATE_INTERVAL": + value = int(value) + if len(task_dict) != 0 and (st := intervals["status"]): + for cid, intvl in list(st.items()): + intvl.cancel() + intervals["status"][cid] = SetInterval( + value, update_status_message, cid + ) + elif key == "TORRENT_TIMEOUT": + await TorrentManager.change_aria2_option("bt-stop-timeout", value) + value = int(value) + elif key == "LEECH_SPLIT_SIZE": + value = min(int(value), TgClient.MAX_SPLIT_SIZE) + elif key == "BASE_URL_PORT": + value = int(value) + if Config.BASE_URL: + await (await create_subprocess_exec("pkill", "-9", "-f", "gunicorn")).wait() + await create_subprocess_shell( + f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{value}" + ) + elif key == "EXCLUDED_EXTENSIONS": + fx = value.split() + excluded_extensions.clear() + excluded_extensions.extend(["aria2", "!qB"]) + for x in fx: + x = x.lstrip(".") + excluded_extensions.append(x.strip().lower()) + elif key == "INCLUDED_EXTENSIONS": + fx = value.split() + included_extensions.clear() + for x in fx: + x = x.lstrip(".") + included_extensions.append(x.strip().lower()) + elif key == "GDRIVE_ID": + if drives_names and drives_names[0] == "Main": + drives_ids[0] = value + else: + drives_ids.insert(0, value) + elif key == "INDEX_URL": + if drives_names and drives_names[0] == "Main": + index_urls[0] = value + else: + index_urls.insert(0, value) + elif key == "AUTHORIZED_CHATS": + aid = value.split() + auth_chats.clear() + for id_ in aid: + chat_id, *thread_ids = id_.split("|") + chat_id = int(chat_id.strip()) + if thread_ids: + thread_ids = list(map(lambda x: int(x.strip()), thread_ids)) + auth_chats[chat_id] = thread_ids + else: + auth_chats[chat_id] = [] + elif key == "SUDO_USERS": + sudo_users.clear() + aid = value.split() + for id_ in aid: + sudo_users.append(int(id_.strip())) + elif value.isdigit(): + value = int(value) + elif value.startswith("[") and value.endswith("]"): + value = eval(value) + elif value.startswith("{") and value.endswith("}"): + value = eval(value) + Config.set(key, value) + await update_buttons(pre_message, "var") + await delete_message(message) + await database.update_config({key: value}) + if key in ["SEARCH_PLUGINS", "SEARCH_API_LINK"]: + await initiate_search_tools() + elif key in ["QUEUE_ALL", "QUEUE_DOWNLOAD", "QUEUE_UPLOAD"]: + await start_from_queued() + elif key in [ + "RCLONE_SERVE_URL", + "RCLONE_SERVE_PORT", + "RCLONE_SERVE_USER", + "RCLONE_SERVE_PASS", + ]: + await rclone_serve_booter() + elif key in ["JD_EMAIL", "JD_PASS"]: + await jdownloader.boot() + elif key == "RSS_DELAY": + add_job() + elif key == "USET_SERVERS": + for s in value: + await sabnzbd_client.set_special_config("servers", s) + + +@new_task +async def edit_aria(_, message, pre_message, key): + handler_dict[message.chat.id] = False + value = str(message.text) + if key == "newkey": + key, value = [x.strip() for x in value.split(":", 1)] + elif value.lower() == "true": + value = "true" + elif value.lower() == "false": + value = "false" + await TorrentManager.change_aria2_option(key, value) + await update_buttons(pre_message, "aria") + await delete_message(message) + await database.update_aria2(key, value) + + +@new_task +async def edit_qbit(_, message, pre_message, key): + handler_dict[message.chat.id] = False + value = str(message.text) + if value.lower() == "true": + value = True + elif value.lower() == "false": + value = False + elif key == "max_ratio": + value = float(value) + elif value.isdigit(): + value = int(value) + await TorrentManager.qbittorrent.app.set_preferences({key: value}) + qbit_options[key] = value + await update_buttons(pre_message, "qbit") + await delete_message(message) + await database.update_qbittorrent(key, value) + + +@new_task +async def edit_nzb(_, message, pre_message, key): + handler_dict[message.chat.id] = False + value = str(message.text) + if value.isdigit(): + value = int(value) + elif value.startswith("[") and value.endswith("]"): + try: + value = ",".join(eval(value)) + except Exception as e: + LOGGER.error(e) + await update_buttons(pre_message, "nzb") + return + res = await sabnzbd_client.set_config("misc", key, value) + nzb_options[key] = res["config"]["misc"][key] + await update_buttons(pre_message, "nzb") + await delete_message(message) + await database.update_nzb_config() + + +@new_task +async def edit_nzb_server(_, message, pre_message, key, index=0): + handler_dict[message.chat.id] = False + value = str(message.text) + if key == "newser": + if value.startswith("{") and value.endswith("}"): + try: + value = eval(value) + except: + await send_message(message, "Invalid dict format!") + await update_buttons(pre_message, "nzbserver") + return + res = await sabnzbd_client.add_server(value) + if not res["config"]["servers"][0]["host"]: + await send_message(message, "Invalid server!") + await update_buttons(pre_message, "nzbserver") + return + Config.USENET_SERVERS.append(value) + await update_buttons(pre_message, "nzbserver") + else: + await send_message(message, "Invalid dict format!") + await update_buttons(pre_message, "nzbserver") + return + else: + if value.isdigit(): + value = int(value) + res = await sabnzbd_client.add_server( + {"name": Config.USENET_SERVERS[index]["name"], key: value} + ) + if res["config"]["servers"][0][key] == "": + await send_message(message, "Invalid value") + return + Config.USENET_SERVERS[index][key] = value + await update_buttons(pre_message, f"nzbser{index}") + await delete_message(message) + await database.update_config({"USENET_SERVERS": Config.USENET_SERVERS}) + + +async def sync_jdownloader(): + async with jd_listener_lock: + if not Config.DATABASE_URL or not jdownloader.is_connected: + return + await jdownloader.device.system.exit_jd() + if await aiopath.exists("cfg.zip"): + await remove("cfg.zip") + await ( + await create_subprocess_exec("7z", "a", "cfg.zip", "/JDownloader/cfg") + ).wait() + await database.update_private_file("cfg.zip") + + +@new_task +async def update_private_file(_, message, pre_message): + handler_dict[message.chat.id] = False + if not message.media and (file_name := str(message.text)): + if await aiopath.isfile(file_name) and file_name != "config.py": + await remove(file_name) + if file_name == "accounts.zip": + if await aiopath.exists("accounts"): + await rmtree("accounts", ignore_errors=True) + if await aiopath.exists("rclone_sa"): + await rmtree("rclone_sa", ignore_errors=True) + Config.USE_SERVICE_ACCOUNTS = False + await database.update_config({"USE_SERVICE_ACCOUNTS": False}) + elif file_name in {".netrc", "netrc"}: + await (await create_subprocess_exec("touch", ".netrc")).wait() + await (await create_subprocess_exec("chmod", "600", ".netrc")).wait() + await (await create_subprocess_exec("cp", ".netrc", "/root/.netrc")).wait() + await delete_message(message) + elif doc := message.document: + file_name = doc.file_name + fpath = f"{getcwd()}/{file_name}" + if await aiopath.exists(fpath): + await remove(fpath) + await message.download(file_name=fpath) + if file_name == "accounts.zip": + if await aiopath.exists("accounts"): + await rmtree("accounts", ignore_errors=True) + if await aiopath.exists("rclone_sa"): + await rmtree("rclone_sa", ignore_errors=True) + await ( + await create_subprocess_exec( + "7z", "x", "-o.", "-aoa", "accounts.zip", "accounts/*.json" + ) + ).wait() + await ( + await create_subprocess_exec("chmod", "-R", "777", "accounts") + ).wait() + elif file_name == "list_drives.txt": + drives_ids.clear() + drives_names.clear() + index_urls.clear() + if Config.GDRIVE_ID: + drives_names.append("Main") + drives_ids.append(Config.GDRIVE_ID) + index_urls.append(Config.INDEX_URL) + async with aiopen("list_drives.txt", "r+") as f: + lines = await f.readlines() + for line in lines: + temp = line.strip().split() + drives_ids.append(temp[1]) + drives_names.append(temp[0].replace("_", " ")) + if len(temp) > 2: + index_urls.append(temp[2]) + else: + index_urls.append("") + elif file_name in [".netrc", "netrc"]: + if file_name == "netrc": + await rename("netrc", ".netrc") + file_name = ".netrc" + await (await create_subprocess_exec("chmod", "600", ".netrc")).wait() + await (await create_subprocess_exec("cp", ".netrc", "/root/.netrc")).wait() + elif file_name == "config.py": + await load_config() + if "@github.com" in Config.UPSTREAM_REPO: + buttons = ButtonMaker() + msg = "Push to UPSTREAM_REPO ?" + buttons.data_button("Yes!", f"botset push {file_name}") + buttons.data_button("No", "botset close") + await send_message(message, msg, buttons.build_menu(2)) + else: + await delete_message(message) + if file_name == "rclone.conf": + await rclone_serve_booter() + await update_buttons(pre_message) + await database.update_private_file(file_name) + + +async def event_handler(client, query, pfunc, rfunc, document=False): + chat_id = query.message.chat.id + handler_dict[chat_id] = True + start_time = time() + + async def event_filter(_, __, event): + user = event.from_user or event.sender_chat + return bool( + user.id == query.from_user.id + and event.chat.id == chat_id + and (event.text or event.document and document) + ) + + handler = client.add_handler( + MessageHandler(pfunc, filters=create(event_filter)), group=-1 + ) + while handler_dict[chat_id]: + await sleep(0.5) + if time() - start_time > 60: + handler_dict[chat_id] = False + await rfunc() + client.remove_handler(*handler) + + +@new_task +async def edit_bot_settings(client, query): + data = query.data.split() + message = query.message + handler_dict[message.chat.id] = False + if data[1] == "close": + await query.answer() + await delete_message(message.reply_to_message) + await delete_message(message) + elif data[1] == "back": + await query.answer() + globals()["start"] = 0 + await update_buttons(message, None) + elif data[1] == "syncjd": + if not Config.JD_EMAIL or not Config.JD_PASS: + await query.answer( + "No Email or Password provided!", + show_alert=True, + ) + return + await query.answer( + "Synchronization Started. JDownloader will get restarted. It takes up to 10 sec!", + show_alert=True, + ) + await sync_jdownloader() + elif data[1] in ["var", "aria", "qbit", "nzb", "nzbserver"] or data[1].startswith( + "nzbser" + ): + if data[1] == "nzbserver": + globals()["start"] = 0 + await query.answer() + await update_buttons(message, data[1]) + elif data[1] == "resetvar": + await query.answer() + expected_type = type(getattr(Config, data[2])) + if expected_type == bool: + value = False + elif expected_type == int: + value = 0 + elif expected_type == str: + value = "" + elif expected_type == list: + value = [] + elif expected_type == dict: + value = {} + if data[2] in DEFAULT_VALUES: + value = DEFAULT_VALUES[data[2]] + if ( + data[2] == "STATUS_UPDATE_INTERVAL" + and len(task_dict) != 0 + and (st := intervals["status"]) + ): + for key, intvl in list(st.items()): + intvl.cancel() + intervals["status"][key] = SetInterval( + value, update_status_message, key + ) + elif data[2] == "EXCLUDED_EXTENSIONS": + excluded_extensions.clear() + excluded_extensions.extend(["aria2", "!qB"]) + elif data[2] == "INCLUDED_EXTENSIONS": + included_extensions.clear() + elif data[2] == "TORRENT_TIMEOUT": + await TorrentManager.change_aria2_option("bt-stop-timeout", "0") + await database.update_aria2("bt-stop-timeout", "0") + elif data[2] == "BASE_URL": + await (await create_subprocess_exec("pkill", "-9", "-f", "gunicorn")).wait() + elif data[2] == "BASE_URL_PORT": + value = 80 + if Config.BASE_URL: + await ( + await create_subprocess_exec("pkill", "-9", "-f", "gunicorn") + ).wait() + await create_subprocess_shell( + f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{value}" + ) + elif data[2] == "GDRIVE_ID": + if drives_names and drives_names[0] == "Main": + drives_names.pop(0) + drives_ids.pop(0) + index_urls.pop(0) + elif data[2] == "INDEX_URL": + if drives_names and drives_names[0] == "Main": + index_urls[0] = "" + elif data[2] == "INCOMPLETE_TASK_NOTIFIER": + await database.trunc_table("tasks") + elif data[2] in ["JD_EMAIL", "JD_PASS"]: + await create_subprocess_exec("pkill", "-9", "-f", "java") + elif data[2] == "USENET_SERVERS": + for s in Config.USENET_SERVERS: + await sabnzbd_client.delete_config("servers", s["name"]) + elif data[2] == "AUTHORIZED_CHATS": + auth_chats.clear() + elif data[2] == "SUDO_USERS": + sudo_users.clear() + Config.set(data[2], value) + await update_buttons(message, "var") + if data[2] == "DATABASE_URL": + await database.disconnect() + await database.update_config({data[2]: value}) + if data[2] in ["SEARCH_PLUGINS", "SEARCH_API_LINK"]: + await initiate_search_tools() + elif data[2] in ["QUEUE_ALL", "QUEUE_DOWNLOAD", "QUEUE_UPLOAD"]: + await start_from_queued() + elif data[2] in [ + "RCLONE_SERVE_URL", + "RCLONE_SERVE_PORT", + "RCLONE_SERVE_USER", + "RCLONE_SERVE_PASS", + ]: + await rclone_serve_booter() + elif data[1] == "resetnzb": + await query.answer() + res = await sabnzbd_client.set_config_default(data[2]) + nzb_options[data[2]] = res["config"]["misc"][data[2]] + await update_buttons(message, "nzb") + await database.update_nzb_config() + elif data[1] == "syncnzb": + await query.answer( + "Synchronization Started. It takes up to 2 sec!", show_alert=True + ) + nzb_options.clear() + await update_nzb_options() + await database.update_nzb_config() + elif data[1] == "syncqbit": + await query.answer( + "Synchronization Started. It takes up to 2 sec!", show_alert=True + ) + qbit_options.clear() + await update_qb_options() + await database.save_qbit_settings() + elif data[1] == "emptyaria": + await query.answer() + aria2_options[data[2]] = "" + await update_buttons(message, "aria") + await TorrentManager.change_aria2_option(data[2], "") + await database.update_aria2(data[2], "") + elif data[1] == "emptyqbit": + await query.answer() + await TorrentManager.qbittorrent.app.set_preferences({data[2]: value}) + qbit_options[data[2]] = "" + await update_buttons(message, "qbit") + await database.update_qbittorrent(data[2], "") + elif data[1] == "emptynzb": + await query.answer() + res = await sabnzbd_client.set_config("misc", data[2], "") + nzb_options[data[2]] = res["config"]["misc"][data[2]] + await update_buttons(message, "nzb") + await database.update_nzb_config() + elif data[1] == "remser": + index = int(data[2]) + await sabnzbd_client.delete_config( + "servers", Config.USENET_SERVERS[index]["name"] + ) + del Config.USENET_SERVERS[index] + await update_buttons(message, "nzbserver") + await database.update_config({"USENET_SERVERS": Config.USENET_SERVERS}) + elif data[1] == "private": + await query.answer() + await update_buttons(message, data[1]) + pfunc = partial(update_private_file, pre_message=message) + rfunc = partial(update_buttons, message) + await event_handler(client, query, pfunc, rfunc, True) + elif data[1] == "botvar" and state == "edit": + await query.answer() + await update_buttons(message, data[2], data[1]) + pfunc = partial(edit_variable, pre_message=message, key=data[2]) + rfunc = partial(update_buttons, message, "var") + await event_handler(client, query, pfunc, rfunc) + elif data[1] == "botvar" and state == "view": + value = f"{Config.get(data[2])}" + if len(value) > 200: + await query.answer() + with BytesIO(str.encode(value)) as out_file: + out_file.name = f"{data[2]}.txt" + await send_file(message, out_file) + return + elif value == "": + value = None + await query.answer(f"{value}", show_alert=True) + elif data[1] == "ariavar" and (state == "edit" or data[2] == "newkey"): + await query.answer() + await update_buttons(message, data[2], data[1]) + pfunc = partial(edit_aria, pre_message=message, key=data[2]) + rfunc = partial(update_buttons, message, "aria") + await event_handler(client, query, pfunc, rfunc) + elif data[1] == "ariavar" and state == "view": + value = f"{aria2_options[data[2]]}" + if len(value) > 200: + await query.answer() + with BytesIO(str.encode(value)) as out_file: + out_file.name = f"{data[2]}.txt" + await send_file(message, out_file) + return + elif value == "": + value = None + await query.answer(f"{value}", show_alert=True) + elif data[1] == "qbitvar" and state == "edit": + await query.answer() + await update_buttons(message, data[2], data[1]) + pfunc = partial(edit_qbit, pre_message=message, key=data[2]) + rfunc = partial(update_buttons, message, "qbit") + await event_handler(client, query, pfunc, rfunc) + elif data[1] == "qbitvar" and state == "view": + value = f"{qbit_options[data[2]]}" + if len(value) > 200: + await query.answer() + with BytesIO(str.encode(value)) as out_file: + out_file.name = f"{data[2]}.txt" + await send_file(message, out_file) + return + elif value == "": + value = None + await query.answer(f"{value}", show_alert=True) + elif data[1] == "nzbvar" and state == "edit": + await query.answer() + await update_buttons(message, data[2], data[1]) + pfunc = partial(edit_nzb, pre_message=message, key=data[2]) + rfunc = partial(update_buttons, message, "nzb") + await event_handler(client, query, pfunc, rfunc) + elif data[1] == "nzbvar" and state == "view": + value = f"{nzb_options[data[2]]}" + if len(value) > 200: + await query.answer() + with BytesIO(str.encode(value)) as out_file: + out_file.name = f"{data[2]}.txt" + await send_file(message, out_file) + return + elif value == "": + value = None + await query.answer(f"{value}", show_alert=True) + elif data[1] == "emptyserkey": + await query.answer() + await update_buttons(message, f"nzbser{data[2]}") + index = int(data[2]) + res = await sabnzbd_client.add_server( + {"name": Config.USENET_SERVERS[index]["name"], data[3]: ""} + ) + Config.USENET_SERVERS[index][data[3]] = res["config"]["servers"][0][data[3]] + await database.update_config({"USENET_SERVERS": Config.USENET_SERVERS}) + elif data[1].startswith("nzbsevar") and (state == "edit" or data[2] == "newser"): + index = 0 if data[2] == "newser" else int(data[1].replace("nzbsevar", "")) + await query.answer() + await update_buttons(message, data[2], data[1]) + pfunc = partial(edit_nzb_server, pre_message=message, key=data[2], index=index) + rfunc = partial( + update_buttons, + message, + f"nzbser{index}" if data[2] != "newser" else "nzbserver", + ) + await event_handler(client, query, pfunc, rfunc) + elif data[1].startswith("nzbsevar") and state == "view": + index = int(data[1].replace("nzbsevar", "")) + value = f"{Config.USENET_SERVERS[index][data[2]]}" + if len(value) > 200: + await query.answer() + with BytesIO(str.encode(value)) as out_file: + out_file.name = f"{data[2]}.txt" + await send_file(message, out_file) + return + elif value == "": + value = None + await query.answer(f"{value}", show_alert=True) + elif data[1] == "edit": + await query.answer() + globals()["state"] = "edit" + await update_buttons(message, data[2]) + elif data[1] == "view": + await query.answer() + globals()["state"] = "view" + await update_buttons(message, data[2]) + elif data[1] == "start": + await query.answer() + if start != int(data[3]): + globals()["start"] = int(data[3]) + await update_buttons(message, data[2]) + elif data[1] == "push": + await query.answer() + filename = data[2].rsplit(".zip", 1)[0] + if await aiopath.exists(filename): + await ( + await create_subprocess_shell( + f"git add -f {filename} \ + && git commit -sm botsettings -q \ + && git push origin {Config.UPSTREAM_BRANCH} -qf" + ) + ).wait() + else: + await ( + await create_subprocess_shell( + f"git rm -r --cached {filename} \ + && git commit -sm botsettings -q \ + && git push origin {Config.UPSTREAM_BRANCH} -qf" + ) + ).wait() + await delete_message(message.reply_to_message) + await delete_message(message) + + +@new_task +async def send_bot_settings(_, message): + handler_dict[message.chat.id] = False + msg, button = await get_buttons() + globals()["start"] = 0 + await send_message(message, msg, button) + + +async def load_config(): + Config.load() + drives_ids.clear() + drives_names.clear() + index_urls.clear() + await update_variables() + + if not await aiopath.exists("accounts"): + Config.USE_SERVICE_ACCOUNTS = False + + if len(task_dict) != 0 and (st := intervals["status"]): + for key, intvl in list(st.items()): + intvl.cancel() + intervals["status"][key] = SetInterval( + Config.STATUS_UPDATE_INTERVAL, update_status_message, key + ) + + if Config.TORRENT_TIMEOUT: + await TorrentManager.change_aria2_option( + "bt-stop-timeout", f"{Config.TORRENT_TIMEOUT}" + ) + await database.update_aria2("bt-stop-timeout", f"{Config.TORRENT_TIMEOUT}") + + if not Config.INCOMPLETE_TASK_NOTIFIER: + await database.trunc_table("tasks") + + await (await create_subprocess_exec("pkill", "-9", "-f", "gunicorn")).wait() + if Config.BASE_URL: + await create_subprocess_shell( + f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{Config.BASE_URL_PORT}" + ) + + if Config.DATABASE_URL: + await database.connect() + config_dict = Config.get_all() + await database.update_config(config_dict) + else: + await database.disconnect() + await gather(initiate_search_tools(), start_from_queued(), rclone_serve_booter()) + add_job() diff --git a/bot/modules/cancel_task.py b/bot/modules/cancel_task.py new file mode 100644 index 0000000000000000000000000000000000000000..337ecf0f837910f01c90e57f771623f7e24819a8 --- /dev/null +++ b/bot/modules/cancel_task.py @@ -0,0 +1,179 @@ +from asyncio import sleep + +from .. import task_dict, task_dict_lock, user_data, multi_tags +from ..core.config_manager import Config +from ..helper.ext_utils.bot_utils import new_task +from ..helper.ext_utils.status_utils import ( + get_task_by_gid, + get_all_tasks, + MirrorStatus, +) +from ..helper.telegram_helper import button_build +from ..helper.telegram_helper.bot_commands import BotCommands +from ..helper.telegram_helper.filters import CustomFilters +from ..helper.telegram_helper.message_utils import ( + send_message, + auto_delete_message, + delete_message, + edit_message, +) + + +@new_task +async def cancel(_, message): + user_id = message.from_user.id if message.from_user else message.sender_chat.id + msg = message.text.split() + if len(msg) > 1: + gid = msg[1] + if len(gid) == 4: + multi_tags.discard(gid) + return + else: + task = await get_task_by_gid(gid) + if task is None: + await send_message(message, f"GID: {gid} Not Found.") + return + elif reply_to_id := message.reply_to_message_id: + async with task_dict_lock: + task = task_dict.get(reply_to_id) + if task is None: + await send_message(message, "This is not an active task!") + return + elif len(msg) == 1: + msg = ( + "Reply to an active Command message which was used to start the download" + f" or send /{BotCommands.CancelTaskCommand[0]} GID to cancel it!" + ) + await send_message(message, msg) + return + if ( + Config.OWNER_ID != user_id + and task.listener.user_id != user_id + and (user_id not in user_data or not user_data[user_id].get("SUDO")) + ): + await send_message(message, "This task is not for you!") + return + obj = task.task() + await obj.cancel_task() + + +@new_task +async def cancel_multi(_, query): + data = query.data.split() + user_id = query.from_user.id + if user_id != int(data[1]) and not await CustomFilters.sudo("", query): + await query.answer("Not Yours!", show_alert=True) + return + tag = int(data[2]) + if tag in multi_tags: + multi_tags.discard(int(data[2])) + msg = "Stopped!" + else: + msg = "Already Stopped/Finished!" + await query.answer(msg, show_alert=True) + await delete_message(query.message) + + +async def cancel_all(status, user_id): + matches = await get_all_tasks(status.strip(), user_id) + if not matches: + return False + for task in matches: + obj = task.task() + await obj.cancel_task() + await sleep(2) + return True + + +def create_cancel_buttons(is_sudo, user_id=""): + buttons = button_build.ButtonMaker() + buttons.data_button( + "Downloading", f"canall ms {MirrorStatus.STATUS_DOWNLOAD} {user_id}" + ) + buttons.data_button( + "Uploading", f"canall ms {MirrorStatus.STATUS_UPLOAD} {user_id}" + ) + buttons.data_button("Seeding", f"canall ms {MirrorStatus.STATUS_SEED} {user_id}") + buttons.data_button("Spltting", f"canall ms {MirrorStatus.STATUS_SPLIT} {user_id}") + buttons.data_button("Cloning", f"canall ms {MirrorStatus.STATUS_CLONE} {user_id}") + buttons.data_button( + "Extracting", f"canall ms {MirrorStatus.STATUS_EXTRACT} {user_id}" + ) + buttons.data_button( + "Archiving", f"canall ms {MirrorStatus.STATUS_ARCHIVE} {user_id}" + ) + buttons.data_button( + "QueuedDl", f"canall ms {MirrorStatus.STATUS_QUEUEDL} {user_id}" + ) + buttons.data_button( + "QueuedUp", f"canall ms {MirrorStatus.STATUS_QUEUEUP} {user_id}" + ) + buttons.data_button( + "SampleVideo", f"canall ms {MirrorStatus.STATUS_SAMVID} {user_id}" + ) + buttons.data_button( + "ConvertMedia", f"canall ms {MirrorStatus.STATUS_CONVERT} {user_id}" + ) + buttons.data_button("FFmpeg", f"canall ms {MirrorStatus.STATUS_FFMPEG} {user_id}") + buttons.data_button("Paused", f"canall ms {MirrorStatus.STATUS_PAUSED} {user_id}") + buttons.data_button("All", f"canall ms All {user_id}") + if is_sudo: + if user_id: + buttons.data_button("All Added Tasks", f"canall bot ms {user_id}") + else: + buttons.data_button("My Tasks", f"canall user ms {user_id}") + buttons.data_button("Close", f"canall close ms {user_id}") + return buttons.build_menu(2) + + +@new_task +async def cancel_all_buttons(_, message): + async with task_dict_lock: + count = len(task_dict) + if count == 0: + await send_message(message, "No active tasks!") + return + is_sudo = await CustomFilters.sudo("", message) + button = create_cancel_buttons(is_sudo, message.from_user.id) + can_msg = await send_message(message, "Choose tasks to cancel!", button) + await auto_delete_message(message, can_msg) + + +@new_task +async def cancel_all_update(_, query): + data = query.data.split() + message = query.message + reply_to = message.reply_to_message + user_id = int(data[3]) if len(data) > 3 else "" + is_sudo = await CustomFilters.sudo("", query) + if not is_sudo and user_id and user_id != query.from_user.id: + await query.answer("Not Yours!", show_alert=True) + else: + await query.answer() + if data[1] == "close": + await delete_message(reply_to) + await delete_message(message) + elif data[1] == "back": + button = create_cancel_buttons(is_sudo, user_id) + await edit_message(message, "Choose tasks to cancel!", button) + elif data[1] == "bot": + button = create_cancel_buttons(is_sudo, "") + await edit_message(message, "Choose tasks to cancel!", button) + elif data[1] == "user": + button = create_cancel_buttons(is_sudo, query.from_user.id) + await edit_message(message, "Choose tasks to cancel!", button) + elif data[1] == "ms": + buttons = button_build.ButtonMaker() + buttons.data_button("Yes!", f"canall {data[2]} confirm {user_id}") + buttons.data_button("Back", f"canall back confirm {user_id}") + buttons.data_button("Close", f"canall close confirm {user_id}") + button = buttons.build_menu(2) + await edit_message( + message, f"Are you sure you want to cancel all {data[2]} tasks", button + ) + else: + button = create_cancel_buttons(is_sudo, user_id) + await edit_message(message, "Choose tasks to cancel.", button) + res = await cancel_all(data[1], user_id) + if not res: + await send_message(reply_to, f"No matching tasks for {data[1]}!") diff --git a/bot/modules/chat_permission.py b/bot/modules/chat_permission.py new file mode 100644 index 0000000000000000000000000000000000000000..3247c03a894ead3fa9a2d79564aade6eaa625ec6 --- /dev/null +++ b/bot/modules/chat_permission.py @@ -0,0 +1,130 @@ +from .. import user_data +from ..helper.ext_utils.bot_utils import update_user_ldata, new_task +from ..helper.ext_utils.db_handler import database +from ..helper.telegram_helper.message_utils import send_message + + +@new_task +async def authorize(_, message): + msg = message.text.split() + thread_id = None + try: + if len(msg) > 1: + if "|" in msg: + chat_id, thread_id = list(map(int, msg[1].split("|"))) + else: + chat_id = int(msg[1].strip()) + elif ( + reply_to := message.reply_to_message + ) and reply_to.id != message.message_thread_id: + chat_id = ( + reply_to.from_user.id if reply_to.from_user else reply_to.sender_chat.id + ) + else: + if message.topic_message: + thread_id = message.message_thread_id + chat_id = message.chat.id + if chat_id in user_data and user_data[chat_id].get("AUTH"): + if ( + thread_id is not None + and thread_id in user_data[chat_id].get("thread_ids", []) + or thread_id is None + ): + msg = "Already Authorized!" + else: + if "thread_ids" in user_data[chat_id]: + user_data[chat_id]["thread_ids"].append(thread_id) + else: + user_data[chat_id]["thread_ids"] = [thread_id] + msg = "Authorized" + else: + update_user_ldata(chat_id, "AUTH", True) + if thread_id is not None: + update_user_ldata(chat_id, "thread_ids", [thread_id]) + await database.update_user_data(chat_id) + msg = "Authorized" + except Exception as e: + msg = f"Error: {e}" + await send_message(message, msg) + + +@new_task +async def unauthorize(_, message): + msg = message.text.split() + thread_id = None + try: + if len(msg) > 1: + if "|" in msg: + chat_id, thread_id = list(map(int, msg[1].split("|"))) + else: + chat_id = int(msg[1].strip()) + elif ( + reply_to := message.reply_to_message + ) and reply_to.id != message.message_thread_id: + chat_id = ( + reply_to.from_user.id if reply_to.from_user else reply_to.sender_chat.id + ) + else: + if message.topic_message: + thread_id = message.message_thread_id + chat_id = message.chat.id + if chat_id in user_data and user_data[chat_id].get("AUTH"): + if thread_id is not None and thread_id in user_data[chat_id].get( + "thread_ids", [] + ): + user_data[chat_id]["thread_ids"].remove(thread_id) + else: + update_user_ldata(chat_id, "AUTH", False) + await database.update_user_data(chat_id) + msg = "Unauthorized" + else: + msg = "Already Unauthorized! Authorized Chats added from config must be removed from config." + except Exception as e: + msg = f"Error: {e}" + await send_message(message, msg) + + +@new_task +async def add_sudo(_, message): + id_ = "" + msg = message.text.split() + try: + if len(msg) > 1: + id_ = int(msg[1].strip()) + elif reply_to := message.reply_to_message: + id_ = reply_to.from_user.id if reply_to.from_user else reply_to.sender_chat.id + if id_: + if id_ in user_data and user_data[id_].get("SUDO"): + msg = "Already Sudo!" + else: + update_user_ldata(id_, "SUDO", True) + await database.update_user_data(id_) + msg = "Promoted as Sudo" + else: + msg = "Give ID or Reply To message of whom you want to Promote." + except Exception as e: + msg = f"Error: {e}" + await send_message(message, msg) + + +@new_task +async def remove_sudo(_, message): + id_ = "" + msg = message.text.split() + try: + if len(msg) > 1: + id_ = int(msg[1].strip()) + elif reply_to := message.reply_to_message: + id_ = reply_to.from_user.id if reply_to.from_user else reply_to.sender_chat.id + if id_: + if id_ in user_data and user_data[id_].get("SUDO"): + update_user_ldata(id_, "SUDO", False) + await database.update_user_data(id_) + msg = "Demoted" + else: + msg = "Already Not Sudo! Sudo users added from config must be removed from config." + else: + msg = "Give ID or Reply To message of whom you want to remove from Sudo" + except Exception as e: + msg = f"Error: {e}" + await send_message(message, msg) diff --git a/bot/modules/clone.py b/bot/modules/clone.py new file mode 100644 index 0000000000000000000000000000000000000000..27a48216ec0f63487da70bcb07fd0c67cb31170f --- /dev/null +++ b/bot/modules/clone.py @@ -0,0 +1,296 @@ +from asyncio import gather +from json import loads +from secrets import token_urlsafe +from aiofiles.os import remove + +from .. import LOGGER, task_dict, task_dict_lock, bot_loop +from ..helper.ext_utils.bot_utils import ( + sync_to_async, + cmd_exec, + arg_parser, + COMMAND_USAGE, +) +from ..helper.ext_utils.exceptions import DirectDownloadLinkException +from ..helper.ext_utils.links_utils import ( + is_gdrive_link, + is_share_link, + is_rclone_path, + is_gdrive_id, +) +from ..helper.ext_utils.task_manager import stop_duplicate_check +from ..helper.listeners.task_listener import TaskListener +from ..helper.mirror_leech_utils.download_utils.direct_link_generator import ( + direct_link_generator, +) +from ..helper.mirror_leech_utils.gdrive_utils.clone import GoogleDriveClone +from ..helper.mirror_leech_utils.gdrive_utils.count import GoogleDriveCount +from ..helper.mirror_leech_utils.rclone_utils.transfer import RcloneTransferHelper +from ..helper.mirror_leech_utils.status_utils.gdrive_status import GoogleDriveStatus +from ..helper.mirror_leech_utils.status_utils.rclone_status import RcloneStatus +from ..helper.telegram_helper.message_utils import ( + send_message, + delete_message, + send_status_message, +) + + +class Clone(TaskListener): + def __init__( + self, + client, + message, + _=None, + __=None, + ___=None, + ____=None, + _____=None, + bulk=None, + multi_tag=None, + options="", + ): + if bulk is None: + bulk = [] + self.message = message + self.client = client + self.multi_tag = multi_tag + self.options = options + self.same_dir = {} + self.bulk = bulk + super().__init__() + self.is_clone = True + + async def new_event(self): + text = self.message.text.split("\n") + input_list = text[0].split(" ") + + args = { + "link": "", + "-i": 0, + "-b": False, + "-n": "", + "-up": "", + "-rcf": "", + "-sync": False, + } + + arg_parser(input_list[1:], args) + + try: + self.multi = int(args["-i"]) + except: + self.multi = 0 + + self.up_dest = args["-up"] + self.rc_flags = args["-rcf"] + self.link = args["link"] + self.name = args["-n"] + + is_bulk = args["-b"] + sync = args["-sync"] + bulk_start = 0 + bulk_end = 0 + + if not isinstance(is_bulk, bool): + dargs = is_bulk.split(":") + bulk_start = dargs[0] or 0 + if len(dargs) == 2: + bulk_end = dargs[1] or 0 + is_bulk = True + + if is_bulk: + await self.init_bulk(input_list, bulk_start, bulk_end, Clone) + return + + await self.get_tag(text) + + if not self.link and (reply_to := self.message.reply_to_message): + self.link = reply_to.text.split("\n", 1)[0].strip() + + await self.run_multi(input_list, Clone) + + if len(self.link) == 0: + await send_message( + self.message, COMMAND_USAGE["clone"][0], COMMAND_USAGE["clone"][1] + ) + return + LOGGER.info(self.link) + try: + await self.before_start() + except Exception as e: + await send_message(self.message, e) + return + await self._proceed_to_clone(sync) + + async def _proceed_to_clone(self, sync): + if is_share_link(self.link): + try: + self.link = await sync_to_async(direct_link_generator, self.link) + LOGGER.info(f"Generated link: {self.link}") + except DirectDownloadLinkException as e: + LOGGER.error(str(e)) + if str(e).startswith("ERROR:"): + await send_message(self.message, str(e)) + return + if is_gdrive_link(self.link) or is_gdrive_id(self.link): + self.name, mime_type, self.size, files, _ = await sync_to_async( + GoogleDriveCount().count, self.link, self.user_id + ) + if mime_type is None: + await send_message(self.message, self.name) + return + msg, button = await stop_duplicate_check(self) + if msg: + await send_message(self.message, msg, button) + return + await self.on_download_start() + LOGGER.info(f"Clone Started: Name: {self.name} - Source: {self.link}") + drive = GoogleDriveClone(self) + if files <= 10: + msg = await send_message( + self.message, f"Cloning: {self.link}" + ) + else: + msg = "" + gid = token_urlsafe(12) + async with task_dict_lock: + task_dict[self.mid] = GoogleDriveStatus(self, drive, gid, "cl") + if self.multi <= 1: + await send_status_message(self.message) + flink, mime_type, files, folders, dir_id = await sync_to_async(drive.clone) + if msg: + await delete_message(msg) + if not flink: + return + await self.on_upload_complete( + flink, files, folders, mime_type, dir_id=dir_id + ) + LOGGER.info(f"Cloning Done: {self.name}") + elif is_rclone_path(self.link): + if self.link.startswith("mrcc:"): + self.link = self.link.replace("mrcc:", "", 1) + self.up_dest = self.up_dest.replace("mrcc:", "", 1) + config_path = f"rclone/{self.user_id}.conf" + else: + config_path = "rclone.conf" + + remote, src_path = self.link.split(":", 1) + self.link = src_path.strip("/") + if self.link.startswith("rclone_select"): + mime_type = "Folder" + src_path = "" + if not self.name: + self.name = self.link + else: + src_path = self.link + cmd = [ + "rclone", + "lsjson", + "--fast-list", + "--stat", + "--no-modtime", + "--config", + config_path, + f"{remote}:{src_path}", + ] + res = await cmd_exec(cmd) + if res[2] != 0: + if res[2] != -9: + msg = f"Error: While getting rclone stat. Path: {remote}:{src_path}. Stderr: {res[1][:4000]}" + await send_message(self.message, msg) + return + rstat = loads(res[0]) + if rstat["IsDir"]: + if not self.name: + self.name = src_path.rsplit("/", 1)[-1] if src_path else remote + self.up_dest += ( + self.name if self.up_dest.endswith(":") else f"/{self.name}" + ) + mime_type = "Folder" + else: + if not self.name: + self.name = src_path.rsplit("/", 1)[-1] + mime_type = rstat["MimeType"] + + await self.on_download_start() + + RCTransfer = RcloneTransferHelper(self) + LOGGER.info( + f"Clone Started: Name: {self.name} - Source: {self.link} - Destination: {self.up_dest}" + ) + gid = token_urlsafe(12) + async with task_dict_lock: + task_dict[self.mid] = RcloneStatus(self, RCTransfer, gid, "cl") + if self.multi <= 1: + await send_status_message(self.message) + method = "sync" if sync else "copy" + flink, destination = await RCTransfer.clone( + config_path, + remote, + src_path, + mime_type, + method, + ) + if self.link.startswith("rclone_select"): + await remove(self.link) + if not destination: + return + LOGGER.info(f"Cloning Done: {self.name}") + cmd1 = [ + "rclone", + "lsf", + "--fast-list", + "-R", + "--files-only", + "--config", + config_path, + destination, + ] + cmd2 = [ + "rclone", + "lsf", + "--fast-list", + "-R", + "--dirs-only", + "--config", + config_path, + destination, + ] + cmd3 = [ + "rclone", + "size", + "--fast-list", + "--json", + "--config", + config_path, + destination, + ] + res1, res2, res3 = await gather( + cmd_exec(cmd1), + cmd_exec(cmd2), + cmd_exec(cmd3), + ) + if res1[2] != 0 or res2[2] != 0 or res3[2] != 0: + if res1[2] == -9: + return + files = None + folders = None + self.size = 0 + error = res1[1] or res2[1] or res3[1] + msg = f"Error: While getting rclone stat. Path: {destination}. Stderr: {error[:4000]}" + await self.on_upload_error(msg) + else: + files = len(res1[0].split("\n")) + folders = len(res2[0].strip().split("\n")) if res2[0] else 0 + rsize = loads(res3[0]) + self.size = rsize["bytes"] + await self.on_upload_complete( + flink, files, folders, mime_type, destination + ) + else: + await send_message( + self.message, COMMAND_USAGE["clone"][0], COMMAND_USAGE["clone"][1] + ) + + +async def clone_node(client, message): + bot_loop.create_task(Clone(client, message).new_event()) diff --git a/bot/modules/exec.py b/bot/modules/exec.py new file mode 100644 index 0000000000000000000000000000000000000000..3b2c1992d040dcc398b1450f02692798252ebfb6 --- /dev/null +++ b/bot/modules/exec.py @@ -0,0 +1,114 @@ +from aiofiles import open as aiopen +from contextlib import redirect_stdout +from io import StringIO, BytesIO +from os import path as ospath, getcwd, chdir +from textwrap import indent +from traceback import format_exc + +from .. import LOGGER +from ..core.telegram_manager import TgClient +from ..helper.ext_utils.bot_utils import sync_to_async, new_task +from ..helper.telegram_helper.message_utils import send_file, send_message + +namespaces = {} + + +def namespace_of(message): + if message.chat.id not in namespaces: + namespaces[message.chat.id] = { + "__builtins__": globals()["__builtins__"], + "bot": TgClient.bot, + "message": message, + "user": message.from_user or message.sender_chat, + "chat": message.chat, + } + + return namespaces[message.chat.id] + + +def log_input(message): + LOGGER.info( + f"IN: {message.text} (user={message.from_user.id if message.from_user else message.sender_chat.id}, chat={message.chat.id})" + ) + + +async def send(msg, message): + if len(str(msg)) > 2000: + with BytesIO(str.encode(msg)) as out_file: + out_file.name = "output.txt" + await send_file(message, out_file) + else: + LOGGER.info(f"OUT: '{msg}'") + await send_message(message, f"{msg}") + + +@new_task +async def aioexecute(_, message): + await send(await do("aexec", message), message) + + +@new_task +async def execute(_, message): + await send(await do("exec", message), message) + + +def cleanup_code(code): + if code.startswith("```") and code.endswith("```"): + return "\n".join(code.split("\n")[1:-1]) + return code.strip("` \n") + + +async def do(func, message): + log_input(message) + content = message.text.split(maxsplit=1)[-1] + body = cleanup_code(content) + env = namespace_of(message) + + chdir(getcwd()) + async with aiopen(ospath.join(getcwd(), "bot/modules/temp.txt"), "w") as temp: + await temp.write(body) + + stdout = StringIO() + + try: + if func == "exec": + exec(f"def func():\n{indent(body, ' ')}", env) + else: + exec(f"async def func():\n{indent(body, ' ')}", env) + except Exception as e: + return f"{e.__class__.__name__}: {e}" + + rfunc = env["func"] + + try: + with redirect_stdout(stdout): + func_return = ( + await sync_to_async(rfunc) if func == "exec" else await rfunc() + ) + except: + value = stdout.getvalue() + return f"{value}{format_exc()}" + else: + value = stdout.getvalue() + result = None + if func_return is None: + if value: + result = f"{value}" + else: + try: + result = f"{repr(await sync_to_async(eval, body, env))}" + except: + pass + else: + result = f"{value}{func_return}" + if result: + return result + + +@new_task +async def clear(_, message): + log_input(message) + global namespaces + if message.chat.id in namespaces: + del namespaces[message.chat.id] + await send("Locals Cleared.", message) diff --git a/bot/modules/file_selector.py b/bot/modules/file_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..cd903b8c3226392c09e12401816a64b1ba4bc09a --- /dev/null +++ b/bot/modules/file_selector.py @@ -0,0 +1,158 @@ +from aiofiles.os import remove, path as aiopath +from asyncio import iscoroutinefunction + +from .. import ( + task_dict, + task_dict_lock, + user_data, + LOGGER, + sabnzbd_client, +) +from ..core.config_manager import Config +from ..core.torrent_manager import TorrentManager +from ..helper.ext_utils.bot_utils import ( + bt_selection_buttons, + new_task, +) +from ..helper.ext_utils.status_utils import get_task_by_gid, MirrorStatus +from ..helper.telegram_helper.message_utils import ( + send_message, + send_status_message, + delete_message, +) + + +@new_task +async def select(_, message): + if not Config.BASE_URL: + await send_message(message, "Base URL not defined!") + return + user_id = message.from_user.id + msg = message.text.split() + if len(msg) > 1: + gid = msg[1] + task = await get_task_by_gid(gid) + if task is None: + await send_message(message, f"GID: {gid} Not Found.") + return + elif reply_to_id := message.reply_to_message_id: + async with task_dict_lock: + task = task_dict.get(reply_to_id) + if task is None: + await send_message(message, "This is not an active task!") + return + elif len(msg) == 1: + msg = ( + "Reply to an active /cmd which was used to start the download or add gid along with cmd\n\n" + + "This command mainly for selection incase you decided to select files from already added torrent/nzb. " + + "But you can always use /cmd with arg `s` to select files before download start." + ) + await send_message(message, msg) + return + if ( + Config.OWNER_ID != user_id + and task.listener.user_id != user_id + and (user_id not in user_data or not user_data[user_id].get("SUDO")) + ): + await send_message(message, "This task is not for you!") + return + if not iscoroutinefunction(task.status): + await send_message(message, "The task have finished the download stage!") + return + if await task.status() not in [ + MirrorStatus.STATUS_DOWNLOAD, + MirrorStatus.STATUS_PAUSED, + MirrorStatus.STATUS_QUEUEDL, + ]: + await send_message( + message, + "Task should be in download or pause (incase message deleted by wrong) or queued status (incase you have used torrent or nzb file)!", + ) + return + if task.name().startswith("[METADATA]") or task.name().startswith("Trying"): + await send_message(message, "Try after downloading metadata finished!") + return + + try: + if not task.queued: + await task.update() + id_ = task.gid() + if task.listener.is_nzb: + await sabnzbd_client.pause_job(id_) + elif task.listener.is_qbit: + id_ = task.hash() + await TorrentManager.qbittorrent.torrents.stop([id_]) + else: + try: + await TorrentManager.aria2.forcePause(id_) + except Exception as e: + LOGGER.error( + f"{e} Error in pause, this mostly happens after abuse aria2" + ) + task.listener.select = True + except: + await send_message(message, "This is not a bittorrent or sabnzbd task!") + return + + SBUTTONS = bt_selection_buttons(id_) + msg = "Your download paused. Choose files then press Done Selecting button to resume downloading." + await send_message(message, msg, SBUTTONS) + + +@new_task +async def confirm_selection(_, query): + user_id = query.from_user.id + data = query.data.split() + message = query.message + task = await get_task_by_gid(data[2]) + if task is None: + await query.answer("This task has been cancelled!", show_alert=True) + await delete_message(message) + return + if user_id != task.listener.user_id: + await query.answer("This task is not for you!", show_alert=True) + elif data[1] == "pin": + await query.answer(data[3], show_alert=True) + elif data[1] == "done": + await query.answer() + id_ = data[3] + if hasattr(task, "seeding"): + if task.listener.is_qbit: + tor_info = ( + await TorrentManager.qbittorrent.torrents.info(hashes=[id_]) + )[0] + path = tor_info.content_path.rsplit("/", 1)[0] + res = await TorrentManager.qbittorrent.torrents.files(id_) + for f in res: + if f.priority == 0: + f_paths = [f"{path}/{f.name}", f"{path}/{f.name}.!qB"] + for f_path in f_paths: + if await aiopath.exists(f_path): + try: + await remove(f_path) + except: + pass + if not task.queued: + await TorrentManager.qbittorrent.torrents.start([id_]) + else: + res = await TorrentManager.aria2.getFiles(id_) + for f in res: + if f["selected"] == "false" and await aiopath.exists(f["path"]): + try: + await remove(f["path"]) + except: + pass + if not task.queued: + try: + await TorrentManager.aria2.unpause(id_) + except Exception as e: + LOGGER.error( + f"{e} Error in resume, this mostly happens after abuse aria2. Try to use select cmd again!" + ) + elif task.listener.is_nzb: + await sabnzbd_client.resume_job(id_) + await send_status_message(message) + await delete_message(message) + else: + await delete_message(message) + await task.cancel_task() diff --git a/bot/modules/force_start.py b/bot/modules/force_start.py new file mode 100644 index 0000000000000000000000000000000000000000..8a90c475b093f1e33a553c7b3d1c28953f3f83b0 --- /dev/null +++ b/bot/modules/force_start.py @@ -0,0 +1,83 @@ +from .. import ( + task_dict, + task_dict_lock, + user_data, + queued_up, + queued_dl, + queue_dict_lock, +) +from ..core.config_manager import Config +from ..helper.ext_utils.bot_utils import new_task +from ..helper.ext_utils.status_utils import get_task_by_gid +from ..helper.telegram_helper.bot_commands import BotCommands +from ..helper.telegram_helper.message_utils import send_message +from ..helper.ext_utils.task_manager import start_dl_from_queued, start_up_from_queued + + +@new_task +async def remove_from_queue(_, message): + user_id = message.from_user.id if message.from_user else message.sender_chat.id + msg = message.text.split() + status = msg[1] if len(msg) > 1 and msg[1] in ["fd", "fu"] else "" + if status and len(msg) > 2 or not status and len(msg) > 1: + gid = msg[2] if status else msg[1] + task = await get_task_by_gid(gid) + if task is None: + await send_message(message, f"GID: {gid} Not Found.") + return + elif reply_to_id := message.reply_to_message_id: + async with task_dict_lock: + task = task_dict.get(reply_to_id) + if task is None: + await send_message(message, "This is not an active task!") + return + elif len(msg) in {1, 2}: + msg = f"""Reply to an active Command message which was used to start the download/upload. +/{BotCommands.ForceStartCommand[0]} fd (to remove it from download queue) or fu (to remove it from upload queue) or nothing to start remove it from both download and upload queue. +Also send /{BotCommands.ForceStartCommand[0]} GID fu|fd or obly gid to force start by removing the task rom queue! +Examples: +/{BotCommands.ForceStartCommand[1]} GID fu (force upload) +/{BotCommands.ForceStartCommand[1]} GID (force download and upload) +By reply to task cmd: +/{BotCommands.ForceStartCommand[1]} (force download and upload) +/{BotCommands.ForceStartCommand[1]} fd (force download) +""" + await send_message(message, msg) + return + if ( + Config.OWNER_ID != user_id + and task.listener.user_id != user_id + and (user_id not in user_data or not user_data[user_id].get("SUDO")) + ): + await send_message(message, "This task is not for you!") + return + listener = task.listener + msg = "" + async with queue_dict_lock: + if status == "fu": + listener.force_upload = True + if listener.mid in queued_up: + await start_up_from_queued(listener.mid) + msg = "Task have been force started to upload!" + else: + msg = "Force upload enabled for this task!" + elif status == "fd": + listener.force_download = True + if listener.mid in queued_dl: + await start_dl_from_queued(listener.mid) + msg = "Task have been force started to download only!" + else: + msg = "This task not in download queue!" + else: + listener.force_download = True + listener.force_upload = True + if listener.mid in queued_up: + await start_up_from_queued(listener.mid) + msg = "Task have been force started to upload!" + elif listener.mid in queued_dl: + await start_dl_from_queued(listener.mid) + msg = "Task have been force started to download and upload will start once download finish!" + else: + msg = "This task not in queue!" + if msg: + await send_message(message, msg) diff --git a/bot/modules/gd_count.py b/bot/modules/gd_count.py new file mode 100644 index 0000000000000000000000000000000000000000..10092f3d2ececadf32caf51154548ed4a2956ed1 --- /dev/null +++ b/bot/modules/gd_count.py @@ -0,0 +1,45 @@ +from ..helper.ext_utils.bot_utils import sync_to_async, new_task +from ..helper.ext_utils.links_utils import is_gdrive_link +from ..helper.ext_utils.status_utils import get_readable_file_size +from ..helper.mirror_leech_utils.gdrive_utils.count import GoogleDriveCount +from ..helper.telegram_helper.message_utils import delete_message, send_message + + +@new_task +async def count_node(_, message): + args = message.text.split() + user = message.from_user or message.sender_chat + if username := user.username: + tag = f"@{username}" + else: + tag = message.from_user.mention + + link = args[1] if len(args) > 1 else "" + if len(link) == 0 and (reply_to := message.reply_to_message): + link = reply_to.text.split(maxsplit=1)[0].strip() + + if is_gdrive_link(link): + msg = await send_message(message, f"Counting: {link}") + name, mime_type, size, files, folders = await sync_to_async( + GoogleDriveCount().count, link, user.id + ) + if mime_type is None: + await send_message(message, name) + return + await delete_message(msg) + msg = f"Name: {name}" + msg += f"\n\nSize: {get_readable_file_size(size)}" + msg += f"\n\nType: {mime_type}" + if mime_type == "Folder": + msg += f"\nSubFolders: {folders}" + msg += f"\nFiles: {files}" + msg += f"\n\ncc: {tag}" + else: + msg = ( + "Send Gdrive link along with command or by replying to the link by command" + ) + + await send_message(message, msg) + + + diff --git a/bot/modules/gd_delete.py b/bot/modules/gd_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..81ef83539340f51c2c5a15151e2edfdf630a36f6 --- /dev/null +++ b/bot/modules/gd_delete.py @@ -0,0 +1,29 @@ +from .. import LOGGER +from ..helper.ext_utils.bot_utils import sync_to_async, new_task +from ..helper.ext_utils.links_utils import is_gdrive_link +from ..helper.mirror_leech_utils.gdrive_utils.delete import GoogleDriveDelete +from ..helper.telegram_helper.message_utils import auto_delete_message, send_message + + +@new_task +async def delete_file(_, message): + args = message.text.split() + user = message.from_user or message.sender_chat + if len(args) > 1: + link = args[1] + elif reply_to := message.reply_to_message: + link = reply_to.text.split(maxsplit=1)[0].strip() + else: + link = "" + if is_gdrive_link(link): + LOGGER.info(link) + msg = await sync_to_async(GoogleDriveDelete().deletefile, link, user.id) + else: + msg = ( + "Send Gdrive link along with command or by replying to the link by command" + ) + reply_message = await send_message(message, msg) + await auto_delete_message(message, reply_message) + + + diff --git a/bot/modules/gd_search.py b/bot/modules/gd_search.py new file mode 100644 index 0000000000000000000000000000000000000000..1fbc0f3dff609f353670e40d43c6ade36c9d6e41 --- /dev/null +++ b/bot/modules/gd_search.py @@ -0,0 +1,99 @@ +from .. import LOGGER, user_data +from ..helper.ext_utils.bot_utils import ( + sync_to_async, + get_telegraph_list, + new_task, +) +from ..helper.mirror_leech_utils.gdrive_utils.search import GoogleDriveSearch +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import send_message, edit_message + + +async def list_buttons(user_id, is_recursive=True, user_token=False): + buttons = ButtonMaker() + buttons.data_button( + "Folders", f"list_types {user_id} folders {is_recursive} {user_token}" + ) + buttons.data_button( + "Files", f"list_types {user_id} files {is_recursive} {user_token}" + ) + buttons.data_button( + "Both", f"list_types {user_id} both {is_recursive} {user_token}" + ) + buttons.data_button( + f"Recursive: {is_recursive}", + f"list_types {user_id} rec {is_recursive} {user_token}", + ) + buttons.data_button( + f"User Token: {user_token}", + f"list_types {user_id} ut {is_recursive} {user_token}", + ) + buttons.data_button("Cancel", f"list_types {user_id} cancel") + return buttons.build_menu(2) + + +async def _list_drive(key, message, item_type, is_recursive, user_token, user_id): + LOGGER.info(f"listing: {key}") + if user_token: + user_dict = user_data.get(user_id, {}) + target_id = user_dict.get("gdrive_id", "") or "" + LOGGER.info(target_id) + else: + target_id = "" + telegraph_content, contents_no = await sync_to_async( + GoogleDriveSearch(is_recursive=is_recursive, item_type=item_type).drive_list, + key, + target_id, + user_id, + ) + if telegraph_content: + try: + button = await get_telegraph_list(telegraph_content) + except Exception as e: + await edit_message(message, e) + return + msg = f"Found {contents_no} result for {key}" + await edit_message(message, msg, button) + else: + await edit_message(message, f"No result found for {key}") + + +@new_task +async def select_type(_, query): + user_id = query.from_user.id + message = query.message + key = message.reply_to_message.text.split(maxsplit=1)[1].strip() + data = query.data.split() + if user_id != int(data[1]): + return await query.answer(text="Not Yours!", show_alert=True) + elif data[2] == "rec": + await query.answer() + is_recursive = not bool(eval(data[3])) + buttons = await list_buttons(user_id, is_recursive, eval(data[4])) + return await edit_message(message, "Choose list options:", buttons) + elif data[2] == "ut": + await query.answer() + user_token = not bool(eval(data[4])) + buttons = await list_buttons(user_id, eval(data[3]), user_token) + return await edit_message(message, "Choose list options:", buttons) + elif data[2] == "cancel": + await query.answer() + return await edit_message(message, "list has been canceled!") + await query.answer() + item_type = data[2] + is_recursive = eval(data[3]) + user_token = eval(data[4]) + await edit_message(message, f"Searching for {key}") + await _list_drive(key, message, item_type, is_recursive, user_token, user_id) + + +@new_task +async def gdrive_search(_, message): + if len(message.text.split()) == 1: + return await send_message(message, "Send a search key along with command") + user_id = message.from_user.id + buttons = await list_buttons(user_id) + await send_message(message, "Choose list options:", buttons) + + + diff --git a/bot/modules/help.py b/bot/modules/help.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b6d8fd2e7eda00f11f6daf239f5333553ec92a --- /dev/null +++ b/bot/modules/help.py @@ -0,0 +1,48 @@ +from ..helper.ext_utils.bot_utils import COMMAND_USAGE, new_task +from ..helper.ext_utils.help_messages import ( + YT_HELP_DICT, + MIRROR_HELP_DICT, + CLONE_HELP_DICT, +) +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import edit_message, delete_message, send_message +from ..helper.ext_utils.help_messages import help_string + + +@new_task +async def arg_usage(_, query): + data = query.data.split() + message = query.message + if data[1] == "close": + await delete_message(message) + elif data[1] == "back": + if data[2] == "m": + await edit_message( + message, COMMAND_USAGE["mirror"][0], COMMAND_USAGE["mirror"][1] + ) + elif data[2] == "y": + await edit_message(message, COMMAND_USAGE["yt"][0], COMMAND_USAGE["yt"][1]) + elif data[2] == "c": + await edit_message( + message, COMMAND_USAGE["clone"][0], COMMAND_USAGE["clone"][1] + ) + elif data[1] == "mirror": + buttons = ButtonMaker() + buttons.data_button("Back", "help back m") + button = buttons.build_menu() + await edit_message(message, MIRROR_HELP_DICT[data[2]], button) + elif data[1] == "yt": + buttons = ButtonMaker() + buttons.data_button("Back", "help back y") + button = buttons.build_menu() + await edit_message(message, YT_HELP_DICT[data[2]], button) + elif data[1] == "clone": + buttons = ButtonMaker() + buttons.data_button("Back", "help back c") + button = buttons.build_menu() + await edit_message(message, CLONE_HELP_DICT[data[2]], button) + + +@new_task +async def bot_help(_, message): + await send_message(message, help_string) diff --git a/bot/modules/mirror_leech.py b/bot/modules/mirror_leech.py new file mode 100644 index 0000000000000000000000000000000000000000..2a60f06b30b23546a8ceae0a1667d7bf775669bf --- /dev/null +++ b/bot/modules/mirror_leech.py @@ -0,0 +1,397 @@ +from aiofiles.os import path as aiopath +from base64 import b64encode +from re import match as re_match + +from .. import LOGGER, bot_loop, task_dict_lock, DOWNLOAD_DIR +from ..helper.ext_utils.bot_utils import ( + get_content_type, + sync_to_async, + arg_parser, + COMMAND_USAGE, +) +from ..helper.ext_utils.exceptions import DirectDownloadLinkException +from ..helper.ext_utils.links_utils import ( + is_url, + is_magnet, + is_gdrive_link, + is_rclone_path, + is_telegram_link, + is_gdrive_id, +) +from ..helper.listeners.task_listener import TaskListener +from ..helper.mirror_leech_utils.download_utils.aria2_download import ( + add_aria2_download, +) +from ..helper.mirror_leech_utils.download_utils.direct_downloader import ( + add_direct_download, +) +from ..helper.mirror_leech_utils.download_utils.direct_link_generator import ( + direct_link_generator, +) +from ..helper.mirror_leech_utils.download_utils.gd_download import add_gd_download +from ..helper.mirror_leech_utils.download_utils.jd_download import add_jd_download +from ..helper.mirror_leech_utils.download_utils.qbit_download import add_qb_torrent +from ..helper.mirror_leech_utils.download_utils.nzb_downloader import add_nzb +from ..helper.mirror_leech_utils.download_utils.rclone_download import ( + add_rclone_download, +) +from ..helper.mirror_leech_utils.download_utils.telegram_download import ( + TelegramDownloadHelper, +) +from ..helper.telegram_helper.message_utils import send_message, get_tg_link_message + + +class Mirror(TaskListener): + def __init__( + self, + client, + message, + is_qbit=False, + is_leech=False, + is_jd=False, + is_nzb=False, + same_dir=None, + bulk=None, + multi_tag=None, + options="", + ): + if same_dir is None: + same_dir = {} + if bulk is None: + bulk = [] + self.message = message + self.client = client + self.multi_tag = multi_tag + self.options = options + self.same_dir = same_dir + self.bulk = bulk + super().__init__() + self.is_qbit = is_qbit + self.is_leech = is_leech + self.is_jd = is_jd + self.is_nzb = is_nzb + + async def new_event(self): + text = self.message.text.split("\n") + input_list = text[0].split(" ") + + args = { + "-doc": False, + "-med": False, + "-d": False, + "-j": False, + "-s": False, + "-b": False, + "-e": False, + "-z": False, + "-sv": False, + "-ss": False, + "-f": False, + "-fd": False, + "-fu": False, + "-hl": False, + "-bt": False, + "-ut": False, + "-i": 0, + "-sp": 0, + "link": "", + "-n": "", + "-m": "", + "-up": "", + "-rcf": "", + "-au": "", + "-ap": "", + "-h": [], + "-t": "", + "-ca": "", + "-cv": "", + "-ns": "", + "-tl": "", + "-ff": set(), + } + + arg_parser(input_list[1:], args) + + self.select = args["-s"] + self.seed = args["-d"] + self.name = args["-n"] + self.up_dest = args["-up"] + self.rc_flags = args["-rcf"] + self.link = args["link"] + self.compress = args["-z"] + self.extract = args["-e"] + self.join = args["-j"] + self.thumb = args["-t"] + self.split_size = args["-sp"] + self.sample_video = args["-sv"] + self.screen_shots = args["-ss"] + self.force_run = args["-f"] + self.force_download = args["-fd"] + self.force_upload = args["-fu"] + self.convert_audio = args["-ca"] + self.convert_video = args["-cv"] + self.name_sub = args["-ns"] + self.hybrid_leech = args["-hl"] + self.thumbnail_layout = args["-tl"] + self.as_doc = args["-doc"] + self.as_med = args["-med"] + self.folder_name = f"/{args["-m"]}".rstrip("/") if len(args["-m"]) > 0 else "" + self.bot_trans = args["-bt"] + self.user_trans = args["-ut"] + self.ffmpeg_cmds = args["-ff"] + + headers = args["-h"] + if headers: + headers = headers.split("|") + is_bulk = args["-b"] + + bulk_start = 0 + bulk_end = 0 + ratio = None + seed_time = None + reply_to = None + file_ = None + session = "" + + try: + self.multi = int(args["-i"]) + except: + self.multi = 0 + + if not isinstance(self.seed, bool): + dargs = self.seed.split(":") + ratio = dargs[0] or None + if len(dargs) == 2: + seed_time = dargs[1] or None + self.seed = True + + if not isinstance(is_bulk, bool): + dargs = is_bulk.split(":") + bulk_start = dargs[0] or "0" + if len(dargs) == 2: + bulk_end = dargs[1] or "0" + is_bulk = True + + if not is_bulk: + if self.multi > 0: + if self.folder_name: + async with task_dict_lock: + if self.folder_name in self.same_dir: + self.same_dir[self.folder_name]["tasks"].add(self.mid) + for fd_name in self.same_dir: + if fd_name != self.folder_name: + self.same_dir[fd_name]["total"] -= 1 + elif self.same_dir: + self.same_dir[self.folder_name] = { + "total": self.multi, + "tasks": {self.mid}, + } + for fd_name in self.same_dir: + if fd_name != self.folder_name: + self.same_dir[fd_name]["total"] -= 1 + else: + self.same_dir = { + self.folder_name: { + "total": self.multi, + "tasks": {self.mid}, + } + } + elif self.same_dir: + async with task_dict_lock: + for fd_name in self.same_dir: + self.same_dir[fd_name]["total"] -= 1 + else: + await self.init_bulk(input_list, bulk_start, bulk_end, Mirror) + return + + if len(self.bulk) != 0: + del self.bulk[0] + + await self.run_multi(input_list, Mirror) + + await self.get_tag(text) + + path = f"{DOWNLOAD_DIR}{self.mid}{self.folder_name}" + + if not self.link and (reply_to := self.message.reply_to_message): + if reply_to.text: + self.link = reply_to.text.split("\n", 1)[0].strip() + if is_telegram_link(self.link): + try: + reply_to, session = await get_tg_link_message(self.link) + except Exception as e: + await send_message(self.message, f"ERROR: {e}") + await self.remove_from_same_dir() + return + + if isinstance(reply_to, list): + self.bulk = reply_to + b_msg = input_list[:1] + self.options = " ".join(input_list[1:]) + b_msg.append(f"{self.bulk[0]} -i {len(self.bulk)} {self.options}") + nextmsg = await send_message(self.message, " ".join(b_msg)) + if self.message.from_user: + nextmsg.from_user = self.user + else: + nextmsg.sender_chat = self.user + await Mirror( + self.client, + nextmsg, + self.is_qbit, + self.is_leech, + self.is_jd, + self.is_nzb, + self.same_dir, + self.bulk, + self.multi_tag, + self.options, + ).new_event() + return + + if reply_to: + file_ = ( + reply_to.document + or reply_to.photo + or reply_to.video + or reply_to.audio + or reply_to.voice + or reply_to.video_note + or reply_to.sticker + or reply_to.animation + or None + ) + + if file_ is None: + if reply_text := reply_to.text: + self.link = reply_text.split("\n", 1)[0].strip() + else: + reply_to = None + elif reply_to.document and ( + file_.mime_type == "application/x-bittorrent" + or file_.file_name.endswith((".torrent", ".dlc", ".nzb")) + ): + self.link = await reply_to.download() + file_ = None + + if ( + not self.link + and file_ is None + or is_telegram_link(self.link) + and reply_to is None + or file_ is None + and not is_url(self.link) + and not is_magnet(self.link) + and not await aiopath.exists(self.link) + and not is_rclone_path(self.link) + and not is_gdrive_id(self.link) + and not is_gdrive_link(self.link) + ): + await send_message( + self.message, COMMAND_USAGE["mirror"][0], COMMAND_USAGE["mirror"][1] + ) + await self.remove_from_same_dir() + return + + if len(self.link) > 0: + LOGGER.info(self.link) + + try: + await self.before_start() + except Exception as e: + await send_message(self.message, e) + await self.remove_from_same_dir() + return + + if ( + not self.is_jd + and not self.is_nzb + and not self.is_qbit + and not is_magnet(self.link) + and not is_rclone_path(self.link) + and not is_gdrive_link(self.link) + and not self.link.endswith(".torrent") + and file_ is None + and not is_gdrive_id(self.link) + ): + content_type = await get_content_type(self.link) + if content_type is None or re_match(r"text/html|text/plain", content_type): + try: + self.link = await sync_to_async(direct_link_generator, self.link) + if isinstance(self.link, tuple): + self.link, headers = self.link + elif isinstance(self.link, str): + LOGGER.info(f"Generated link: {self.link}") + except DirectDownloadLinkException as e: + e = str(e) + if "This link requires a password!" not in e: + LOGGER.info(e) + if e.startswith("ERROR:"): + await send_message(self.message, e) + await self.remove_from_same_dir() + return + except Exception as e: + await send_message(self.message, e) + await self.remove_from_same_dir() + return + + if file_ is not None: + await TelegramDownloadHelper(self).add_download( + reply_to, f"{path}/", session + ) + elif isinstance(self.link, dict): + await add_direct_download(self, path) + elif self.is_jd: + await add_jd_download(self, path) + elif self.is_qbit: + await add_qb_torrent(self, path, ratio, seed_time) + elif self.is_nzb: + await add_nzb(self, path) + elif is_rclone_path(self.link): + await add_rclone_download(self, f"{path}/") + elif is_gdrive_link(self.link) or is_gdrive_id(self.link): + await add_gd_download(self, path) + else: + ussr = args["-au"] + pssw = args["-ap"] + if ussr or pssw: + auth = f"{ussr}:{pssw}" + headers.extend( + [f"authorization: Basic {b64encode(auth.encode()).decode('ascii')}"] + ) + await add_aria2_download(self, path, headers, ratio, seed_time) + + +async def mirror(client, message): + bot_loop.create_task(Mirror(client, message).new_event()) + + +async def qb_mirror(client, message): + bot_loop.create_task(Mirror(client, message, is_qbit=True).new_event()) + + +async def jd_mirror(client, message): + bot_loop.create_task(Mirror(client, message, is_jd=True).new_event()) + + +async def nzb_mirror(client, message): + bot_loop.create_task(Mirror(client, message, is_nzb=True).new_event()) + + +async def leech(client, message): + bot_loop.create_task(Mirror(client, message, is_leech=True).new_event()) + + +async def qb_leech(client, message): + bot_loop.create_task( + Mirror(client, message, is_qbit=True, is_leech=True).new_event() + ) + + +async def jd_leech(client, message): + bot_loop.create_task(Mirror(client, message, is_leech=True, is_jd=True).new_event()) + + +async def nzb_leech(client, message): + bot_loop.create_task( + Mirror(client, message, is_leech=True, is_nzb=True).new_event() + ) diff --git a/bot/modules/nzb_search.py b/bot/modules/nzb_search.py new file mode 100644 index 0000000000000000000000000000000000000000..da921871ac5f3f45f12fd47289ad6711f515f5de --- /dev/null +++ b/bot/modules/nzb_search.py @@ -0,0 +1,123 @@ +from xml.etree import ElementTree as ET +from aiohttp import ClientSession + +from .. import LOGGER +from ..core.config_manager import Config +from ..helper.ext_utils.bot_utils import new_task +from ..helper.ext_utils.status_utils import get_readable_file_size +from ..helper.ext_utils.telegraph_helper import telegraph +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import edit_message, send_message + + +@new_task +async def hydra_search(_, message): + key = message.text.split() + if len(key) == 1: + await send_message( + message, + "Please provide a search query. Example: `/nzbsearch movie title`.", + ) + return + + query = " ".join(key[1:]).strip() + message = await send_message(message, f"Searching for '{query}'...") + try: + items = await search_nzbhydra(query) + if not items: + await edit_message(message, "No results found.") + LOGGER.info(f"No results found for search query: {query}") + return + + page_url = await create_telegraph_page(query, items) + buttons = ButtonMaker() + buttons.url_button("Results", page_url) + button = buttons.build_menu() + await edit_message( + message, + f"Search results for '{query}' are available here", + button, + ) + except Exception as e: + LOGGER.error(f"Error in hydra_search: {e!s}") + await edit_message(message, "Something went wrong.") + + +async def search_nzbhydra(query, limit=50): + search_url = f"{Config.HYDRA_IP}/api" + params = { + "apikey": Config.HYDRA_API_KEY, + "t": "search", + "q": query, + "limit": limit, + } + + headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3", + } + + async with ClientSession() as session: + try: + async with session.get( + search_url, + params=params, + headers=headers, + ) as response: + if response.status == 200: + content = await response.text() + root = ET.fromstring(content) + return root.findall(".//item") + + LOGGER.error( + f"Failed to search NZBHydra. Status Code: {response.status}", + ) + LOGGER.error(f"Response Text: {await response.text()}") + return None + except ET.ParseError: + LOGGER.error("Failed to parse the XML response.") + return None + except Exception as e: + LOGGER.error(f"Error in search_nzbhydra: {e!s}") + return None + + +async def create_telegraph_page(query, items): + content = "Search Results:

" + sorted_items = sorted( + [ + ( + int(item.find("size").text) if item.find("size") is not None else 0, + item, + ) + for item in items[:100] + ], + reverse=True, + key=lambda x: x[0], + ) + + for idx, (size_bytes, item) in enumerate(sorted_items, 1): + title = ( + item.find("title").text + if item.find("title") is not None + else "No Title Available" + ) + download_url = ( + item.find("link").text + if item.find("link") is not None + else "No Link Available" + ) + size = get_readable_file_size(size_bytes) + + content += ( + f"{idx}. {title}
" + f"Download URL | Share Download URL
" + f"Size: {size}
" + f"━━━━━━━━━━━━━━━━━━━━━━

" + ) + + response = await telegraph.create_page( + title=f"Search Results for '{query}'", + content=content, + ) + LOGGER.info(f"Telegraph page created for search: {query}") + return f"https://telegra.ph/{response['path']}" diff --git a/bot/modules/restart.py b/bot/modules/restart.py new file mode 100644 index 0000000000000000000000000000000000000000..0b564017c43441be689719e1e7d0f591a933e473 --- /dev/null +++ b/bot/modules/restart.py @@ -0,0 +1,136 @@ +from sys import executable +from aiofiles import open as aiopen +from aiofiles.os import path as aiopath, remove +from asyncio import gather, create_subprocess_exec +from os import execl as osexecl + +from .. import intervals, scheduler, sabnzbd_client, LOGGER +from ..helper.ext_utils.bot_utils import new_task +from ..helper.telegram_helper.message_utils import ( + send_message, + delete_message, +) +from ..helper.ext_utils.db_handler import database +from ..helper.ext_utils.files_utils import clean_all +from ..helper.telegram_helper.button_build import ButtonMaker +from ..core.telegram_manager import TgClient +from ..core.config_manager import Config +from ..core.jdownloader_booter import jdownloader +from ..core.torrent_manager import TorrentManager + + +@new_task +async def restart_bot(_, message): + buttons = ButtonMaker() + buttons.data_button("Yes!", "botrestart confirm") + buttons.data_button("Cancel", "botrestart cancel") + button = buttons.build_menu(2) + await send_message(message, "Are you sure you want to restart the bot ?!", button) + + +async def send_incomplete_task_message(cid, msg_id, msg): + try: + if msg.startswith("Restarted Successfully!"): + await TgClient.bot.edit_message_text( + chat_id=cid, + message_id=msg_id, + text=msg, + ) + await remove(".restartmsg") + else: + await TgClient.bot.send_message( + chat_id=cid, + text=msg, + disable_notification=True, + ) + except Exception as e: + LOGGER.error(e) + + +async def restart_notification(): + if await aiopath.isfile(".restartmsg"): + with open(".restartmsg") as f: + chat_id, msg_id = map(int, f) + else: + chat_id, msg_id = 0, 0 + + if Config.INCOMPLETE_TASK_NOTIFIER and Config.DATABASE_URL: + if notifier_dict := await database.get_incomplete_tasks(): + for cid, data in notifier_dict.items(): + msg = "Restarted Successfully!" if cid == chat_id else "Bot Restarted!" + for tag, links in data.items(): + msg += f"\n\n{tag}: " + for index, link in enumerate(links, start=1): + msg += f" {index} |" + if len(msg.encode()) > 4000: + await send_incomplete_task_message(cid, msg_id, msg) + msg = "" + if msg: + await send_incomplete_task_message(cid, msg_id, msg) + + if await aiopath.isfile(".restartmsg"): + try: + await TgClient.bot.edit_message_text( + chat_id=chat_id, message_id=msg_id, text="Restarted Successfully!" + ) + except: + pass + await remove(".restartmsg") + + +@new_task +async def confirm_restart(_, query): + await query.answer() + data = query.data.split() + message = query.message + if data[1] == "confirm": + reply_to = message.reply_to_message + intervals["stopAll"] = True + restart_message = await send_message(reply_to, "Restarting...") + await delete_message(message) + await TgClient.stop() + if scheduler.running: + scheduler.shutdown(wait=False) + if qb := intervals["qb"]: + qb.cancel() + if jd := intervals["jd"]: + jd.cancel() + if nzb := intervals["nzb"]: + nzb.cancel() + if st := intervals["status"]: + for intvl in list(st.values()): + intvl.cancel() + await clean_all() + await TorrentManager.close_all() + if sabnzbd_client.LOGGED_IN: + await gather( + sabnzbd_client.pause_all(), + sabnzbd_client.delete_job("all", True), + sabnzbd_client.purge_all(True), + sabnzbd_client.delete_history("all", delete_files=True), + ) + await sabnzbd_client.close() + if jdownloader.is_connected: + await gather( + jdownloader.device.downloadcontroller.stop_downloads(), + jdownloader.device.linkgrabber.clear_list(), + jdownloader.device.downloads.cleanup( + "DELETE_ALL", + "REMOVE_LINKS_AND_DELETE_FILES", + "ALL", + ), + ) + await jdownloader.close() + proc1 = await create_subprocess_exec( + "pkill", + "-9", + "-f", + "gunicorn|aria2c|qbittorrent-nox|ffmpeg|rclone|java|sabnzbdplus|7z|split", + ) + proc2 = await create_subprocess_exec("python3", "update.py") + await gather(proc1.wait(), proc2.wait()) + async with aiopen(".restartmsg", "w") as f: + await f.write(f"{restart_message.chat.id}\n{restart_message.id}\n") + osexecl(executable, executable, "-m", "bot") + else: + await delete_message(message) diff --git a/bot/modules/rss.py b/bot/modules/rss.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b4230ca81980e48a1e271e72bb5806561a5fae --- /dev/null +++ b/bot/modules/rss.py @@ -0,0 +1,835 @@ +from httpx import AsyncClient +from apscheduler.triggers.interval import IntervalTrigger +from asyncio import Lock, sleep +from datetime import datetime, timedelta +from feedparser import parse as feed_parse +from functools import partial +from io import BytesIO +from pyrogram.filters import create +from pyrogram.handlers import MessageHandler +from time import time +from re import compile, I + +from .. import scheduler, rss_dict, LOGGER +from ..core.config_manager import Config +from ..helper.ext_utils.bot_utils import new_task, arg_parser, get_size_bytes +from ..helper.ext_utils.status_utils import get_readable_file_size +from ..helper.ext_utils.db_handler import database +from ..helper.ext_utils.exceptions import RssShutdownException +from ..helper.ext_utils.help_messages import RSS_HELP_MESSAGE +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.filters import CustomFilters +from ..helper.telegram_helper.message_utils import ( + send_message, + edit_message, + send_rss, + send_file, + delete_message, +) + +rss_dict_lock = Lock() +handler_dict = {} +size_regex = compile(r"(\d+(\.\d+)?\s?(GB|MB|KB|GiB|MiB|KiB))", I) + +headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Language": "en-US,en;q=0.5", +} + + +async def rss_menu(event): + user_id = event.from_user.id + buttons = ButtonMaker() + buttons.data_button("Subscribe", f"rss sub {user_id}") + buttons.data_button("Subscriptions", f"rss list {user_id} 0") + buttons.data_button("Get Items", f"rss get {user_id}") + buttons.data_button("Edit", f"rss edit {user_id}") + buttons.data_button("Pause", f"rss pause {user_id}") + buttons.data_button("Resume", f"rss resume {user_id}") + buttons.data_button("Unsubscribe", f"rss unsubscribe {user_id}") + if await CustomFilters.sudo("", event): + buttons.data_button("All Subscriptions", f"rss listall {user_id} 0") + buttons.data_button("Pause All", f"rss allpause {user_id}") + buttons.data_button("Resume All", f"rss allresume {user_id}") + buttons.data_button("Unsubscribe All", f"rss allunsub {user_id}") + buttons.data_button("Delete User", f"rss deluser {user_id}") + if scheduler.running: + buttons.data_button("Shutdown Rss", f"rss shutdown {user_id}") + else: + buttons.data_button("Start Rss", f"rss start {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + msg = f"Rss Menu | Users: {len(rss_dict)} | Running: {scheduler.running}" + return msg, button + + +async def update_rss_menu(query): + msg, button = await rss_menu(query) + await edit_message(query.message, msg, button) + + +@new_task +async def get_rss_menu(_, message): + msg, button = await rss_menu(message) + await send_message(message, msg, button) + + +@new_task +async def rss_sub(_, message, pre_event): + user_id = message.from_user.id + handler_dict[user_id] = False + if username := message.from_user.username: + tag = f"@{username}" + else: + tag = message.from_user.mention + msg = "" + items = message.text.split("\n") + for index, item in enumerate(items, start=1): + args = item.split() + if len(args) < 2: + await send_message( + message, + f"{item}. Wrong Input format. Read help message before adding new subscription!", + ) + continue + title = args[0].strip() + if (user_feeds := rss_dict.get(user_id, False)) and title in user_feeds: + await send_message( + message, f"This title {title} already subscribed! Choose another title!" + ) + continue + feed_link = args[1].strip() + if feed_link.startswith(("-inf", "-exf", "-c")): + await send_message( + message, + f"Wrong input in line {index}! Add Title! Read the example!", + ) + continue + inf_lists = [] + exf_lists = [] + if len(args) > 2: + arg_base = {"-c": None, "-inf": None, "-exf": None, "-stv": None} + arg_parser(args[2:], arg_base) + cmd = arg_base["-c"] + inf = arg_base["-inf"] + exf = arg_base["-exf"] + stv = arg_base["-stv"] + if stv is not None: + stv = stv.lower() == "true" + if inf is not None: + filters_list = inf.split("|") + for x in filters_list: + y = x.split(" or ") + inf_lists.append(y) + if exf is not None: + filters_list = exf.split("|") + for x in filters_list: + y = x.split(" or ") + exf_lists.append(y) + else: + inf = None + exf = None + cmd = None + stv = False + try: + async with AsyncClient( + headers=headers, follow_redirects=True, timeout=60, verify=False + ) as client: + res = await client.get(feed_link) + html = res.text + rss_d = feed_parse(html) + last_title = rss_d.entries[0]["title"] + if rss_d.entries[0].get("size"): + size = int(rss_d.entries[0]["size"]) + elif rss_d.entries[0].get("summary"): + summary = rss_d.entries[0]["summary"] + matches = size_regex.findall(summary) + sizes = [match[0] for match in matches] + size = get_size_bytes(sizes[0]) + else: + size = 0 + msg += "Subscribed!" + msg += f"\nTitle: {title}\nFeed Url: {feed_link}" + msg += f"\nlatest record for {rss_d.feed.title}:" + msg += ( + f"\nName: {last_title.replace('>', '').replace('<', '')}" + ) + try: + last_link = rss_d.entries[0]["links"][1]["href"] + except IndexError: + last_link = rss_d.entries[0]["link"] + msg += f"\nLink: {last_link}" + if size: + msg += f"\nSize: {get_readable_file_size(size)}" + msg += f"\nCommand: {cmd}" + msg += f"\nFilters:-\ninf: {inf}\nexf: {exf}\nsensitive: {stv}" + async with rss_dict_lock: + if rss_dict.get(user_id, False): + rss_dict[user_id][title] = { + "link": feed_link, + "last_feed": last_link, + "last_title": last_title, + "inf": inf_lists, + "exf": exf_lists, + "paused": False, + "command": cmd, + "sensitive": stv, + "tag": tag, + } + else: + rss_dict[user_id] = { + title: { + "link": feed_link, + "last_feed": last_link, + "last_title": last_title, + "inf": inf_lists, + "exf": exf_lists, + "paused": False, + "command": cmd, + "sensitive": stv, + "tag": tag, + } + } + LOGGER.info( + f"Rss Feed Added: id: {user_id} - title: {title} - link: {feed_link} - c: {cmd} - inf: {inf} - exf: {exf} - stv: {stv}" + ) + except (IndexError, AttributeError) as e: + emsg = f"The link: {feed_link} doesn't seem to be a RSS feed or it's region-blocked!" + await send_message(message, emsg + "\nError: " + str(e)) + except Exception as e: + await send_message(message, str(e)) + if msg: + await database.rss_update(user_id) + await send_message(message, msg) + is_sudo = await CustomFilters.sudo("", message) + if scheduler.state == 2: + scheduler.resume() + elif is_sudo and not scheduler.running: + add_job() + scheduler.start() + await update_rss_menu(pre_event) + + +async def get_user_id(title): + async with rss_dict_lock: + return next( + ( + (True, user_id) + for user_id, feed in rss_dict.items() + if feed["title"] == title + ), + (False, False), + ) + + +@new_task +async def rss_update(_, message, pre_event, state): + user_id = message.from_user.id + handler_dict[user_id] = False + titles = message.text.split() + is_sudo = await CustomFilters.sudo("", message) + updated = [] + for title in titles: + title = title.strip() + if not (res := rss_dict[user_id].get(title, False)): + if is_sudo: + res, user_id = await get_user_id(title) + if not res: + user_id = message.from_user.id + await send_message(message, f"{title} not found!") + continue + istate = rss_dict[user_id][title].get("paused", False) + if istate and state == "pause" or not istate and state == "resume": + await send_message(message, f"{title} already {state}d!") + continue + async with rss_dict_lock: + updated.append(title) + if state == "unsubscribe": + del rss_dict[user_id][title] + elif state == "pause": + rss_dict[user_id][title]["paused"] = True + elif state == "resume": + rss_dict[user_id][title]["paused"] = False + if state == "resume": + if scheduler.state == 2: + scheduler.resume() + elif is_sudo and not scheduler.running: + add_job() + scheduler.start() + if is_sudo and Config.DATABASE_URL and user_id != message.from_user.id: + await database.rss_update(user_id) + if not rss_dict[user_id]: + async with rss_dict_lock: + del rss_dict[user_id] + await database.rss_delete(user_id) + if not rss_dict: + await database.trunc_table("rss") + if updated: + LOGGER.info(f"Rss link with Title(s): {updated} has been {state}d!") + await send_message( + message, + f"Rss links with Title(s): {updated} has been {state}d!", + ) + if rss_dict.get(user_id): + await database.rss_update(user_id) + await update_rss_menu(pre_event) + + +async def rss_list(query, start, all_users=False): + user_id = query.from_user.id + buttons = ButtonMaker() + if all_users: + list_feed = f"All subscriptions | Page: {int(start / 5)} " + async with rss_dict_lock: + keysCount = sum(len(v.keys()) for v in rss_dict.values()) + index = 0 + for titles in rss_dict.values(): + for index, (title, data) in enumerate( + list(titles.items())[start : 5 + start] + ): + list_feed += f"\n\nTitle: {title}\n" + list_feed += f"Feed Url: {data['link']}\n" + list_feed += f"Command: {data['command']}\n" + list_feed += f"Inf: {data['inf']}\n" + list_feed += f"Exf: {data['exf']}\n" + list_feed += f"Sensitive: {data.get('sensitive', False)}\n" + list_feed += f"Paused: {data['paused']}\n" + list_feed += f"User: {data['tag'].replace('@', '', 1)}" + index += 1 + if index == 5: + break + else: + list_feed = f"Your subscriptions | Page: {int(start / 5)} " + async with rss_dict_lock: + keysCount = len(rss_dict.get(user_id, {}).keys()) + for title, data in list(rss_dict[user_id].items())[start : 5 + start]: + list_feed += f"\n\nTitle: {title}\nFeed Url: {data['link']}\n" + list_feed += f"Command: {data['command']}\n" + list_feed += f"Inf: {data['inf']}\n" + list_feed += f"Exf: {data['exf']}\n" + list_feed += ( + f"Sensitive: {data.get('sensitive', False)}\n" + ) + list_feed += f"Paused: {data['paused']}\n" + buttons.data_button("Back", f"rss back {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + if keysCount > 5: + for x in range(0, keysCount, 5): + buttons.data_button( + f"{int(x / 5)}", f"rss list {user_id} {x}", position="footer" + ) + button = buttons.build_menu(2) + if query.message.text.html == list_feed: + return + await edit_message(query.message, list_feed, button) + + +@new_task +async def rss_get(_, message, pre_event): + user_id = message.from_user.id + handler_dict[user_id] = False + args = message.text.split() + if len(args) < 2: + await send_message( + message, + f"{args}. Wrong Input format. You should add number of the items you want to get. Read help message before adding new subscription!", + ) + await update_rss_menu(pre_event) + return + try: + title = args[0] + count = int(args[1]) + data = rss_dict[user_id].get(title, False) + if data and count > 0: + try: + msg = await send_message( + message, f"Getting the last {count} item(s) from {title}" + ) + async with AsyncClient( + headers=headers, follow_redirects=True, timeout=60, verify=False + ) as client: + res = await client.get(data["link"]) + html = res.text + rss_d = feed_parse(html) + item_info = "" + for item_num in range(count): + try: + link = rss_d.entries[item_num]["links"][1]["href"] + except IndexError: + link = rss_d.entries[item_num]["link"] + item_info += f"Name: {rss_d.entries[item_num]['title'].replace('>', '').replace('<', '')}\n" + item_info += f"Link: {link}\n\n" + item_info_ecd = item_info.encode() + if len(item_info_ecd) > 4000: + with BytesIO(item_info_ecd) as out_file: + out_file.name = f"rssGet {title} items_no. {count}.txt" + await send_file(message, out_file) + await delete_message(msg) + else: + await edit_message(msg, item_info) + except IndexError as e: + LOGGER.error(str(e)) + await edit_message( + msg, "Parse depth exceeded. Try again with a lower value." + ) + except Exception as e: + LOGGER.error(str(e)) + await edit_message(msg, str(e)) + else: + await send_message(message, "Enter a valid title. Title not found!") + except Exception as e: + LOGGER.error(str(e)) + await send_message(message, f"Enter a valid value!. {e}") + await update_rss_menu(pre_event) + + +@new_task +async def rss_edit(_, message, pre_event): + user_id = message.from_user.id + handler_dict[user_id] = False + items = message.text.split("\n") + updated = False + for item in items: + args = item.split() + title = args[0].strip() + if len(args) < 2: + await send_message( + message, + f"{item}. Wrong Input format. Read help message before editing!", + ) + continue + elif not rss_dict[user_id].get(title, False): + await send_message(message, "Enter a valid title. Title not found!") + continue + updated = True + inf_lists = [] + exf_lists = [] + arg_base = {"-c": None, "-inf": None, "-exf": None, "-stv": None} + arg_parser(args[1:], arg_base) + cmd = arg_base["-c"] + inf = arg_base["-inf"] + exf = arg_base["-exf"] + stv = arg_base["-stv"] + async with rss_dict_lock: + if stv is not None: + stv = stv.lower() == "true" + rss_dict[user_id][title]["sensitive"] = stv + if cmd is not None: + if cmd.lower() == "none": + cmd = None + rss_dict[user_id][title]["command"] = cmd + if inf is not None: + if inf.lower() != "none": + filters_list = inf.split("|") + for x in filters_list: + y = x.split(" or ") + inf_lists.append(y) + rss_dict[user_id][title]["inf"] = inf_lists + if exf is not None: + if exf.lower() != "none": + filters_list = exf.split("|") + for x in filters_list: + y = x.split(" or ") + exf_lists.append(y) + rss_dict[user_id][title]["exf"] = exf_lists + if updated: + await database.rss_update(user_id) + await update_rss_menu(pre_event) + + +@new_task +async def rss_delete(_, message, pre_event): + handler_dict[message.from_user.id] = False + users = message.text.split() + for user in users: + user = int(user) + async with rss_dict_lock: + del rss_dict[user] + await database.rss_delete(user) + await update_rss_menu(pre_event) + + +async def event_handler(client, query, pfunc): + user_id = query.from_user.id + handler_dict[user_id] = True + start_time = time() + + async def event_filter(_, __, event): + user = event.from_user or event.sender_chat + return bool( + user.id == user_id and event.chat.id == query.message.chat.id and event.text + ) + + handler = client.add_handler(MessageHandler(pfunc, create(event_filter)), group=-1) + while handler_dict[user_id]: + await sleep(0.5) + if time() - start_time > 60: + handler_dict[user_id] = False + await update_rss_menu(query) + client.remove_handler(*handler) + + +@new_task +async def rss_listener(client, query): + user_id = query.from_user.id + message = query.message + data = query.data.split() + if int(data[2]) != user_id and not await CustomFilters.sudo("", query): + await query.answer( + text="You don't have permission to use these buttons!", show_alert=True + ) + elif data[1] == "close": + await query.answer() + handler_dict[user_id] = False + await delete_message(message.reply_to_message) + await delete_message(message) + elif data[1] == "back": + await query.answer() + handler_dict[user_id] = False + await update_rss_menu(query) + elif data[1] == "sub": + await query.answer() + handler_dict[user_id] = False + buttons = ButtonMaker() + buttons.data_button("Back", f"rss back {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + await edit_message(message, RSS_HELP_MESSAGE, button) + pfunc = partial(rss_sub, pre_event=query) + await event_handler(client, query, pfunc) + elif data[1] == "list": + handler_dict[user_id] = False + if len(rss_dict.get(int(data[2]), {})) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + start = int(data[3]) + await rss_list(query, start) + elif data[1] == "get": + handler_dict[user_id] = False + if len(rss_dict.get(int(data[2]), {})) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + buttons = ButtonMaker() + buttons.data_button("Back", f"rss back {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + await edit_message( + message, + "Send one title with value separated by space get last X items.\nTitle Value\nTimeout: 60 sec.", + button, + ) + pfunc = partial(rss_get, pre_event=query) + await event_handler(client, query, pfunc) + elif data[1] in ["unsubscribe", "pause", "resume"]: + handler_dict[user_id] = False + if len(rss_dict.get(int(data[2]), {})) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + buttons = ButtonMaker() + buttons.data_button("Back", f"rss back {user_id}") + if data[1] == "pause": + buttons.data_button("Pause AllMyFeeds", f"rss uallpause {user_id}") + elif data[1] == "resume": + buttons.data_button("Resume AllMyFeeds", f"rss uallresume {user_id}") + elif data[1] == "unsubscribe": + buttons.data_button("Unsub AllMyFeeds", f"rss uallunsub {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + await edit_message( + message, + f"Send one or more rss titles separated by space to {data[1]}.\nTimeout: 60 sec.", + button, + ) + pfunc = partial(rss_update, pre_event=query, state=data[1]) + await event_handler(client, query, pfunc) + elif data[1] == "edit": + handler_dict[user_id] = False + if len(rss_dict.get(int(data[2]), {})) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + buttons = ButtonMaker() + buttons.data_button("Back", f"rss back {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + msg = """Send one or more rss titles with new filters or command separated by new line. +Examples: +Title1 -c mirror -up remote:path/subdir -exf none -inf 1080 or 720 -stv true +Title2 -c none -inf none -stv false +Title3 -c mirror -rcf xxx -up xxx -z pswd -stv false +Note: Only what you provide will be edited, the rest will be the same like example 2: exf will stay same as it is. +Timeout: 60 sec. Argument -c for command and arguments + """ + await edit_message(message, msg, button) + pfunc = partial(rss_edit, pre_event=query) + await event_handler(client, query, pfunc) + elif data[1].startswith("uall"): + handler_dict[user_id] = False + if len(rss_dict.get(int(data[2]), {})) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + return + await query.answer() + if data[1].endswith("unsub"): + async with rss_dict_lock: + del rss_dict[int(data[2])] + await database.rss_delete(int(data[2])) + await update_rss_menu(query) + elif data[1].endswith("pause"): + async with rss_dict_lock: + for info in rss_dict[int(data[2])].values(): + info["paused"] = True + await database.rss_update(int(data[2])) + elif data[1].endswith("resume"): + async with rss_dict_lock: + for info in rss_dict[int(data[2])].values(): + info["paused"] = False + if scheduler.state == 2: + scheduler.resume() + await database.rss_update(int(data[2])) + await update_rss_menu(query) + elif data[1].startswith("all"): + if len(rss_dict) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + return + await query.answer() + if data[1].endswith("unsub"): + async with rss_dict_lock: + rss_dict.clear() + await database.trunc_table("rss") + await update_rss_menu(query) + elif data[1].endswith("pause"): + async with rss_dict_lock: + for user_feeds in rss_dict.values(): + for feed in user_feeds.values(): + feed["paused"] = True + if scheduler.running: + scheduler.pause() + await database.rss_update_all() + elif data[1].endswith("resume"): + async with rss_dict_lock: + for user_feeds in rss_dict.values(): + for feed in user_feeds.values(): + feed["paused"] = False + if scheduler.state == 2: + scheduler.resume() + elif not scheduler.running: + add_job() + scheduler.start() + await update_rss_menu(query) + await database.rss_update_all() + elif data[1] == "deluser": + if len(rss_dict) == 0: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + buttons = ButtonMaker() + buttons.data_button("Back", f"rss back {user_id}") + buttons.data_button("Close", f"rss close {user_id}") + button = buttons.build_menu(2) + msg = "Send one or more user_id separated by space to delete their resources.\nTimeout: 60 sec." + await edit_message(message, msg, button) + pfunc = partial(rss_delete, pre_event=query) + await event_handler(client, query, pfunc) + elif data[1] == "listall": + if not rss_dict: + await query.answer(text="No subscriptions!", show_alert=True) + else: + await query.answer() + start = int(data[3]) + await rss_list(query, start, all_users=True) + elif data[1] == "shutdown": + if scheduler.running: + await query.answer() + scheduler.shutdown(wait=False) + await sleep(0.5) + await update_rss_menu(query) + else: + await query.answer(text="Already Stopped!", show_alert=True) + elif data[1] == "start": + if not scheduler.running: + await query.answer() + add_job() + scheduler.start() + await update_rss_menu(query) + else: + await query.answer(text="Already Running!", show_alert=True) + + +async def rss_monitor(): + chat = Config.RSS_CHAT + if not chat: + LOGGER.warning("RSS_CHAT not added! Shutting down rss scheduler...") + scheduler.shutdown(wait=False) + return + if len(rss_dict) == 0: + scheduler.pause() + return + all_paused = True + rss_topic_id = rss_chat_id = None + if isinstance(chat, int): + rss_chat_id = chat + elif "|" in chat: + rss_chat_id, rss_topic_id = list( + map( + lambda x: int(x) if x.lstrip("-").isdigit() else x, + chat.split("|", 1), + ) + ) + elif chat.lstrip("-").isdigit(): + rss_chat_id = int(chat) + for user, items in list(rss_dict.items()): + for title, data in items.items(): + try: + if data["paused"]: + continue + tries = 0 + while True: + try: + async with AsyncClient( + headers=headers, + follow_redirects=True, + timeout=60, + verify=False, + ) as client: + res = await client.get(data["link"]) + html = res.text + break + except: + tries += 1 + if tries > 3: + raise + continue + rss_d = feed_parse(html) + if not rss_d.entries: + LOGGER.warning( + f"No entries found for > Feed Title: {title} - Feed Link: {data['link']}" + ) + continue + entry0 = rss_d.entries[0] + links = entry0.get("links", []) + if len(links) > 1: + last_link = links[1].get("href") + elif links: + last_link = links[0].get("href") + else: + last_link = entry0.get("link") + last_title = entry0.get("title") + all_paused = False + if data["last_feed"] == last_link or data["last_title"] == last_title: + continue + feed_count = 0 + while True: + try: + await sleep(10) + except: + raise RssShutdownException("Rss Monitor Stopped!") + try: + item_title = rss_d.entries[feed_count]["title"] + try: + url = rss_d.entries[feed_count]["links"][1]["href"] + except IndexError: + url = rss_d.entries[feed_count]["link"] + if data["last_feed"] == url or data["last_title"] == item_title: + break + if rss_d.entries[feed_count].get("size"): + size = int(rss_d.entries[feed_count]["size"]) + elif rss_d.entries[feed_count].get("summary"): + summary = rss_d.entries[feed_count]["summary"] + matches = size_regex.findall(summary) + sizes = [match[0] for match in matches] + size = get_size_bytes(sizes[0]) + else: + size = 0 + except IndexError: + LOGGER.warning( + f"Reached Max index no. {feed_count} for this feed: {title}. Maybe you need to use less RSS_DELAY to not miss some torrents" + ) + break + parse = True + for flist in data["inf"]: + if ( + data.get("sensitive", False) + and all(x.lower() not in item_title.lower() for x in flist) + ) or ( + not data.get("sensitive", False) + and all(x not in item_title for x in flist) + ): + parse = False + feed_count += 1 + break + if not parse: + continue + for flist in data["exf"]: + if ( + data.get("sensitive", False) + and any(x.lower() in item_title.lower() for x in flist) + ) or ( + not data.get("sensitive", False) + and any(x in item_title for x in flist) + ): + parse = False + feed_count += 1 + break + if not parse: + continue + if command := data["command"]: + if ( + size + and Config.RSS_SIZE_LIMIT + and Config.RSS_SIZE_LIMIT < size + ): + feed_count += 1 + continue + cmd = command.split(maxsplit=1) + cmd.insert(1, url) + feed_msg = " ".join(cmd) + if not feed_msg.startswith("/"): + feed_msg = f"/{feed_msg}" + else: + feed_msg = f"Name: {item_title.replace('>', '').replace('<', '')}" + feed_msg += f"\n\nLink: {url}" + if size: + feed_msg += f"\nSize: {get_readable_file_size(size)}" + feed_msg += ( + f"\nTag: {data['tag']} {user}" + ) + await send_rss(feed_msg, rss_chat_id, rss_topic_id) + feed_count += 1 + async with rss_dict_lock: + if user not in rss_dict or not rss_dict[user].get(title, False): + continue + rss_dict[user][title].update( + {"last_feed": last_link, "last_title": last_title} + ) + await database.rss_update(user) + LOGGER.info(f"Feed Name: {title}") + LOGGER.info(f"Last item: {last_link}") + except RssShutdownException as ex: + LOGGER.info(ex) + break + except Exception as e: + LOGGER.error(f"{e} - Feed Name: {title} - Feed Link: {data['link']}") + continue + if all_paused: + scheduler.pause() + + +def add_job(): + scheduler.add_job( + rss_monitor, + trigger=IntervalTrigger(seconds=Config.RSS_DELAY), + id="0", + name="RSS", + misfire_grace_time=15, + max_instances=1, + next_run_time=datetime.now() + timedelta(seconds=20), + replace_existing=True, + ) + + +add_job() +scheduler.start() diff --git a/bot/modules/search.py b/bot/modules/search.py new file mode 100644 index 0000000000000000000000000000000000000000..9b89c6d7920c07833ab1d3e5ba041ab57ed115fd --- /dev/null +++ b/bot/modules/search.py @@ -0,0 +1,297 @@ +from httpx import AsyncClient +from html import escape +from urllib.parse import quote + +from .. import LOGGER +from ..core.config_manager import Config +from ..core.torrent_manager import TorrentManager +from ..helper.ext_utils.bot_utils import new_task +from ..helper.ext_utils.status_utils import get_readable_file_size +from ..helper.ext_utils.telegraph_helper import telegraph +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import edit_message, send_message + +PLUGINS = [] +SITES = None +TELEGRAPH_LIMIT = 300 + + +async def initiate_search_tools(): + qb_plugins = await TorrentManager.qbittorrent.search.plugins() + if qb_plugins: + names = [plugin.name for plugin in qb_plugins] + await TorrentManager.qbittorrent.search.uninstall_plugin(names) + PLUGINS.clear() + if Config.SEARCH_PLUGINS: + await TorrentManager.qbittorrent.search.install_plugin(Config.SEARCH_PLUGINS) + + if Config.SEARCH_API_LINK: + global SITES + try: + async with AsyncClient() as client: + response = await client.get(f"{Config.SEARCH_API_LINK}/api/v1/sites") + data = response.json() + SITES = { + str(site): str(site).capitalize() for site in data["supported_sites"] + } + SITES["all"] = "All" + except Exception as e: + LOGGER.error( + f"{e} Can't fetching sites from SEARCH_API_LINK make sure use latest version of API" + ) + SITES = None + + +async def search(key, site, message, method): + if method.startswith("api"): + if method == "apisearch": + LOGGER.info(f"API Searching: {key} from {site}") + if site == "all": + api = f"{Config.SEARCH_API_LINK}/api/v1/all/search?query={key}&limit={Config.SEARCH_LIMIT}" + else: + api = f"{Config.SEARCH_API_LINK}/api/v1/search?site={site}&query={key}&limit={Config.SEARCH_LIMIT}" + elif method == "apitrend": + LOGGER.info(f"API Trending from {site}") + if site == "all": + api = f"{Config.SEARCH_API_LINK}/api/v1/all/trending?limit={Config.SEARCH_LIMIT}" + else: + api = f"{Config.SEARCH_API_LINK}/api/v1/trending?site={site}&limit={Config.SEARCH_LIMIT}" + elif method == "apirecent": + LOGGER.info(f"API Recent from {site}") + if site == "all": + api = f"{Config.SEARCH_API_LINK}/api/v1/all/recent?limit={Config.SEARCH_LIMIT}" + else: + api = f"{Config.SEARCH_API_LINK}/api/v1/recent?site={site}&limit={Config.SEARCH_LIMIT}" + try: + async with AsyncClient() as client: + response = await client.get(api) + search_results = response.json() + if "error" in search_results or search_results["total"] == 0: + await edit_message( + message, + f"No result found for {key}\nTorrent Site:- {SITES.get(site)}", + ) + return + msg = f"Found {min(search_results['total'], TELEGRAPH_LIMIT)}" + if method == "apitrend": + msg += f" trending result(s)\nTorrent Site:- {SITES.get(site)}" + elif method == "apirecent": + msg += ( + f" recent result(s)\nTorrent Site:- {SITES.get(site)}" + ) + else: + msg += f" result(s) for {key}\nTorrent Site:- {SITES.get(site)}" + search_results = search_results["data"] + except Exception as e: + await edit_message(message, str(e)) + return + else: + LOGGER.info(f"PLUGINS Searching: {key} from {site}") + search = await TorrentManager.qbittorrent.search.start( + pattern=key, plugins=[site], category="all" + ) + search_id = search.id + while True: + result_status = await TorrentManager.qbittorrent.search.status(search_id) + status = result_status[0].status + if status != "Running": + break + dict_search_results = await TorrentManager.qbittorrent.search.results( + id=search_id, limit=TELEGRAPH_LIMIT + ) + search_results = dict_search_results.results + total_results = dict_search_results.total + if total_results == 0: + await edit_message( + message, + f"No result found for {key}\nTorrent Site:- {site.capitalize()}", + ) + return + msg = f"Found {min(total_results, TELEGRAPH_LIMIT)}" + msg += f" result(s) for {key}\nTorrent Site:- {site.capitalize()}" + await TorrentManager.qbittorrent.search.delete(search_id) + link = await get_result(search_results, key, message, method) + buttons = ButtonMaker() + buttons.url_button("🔎 VIEW", link) + button = buttons.build_menu(1) + await edit_message(message, msg, button) + + +async def get_result(search_results, key, message, method): + telegraph_content = [] + if method == "apirecent": + msg = "

API Recent Results

" + elif method == "apisearch": + msg = f"

API Search Result(s) For {key}

" + elif method == "apitrend": + msg = "

API Trending Results

" + else: + msg = f"

PLUGINS Search Result(s) For {key}

" + for index, result in enumerate(search_results, start=1): + if method.startswith("api"): + try: + if "name" in result.keys(): + msg += f"{escape(result['name'])}
" + if "torrents" in result.keys(): + for subres in result["torrents"]: + msg += f"Quality: {subres['quality']} | Type: {subres['type']} | " + msg += f"Size: {subres['size']}
" + if "torrent" in subres.keys(): + msg += f"Direct Link
" + elif "magnet" in subres.keys(): + msg += "Share Magnet to " + msg += f"Telegram
" + msg += "
" + else: + msg += f"Size: {result['size']}
" + try: + msg += f"Seeders: {result['seeders']} | Leechers: {result['leechers']}
" + except: + pass + if "torrent" in result.keys(): + msg += f"Direct Link

" + elif "magnet" in result.keys(): + msg += "Share Magnet to " + msg += f"Telegram

" + else: + msg += "
" + except: + continue + else: + msg += f"{escape(result.fileName)}
" + msg += f"Size: {get_readable_file_size(result.fileSize)}
" + msg += f"Seeders: {result.nbSeeders} | Leechers: {result.nbLeechers}
" + link = result.fileUrl + if link.startswith("magnet:"): + msg += f"Share Magnet to Telegram

" + else: + msg += f"Direct Link

" + + if len(msg.encode("utf-8")) > 39000: + telegraph_content.append(msg) + msg = "" + + if index == TELEGRAPH_LIMIT: + break + + if msg != "": + telegraph_content.append(msg) + + await edit_message( + message, f"Creating {len(telegraph_content)} Telegraph pages." + ) + path = [ + ( + await telegraph.create_page( + title="Mirror-leech-bot Torrent Search", content=content + ) + )["path"] + for content in telegraph_content + ] + if len(path) > 1: + await edit_message( + message, f"Editing {len(telegraph_content)} Telegraph pages." + ) + await telegraph.edit_telegraph(path, telegraph_content) + return f"https://telegra.ph/{path[0]}" + + +def api_buttons(user_id, method): + buttons = ButtonMaker() + for data, name in SITES.items(): + buttons.data_button(name, f"torser {user_id} {data} {method}") + buttons.data_button("Cancel", f"torser {user_id} cancel") + return buttons.build_menu(2) + + +async def plugin_buttons(user_id): + buttons = ButtonMaker() + if not PLUGINS: + pl = await TorrentManager.qbittorrent.search.plugins() + for i in pl: + PLUGINS.append(i.name) + for siteName in PLUGINS: + buttons.data_button( + siteName.capitalize(), f"torser {user_id} {siteName} plugin" + ) + buttons.data_button("All", f"torser {user_id} all plugin") + buttons.data_button("Cancel", f"torser {user_id} cancel") + return buttons.build_menu(2) + + +@new_task +async def torrent_search(_, message): + user_id = message.from_user.id + buttons = ButtonMaker() + key = message.text.split() + if SITES is None and not Config.SEARCH_PLUGINS: + await send_message( + message, "No API link or search PLUGINS added for this function" + ) + elif len(key) == 1 and SITES is None: + await send_message(message, "Send a search key along with command") + elif len(key) == 1: + buttons.data_button("Trending", f"torser {user_id} apitrend") + buttons.data_button("Recent", f"torser {user_id} apirecent") + buttons.data_button("Cancel", f"torser {user_id} cancel") + button = buttons.build_menu(2) + await send_message(message, "Send a search key along with command", button) + elif SITES is not None and Config.SEARCH_PLUGINS: + buttons.data_button("Api", f"torser {user_id} apisearch") + buttons.data_button("Plugins", f"torser {user_id} plugin") + buttons.data_button("Cancel", f"torser {user_id} cancel") + button = buttons.build_menu(2) + await send_message(message, "Choose tool to search:", button) + elif SITES is not None: + button = api_buttons(user_id, "apisearch") + await send_message(message, "Choose site to search | API:", button) + else: + button = await plugin_buttons(user_id) + await send_message(message, "Choose site to search | Plugins:", button) + + +@new_task +async def torrent_search_update(_, query): + user_id = query.from_user.id + message = query.message + key = message.reply_to_message.text.split(maxsplit=1) + key = key[1].strip() if len(key) > 1 else None + data = query.data.split() + if user_id != int(data[1]): + await query.answer("Not Yours!", show_alert=True) + elif data[2].startswith("api"): + await query.answer() + button = api_buttons(user_id, data[2]) + await edit_message(message, "Choose site:", button) + elif data[2] == "plugin": + await query.answer() + button = await plugin_buttons(user_id) + await edit_message(message, "Choose site:", button) + elif data[2] != "cancel": + await query.answer() + site = data[2] + method = data[3] + if method.startswith("api"): + if key is None: + if method == "apirecent": + endpoint = "Recent" + elif method == "apitrend": + endpoint = "Trending" + await edit_message( + message, + f"Listing {endpoint} Items...\nTorrent Site:- {SITES.get(site)}", + ) + else: + await edit_message( + message, + f"Searching for {key}\nTorrent Site:- {SITES.get(site)}", + ) + else: + await edit_message( + message, + f"Searching for {key}\nTorrent Site:- {site.capitalize()}", + ) + await search(key, site, message, method) + else: + await query.answer() + await edit_message(message, "Search has been canceled!") diff --git a/bot/modules/services.py b/bot/modules/services.py new file mode 100644 index 0000000000000000000000000000000000000000..3d45e7484f9dd04f1aedab32753a4f710fe19f2d --- /dev/null +++ b/bot/modules/services.py @@ -0,0 +1,42 @@ +from time import time + +from ..helper.ext_utils.bot_utils import new_task +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import send_message, edit_message, send_file +from ..helper.telegram_helper.filters import CustomFilters +from ..helper.telegram_helper.bot_commands import BotCommands + + +@new_task +async def start(_, message): + buttons = ButtonMaker() + buttons.url_button( + "Repo", "https://www.github.com/anasty17/mirror-leech-telegram-bot" + ) + buttons.url_button("Code Owner", "https://t.me/anas_tayyar") + reply_markup = buttons.build_menu(2) + if await CustomFilters.authorized(_, message): + start_string = f""" +This bot can mirror from links|tgfiles|torrents|nzb|rclone-cloud to any rclone cloud, Google Drive or to telegram. +Type /{BotCommands.HelpCommand} to get a list of available commands +""" + await send_message(message, start_string, reply_markup) + else: + await send_message( + message, + "This bot can mirror from links|tgfiles|torrents|nzb|rclone-cloud to any rclone cloud, Google Drive or to telegram.\n\n⚠️ You Are not authorized user! Deploy your own mirror-leech bot", + reply_markup, + ) + + +@new_task +async def ping(_, message): + start_time = int(round(time() * 1000)) + reply = await send_message(message, "Starting Ping") + end_time = int(round(time() * 1000)) + await edit_message(reply, f"{end_time - start_time} ms") + + +@new_task +async def log(_, message): + await send_file(message, "log.txt") diff --git a/bot/modules/shell.py b/bot/modules/shell.py new file mode 100644 index 0000000000000000000000000000000000000000..55b998d00c5259bd41f91d2e533f5a98ca60c4ce --- /dev/null +++ b/bot/modules/shell.py @@ -0,0 +1,30 @@ +from io import BytesIO + +from .. import LOGGER +from ..helper.ext_utils.bot_utils import cmd_exec, new_task +from ..helper.telegram_helper.message_utils import send_message, send_file + + +@new_task +async def run_shell(_, message): + cmd = message.text.split(maxsplit=1) + if len(cmd) == 1: + await send_message(message, "No command to execute was given.") + return + cmd = cmd[1] + stdout, stderr, _ = await cmd_exec(cmd, shell=True) + reply = "" + if len(stdout) != 0: + reply += f"*Stdout*\n{stdout}\n" + LOGGER.info(f"Shell - {cmd} - {stdout}") + if len(stderr) != 0: + reply += f"*Stderr*\n{stderr}" + LOGGER.error(f"Shell - {cmd} - {stderr}") + if len(reply) > 3000: + with BytesIO(str.encode(reply)) as out_file: + out_file.name = "shell_output.txt" + await send_file(message, out_file) + elif len(reply) != 0: + await send_message(message, reply) + else: + await send_message(message, "No Reply") diff --git a/bot/modules/stats.py b/bot/modules/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..d98e5702cdb0b74ff238b4c9481f607dcc831ec2 --- /dev/null +++ b/bot/modules/stats.py @@ -0,0 +1,102 @@ +from time import time +from re import search as research +from asyncio import gather +from aiofiles.os import path as aiopath +from psutil import ( + disk_usage, + cpu_percent, + swap_memory, + cpu_count, + virtual_memory, + net_io_counters, + boot_time, +) + +from .. import bot_start_time +from ..helper.ext_utils.status_utils import get_readable_file_size, get_readable_time +from ..helper.ext_utils.bot_utils import cmd_exec, new_task +from ..helper.telegram_helper.message_utils import send_message + +commands = { + "aria2": (["aria2c", "--version"], r"aria2 version ([\d.]+)"), + "qBittorrent": (["qbittorrent-nox", "--version"], r"qBittorrent v([\d.]+)"), + "SABnzbd+": (["sabnzbdplus", "--version"], r"sabnzbdplus-([\d.]+)"), + "python": (["python3", "--version"], r"Python ([\d.]+)"), + "rclone": (["rclone", "--version"], r"rclone v([\d.]+)"), + "yt-dlp": (["yt-dlp", "--version"], r"([\d.]+)"), + "ffmpeg": (["ffmpeg", "-version"], r"ffmpeg version ([\d.]+(-\w+)?).*"), + "7z": (["7z", "i"], r"7-Zip ([\d.]+)"), +} + + +@new_task +async def bot_stats(_, message): + total, used, free, disk = disk_usage("/") + swap = swap_memory() + memory = virtual_memory() + per_cpu = cpu_percent(interval=1, percpu=True) + per_cpu_str = " | ".join([f"CPU{i+1}: {round(p)}%" for i, p in enumerate(per_cpu)]) + stats = f""" +Commit Date: {commands["commit"]} + +Bot Uptime: {get_readable_time(time() - bot_start_time)} +OS Uptime: {get_readable_time(time() - boot_time())} + +Total Disk Space: {get_readable_file_size(total)} +Used: {get_readable_file_size(used)} | Free: {get_readable_file_size(free)} + +Upload: {get_readable_file_size(net_io_counters().bytes_sent)} +Download: {get_readable_file_size(net_io_counters().bytes_recv)} + +CPU: {cpu_percent(interval=1)}% +CPU Cores: +{per_cpu_str} + +RAM: {memory.percent}% +DISK: {disk}% + +Physical Cores: {cpu_count(logical=False)} +Total Cores: {cpu_count()} +SWAP: {get_readable_file_size(swap.total)} | Used: {swap.percent}% + +Memory Total: {get_readable_file_size(memory.total)} +Memory Free: {get_readable_file_size(memory.available)} +Memory Used: {get_readable_file_size(memory.used)} + +python: {commands["python"]} +aria2: {commands["aria2"]} +qBittorrent: {commands["qBittorrent"]} +SABnzbd+: {commands["SABnzbd+"]} +rclone: {commands["rclone"]} +yt-dlp: {commands["yt-dlp"]} +ffmpeg: {commands["ffmpeg"]} +7z: {commands["7z"]} +""" + await send_message(message, stats) + + +async def get_version_async(command, regex): + try: + out, err, code = await cmd_exec(command) + if code != 0: + return f"Error: {err}" + match = research(regex, out) + return match.group(1) if match else "Version not found" + except Exception as e: + return f"Exception: {str(e)}" + + +@new_task +async def get_packages_version(): + tasks = [get_version_async(command, regex) for command, regex in commands.values()] + versions = await gather(*tasks) + for tool, version in zip(commands.keys(), versions): + commands[tool] = version + if await aiopath.exists(".git"): + last_commit = await cmd_exec( + "git log -1 --date=short --pretty=format:'%cd From %cr'", True + ) + last_commit = last_commit[0] + else: + last_commit = "No UPSTREAM_REPO" + commands["commit"] = last_commit diff --git a/bot/modules/status.py b/bot/modules/status.py new file mode 100644 index 0000000000000000000000000000000000000000..1491bd4cd53c68b842f60ce550fa39c3eedab10b --- /dev/null +++ b/bot/modules/status.py @@ -0,0 +1,184 @@ +from psutil import cpu_percent, virtual_memory, disk_usage +from time import time +from asyncio import gather, iscoroutinefunction + +from .. import ( + task_dict_lock, + status_dict, + task_dict, + bot_start_time, + intervals, + sabnzbd_client, + DOWNLOAD_DIR, +) +from ..core.torrent_manager import TorrentManager +from ..core.jdownloader_booter import jdownloader +from ..helper.ext_utils.bot_utils import new_task +from ..helper.ext_utils.status_utils import ( + MirrorStatus, + get_readable_file_size, + get_readable_time, + speed_string_to_bytes, +) +from ..helper.telegram_helper.bot_commands import BotCommands +from ..helper.telegram_helper.message_utils import ( + send_message, + delete_message, + auto_delete_message, + send_status_message, + update_status_message, + edit_message, +) +from ..helper.telegram_helper.button_build import ButtonMaker + + +@new_task +async def task_status(_, message): + async with task_dict_lock: + count = len(task_dict) + if count == 0: + currentTime = get_readable_time(time() - bot_start_time) + free = get_readable_file_size(disk_usage(DOWNLOAD_DIR).free) + msg = f"No Active Tasks!\nEach user can get status for his tasks by adding me or user_id after cmd: /{BotCommands.StatusCommand} me" + msg += ( + f"\nCPU: {cpu_percent()}% | FREE: {free}" + f"\nRAM: {virtual_memory().percent}% | UPTIME: {currentTime}" + ) + reply_message = await send_message(message, msg) + await auto_delete_message(message, reply_message) + else: + text = message.text.split() + if len(text) > 1: + user_id = message.from_user.id if text[1] == "me" else int(text[1]) + else: + user_id = 0 + sid = message.chat.id + if obj := intervals["status"].get(sid): + obj.cancel() + del intervals["status"][sid] + await send_status_message(message, user_id) + await delete_message(message) + + +async def get_download_status(download): + tool = download.tool + if tool in [ + "telegram", + "yt-dlp", + "rclone", + "gDriveApi", + ]: + speed = download.speed() + else: + speed = 0 + return ( + await download.status() + if iscoroutinefunction(download.status) + else download.status() + ), speed + + +@new_task +async def status_pages(_, query): + data = query.data.split() + key = int(data[1]) + await query.answer() + if data[2] == "ref": + await update_status_message(key, force=True) + elif data[2] in ["nex", "pre"]: + async with task_dict_lock: + if key in status_dict: + if data[2] == "nex": + status_dict[key]["page_no"] += status_dict[key]["page_step"] + else: + status_dict[key]["page_no"] -= status_dict[key]["page_step"] + elif data[2] == "ps": + async with task_dict_lock: + if key in status_dict: + status_dict[key]["page_step"] = int(data[3]) + elif data[2] == "st": + async with task_dict_lock: + if key in status_dict: + status_dict[key]["status"] = data[3] + await update_status_message(key, force=True) + elif data[2] == "ov": + ds, ss = await TorrentManager.overall_speed() + if sabnzbd_client.LOGGED_IN: + sds = await sabnzbd_client.get_downloads() + sds = int(float(sds["queue"].get("kbpersec", "0"))) * 1024 + ds += sds + if jdownloader.is_connected: + jdres = await jdownloader.device.downloadcontroller.get_speed_in_bytes() + ds += jdres + message = query.message + tasks = { + "Download": 0, + "Upload": 0, + "Seed": 0, + "Archive": 0, + "Extract": 0, + "Split": 0, + "QueueDl": 0, + "QueueUp": 0, + "Clone": 0, + "CheckUp": 0, + "Pause": 0, + "SamVid": 0, + "ConvertMedia": 0, + "FFmpeg": 0, + } + dl_speed = ds + up_speed = 0 + seed_speed = ss + async with task_dict_lock: + status_results = await gather( + *(get_download_status(download) for download in task_dict.values()) + ) + for status, speed in status_results: + match status: + case MirrorStatus.STATUS_DOWNLOAD: + tasks["Download"] += 1 + if speed: + dl_speed += speed_string_to_bytes(speed) + case MirrorStatus.STATUS_UPLOAD: + tasks["Upload"] += 1 + up_speed += speed_string_to_bytes(speed) + case MirrorStatus.STATUS_SEED: + tasks["Seed"] += 1 + case MirrorStatus.STATUS_ARCHIVE: + tasks["Archive"] += 1 + case MirrorStatus.STATUS_EXTRACT: + tasks["Extract"] += 1 + case MirrorStatus.STATUS_SPLIT: + tasks["Split"] += 1 + case MirrorStatus.STATUS_QUEUEDL: + tasks["QueueDl"] += 1 + case MirrorStatus.STATUS_QUEUEUP: + tasks["QueueUp"] += 1 + case MirrorStatus.STATUS_CLONE: + tasks["Clone"] += 1 + case MirrorStatus.STATUS_CHECK: + tasks["CheckUp"] += 1 + case MirrorStatus.STATUS_PAUSED: + tasks["Pause"] += 1 + case MirrorStatus.STATUS_SAMVID: + tasks["SamVid"] += 1 + case MirrorStatus.STATUS_CONVERT: + tasks["ConvertMedia"] += 1 + case MirrorStatus.STATUS_FFMPEG: + tasks["FFmpeg"] += 1 + case _: + tasks["Download"] += 1 + + msg = f"""DL: {tasks['Download']} | UP: {tasks['Upload']} | SD: {tasks['Seed']} | AR: {tasks['Archive']} +EX: {tasks['Extract']} | SP: {tasks['Split']} | QD: {tasks['QueueDl']} | QU: {tasks['QueueUp']} +CL: {tasks['Clone']} | CK: {tasks['CheckUp']} | PA: {tasks['Pause']} | SV: {tasks['SamVid']} +CM: {tasks['ConvertMedia']} | FF: {tasks['FFmpeg']} + +ODLS: {get_readable_file_size(dl_speed)}/s +OULS: {get_readable_file_size(up_speed)}/s +OSDS: {get_readable_file_size(seed_speed)}/s +""" + button = ButtonMaker() + button.data_button("Back", f"status {data[1]} ref") + await edit_message(message, msg, button.build_menu()) diff --git a/bot/modules/users_settings.py b/bot/modules/users_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..37980e6c690e2f9d6c50e94e7aa0658dd4c486d2 --- /dev/null +++ b/bot/modules/users_settings.py @@ -0,0 +1,791 @@ +from aiofiles.os import remove, path as aiopath, makedirs +from asyncio import sleep +from functools import partial +from html import escape +from io import BytesIO +from os import getcwd +from pyrogram.filters import create +from pyrogram.handlers import MessageHandler +from time import time +from re import findall + +from .. import ( + user_data, + excluded_extensions, + auth_chats, + sudo_users, + included_extensions, +) +from ..core.config_manager import Config +from ..core.telegram_manager import TgClient +from ..helper.ext_utils.db_handler import database +from ..helper.ext_utils.media_utils import create_thumb +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.ext_utils.help_messages import user_settings_text +from ..helper.ext_utils.bot_utils import ( + update_user_ldata, + new_task, + get_size_bytes, +) +from ..helper.telegram_helper.message_utils import ( + send_message, + edit_message, + send_file, + delete_message, +) + +handler_dict = {} + +leech_options = [ + "THUMBNAIL", + "LEECH_SPLIT_SIZE", + "LEECH_DUMP_CHAT", + "LEECH_FILENAME_PREFIX", + "THUMBNAIL_LAYOUT", + "CLONE_DUMP_CHATS" +] +rclone_options = ["RCLONE_CONFIG", "RCLONE_PATH", "RCLONE_FLAGS"] +gdrive_options = ["TOKEN_PICKLE", "GDRIVE_ID", "INDEX_URL"] + + +async def get_user_settings(from_user, stype="main"): + user_id = from_user.id + name = from_user.mention + buttons = ButtonMaker() + rclone_conf = f"rclone/{user_id}.conf" + token_pickle = f"tokens/{user_id}.pickle" + user_dict = user_data.get(user_id, {}) + + if stype == "leech": + thumbpath = f"thumbnails/{user_id}.jpg" + buttons.data_button("Thumbnail", f"userset {user_id} menu THUMBNAIL") + thumbmsg = "Exists" if await aiopath.exists(thumbpath) else "Not Exists" + buttons.data_button( + "Leech Split Size", f"userset {user_id} menu LEECH_SPLIT_SIZE" + ) + if user_dict.get("LEECH_SPLIT_SIZE", False): + split_size = user_dict["LEECH_SPLIT_SIZE"] + else: + split_size = Config.LEECH_SPLIT_SIZE + buttons.data_button( + "Leech Destination", f"userset {user_id} menu LEECH_DUMP_CHAT" + ) + if user_dict.get("LEECH_DUMP_CHAT", False): + leech_dest = user_dict["LEECH_DUMP_CHAT"] + elif "LEECH_DUMP_CHAT" not in user_dict and Config.LEECH_DUMP_CHAT: + leech_dest = Config.LEECH_DUMP_CHAT + else: + leech_dest = "None" + buttons.data_button( + "Leech Prefix", f"userset {user_id} menu LEECH_FILENAME_PREFIX" + ) + if user_dict.get("LEECH_FILENAME_PREFIX", False): + lprefix = user_dict["LEECH_FILENAME_PREFIX"] + elif "LEECH_FILENAME_PREFIX" not in user_dict and Config.LEECH_FILENAME_PREFIX: + lprefix = Config.LEECH_FILENAME_PREFIX + else: + lprefix = "None" + if ( + user_dict.get("AS_DOCUMENT", False) + or "AS_DOCUMENT" not in user_dict + and Config.AS_DOCUMENT + ): + ltype = "DOCUMENT" + buttons.data_button("Send As Media", f"userset {user_id} tog AS_DOCUMENT f") + else: + ltype = "MEDIA" + buttons.data_button( + "Send As Document", f"userset {user_id} tog AS_DOCUMENT t" + ) + if ( + user_dict.get("EQUAL_SPLITS", False) + or "EQUAL_SPLITS" not in user_dict + and Config.EQUAL_SPLITS + ): + buttons.data_button( + "Disable Equal Splits", f"userset {user_id} tog EQUAL_SPLITS f" + ) + equal_splits = "Enabled" + else: + buttons.data_button( + "Enable Equal Splits", f"userset {user_id} tog EQUAL_SPLITS t" + ) + equal_splits = "Disabled" + if ( + user_dict.get("MEDIA_GROUP", False) + or "MEDIA_GROUP" not in user_dict + and Config.MEDIA_GROUP + ): + buttons.data_button( + "Disable Media Group", f"userset {user_id} tog MEDIA_GROUP f" + ) + media_group = "Enabled" + else: + buttons.data_button( + "Enable Media Group", f"userset {user_id} tog MEDIA_GROUP t" + ) + media_group = "Disabled" + if ( + TgClient.IS_PREMIUM_USER + and user_dict.get("USER_TRANSMISSION", False) + or "USER_TRANSMISSION" not in user_dict + and Config.USER_TRANSMISSION + ): + buttons.data_button( + "Leech by Bot", f"userset {user_id} tog USER_TRANSMISSION f" + ) + leech_method = "user" + elif TgClient.IS_PREMIUM_USER: + leech_method = "bot" + buttons.data_button( + "Leech by User", f"userset {user_id} tog USER_TRANSMISSION t" + ) + else: + leech_method = "bot" + + if ( + TgClient.IS_PREMIUM_USER + and user_dict.get("HYBRID_LEECH", False) + or "HYBRID_LEECH" not in user_dict + and Config.HYBRID_LEECH + ): + hybrid_leech = "Enabled" + buttons.data_button( + "Disable Hybride Leech", f"userset {user_id} tog HYBRID_LEECH f" + ) + elif TgClient.IS_PREMIUM_USER: + hybrid_leech = "Disabled" + buttons.data_button( + "Enable HYBRID Leech", f"userset {user_id} tog HYBRID_LEECH t" + ) + else: + hybrid_leech = "Disabled" + + if ( + user_dict.get("FILES_LINKS", False) + or "FILES_LINKS" not in user_dict + and Config.FILES_LINKS + ): + fl = "Enabled" + buttons.data_button( + "Disable FILES LINKS", f"userset {user_id} tog FILES_LINKS f" + ) + else: + fl = "Disabled" + buttons.data_button( + "Enable FILES LINKS", f"userset {user_id} tog FILES_LINKS t" + ) + buttons.data_button( + "Thumbnail Layout", f"userset {user_id} menu THUMBNAIL_LAYOUT" + ) + if user_dict.get("THUMBNAIL_LAYOUT", False): + thumb_layout = user_dict["THUMBNAIL_LAYOUT"] + elif "THUMBNAIL_LAYOUT" not in user_dict and Config.THUMBNAIL_LAYOUT: + thumb_layout = Config.THUMBNAIL_LAYOUT + else: + thumb_layout = "None" + buttons.data_button( + "Clone Dump Chats", f"userset {user_id} menu CLONE_DUMP_CHATS" + ) + if user_dict.get("CLONE_DUMP_CHATS", False): + cdc = user_dict["CLONE_DUMP_CHATS"] + elif "CLONE_DUMP_CHATS" not in user_dict and Config.CLONE_DUMP_CHATS: + cdc = Config.CLONE_DUMP_CHATS + else: + cdc = "None" + buttons.data_button("Back", f"userset {user_id} back") + buttons.data_button("Close", f"userset {user_id} close") + + text = f"""Leech Settings for {name} +Leech Type is {ltype} +Custom Thumbnail {thumbmsg} +Leech Split Size is {split_size} +Equal Splits is {equal_splits} +Media Group is {media_group} +Leech Prefix is {escape(lprefix)} +Leech Destination is {leech_dest} +Clone Dump Chats is {cdc} +Leech by {leech_method} session +HYBRID Leech is {hybrid_leech} +Thumbnail Layout is {thumb_layout} +Files Links is {fl} +""" + elif stype == "rclone": + buttons.data_button("Rclone Config", f"userset {user_id} menu RCLONE_CONFIG") + buttons.data_button( + "Default Rclone Path", f"userset {user_id} menu RCLONE_PATH" + ) + buttons.data_button("Rclone Flags", f"userset {user_id} menu RCLONE_FLAGS") + buttons.data_button("Back", f"userset {user_id} back") + buttons.data_button("Close", f"userset {user_id} close") + rccmsg = "Exists" if await aiopath.exists(rclone_conf) else "Not Exists" + if user_dict.get("RCLONE_PATH", False): + rccpath = user_dict["RCLONE_PATH"] + elif Config.RCLONE_PATH: + rccpath = Config.RCLONE_PATH + else: + rccpath = "None" + if user_dict.get("RCLONE_FLAGS", False): + rcflags = user_dict["RCLONE_FLAGS"] + elif "RCLONE_FLAGS" not in user_dict and Config.RCLONE_FLAGS: + rcflags = Config.RCLONE_FLAGS + else: + rcflags = "None" + text = f"""Rclone Settings for {name} +Rclone Config {rccmsg} +Rclone Path is {rccpath} +Rclone Flags is {rcflags}""" + elif stype == "gdrive": + buttons.data_button("token.pickle", f"userset {user_id} menu TOKEN_PICKLE") + buttons.data_button("Default Gdrive ID", f"userset {user_id} menu GDRIVE_ID") + buttons.data_button("Index URL", f"userset {user_id} menu INDEX_URL") + if ( + user_dict.get("STOP_DUPLICATE", False) + or "STOP_DUPLICATE" not in user_dict + and Config.STOP_DUPLICATE + ): + buttons.data_button( + "Disable Stop Duplicate", f"userset {user_id} tog STOP_DUPLICATE f" + ) + sd_msg = "Enabled" + else: + buttons.data_button( + "Enable Stop Duplicate", f"userset {user_id} tog STOP_DUPLICATE t" + ) + sd_msg = "Disabled" + buttons.data_button("Back", f"userset {user_id} back") + buttons.data_button("Close", f"userset {user_id} close") + tokenmsg = "Exists" if await aiopath.exists(token_pickle) else "Not Exists" + if user_dict.get("GDRIVE_ID", False): + gdrive_id = user_dict["GDRIVE_ID"] + elif GDID := Config.GDRIVE_ID: + gdrive_id = GDID + else: + gdrive_id = "None" + index = user_dict["INDEX_URL"] if user_dict.get("INDEX_URL", False) else "None" + text = f"""Gdrive API Settings for {name} +Gdrive Token {tokenmsg} +Gdrive ID is {gdrive_id} +Index URL is {index} +Stop Duplicate is {sd_msg}""" + else: + buttons.data_button("Leech", f"userset {user_id} leech") + buttons.data_button("Rclone", f"userset {user_id} rclone") + buttons.data_button("Gdrive API", f"userset {user_id} gdrive") + + upload_paths = user_dict.get("UPLOAD_PATHS", {}) + if not upload_paths and "UPLOAD_PATHS" not in user_dict and Config.UPLOAD_PATHS: + upload_paths = Config.UPLOAD_PATHS + if not upload_paths: + upload_paths = "None" + + buttons.data_button("Upload Paths", f"userset {user_id} menu UPLOAD_PATHS") + + if user_dict.get("DEFAULT_UPLOAD", ""): + default_upload = user_dict["DEFAULT_UPLOAD"] + elif "DEFAULT_UPLOAD" not in user_dict: + default_upload = Config.DEFAULT_UPLOAD + du = "Gdrive API" if default_upload == "gd" else "Rclone" + dur = "Gdrive API" if default_upload != "gd" else "Rclone" + buttons.data_button( + f"Upload using {dur}", f"userset {user_id} {default_upload}" + ) + + user_tokens = user_dict.get("USER_TOKENS", False) + tr = "MY" if user_tokens else "OWNER" + trr = "OWNER" if user_tokens else "MY" + buttons.data_button( + f"Use {trr} token/config", + f"userset {user_id} tog USER_TOKENS {'f' if user_tokens else 't'}", + ) + + buttons.data_button( + "Excluded Extensions", f"userset {user_id} menu EXCLUDED_EXTENSIONS" + ) + if user_dict.get("EXCLUDED_EXTENSIONS", False): + ex_ex = user_dict["EXCLUDED_EXTENSIONS"] + elif "EXCLUDED_EXTENSIONS" not in user_dict: + ex_ex = excluded_extensions + else: + ex_ex = "None" + + buttons.data_button( + "Included Extensions", f"userset {user_id} menu INCLUDED_EXTENSIONS" + ) + if user_dict.get("INCLUDED_EXTENSIONS", False): + inc_ex = user_dict["INCLUDED_EXTENSIONS"] + elif "INCLUDED_EXTENSIONS" not in user_dict: + inc_ex = included_extensions + else: + inc_ex = "None" + + if user_dict.get("NAME_SUBSTITUTE", False): + ns_msg = "Added" + elif "NAME_SUBSTITUTE" not in user_dict and Config.NAME_SUBSTITUTE: + ns_msg = "Added" + else: + ns_msg = "None" + buttons.data_button( + "Name Substitute", f"userset {user_id} menu NAME_SUBSTITUTE" + ) + + buttons.data_button("YT-DLP Options", f"userset {user_id} menu YT_DLP_OPTIONS") + if user_dict.get("YT_DLP_OPTIONS", False): + ytopt = user_dict["YT_DLP_OPTIONS"] + elif "YT_DLP_OPTIONS" not in user_dict and Config.YT_DLP_OPTIONS: + ytopt = Config.YT_DLP_OPTIONS + else: + ytopt = "None" + + buttons.data_button("FFmpeg Cmds", f"userset {user_id} menu FFMPEG_CMDS") + if user_dict.get("FFMPEG_CMDS", False): + ffc = "Exists" + elif "FFMPEG_CMDS" not in user_dict and Config.FFMPEG_CMDS: + ffc = "Exists" + else: + ffc = "None" + + if user_dict: + buttons.data_button("Reset All", f"userset {user_id} reset all") + + buttons.data_button("Close", f"userset {user_id} close") + + text = f"""Settings for {name} +Default Package is {du} +Use {tr} token/config +Upload Paths is {upload_paths} + +Name substitution is {ns_msg} + +Excluded Extensions is {ex_ex} + +Included Extensions is {inc_ex} + +YT-DLP Options is {ytopt} + +FFMPEG Commands is {ffc}""" + + return text, buttons.build_menu(2) + + +async def update_user_settings(query, stype="main"): + handler_dict[query.from_user.id] = False + msg, button = await get_user_settings(query.from_user, stype) + await edit_message(query.message, msg, button) + + +@new_task +async def send_user_settings(_, message): + from_user = message.from_user + handler_dict[from_user.id] = False + msg, button = await get_user_settings(from_user) + await send_message(message, msg, button) + + +@new_task +async def add_file(_, message, ftype): + user_id = message.from_user.id + handler_dict[user_id] = False + if ftype == "THUMBNAIL": + des_dir = await create_thumb(message, user_id) + elif ftype == "RCLONE_CONFIG": + rpath = f"{getcwd()}/rclone/" + await makedirs(rpath, exist_ok=True) + des_dir = f"{rpath}{user_id}.conf" + await message.download(file_name=des_dir) + elif ftype == "TOKEN_PICKLE": + tpath = f"{getcwd()}/tokens/" + await makedirs(tpath, exist_ok=True) + des_dir = f"{tpath}{user_id}.pickle" + await message.download(file_name=des_dir) + update_user_ldata(user_id, ftype, des_dir) + await delete_message(message) + await database.update_user_doc(user_id, ftype, des_dir) + + +@new_task +async def add_one(_, message, option): + user_id = message.from_user.id + handler_dict[user_id] = False + user_dict = user_data.get(user_id, {}) + value = message.text + if value.startswith("{") and value.endswith("}"): + try: + value = eval(value) + if user_dict[option]: + user_dict[option].update(value) + else: + update_user_ldata(user_id, option, value) + except Exception as e: + await send_message(message, str(e)) + return + else: + await send_message(message, "It must be dict!") + return + await delete_message(message) + await database.update_user_data(user_id) + + +@new_task +async def remove_one(_, message, option): + user_id = message.from_user.id + handler_dict[user_id] = False + user_dict = user_data.get(user_id, {}) + names = message.text.split("/") + for name in names: + if name in user_dict[option]: + del user_dict[option][name] + await delete_message(message) + await database.update_user_data(user_id) + + +@new_task +async def set_option(_, message, option): + user_id = message.from_user.id + handler_dict[user_id] = False + value = message.text + if option == "LEECH_SPLIT_SIZE": + if not value.isdigit(): + value = get_size_bytes(value) + value = min(int(value), TgClient.MAX_SPLIT_SIZE) + elif option == "EXCLUDED_EXTENSIONS": + fx = value.split() + value = ["aria2", "!qB"] + for x in fx: + x = x.lstrip(".") + value.append(x.strip().lower()) + elif option == "INCLUDED_EXTENSIONS": + fx = value.split() + value = [] + for x in fx: + x = x.lstrip(".") + value.append(x.strip().lower()) + elif option == "INDEX_URL": + value = value + elif option in ["UPLOAD_PATHS", "FFMPEG_CMDS", "YT_DLP_OPTIONS"]: + if value.startswith("{") and value.endswith("}"): + try: + value = eval(value) + except Exception as e: + await send_message(message, str(e)) + return + else: + await send_message(message, "It must be dict!") + return + update_user_ldata(user_id, option, value) + await delete_message(message) + await database.update_user_data(user_id) + + +async def get_menu(option, message, user_id): + handler_dict[user_id] = False + user_dict = user_data.get(user_id, {}) + buttons = ButtonMaker() + if option in ["THUMBNAIL", "RCLONE_CONFIG", "TOKEN_PICKLE"]: + key = "file" + else: + key = "set" + buttons.data_button("Set", f"userset {user_id} {key} {option}") + if option in user_dict and key != "file": + buttons.data_button("Reset", f"userset {user_id} reset {option}") + buttons.data_button("Remove", f"userset {user_id} remove {option}") + if option == "FFMPEG_CMDS": + ffc = None + if user_dict.get("FFMPEG_CMDS", False): + ffc = user_dict["FFMPEG_CMDS"] + buttons.data_button("Add one", f"userset {user_id} addone {option}") + buttons.data_button("Remove one", f"userset {user_id} rmone {option}") + elif "FFMPEG_CMDS" not in user_dict and Config.FFMPEG_CMDS: + ffc = Config.FFMPEG_CMDS + if ffc: + buttons.data_button("FFMPEG VARIABLES", f"userset {user_id} ffvar") + buttons.data_button("View", f"userset {user_id} view {option}") + elif option in user_dict and user_dict[option]: + if option == "THUMBNAIL": + buttons.data_button("View", f"userset {user_id} view {option}") + elif option in ["YT_DLP_OPTIONS", "UPLOAD_PATHS"]: + buttons.data_button("Add one", f"userset {user_id} addone {option}") + buttons.data_button("Remove one", f"userset {user_id} rmone {option}") + if option in leech_options: + back_to = "leech" + elif option in rclone_options: + back_to = "rclone" + elif option in gdrive_options: + back_to = "gdrive" + else: + back_to = "back" + buttons.data_button("Back", f"userset {user_id} {back_to}") + buttons.data_button("Close", f"userset {user_id} close") + text = f"Edit menu for: {option}" + await edit_message(message, text, buttons.build_menu(2)) + + +async def set_ffmpeg_variable(_, message, key, value, index): + user_id = message.from_user.id + handler_dict[user_id] = False + txt = message.text + user_dict = user_data.setdefault(user_id, {}) + ffvar_data = user_dict.setdefault("FFMPEG_VARIABLES", {}) + ffvar_data = ffvar_data.setdefault(key, {}) + ffvar_data = ffvar_data.setdefault(index, {}) + ffvar_data[value] = txt + await delete_message(message) + await database.update_user_data(user_id) + + +async def ffmpeg_variables( + client, query, message, user_id, key=None, value=None, index=None +): + user_dict = user_data.get(user_id, {}) + ffc = None + if user_dict.get("FFMPEG_CMDS", False): + ffc = user_dict["FFMPEG_CMDS"] + elif "FFMPEG_CMDS" not in user_dict and Config.FFMPEG_CMDS: + ffc = Config.FFMPEG_CMDS + if ffc: + buttons = ButtonMaker() + if key is None: + msg = "Choose which key you want to fill/edit variables in it:" + for k, v in list(ffc.items()): + add = False + for l in v: + if variables := findall(r"\{(.*?)\}", l): + add = True + if add: + buttons.data_button(k, f"userset {user_id} ffvar {k}") + buttons.data_button("Back", f"userset {user_id} menu FFMPEG_CMDS") + buttons.data_button("Close", f"userset {user_id} close") + elif key in ffc and value is None: + msg = f"Choose which variable you want to fill/edit: {key}\n\nCMDS:\n{ffc[key]}" + for ind, vl in enumerate(ffc[key]): + if variables := set(findall(r"\{(.*?)\}", vl)): + for var in variables: + buttons.data_button( + var, f"userset {user_id} ffvar {key} {var} {ind}" + ) + buttons.data_button( + "Reset", f"userset {user_id} ffvar {key} ffmpegvarreset" + ) + buttons.data_button("Back", f"userset {user_id} ffvar") + buttons.data_button("Close", f"userset {user_id} close") + elif key in ffc and value: + old_value = ( + user_dict.get("FFMPEG_VARIABLES", {}) + .get(key, {}) + .get(index, {}) + .get(value, "") + ) + msg = f"Edit/Fill this FFmpeg Variable: {key}\n\nItem: {ffc[key][int(index)]}\n\nVariable: {value}" + if old_value: + msg += f"\n\nCurrent Value: {old_value}" + buttons.data_button("Back", f"userset {user_id} setevent") + buttons.data_button("Close", f"userset {user_id} close") + else: + return + await edit_message(message, msg, buttons.build_menu(2)) + if key in ffc and value: + pfunc = partial(set_ffmpeg_variable, key=key, value=value, index=index) + await event_handler(client, query, pfunc) + await ffmpeg_variables(client, query, message, user_id, key) + + +async def event_handler(client, query, pfunc, photo=False, document=False): + user_id = query.from_user.id + handler_dict[user_id] = True + start_time = time() + + async def event_filter(_, __, event): + if photo: + mtype = event.photo + elif document: + mtype = event.document + else: + mtype = event.text + user = event.from_user or event.sender_chat + return bool( + user.id == user_id and event.chat.id == query.message.chat.id and mtype + ) + + handler = client.add_handler( + MessageHandler(pfunc, filters=create(event_filter)), group=-1 + ) + + while handler_dict[user_id]: + await sleep(0.5) + if time() - start_time > 60: + handler_dict[user_id] = False + client.remove_handler(*handler) + + +@new_task +async def edit_user_settings(client, query): + from_user = query.from_user + user_id = from_user.id + name = from_user.mention + message = query.message + data = query.data.split() + handler_dict[user_id] = False + thumb_path = f"thumbnails/{user_id}.jpg" + rclone_conf = f"rclone/{user_id}.conf" + token_pickle = f"tokens/{user_id}.pickle" + user_dict = user_data.get(user_id, {}) + if user_id != int(data[1]): + await query.answer("Not Yours!", show_alert=True) + elif data[2] == "setevent": + await query.answer() + elif data[2] in ["leech", "gdrive", "rclone"]: + await query.answer() + await update_user_settings(query, data[2]) + elif data[2] == "menu": + await query.answer() + await get_menu(data[3], message, user_id) + elif data[2] == "tog": + await query.answer() + update_user_ldata(user_id, data[3], data[4] == "t") + if data[3] == "STOP_DUPLICATE": + back_to = "gdrive" + elif data[3] == "USER_TOKENS": + back_to = "main" + else: + back_to = "leech" + await update_user_settings(query, stype=back_to) + await database.update_user_data(user_id) + elif data[2] == "file": + await query.answer() + buttons = ButtonMaker() + if data[3] == "THUMBNAIL": + text = "Send a photo to save it as custom thumbnail. Timeout: 60 sec" + elif data[3] == "RCLONE_CONFIG": + text = "Send rclone.conf. Timeout: 60 sec" + else: + text = "Send token.pickle. Timeout: 60 sec" + buttons.data_button("Back", f"userset {user_id} setevent") + buttons.data_button("Close", f"userset {user_id} close") + await edit_message(message, text, buttons.build_menu(2)) + pfunc = partial(add_file, ftype=data[3]) + await event_handler( + client, + query, + pfunc, + photo=data[3] == "THUMBNAIL", + document=data[3] != "THUMBNAIL", + ) + await get_menu(data[3], message, user_id) + elif data[2] == "ffvar": + await query.answer() + key = data[3] if len(data) > 3 else None + value = data[4] if len(data) > 4 else None + if value == "ffmpegvarreset": + user_dict = user_data.get(user_id, {}) + ff_data = user_dict.get("FFMPEG_VARIABLES", {}) + if key in ff_data: + del ff_data[key] + await database.update_user_data(user_id) + return + index = data[5] if len(data) > 5 else None + await ffmpeg_variables(client, query, message, user_id, key, value, index) + elif data[2] in ["set", "addone", "rmone"]: + await query.answer() + buttons = ButtonMaker() + if data[2] == "set": + text = user_settings_text[data[3]] + func = set_option + elif data[2] == "addone": + text = f"Add one or more string key and value to {data[3]}. Example: {{'key 1': 62625261, 'key 2': 'value 2'}}. Timeout: 60 sec" + func = add_one + elif data[2] == "rmone": + text = f"Remove one or more key from {data[3]}. Example: key 1/key2/key 3. Timeout: 60 sec" + func = remove_one + buttons.data_button("Back", f"userset {user_id} setevent") + buttons.data_button("Close", f"userset {user_id} close") + await edit_message(message, text, buttons.build_menu(2)) + pfunc = partial(func, option=data[3]) + await event_handler(client, query, pfunc) + await get_menu(data[3], message, user_id) + elif data[2] == "remove": + await query.answer("Removed!", show_alert=True) + if data[3] in ["THUMBNAIL", "RCLONE_CONFIG", "TOKEN_PICKLE"]: + if data[3] == "THUMBNAIL": + fpath = thumb_path + elif data[3] == "RCLONE_CONFIG": + fpath = rclone_conf + else: + fpath = token_pickle + if await aiopath.exists(fpath): + await remove(fpath) + del user_dict[data[3]] + await database.update_user_doc(user_id, data[3]) + else: + update_user_ldata(user_id, data[3], "") + await database.update_user_data(user_id) + elif data[2] == "reset": + await query.answer("Reseted!", show_alert=True) + if data[3] in user_dict: + del user_dict[data[3]] + else: + for k in list(user_dict.keys()): + if k not in [ + "SUDO", + "AUTH", + "THUMBNAIL", + "RCLONE_CONFIG", + "TOKEN_PICKLE", + ]: + del user_dict[k] + await update_user_settings(query) + await database.update_user_data(user_id) + elif data[2] == "view": + await query.answer() + if data[3] == "THUMBNAIL": + await send_file(message, thumb_path, name) + elif data[3] == "FFMPEG_CMDS": + ffc = None + if user_dict.get("FFMPEG_CMDS", False): + ffc = user_dict["FFMPEG_CMDS"] + elif "FFMPEG_CMDS" not in user_dict and Config.FFMPEG_CMDS: + ffc = Config.FFMPEG_CMDS + msg_ecd = str(ffc).encode() + with BytesIO(msg_ecd) as ofile: + ofile.name = "users_settings.txt" + await send_file(message, ofile) + elif data[2] in ["gd", "rc"]: + await query.answer() + du = "rc" if data[2] == "gd" else "gd" + update_user_ldata(user_id, "DEFAULT_UPLOAD", du) + await update_user_settings(query) + await database.update_user_data(user_id) + elif data[2] == "back": + await query.answer() + await update_user_settings(query) + else: + await query.answer() + await delete_message(message.reply_to_message) + await delete_message(message) + + +@new_task +async def get_users_settings(_, message): + msg = "" + if auth_chats: + msg += f"AUTHORIZED_CHATS: {auth_chats}\n" + if sudo_users: + msg += f"SUDO_USERS: {sudo_users}\n\n" + if user_data: + for u, d in user_data.items(): + kmsg = f"\n{u}:\n" + if vmsg := "".join( + f"{k}: {v or None}\n" for k, v in d.items() + ): + msg += kmsg + vmsg + if not msg: + await send_message(message, "No users data!") + return + msg_ecd = msg.encode() + if len(msg_ecd) > 4000: + with BytesIO(msg_ecd) as ofile: + ofile.name = "users_settings.txt" + await send_file(message, ofile) + else: + await send_message(message, msg) + else: + await send_message(message, "No users data!") diff --git a/bot/modules/ytdlp.py b/bot/modules/ytdlp.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c7dfa64d2706fec760bf7c84864e0220c515e9 --- /dev/null +++ b/bot/modules/ytdlp.py @@ -0,0 +1,469 @@ +from httpx import AsyncClient +from asyncio import wait_for, Event +from functools import partial +from pyrogram.filters import regex, user +from pyrogram.handlers import CallbackQueryHandler +from time import time +from yt_dlp import YoutubeDL + +from .. import LOGGER, bot_loop, task_dict_lock, DOWNLOAD_DIR +from ..core.config_manager import Config +from ..helper.ext_utils.bot_utils import ( + new_task, + sync_to_async, + arg_parser, + COMMAND_USAGE, +) +from ..helper.ext_utils.links_utils import is_url +from ..helper.ext_utils.status_utils import get_readable_file_size, get_readable_time +from ..helper.listeners.task_listener import TaskListener +from ..helper.mirror_leech_utils.download_utils.yt_dlp_download import YoutubeDLHelper +from ..helper.telegram_helper.button_build import ButtonMaker +from ..helper.telegram_helper.message_utils import ( + send_message, + edit_message, + delete_message, +) + + +@new_task +async def select_format(_, query, obj): + data = query.data.split() + message = query.message + await query.answer() + + if data[1] == "dict": + b_name = data[2] + await obj.qual_subbuttons(b_name) + elif data[1] == "mp3": + await obj.mp3_subbuttons() + elif data[1] == "audio": + await obj.audio_format() + elif data[1] == "aq": + if data[2] == "back": + await obj.audio_format() + else: + await obj.audio_quality(data[2]) + elif data[1] == "back": + await obj.back_to_main() + elif data[1] == "cancel": + await edit_message(message, "Task has been cancelled.") + obj.qual = None + obj.listener.is_cancelled = True + obj.event.set() + else: + if data[1] == "sub": + obj.qual = obj.formats[data[2]][data[3]][1] + elif "|" in data[1]: + obj.qual = obj.formats[data[1]] + else: + obj.qual = data[1] + obj.event.set() + + +class YtSelection: + def __init__(self, listener): + self.listener = listener + self._is_m4a = False + self._reply_to = None + self._time = time() + self._timeout = 120 + self._is_playlist = False + self._main_buttons = None + self.event = Event() + self.formats = {} + self.qual = None + + async def _event_handler(self): + pfunc = partial(select_format, obj=self) + handler = self.listener.client.add_handler( + CallbackQueryHandler( + pfunc, filters=regex("^ytq") & user(self.listener.user_id) + ), + group=-1, + ) + try: + await wait_for(self.event.wait(), timeout=self._timeout) + except: + await edit_message(self._reply_to, "Timed Out. Task has been cancelled!") + self.qual = None + self.listener.is_cancelled = True + self.event.set() + finally: + self.listener.client.remove_handler(*handler) + + async def get_quality(self, result): + buttons = ButtonMaker() + if "entries" in result: + self._is_playlist = True + for i in ["144", "240", "360", "480", "720", "1080", "1440", "2160"]: + video_format = f"bv*[height<=?{i}][ext=mp4]+ba[ext=m4a]/b[height<=?{i}]" + b_data = f"{i}|mp4" + self.formats[b_data] = video_format + buttons.data_button(f"{i}-mp4", f"ytq {b_data}") + video_format = f"bv*[height<=?{i}][ext=webm]+ba/b[height<=?{i}]" + b_data = f"{i}|webm" + self.formats[b_data] = video_format + buttons.data_button(f"{i}-webm", f"ytq {b_data}") + buttons.data_button("MP3", "ytq mp3") + buttons.data_button("Audio Formats", "ytq audio") + buttons.data_button("Best Videos", "ytq bv*+ba/b") + buttons.data_button("Best Audios", "ytq ba/b") + buttons.data_button("Cancel", "ytq cancel", "footer") + self._main_buttons = buttons.build_menu(3) + msg = f"Choose Playlist Videos Quality:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + else: + format_dict = result.get("formats") + if format_dict is not None: + for item in format_dict: + if item.get("tbr"): + format_id = item["format_id"] + + if item.get("filesize"): + size = item["filesize"] + elif item.get("filesize_approx"): + size = item["filesize_approx"] + else: + size = 0 + + if item.get("video_ext") == "none" and ( + item.get("resolution") == "audio only" + or item.get("acodec") != "none" + ): + if item.get("audio_ext") == "m4a": + self._is_m4a = True + b_name = f"{item.get('acodec') or format_id}-{item['ext']}" + v_format = format_id + elif item.get("height"): + height = item["height"] + ext = item["ext"] + fps = item["fps"] if item.get("fps") else "" + b_name = f"{height}p{fps}-{ext}" + ba_ext = ( + "[ext=m4a]" if self._is_m4a and ext == "mp4" else "" + ) + v_format = f"{format_id}+ba{ba_ext}/b[height=?{height}]" + else: + continue + + self.formats.setdefault(b_name, {})[f"{item['tbr']}"] = [ + size, + v_format, + ] + + for b_name, tbr_dict in self.formats.items(): + if len(tbr_dict) == 1: + tbr, v_list = next(iter(tbr_dict.items())) + buttonName = f"{b_name} ({get_readable_file_size(v_list[0])})" + buttons.data_button(buttonName, f"ytq sub {b_name} {tbr}") + else: + buttons.data_button(b_name, f"ytq dict {b_name}") + buttons.data_button("MP3", "ytq mp3") + buttons.data_button("Audio Formats", "ytq audio") + buttons.data_button("Best Video", "ytq bv*+ba/b") + buttons.data_button("Best Audio", "ytq ba/b") + buttons.data_button("Cancel", "ytq cancel", "footer") + self._main_buttons = buttons.build_menu(2) + msg = f"Choose Video Quality:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + self._reply_to = await send_message( + self.listener.message, msg, self._main_buttons + ) + await self._event_handler() + if not self.listener.is_cancelled: + await delete_message(self._reply_to) + return self.qual + + async def back_to_main(self): + if self._is_playlist: + msg = f"Choose Playlist Videos Quality:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + else: + msg = f"Choose Video Quality:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await edit_message(self._reply_to, msg, self._main_buttons) + + async def qual_subbuttons(self, b_name): + buttons = ButtonMaker() + tbr_dict = self.formats[b_name] + for tbr, d_data in tbr_dict.items(): + button_name = f"{tbr}K ({get_readable_file_size(d_data[0])})" + buttons.data_button(button_name, f"ytq sub {b_name} {tbr}") + buttons.data_button("Back", "ytq back", "footer") + buttons.data_button("Cancel", "ytq cancel", "footer") + subbuttons = buttons.build_menu(2) + msg = f"Choose Bit rate for {b_name}:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await edit_message(self._reply_to, msg, subbuttons) + + async def mp3_subbuttons(self): + i = "s" if self._is_playlist else "" + buttons = ButtonMaker() + audio_qualities = [64, 128, 320] + for q in audio_qualities: + audio_format = f"ba/b-mp3-{q}" + buttons.data_button(f"{q}K-mp3", f"ytq {audio_format}") + buttons.data_button("Back", "ytq back") + buttons.data_button("Cancel", "ytq cancel") + subbuttons = buttons.build_menu(3) + msg = f"Choose mp3 Audio{i} Bitrate:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await edit_message(self._reply_to, msg, subbuttons) + + async def audio_format(self): + i = "s" if self._is_playlist else "" + buttons = ButtonMaker() + for frmt in ["aac", "alac", "flac", "m4a", "opus", "vorbis", "wav"]: + audio_format = f"ba/b-{frmt}-" + buttons.data_button(frmt, f"ytq aq {audio_format}") + buttons.data_button("Back", "ytq back", "footer") + buttons.data_button("Cancel", "ytq cancel", "footer") + subbuttons = buttons.build_menu(3) + msg = f"Choose Audio{i} Format:\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await edit_message(self._reply_to, msg, subbuttons) + + async def audio_quality(self, format): + i = "s" if self._is_playlist else "" + buttons = ButtonMaker() + for qual in range(11): + audio_format = f"{format}{qual}" + buttons.data_button(qual, f"ytq {audio_format}") + buttons.data_button("Back", "ytq aq back") + buttons.data_button("Cancel", "ytq aq cancel") + subbuttons = buttons.build_menu(5) + msg = f"Choose Audio{i} Quality:\n0 is best and 10 is worst\nTimeout: {get_readable_time(self._timeout - (time() - self._time))}" + await edit_message(self._reply_to, msg, subbuttons) + + +def extract_info(link, options): + with YoutubeDL(options) as ydl: + result = ydl.extract_info(link, download=False) + if result is None: + raise ValueError("Info result is None") + return result + + +async def _mdisk(link, name): + key = link.split("/")[-1] + async with AsyncClient(verify=False) as client: + resp = await client.get( + f"https://diskuploader.entertainvideo.com/v1/file/cdnurl?param={key}" + ) + if resp.status_code == 200: + resp_json = resp.json() + link = resp_json["source"] + if not name: + name = resp_json["filename"] + return name, link + + +class YtDlp(TaskListener): + def __init__( + self, + client, + message, + _=None, + is_leech=False, + __=None, + ___=None, + same_dir=None, + bulk=None, + multi_tag=None, + options="", + ): + if same_dir is None: + same_dir = {} + if bulk is None: + bulk = [] + self.message = message + self.client = client + self.multi_tag = multi_tag + self.options = options + self.same_dir = same_dir + self.bulk = bulk + super().__init__() + self.is_ytdlp = True + self.is_leech = is_leech + + async def new_event(self): + text = self.message.text.split("\n") + input_list = text[0].split(" ") + qual = "" + + args = { + "-doc": False, + "-med": False, + "-s": False, + "-b": False, + "-z": False, + "-sv": False, + "-ss": False, + "-f": False, + "-fd": False, + "-fu": False, + "-hl": False, + "-bt": False, + "-ut": False, + "-i": 0, + "-sp": 0, + "link": "", + "-m": "", + "-opt": {}, + "-n": "", + "-up": "", + "-rcf": "", + "-t": "", + "-ca": "", + "-cv": "", + "-ns": "", + "-tl": "", + "-ff": set(), + } + + arg_parser(input_list[1:], args) + + try: + self.multi = int(args["-i"]) + except: + self.multi = 0 + + try: + opt = eval(args["-opt"]) if args["-opt"] else {} + except Exception as e: + LOGGER.error(e) + opt = {} + + self.ffmpeg_cmds = args["-ff"] + self.select = args["-s"] + self.name = args["-n"] + self.up_dest = args["-up"] + self.rc_flags = args["-rcf"] + self.link = args["link"] + self.compress = args["-z"] + self.thumb = args["-t"] + self.split_size = args["-sp"] + self.sample_video = args["-sv"] + self.screen_shots = args["-ss"] + self.force_run = args["-f"] + self.force_download = args["-fd"] + self.force_upload = args["-fu"] + self.convert_audio = args["-ca"] + self.convert_video = args["-cv"] + self.name_sub = args["-ns"] + self.hybrid_leech = args["-hl"] + self.thumbnail_layout = args["-tl"] + self.as_doc = args["-doc"] + self.as_med = args["-med"] + self.folder_name = f"/{args["-m"]}".rstrip("/") if len(args["-m"]) > 0 else "" + self.bot_trans = args["-bt"] + self.user_trans = args["-ut"] + + is_bulk = args["-b"] + + bulk_start = 0 + bulk_end = 0 + reply_to = None + + if not isinstance(is_bulk, bool): + dargs = is_bulk.split(":") + bulk_start = dargs[0] or None + if len(dargs) == 2: + bulk_end = dargs[1] or None + is_bulk = True + + if not is_bulk: + if self.multi > 0: + if self.folder_name: + async with task_dict_lock: + if self.folder_name in self.same_dir: + self.same_dir[self.folder_name]["tasks"].add(self.mid) + for fd_name in self.same_dir: + if fd_name != self.folder_name: + self.same_dir[fd_name]["total"] -= 1 + elif self.same_dir: + self.same_dir[self.folder_name] = { + "total": self.multi, + "tasks": {self.mid}, + } + for fd_name in self.same_dir: + if fd_name != self.folder_name: + self.same_dir[fd_name]["total"] -= 1 + else: + self.same_dir = { + self.folder_name: { + "total": self.multi, + "tasks": {self.mid}, + } + } + elif self.same_dir: + async with task_dict_lock: + for fd_name in self.same_dir: + self.same_dir[fd_name]["total"] -= 1 + else: + await self.init_bulk(input_list, bulk_start, bulk_end, YtDlp) + return + + if len(self.bulk) != 0: + del self.bulk[0] + + path = f"{DOWNLOAD_DIR}{self.mid}{self.folder_name}" + + await self.get_tag(text) + + opt = opt or self.user_dict.get("YT_DLP_OPTIONS") or Config.YT_DLP_OPTIONS + + if not self.link and (reply_to := self.message.reply_to_message): + self.link = reply_to.text.split("\n", 1)[0].strip() + + if not is_url(self.link): + await send_message( + self.message, COMMAND_USAGE["yt"][0], COMMAND_USAGE["yt"][1] + ) + await self.remove_from_same_dir() + return + + if "mdisk.me" in self.link: + self.name, self.link = await _mdisk(self.link, self.name) + + try: + await self.before_start() + except Exception as e: + await send_message(self.message, e) + await self.remove_from_same_dir() + return + options = {"usenetrc": True, "cookiefile": "cookies.txt"} + if opt: + for key, value in opt.items(): + if key in ["postprocessors", "download_ranges"]: + continue + if key == "format" and not self.select: + if value.startswith("ba/b-"): + qual = value + continue + else: + qual = value + options[key] = value + options["playlist_items"] = "0" + try: + result = await sync_to_async(extract_info, self.link, options) + except Exception as e: + msg = str(e).replace("<", " ").replace(">", " ") + await send_message(self.message, f"{self.tag} {msg}") + await self.remove_from_same_dir() + return + finally: + await self.run_multi(input_list, YtDlp) + + if not qual: + qual = await YtSelection(self).get_quality(result) + if qual is None: + await self.remove_from_same_dir() + return + + LOGGER.info(f"Downloading with YT-DLP: {self.link}") + playlist = "entries" in result + ydl = YoutubeDLHelper(self) + await ydl.add_download(path, qual, playlist, opt) + + +async def ytdl(client, message): + bot_loop.create_task(YtDlp(client, message).new_event()) + + +async def ytdl_leech(client, message): + bot_loop.create_task(YtDlp(client, message, is_leech=True).new_event()) diff --git a/captain-definition b/captain-definition new file mode 100644 index 0000000000000000000000000000000000000000..0e14f8239afebd023255144242e4254991dec0fb --- /dev/null +++ b/captain-definition @@ -0,0 +1,4 @@ +{ + "schemaVersion": 2, + "dockerfilePath": "./Dockerfile" +} diff --git a/config_sample.py b/config_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..db132611f424a75fb0dcf0432461fa4413a8c5f7 --- /dev/null +++ b/config_sample.py @@ -0,0 +1,115 @@ +# REQUIRED CONFIG +BOT_TOKEN = "" +OWNER_ID = 0 +TELEGRAM_API = 0 +TELEGRAM_HASH = "" +# OPTIONAL CONFIG +TG_PROXY = {} +USER_SESSION_STRING = "" +CMD_SUFFIX = "" +AUTHORIZED_CHATS = "" +SUDO_USERS = "" +DATABASE_URL = "" +DATABASE_NAME = "mltb" +STATUS_LIMIT = 4 +DEFAULT_UPLOAD = "rc" +STATUS_UPDATE_INTERVAL = 15 +FILELION_API = "" +STREAMWISH_API = "" +EXCLUDED_EXTENSIONS = "" +INCLUDED_EXTENSIONS = "" +INCOMPLETE_TASK_NOTIFIER = False +YT_DLP_OPTIONS = "" +USE_SERVICE_ACCOUNTS = False +NAME_SUBSTITUTE = r"" +FFMPEG_CMDS = {"merge": ["-f concat -safe 0 -i mltb.txt -c copy mltb.mp4 -del"]} +UPLOAD_PATHS = {} +# GDrive Tools +GDRIVE_ID = "" +IS_TEAM_DRIVE = False +STOP_DUPLICATE = False +INDEX_URL = "" +# Rclone +RCLONE_PATH = "" +RCLONE_FLAGS = "" +RCLONE_SERVE_URL = "" +RCLONE_SERVE_PORT = 0 +RCLONE_SERVE_USER = "" +RCLONE_SERVE_PASS = "" +# JDownloader +JD_EMAIL = "" +JD_PASS = "" +# Sabnzbd +USENET_SERVERS = [ + { + "name": "main", + "host": "", + "port": 563, + "timeout": 60, + "username": "", + "password": "", + "connections": 8, + "ssl": 1, + "ssl_verify": 2, + "ssl_ciphers": "", + "enable": 1, + "required": 0, + "optional": 0, + "retention": 0, + "send_group": 0, + "priority": 0, + } +] +# Nzb search +HYDRA_IP = "" +HYDRA_API_KEY = "" +# Update +UPSTREAM_REPO = "" +UPSTREAM_BRANCH = "master" +# Leech +LEECH_SPLIT_SIZE = 0 +AS_DOCUMENT = False +EQUAL_SPLITS = False +MEDIA_GROUP = False +USER_TRANSMISSION = False +HYBRID_LEECH = False +LEECH_FILENAME_PREFIX = "" +LEECH_DUMP_CHAT = "" +CLONE_DUMP_CHATS = "" +FILES_LINKS = False +THUMBNAIL_LAYOUT = "" +# qBittorrent/Aria2c +TORRENT_TIMEOUT = 0 +BASE_URL = "" +BASE_URL_PORT = 0 +WEB_PINCODE = False +# Queueing system +QUEUE_ALL = 0 +QUEUE_DOWNLOAD = 0 +QUEUE_UPLOAD = 0 +# RSS +RSS_DELAY = 600 +RSS_CHAT = "" +RSS_SIZE_LIMIT = 0 +# Torrent Search +SEARCH_API_LINK = "" +SEARCH_LIMIT = 0 +SEARCH_PLUGINS = [ + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/piratebay.py", + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/limetorrents.py", + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/torlock.py", + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/torrentscsv.py", + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/eztv.py", + "https://raw.githubusercontent.com/qbittorrent/search-plugins/master/nova3/engines/torrentproject.py", + "https://raw.githubusercontent.com/MaurizioRicci/qBittorrent_search_engines/master/kickass_torrent.py", + "https://raw.githubusercontent.com/MaurizioRicci/qBittorrent_search_engines/master/yts_am.py", + "https://raw.githubusercontent.com/MadeOfMagicAndWires/qBit-plugins/master/engines/linuxtracker.py", + "https://raw.githubusercontent.com/MadeOfMagicAndWires/qBit-plugins/master/engines/nyaasi.py", + "https://raw.githubusercontent.com/LightDestory/qBittorrent-Search-Plugins/master/src/engines/ettv.py", + "https://raw.githubusercontent.com/LightDestory/qBittorrent-Search-Plugins/master/src/engines/glotorrents.py", + "https://raw.githubusercontent.com/LightDestory/qBittorrent-Search-Plugins/master/src/engines/thepiratebay.py", + "https://raw.githubusercontent.com/v1k45/1337x-qBittorrent-search-plugin/master/leetx.py", + "https://raw.githubusercontent.com/nindogo/qbtSearchScripts/master/magnetdl.py", + "https://raw.githubusercontent.com/msagca/qbittorrent_plugins/main/uniondht.py", + "https://raw.githubusercontent.com/khensolomon/leyts/master/yts.py", +] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..94f29bbcfa83fc22593888afd8c4c387d7dc2080 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,6 @@ +services: + app: + build: . + command: bash start.sh + restart: on-failure + network_mode: "host" diff --git a/driveid.py b/driveid.py new file mode 100644 index 0000000000000000000000000000000000000000..43200c6ac41430ba118b4bfdde6ef94460baa814 --- /dev/null +++ b/driveid.py @@ -0,0 +1,54 @@ +import os +import re + +print( + "\n\n" + " Bot can search files recursively, but you have to add the list of drives you want to search.\n" + " Use the following format: (You can use 'root' in the ID in case you wan to use main drive.)\n" + " teamdrive NAME --> anything that you likes\n" + " teamdrive ID --> id of teamdrives in which you likes to search ('root' for main drive)\n" + " teamdrive INDEX URL --> enter index url for this drive.\n" + " go to the respective drive and copy the url from address bar\n" +) +msg = "" +if os.path.exists("list_drives.txt"): + with open("list_drives.txt", "r+") as f: + lines = f.read() + if not re.match(r"^\s*$", lines): + print(lines) + print( + "\n\n" + " DO YOU WISH TO KEEP THE ABOVE DETAILS THAT YOU PREVIOUSLY ADDED???? ENTER (y/n)\n" + " IF NOTHING SHOWS ENTER n" + ) + while 1: + choice = input() + if choice in ["y", "Y"]: + msg = f"{lines}" + break + elif choice in ["n", "N"]: + break + else: + print( + "\n\n DO YOU WISH TO KEEP THE ABOVE DETAILS ???? y/n <=== this is option ..... OPEN YOUR EYES & READ..." + ) +num = int(input(" How Many Drive/Folder You Likes To Add : ")) +for count in range(1, num + 1): + print(f"\n > DRIVE - {count}\n") + name = input(" Enter Drive NAME (anything) : ") + id = input(" Enter Drive ID : ") + index = input(" Enter Drive INDEX URL (optional) : ") + if not name or not id: + print("\n\n ERROR : Dont leave the name/id without filling.") + exit(1) + name = name.replace(" ", "_") + if index: + if index[-1] == "/": + index = index[:-1] + else: + index = "" + msg += f"{name} {id} {index}\n" +with open("list_drives.txt", "w") as file: + file.truncate(0) + file.write(msg) +print("\n\n Done!") diff --git a/gen_sa_accounts.py b/gen_sa_accounts.py new file mode 100644 index 0000000000000000000000000000000000000000..16a1d0e3e60009e270bdb641bd86edcd3087379a --- /dev/null +++ b/gen_sa_accounts.py @@ -0,0 +1,463 @@ +from argparse import ArgumentParser +from base64 import b64decode +from errno import EEXIST +from glob import glob +from json import loads +from os import mkdir, path as ospath +from pickle import dump, load +from random import choice +from sys import exit +from time import sleep + +from google.auth.transport.requests import Request +from google_auth_oauthlib.flow import InstalledAppFlow +from googleapiclient.discovery import build +from googleapiclient.errors import HttpError + +SCOPES = [ + "https://www.googleapis.com/auth/drive", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/iam", +] +project_create_ops = [] +current_key_dump = [] +sleep_time = 30 +CHARS = "-abcdefghijklmnopqrstuvwxyz1234567890" + + +def _create_accounts(service, project, count): + batch = service.new_batch_http_request(callback=_def_batch_resp) + for _ in range(count): + aid = _generate_id("mfc-") + batch.add( + service.projects() + .serviceAccounts() + .create( + name=f"projects/{project}", + body={ + "accountId": aid, + "serviceAccount": {"displayName": aid}, + }, + ) + ) + try: + batch.execute() + except HttpError as e: + print("Error creating accounts:", e) + + +def _create_remaining_accounts(iam, project): + print(f"Creating accounts in {project}") + sa_count = len(_list_sas(iam, project)) + while sa_count != 100: + _create_accounts(iam, project, 100 - sa_count) + sa_count = len(_list_sas(iam, project)) + + +def _generate_id(prefix="saf-"): + return prefix + "".join(choice(CHARS) for _ in range(25)) + choice(CHARS[1:]) + + +def _get_projects(service): + try: + return [i["projectId"] for i in service.projects().list().execute()["projects"]] + except HttpError as e: + print("Error fetching projects:", e) + return [] + + +def _def_batch_resp(id, resp, exception): + if exception is not None: + if str(exception).startswith(" 0: + current_count = len(_get_projects(cloud)) + if current_count + create_projects <= max_projects: + print("Creating %d projects" % create_projects) + nprjs = _create_projects(cloud, create_projects) + selected_projects = nprjs + else: + exit( + "Cannot create %d new project(s).\n" + "Please reduce the value or delete existing projects.\n" + "Max projects allowed: %d, already in use: %d" + % (create_projects, max_projects, current_count) + ) + else: + print("Overwriting all service accounts in existing projects.") + input("Press Enter to continue...") + + if enable_services: + target = [enable_services] + if enable_services == "~": + target = selected_projects + elif enable_services == "*": + target = _get_projects(cloud) + service_list = [f"{s}.googleapis.com" for s in services] + print("Enabling services") + _enable_services(serviceusage, target, service_list) + if create_sas: + target = [create_sas] + if create_sas == "~": + target = selected_projects + elif create_sas == "*": + target = _get_projects(cloud) + for proj in target: + _create_remaining_accounts(iam, proj) + if download_keys: + target = [download_keys] + if download_keys == "~": + target = selected_projects + elif download_keys == "*": + target = _get_projects(cloud) + _create_sa_keys(iam, target, path) + if delete_sas: + target = [delete_sas] + if delete_sas == "~": + target = selected_projects + elif delete_sas == "*": + target = _get_projects(cloud) + for proj in target: + print(f"Deleting service accounts in {proj}") + _delete_sas(iam, proj) + + +if __name__ == "__main__": + parse = ArgumentParser(description="A tool to create Google service accounts.") + parse.add_argument( + "--path", + "-p", + default="accounts", + help="Specify an alternate directory to output the credential files.", + ) + parse.add_argument("--token", default="token_sa.pickle", help="Token file path.") + parse.add_argument( + "--credentials", + default="credentials.json", + help="Credentials file path.", + ) + parse.add_argument( + "--list-projects", + default=False, + action="store_true", + help="List projects viewable by the user.", + ) + parse.add_argument( + "--list-sas", default=False, help="List service accounts in a project." + ) + parse.add_argument( + "--create-projects", type=int, default=None, help="Creates up to N projects." + ) + parse.add_argument( + "--max-projects", + type=int, + default=12, + help="Max projects allowed. Default: 12", + ) + parse.add_argument( + "--enable-services", + default=None, + help="Enables services on the project. Default: IAM and Drive", + ) + parse.add_argument( + "--services", + nargs="+", + default=["iam", "drive"], + help="Specify a different set of services to enable.", + ) + parse.add_argument( + "--create-sas", default=None, help="Create service accounts in a project." + ) + parse.add_argument( + "--delete-sas", default=None, help="Delete service accounts in a project." + ) + parse.add_argument( + "--download-keys", + default=None, + help="Download keys for service accounts in a project.", + ) + parse.add_argument( + "--quick-setup", + default=None, + type=int, + help="Create projects, enable services, create SAs and download keys.", + ) + parse.add_argument( + "--new-only", + default=False, + action="store_true", + help="Do not use existing projects.", + ) + args = parse.parse_args() + + if not ospath.exists(args.credentials): + options = glob("*.json") + print( + f"No credentials found at {args.credentials}. Please enable the Drive API and save the JSON as {args.credentials}." + ) + if not options: + exit("No available credential files found.") + else: + print("Select a credentials file:") + for idx, opt in enumerate(options): + print(f" {idx + 1}) {opt}") + while True: + inp = input("> ") + try: + choice_idx = int(inp) - 1 + if 0 <= choice_idx < len(options): + args.credentials = options[choice_idx] + break + except ValueError: + if inp in options: + args.credentials = inp + break + print( + f"Use --credentials {args.credentials} next time to use this credentials file." + ) + if args.quick_setup: + opt = "~" if args.new_only else "*" + args.services = ["iam", "drive"] + args.create_projects = args.quick_setup + args.enable_services = opt + args.create_sas = opt + args.download_keys = opt + resp = serviceaccountfactory( + path=args.path, + token=args.token, + credentials=args.credentials, + list_projects=args.list_projects, + list_sas=args.list_sas, + create_projects=args.create_projects, + max_projects=args.max_projects, + create_sas=args.create_sas, + delete_sas=args.delete_sas, + enable_services=args.enable_services, + services=args.services, + download_keys=args.download_keys, + ) + if resp is not None: + if args.list_projects: + if resp: + print("Projects (%d):" % len(resp)) + for proj in resp: + print(f" {proj}") + else: + print("No projects found.") + elif args.list_sas: + if resp: + print("Service accounts in %s (%d):" % (args.list_sas, len(resp))) + for sa in resp: + print(f" {sa['email']} ({sa['uniqueId']})") + else: + print("No service accounts found.") diff --git a/generate_drive_token.py b/generate_drive_token.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6d25c7b5180df2bebe693aefa676aa0867eb68 --- /dev/null +++ b/generate_drive_token.py @@ -0,0 +1,25 @@ +import os +import pickle +from google.auth.transport.requests import Request +from google_auth_oauthlib.flow import InstalledAppFlow + +credentials = None +__G_DRIVE_TOKEN_FILE = "token.pickle" +__OAUTH_SCOPE = ["https://www.googleapis.com/auth/drive"] +if os.path.exists(__G_DRIVE_TOKEN_FILE): + with open(__G_DRIVE_TOKEN_FILE, "rb") as f: + credentials = pickle.load(f) + if ( + (credentials is None or not credentials.valid) + and credentials + and credentials.expired + and credentials.refresh_token + ): + credentials.refresh(Request()) +else: + flow = InstalledAppFlow.from_client_secrets_file("credentials.json", __OAUTH_SCOPE) + credentials = flow.run_local_server(port=0, open_browser=False) + +# Save the credentials for the next run +with open(__G_DRIVE_TOKEN_FILE, "wb") as token: + pickle.dump(credentials, token) diff --git a/generate_string_session.py b/generate_string_session.py new file mode 100644 index 0000000000000000000000000000000000000000..8d40ee1636d062d1d98c4c7781613cbd5ee51705 --- /dev/null +++ b/generate_string_session.py @@ -0,0 +1,12 @@ +try: + from pyrogram import Client +except Exception as e: + print(e) + print("\nInstall pyrogram: pip3 install pyrogram") + exit(1) + +print("Required pyrogram V2 or greater.") +API_KEY = int(input("Enter API KEY: ")) +API_HASH = input("Enter API HASH: ") +with Client(name="USS", api_id=API_KEY, api_hash=API_HASH, in_memory=True) as app: + print(app.export_session_string()) diff --git a/myjd/__init__.py b/myjd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..171bea626cd8275a2b1a33286e1a0b7d969f5e0c --- /dev/null +++ b/myjd/__init__.py @@ -0,0 +1,73 @@ +from .exception import ( + MYJDException, + MYJDConnectionException, + MYJDDeviceNotFoundException, + MYJDDecodeException, + MYJDApiException, + MYJDApiCommandNotFoundException, + MYJDApiInterfaceNotFoundException, + MYJDAuthFailedException, + MYJDBadParametersException, + MYJDBadRequestException, + MYJDChallengeFailedException, + MYJDEmailForbiddenException, + MYJDEmailInvalidException, + MYJDErrorEmailNotConfirmedException, + MYJDFailedException, + MYJDFileNotFoundException, + MYJDInternalServerErrorException, + MYJDMaintenanceException, + MYJDMethodForbiddenException, + MYJDOfflineException, + MYJDOutdatedException, + MYJDOverloadException, + MYJDSessionException, + MYJDStorageAlreadyExistsException, + MYJDStorageInvalidKeyException, + MYJDStorageInvalidStorageIdException, + MYJDStorageKeyNotFoundException, + MYJDStorageLimitReachedException, + MYJDStorageNotFoundException, + MYJDTokenInvalidException, + MYJDTooManyRequestsException, + MYJDUnknownException, +) +from .myjdapi import MyJdApi + +__version__ = "1.1.7" + +__all__ = [ + "MYJDException", + "MYJDConnectionException", + "MYJDDeviceNotFoundException", + "MYJDDecodeException", + "MYJDApiException", + "MYJDApiCommandNotFoundException", + "MYJDApiInterfaceNotFoundException", + "MYJDAuthFailedException", + "MYJDBadParametersException", + "MYJDBadRequestException", + "MYJDChallengeFailedException", + "MYJDEmailForbiddenException", + "MYJDEmailInvalidException", + "MYJDErrorEmailNotConfirmedException", + "MYJDFailedException", + "MYJDFileNotFoundException", + "MYJDInternalServerErrorException", + "MYJDMaintenanceException", + "MYJDMethodForbiddenException", + "MYJDOfflineException", + "MYJDOutdatedException", + "MYJDOverloadException", + "MYJDSessionException", + "MYJDStorageAlreadyExistsException", + "MYJDStorageInvalidKeyException", + "MYJDStorageInvalidStorageIdException", + "MYJDStorageKeyNotFoundException", + "MYJDStorageLimitReachedException", + "MYJDStorageNotFoundException", + "MYJDTokenInvalidException", + "MYJDTooManyRequestsException", + "MYJDUnknownException", + "Myjdapi", +] diff --git a/myjd/const.py b/myjd/const.py new file mode 100644 index 0000000000000000000000000000000000000000..c1cf110d035c81b16dfe8d776a4cbb698f57b528 --- /dev/null +++ b/myjd/const.py @@ -0,0 +1,36 @@ +"""Constants of the MyJDownloader API.""" + +# API Documentation: https://my.jdownloader.org/developers + +# MyJdownloader exception source +EXCEPTION_MYJD = "MYJD" +EXCEPTION_DEVICE = "DEVICE" + +# MyJdownloader exception type +EXCEPTION_API_COMMAND_NOT_FOUND = "API_COMMAND_NOT_FOUND" +EXCEPTION_API_INTERFACE_NOT_FOUND = "API_INTERFACE_NOT_FOUND" +EXCEPTION_AUTH_FAILED = "AUTH_FAILED" +EXCEPTION_BAD_PARAMETERS = "BAD_PARAMETERS" +EXCEPTION_BAD_REQUEST = "BAD_REQUEST" +EXCEPTION_CHALLENGE_FAILED = "CHALLENGE_FAILED" +EXCEPTION_EMAIL_FORBIDDEN = "EMAIL_FORBIDDEN" +EXCEPTION_EMAIL_INVALID = "EMAIL_INVALID" +EXCEPTION_ERROR_EMAIL_NOT_CONFIRMED = "ERROR_EMAIL_NOT_CONFIRMED" +EXCEPTION_FAILED = "FAILED" +EXCEPTION_FILE_NOT_FOUND = "FILE_NOT_FOUND" +EXCEPTION_INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR" +EXCEPTION_MAINTENANCE = "MAINTENANCE" +EXCEPTION_METHOD_FORBIDDEN = "METHOD_FORBIDDEN" +EXCEPTION_OFFLINE = "OFFLINE" +EXCEPTION_OUTDATED = "OUTDATED" +EXCEPTION_OVERLOAD = "OVERLOAD" +EXCEPTION_SESSION = "SESSION" +EXCEPTION_STORAGE_ALREADY_EXISTS = "STORAGE_ALREADY_EXISTS" +EXCEPTION_STORAGE_INVALID_KEY = "STORAGE_INVALID_KEY" +EXCEPTION_STORAGE_INVALID_STORAGEID = "STORAGE_INVALID_STORAGEID" +EXCEPTION_STORAGE_KEY_NOT_FOUND = "STORAGE_KEY_NOT_FOUND" +EXCEPTION_STORAGE_LIMIT_REACHED = "STORAGE_LIMIT_REACHED" +EXCEPTION_STORAGE_NOT_FOUND = "STORAGE_NOT_FOUND" +EXCEPTION_TOKEN_INVALID = "TOKEN_INVALID" +EXCEPTION_TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS" +EXCEPTION_UNKNOWN = "UNKNOWN" diff --git a/myjd/exception.py b/myjd/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..dd307ebb72aeab194086b7a8b5b4c85e87fb42d8 --- /dev/null +++ b/myjd/exception.py @@ -0,0 +1,266 @@ +"""Exceptions of the MyJDownloader API.""" + +from .const import ( + EXCEPTION_API_COMMAND_NOT_FOUND, + EXCEPTION_API_INTERFACE_NOT_FOUND, + EXCEPTION_AUTH_FAILED, + EXCEPTION_BAD_PARAMETERS, + EXCEPTION_BAD_REQUEST, + EXCEPTION_CHALLENGE_FAILED, + EXCEPTION_EMAIL_FORBIDDEN, + EXCEPTION_EMAIL_INVALID, + EXCEPTION_ERROR_EMAIL_NOT_CONFIRMED, + EXCEPTION_FAILED, + EXCEPTION_FILE_NOT_FOUND, + EXCEPTION_INTERNAL_SERVER_ERROR, + EXCEPTION_MAINTENANCE, + EXCEPTION_METHOD_FORBIDDEN, + EXCEPTION_OFFLINE, + EXCEPTION_OUTDATED, + EXCEPTION_OVERLOAD, + EXCEPTION_SESSION, + EXCEPTION_STORAGE_ALREADY_EXISTS, + EXCEPTION_STORAGE_INVALID_KEY, + EXCEPTION_STORAGE_INVALID_STORAGEID, + EXCEPTION_STORAGE_KEY_NOT_FOUND, + EXCEPTION_STORAGE_LIMIT_REACHED, + EXCEPTION_STORAGE_NOT_FOUND, + EXCEPTION_TOKEN_INVALID, + EXCEPTION_TOO_MANY_REQUESTS, + EXCEPTION_UNKNOWN, +) + + +class MYJDException(BaseException): + """Base MyJDownloader Exception.""" + + pass + + +class MYJDConnectionException(MYJDException): + """Connection Exception.""" + + pass + + +class MYJDDeviceNotFoundException(MYJDException): + """Device not found Exception.""" + + pass + + +class MYJDDecodeException(MYJDException): + """Decode Exception.""" + + pass + + +class MYJDApiException(MYJDException): + """Base MyJDownloader API Exception.""" + + @classmethod + def get_exception( + cls, exception_source, exception_type=EXCEPTION_UNKNOWN, *args, **kwargs + ): + """Get exception object from MyJDownloader exception type.""" + return EXCEPTION_CLASSES.get(exception_type.upper(), MYJDUnknownException)( + exception_source, *args, **kwargs + ) + + def __init__(self, exception_source, *args, **kwargs): + """Initialize MyJDownloader API exception.""" + self.source = exception_source.upper() + super(MYJDApiException, self).__init__(*args, **kwargs) + + +class MYJDApiCommandNotFoundException(MYJDApiException): + """MyJDownloader command not found API Exception.""" + + pass + + +class MYJDApiInterfaceNotFoundException(MYJDApiException): + """MyJDownloader interface not found API Exception.""" + + pass + + +class MYJDAuthFailedException(MYJDApiException): + """MyJDownloader auth failed API Exception.""" + + pass + + +class MYJDBadParametersException(MYJDApiException): + """MyJDownloader bad parameters API Exception.""" + + pass + + +class MYJDBadRequestException(MYJDApiException): + """MyJDownloader bad request API Exception.""" + + pass + + +class MYJDChallengeFailedException(MYJDApiException): + """MyJDownloader challenge failed API Exception.""" + + pass + + +class MYJDEmailForbiddenException(MYJDApiException): + """MyJDownloader email forbidden API Exception.""" + + pass + + +class MYJDEmailInvalidException(MYJDApiException): + """MyJDownloader email invalid API Exception.""" + + pass + + +class MYJDErrorEmailNotConfirmedException(MYJDApiException): + """MyJDownloader email not confirmed API Exception.""" + + pass + + +class MYJDFailedException(MYJDApiException): + """MyJDownloader failed API Exception.""" + + pass + + +class MYJDFileNotFoundException(MYJDApiException): + """MyJDownloader file not found API Exception.""" + + pass + + +class MYJDInternalServerErrorException(MYJDApiException): + """MyJDownloader internal server error API Exception.""" + + pass + + +class MYJDMaintenanceException(MYJDApiException): + """MyJDownloader maintenance API Exception.""" + + pass + + +class MYJDMethodForbiddenException(MYJDApiException): + """MyJDownloader method forbidden API Exception.""" + + pass + + +class MYJDOfflineException(MYJDApiException): + """MyJDownloader offline API Exception.""" + + pass + + +class MYJDOutdatedException(MYJDApiException): + """MyJDownloader outdated API Exception.""" + + pass + + +class MYJDOverloadException(MYJDApiException): + """MyJDownloader overload API Exception.""" + + pass + + +class MYJDSessionException(MYJDApiException): + """MyJDownloader session API Exception.""" + + pass + + +class MYJDStorageAlreadyExistsException(MYJDApiException): + """MyJDownloader storage already exists API Exception.""" + + pass + + +class MYJDStorageInvalidKeyException(MYJDApiException): + """MyJDownloader storage invalid key API Exception.""" + + pass + + +class MYJDStorageInvalidStorageIdException(MYJDApiException): + """MyJDownloader storage invalid storage id API Exception.""" + + pass + + +class MYJDStorageKeyNotFoundException(MYJDApiException): + """MyJDownloader storage key not found API Exception.""" + + pass + + +class MYJDStorageLimitReachedException(MYJDApiException): + """MyJDownloader storage limit reached API Exception.""" + + pass + + +class MYJDStorageNotFoundException(MYJDApiException): + """MyJDownloader storage not found API Exception.""" + + pass + + +class MYJDTokenInvalidException(MYJDApiException): + """MyJDownloader token invalid API Exception.""" + + pass + + +class MYJDTooManyRequestsException(MYJDApiException): + """MyJDownloader too many request API Exception.""" + + pass + + +class MYJDUnknownException(MYJDApiException): + """MyJDownloader unknown API Exception.""" + + pass + + +EXCEPTION_CLASSES = { + EXCEPTION_API_COMMAND_NOT_FOUND: MYJDApiCommandNotFoundException, + EXCEPTION_API_INTERFACE_NOT_FOUND: MYJDApiInterfaceNotFoundException, + EXCEPTION_AUTH_FAILED: MYJDAuthFailedException, + EXCEPTION_BAD_PARAMETERS: MYJDBadParametersException, + EXCEPTION_BAD_REQUEST: MYJDBadRequestException, + EXCEPTION_CHALLENGE_FAILED: MYJDChallengeFailedException, + EXCEPTION_EMAIL_FORBIDDEN: MYJDEmailForbiddenException, + EXCEPTION_EMAIL_INVALID: MYJDEmailInvalidException, + EXCEPTION_ERROR_EMAIL_NOT_CONFIRMED: MYJDErrorEmailNotConfirmedException, + EXCEPTION_FAILED: MYJDFailedException, + EXCEPTION_FILE_NOT_FOUND: MYJDFileNotFoundException, + EXCEPTION_INTERNAL_SERVER_ERROR: MYJDInternalServerErrorException, + EXCEPTION_MAINTENANCE: MYJDMaintenanceException, + EXCEPTION_METHOD_FORBIDDEN: MYJDMethodForbiddenException, + EXCEPTION_OFFLINE: MYJDOfflineException, + EXCEPTION_OUTDATED: MYJDOutdatedException, + EXCEPTION_OVERLOAD: MYJDOverloadException, + EXCEPTION_SESSION: MYJDSessionException, + EXCEPTION_STORAGE_ALREADY_EXISTS: MYJDStorageAlreadyExistsException, + EXCEPTION_STORAGE_INVALID_KEY: MYJDStorageInvalidKeyException, + EXCEPTION_STORAGE_INVALID_STORAGEID: MYJDStorageInvalidStorageIdException, + EXCEPTION_STORAGE_KEY_NOT_FOUND: MYJDStorageKeyNotFoundException, + EXCEPTION_STORAGE_LIMIT_REACHED: MYJDStorageLimitReachedException, + EXCEPTION_STORAGE_NOT_FOUND: MYJDStorageNotFoundException, + EXCEPTION_TOKEN_INVALID: MYJDTokenInvalidException, + EXCEPTION_TOO_MANY_REQUESTS: MYJDTooManyRequestsException, + EXCEPTION_UNKNOWN: MYJDUnknownException, +} diff --git a/myjd/myjdapi.py b/myjd/myjdapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1ab31256aea1c4ca2f18d6e993e09181601d2c --- /dev/null +++ b/myjd/myjdapi.py @@ -0,0 +1,781 @@ +from json import JSONDecodeError +from httpx import AsyncClient, AsyncHTTPTransport, RequestError, Timeout + +from .exception import ( + MYJDApiException, + MYJDConnectionException, + MYJDDecodeException, +) + + +class System: + def __init__(self, device): + self.device = device + self.url = "/system" + + async def exit_jd(self): + return await self.device.action(f"{self.url}/exitJD") + + async def restart_jd(self): + return await self.device.action(f"{self.url}/restartJD") + + async def hibernate_os(self): + return await self.device.action(f"{self.url}/hibernateOS") + + async def shutdown_os(self, force): + params = force + return await self.device.action(f"{self.url}/shutdownOS", params) + + async def standby_os(self): + return await self.device.action(f"{self.url}/standbyOS") + + async def get_storage_info(self): + return await self.device.action(f"{self.url}/getStorageInfos?path") + + +class Jd: + def __init__(self, device): + self.device = device + self.url = "/jd" + + async def get_core_revision(self): + return await self.device.action(f"{self.url}/getCoreRevision") + + async def version(self): + return await self.device.action(f"{self.url}/version") + + +class Config: + + def __init__(self, device): + self.device = device + self.url = "/config" + + async def list(self, params=None): + """ + :return: List + """ + if params is None: + return await self.device.action(f"{self.url}/list", params) + else: + return await self.device.action(f"{self.url}/list") + + async def listEnum(self, type): + """ + :return: List + """ + return await self.device.action(f"{self.url}/listEnum", params=[type]) + + async def get(self, interface_name, storage, key): + """ + :param interfaceName: a valid interface name from List + :type: str: + :param storage: 'null' to use default or 'cfg/' + interfaceName + :type: str: + :param key: a valid key from from List + :type: str: + """ + params = [interface_name, storage, key] + return await self.device.action(f"{self.url}/get", params) + + async def getDefault(self, interfaceName, storage, key): + """ + :param interfaceName: a valid interface name from List + :type: str: + :param storage: 'null' to use default or 'cfg/' + interfaceName + :type: str: + :param key: a valid key from from List + :type: str: + """ + params = [interfaceName, storage, key] + return await self.device.action(f"{self.url}/getDefault", params) + + async def query(self, params=None): + """ + :param params: A dictionary with options. The default dictionary is + configured so it returns you all config API entries with all details, but you + can put your own with your options. All the options available are this + ones: + { + "configInterface" : "", + "defaultValues" : True, + "description" : True, + "enumInfo" : True, + "includeExtensions": True, + "pattern" : "", + "values" : "" + } + :type: Dictionary + :rtype: List of dictionaries of this style, with more or less detail based on your options. + """ + if params is None: + params = [ + { + "configInterface": "", + "defaultValues": True, + "description": True, + "enumInfo": True, + "includeExtensions": True, + "pattern": "", + "values": True, + } + ] + return await self.device.action(f"{self.url}/query", params) + + async def reset(self, interfaceName, storage, key): + """ + :param interfaceName: a valid interface name from List + :type: str: + :param storage: 'null' to use default or 'cfg/' + interfaceName + :type: str: + :param key: a valid key from from List + :type: str: + """ + params = [interfaceName, storage, key] + return await self.device.action(f"{self.url}/reset", params) + + async def set(self, interface_name, storage, key, value): + """ + :param interfaceName: a valid interface name from List + :type: str: + :param storage: 'null' to use default or 'cfg/' + interfaceName + :type: str: + :param key: a valid key from from List + :type: str: + :param value: a valid value for the given key (see type value from List) + :type: Object: + """ + params = [interface_name, storage, key, value] + return await self.device.action(f"{self.url}/set", params) + + +class DownloadController: + + def __init__(self, device): + self.device = device + self.url = "/downloadcontroller" + + async def start_downloads(self): + return await self.device.action(f"{self.url}/start") + + async def stop_downloads(self): + return await self.device.action(f"{self.url}/stop") + + async def pause_downloads(self, value): + params = [value] + return await self.device.action(f"{self.url}/pause", params) + + async def get_speed_in_bytes(self): + return await self.device.action(f"{self.url}/getSpeedInBps") + + async def force_download(self, link_ids, package_ids): + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/forceDownload", params) + + async def get_current_state(self): + return await self.device.action(f"{self.url}/getCurrentState") + + +class Extension: + def __init__(self, device): + self.device = device + self.url = "/extensions" + + async def list(self, params=None): + """ + :param params: A dictionary with options. The default dictionary is + configured so it returns you all available extensions, but you + can put your own with your options. All the options available are this + ones: + { + "configInterface" : True, + "description" : True, + "enabled" : True, + "iconKey" : True, + "name" : True, + "pattern" : "", + "installed" : True + } + :type: Dictionary + :rtype: List of dictionaries of this style, with more or less detail based on your options. + """ + if params is None: + params = [ + { + "configInterface": True, + "description": True, + "enabled": True, + "iconKey": True, + "name": True, + "pattern": "", + "installed": True, + } + ] + return await self.device.action(f"{self.url}/list", params=params) + + async def install(self, id): + return await self.device.action(f"{self.url}/install", params=[id]) + + async def isInstalled(self, id): + return await self.device.action(f"{self.url}/isInstalled", params=[id]) + + async def isEnabled(self, id): + return await self.device.action(f"{self.url}/isEnabled", params=[id]) + + async def setEnabled(self, id, enabled): + return await self.device.action(f"{self.url}/setEnabled", params=[id, enabled]) + + +class Linkgrabber: + + def __init__(self, device): + self.device = device + self.url = "/linkgrabberv2" + + async def clear_list(self): + return await self.device.action(f"{self.url}/clearList") + + async def move_to_downloadlist(self, link_ids=None, package_ids=None): + """ + Moves packages and/or links to download list. + + :param package_ids: Package UUID's. + :type: list of strings. + :param link_ids: Link UUID's. + """ + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/moveToDownloadlist", params) + + async def query_links(self, params=None): + """ + + Get the links in the linkcollector/linkgrabber + + :param params: A dictionary with options. The default dictionary is + configured so it returns you all the downloads with all details, but you + can put your own with your options. All the options available are this + ones: + { + "bytesTotal" : false, + "comment" : false, + "status" : false, + "enabled" : false, + "maxResults" : -1, + "startAt" : 0, + "packageUUIDs" : null, + "hosts" : false, + "url" : false, + "availability" : false, + "variantIcon" : false, + "variantName" : false, + "variantID" : false, + "variants" : false, + "priority" : false + } + :type: Dictionary + :rtype: List of dictionaries of this style, with more or less detail based on your options. + + [ { 'availability': 'ONLINE', + 'bytesTotal': 68548274, + 'enabled': True, + 'name': 'The Rick And Morty Theory - The Original Morty_ - ' + 'Cartoon Conspiracy (Ep. 74) @ChannelFred (192kbit).m4a', + 'packageUUID': 1450430888524, + 'url': 'youtubev2://DEMUX_M4A_192_720P_V4/d1NZf1w2BxQ/', + 'uuid': 1450430889576, + 'variant': { 'id': 'DEMUX_M4A_192_720P_V4', + 'name': '192kbit/s M4A-Audio'}, + 'variants': True + }, ... ] + """ + if params is None: + params = [ + { + "bytesTotal": True, + "comment": True, + "status": True, + "enabled": True, + "maxResults": -1, + "startAt": 0, + "hosts": True, + "url": True, + "availability": True, + "variantIcon": True, + "variantName": True, + "variantID": True, + "variants": True, + "priority": True, + } + ] + return await self.device.action(f"{self.url}/queryLinks", params) + + async def cleanup( + self, action, mode, selection_type, link_ids=None, package_ids=None + ): + """ + Clean packages and/or links of the linkgrabber list. + Requires at least a package_ids or link_ids list, or both. + + :param package_ids: Package UUID's. + :type: list of strings. + :param link_ids: link UUID's. + :type: list of strings + :param action: Action to be done. Actions: DELETE_ALL, DELETE_DISABLED, DELETE_FAILED, DELETE_FINISHED, DELETE_OFFLINE, DELETE_DUPE, DELETE_MODE + :type: str: + :param mode: Mode to use. Modes: REMOVE_LINKS_AND_DELETE_FILES, REMOVE_LINKS_AND_RECYCLE_FILES, REMOVE_LINKS_ONLY + :type: str: + :param selection_type: Type of selection to use. Types: SELECTED, UNSELECTED, ALL, NONE + :type: str: + """ + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + params += [action, mode, selection_type] + return await self.device.action(f"{self.url}/cleanup", params) + + async def add_container(self, type_, content): + """ + Adds a container to Linkgrabber. + + :param type_: Type of container. + :type: string. + :param content: The container. + :type: string. + + """ + params = [type_, content] + return await self.device.action(f"{self.url}/addContainer", params) + + async def get_download_urls(self, link_ids, package_ids, url_display_type): + """ + Gets download urls from Linkgrabber. + + :param package_ids: Package UUID's. + :type: List of strings. + :param link_ids: link UUID's. + :type: List of strings + :param url_display_type: No clue. Not documented + :type: Dictionary + """ + params = [package_ids, link_ids, url_display_type] + return await self.device.action(f"{self.url}/getDownloadUrls", params) + + async def set_priority(self, priority, link_ids, package_ids): + """ + Sets the priority of links or packages. + + :param package_ids: Package UUID's. + :type: list of strings. + :param link_ids: link UUID's. + :type: list of strings + :param priority: Priority to set. Priorities: HIGHEST, HIGHER, HIGH, DEFAULT, LOWER; + :type: str: + """ + params = [priority, link_ids, package_ids] + return await self.device.action(f"{self.url}/setPriority", params) + + async def set_enabled(self, enable, link_ids, package_ids): + """ + Enable or disable packages. + + :param enable: Enable or disable package. + :type: boolean + :param link_ids: Links UUID. + :type: list of strings + :param package_ids: Packages UUID. + :type: list of strings. + """ + params = [enable, link_ids, package_ids] + return await self.device.action(f"{self.url}/setEnabled", params) + + async def get_variants(self, params): + """ + Gets the variants of a url/download (not package), for example a youtube + link gives you a package with three downloads, the audio, the video and + a picture, and each of those downloads have different variants (audio + quality, video quality, and picture quality). + + :param params: List with the UUID of the download you want the variants. Ex: [232434] + :type: List + :rtype: Variants in a list with dictionaries like this one: [{'id': + 'M4A_256', 'name': '256kbit/s M4A-Audio'}, {'id': 'AAC_256', 'name': + '256kbit/s AAC-Audio'},.......] + """ + return await self.device.action(f"{self.url}/getVariants", params) + + async def add_links(self, params=None): + """ + Add links to the linkcollector + + { + "autostart" : false, + "links" : null, + "packageName" : null, + "extractPassword" : null, + "priority" : "DEFAULT", + "downloadPassword" : null, + "destinationFolder" : null + } + """ + if params is None: + params = [ + { + "autostart": False, + "links": None, + "packageName": None, + "extractPassword": None, + "priority": "DEFAULT", + "downloadPassword": None, + "destinationFolder": None, + "overwritePackagizerRules": False, + } + ] + return await self.device.action(f"{self.url}/addLinks", params) + + async def is_collecting(self): + """ + Boolean status query about the collecting process + """ + return await self.device.action(f"{self.url}/isCollecting") + + async def set_download_directory(self, dir: str, package_ids: list): + params = [dir, package_ids] + return await self.device.action(f"{self.url}/setDownloadDirectory", params) + + async def move_to_new_package( + self, name: str, path: str, link_ids: list = None, package_ids: list = None + ): + # Requires at least a link_ids or package_ids list, or both. + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids, name, path] + return await self.device.action(f"{self.url}/movetoNewPackage", params) + + async def remove_links(self, link_ids=None, package_ids=None): + """ + Remove packages and/or links of the linkgrabber list. + Requires at least a link_ids or package_ids list, or both. + + :param link_ids: link UUID's. + :type: list of strings + :param package_ids: Package UUID's. + :type: list of strings. + """ + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/removeLinks", params) + + async def rename_link(self, link_id, new_name): + """ + Renames files related with link_id + """ + params = [link_id, new_name] + return await self.device.action(f"{self.url}/renameLink", params) + + async def get_package_count(self): + return await self.device.action(f"{self.url}/getPackageCount") + + async def rename_package(self, package_id, new_name): + """ + Rename package name with package_id + """ + params = [package_id, new_name] + return await self.device.action(f"{self.url}/renamePackage", params) + + async def query_packages(self, params=None): + if params is None: + params = [ + { + "availableOfflineCount": True, + "availableOnlineCount": True, + "availableTempUnknownCount": True, + "availableUnknownCount": True, + "bytesTotal": True, + "childCount": True, + "comment": True, + "enabled": True, + "hosts": True, + "maxResults": -1, + "packageUUIDs": [], + "priority": True, + "saveTo": True, + "startAt": 0, + "status": True, + } + ] + return await self.device.action(f"{self.url}/queryPackages", params) + + +class Downloads: + + def __init__(self, device): + self.device = device + self.url = "/downloadsV2" + + async def query_links(self, params=None): + """ + Get the links in the download list + """ + if params is None: + params = [ + { + "addedDate": True, + "bytesLoaded": True, + "bytesTotal": True, + "comment": True, + "enabled": True, + "eta": True, + "extractionStatus": True, + "finished": True, + "finishedDate": True, + "host": True, + "jobUUIDs": [], + "maxResults": -1, + "packageUUIDs": [], + "password": True, + "priority": True, + "running": True, + "skipped": True, + "speed": True, + "startAt": 0, + "status": True, + "url": True, + } + ] + return await self.device.action(f"{self.url}/queryLinks", params) + + async def query_packages(self, params=None): + if params is None: + params = [ + { + "bytesLoaded": True, + "bytesTotal": True, + "childCount": True, + "comment": True, + "enabled": True, + "eta": True, + "finished": True, + "hosts": True, + "maxResults": -1, + "packageUUIDs": [], + "priority": True, + "running": True, + "saveTo": True, + "speed": True, + "startAt": 0, + "status": True, + } + ] + return await self.device.action(f"{self.url}/queryPackages", params) + + async def cleanup( + self, action, mode, selection_type, link_ids=None, package_ids=None + ): + """ + Clean packages and/or links of the linkgrabber list. + Requires at least a package_ids or link_ids list, or both. + + :param package_ids: Package UUID's. + :type: list of strings. + :param link_ids: link UUID's. + :type: list of strings + :param action: Action to be done. Actions: DELETE_ALL, DELETE_DISABLED, DELETE_FAILED, DELETE_FINISHED, DELETE_OFFLINE, DELETE_DUPE, DELETE_MODE + :type: str: + :param mode: Mode to use. Modes: REMOVE_LINKS_AND_DELETE_FILES, REMOVE_LINKS_AND_RECYCLE_FILES, REMOVE_LINKS_ONLY + :type: str: + :param selection_type: Type of selection to use. Types: SELECTED, UNSELECTED, ALL, NONE + :type: str: + """ + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + params += [action, mode, selection_type] + return await self.device.action(f"{self.url}/cleanup", params) + + async def set_enabled(self, enable, link_ids, package_ids): + """ + Enable or disable packages. + + :param enable: Enable or disable package. + :type: boolean + :param link_ids: Links UUID. + :type: list of strings + :param package_ids: Packages UUID. + :type: list of strings. + """ + params = [enable, link_ids, package_ids] + return await self.device.action(f"{self.url}/setEnabled", params) + + async def force_download(self, link_ids=None, package_ids=None): + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/forceDownload", params) + + async def set_dl_location(self, directory, package_ids=None): + if package_ids is None: + package_ids = [] + params = [directory, package_ids] + return await self.device.action(f"{self.url}/setDownloadDirectory", params) + + async def remove_links(self, link_ids=None, package_ids=None): + """ + Remove packages and/or links of the downloads list. + NOTE: For more specific removal, like deleting the files etc, use the /cleanup api. + Requires at least a link_ids or package_ids list, or both. + + :param link_ids: link UUID's. + :type: list of strings + :param package_ids: Package UUID's. + :type: list of strings. + """ + if link_ids is None: + link_ids = [] + if package_ids is None: + package_ids = [] + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/removeLinks", params) + + async def reset_links(self, link_ids, package_ids): + params = [link_ids, package_ids] + return await self.device.action(f"{self.url}/resetLinks", params) + + async def move_to_new_package( + self, link_ids, package_ids, new_pkg_name, download_path + ): + params = [link_ids, package_ids, new_pkg_name, download_path] + return await self.device.action(f"{self.url}/movetoNewPackage", params) + + async def rename_link(self, link_id: list, new_name: str): + params = [link_id, new_name] + return await self.device.action(f"{self.url}/renameLink", params) + + +class Captcha: + + def __init__(self, device): + self.device = device + self.url = "/captcha" + + async def list(self): + return await self.device.action(f"{self.url}/list", []) + + async def get(self, captcha_id): + return await self.device.action(f"{self.url}/get", (captcha_id,)) + + async def solve(self, captcha_id, solution): + return await self.device.action(f"{self.url}/solve", (captcha_id, solution)) + + +class Jddevice: + + def __init__(self, jd): + """This functions initializes the device instance. + It uses the provided dictionary to create the device. + + :param device_dict: Device dictionary + """ + self.myjd = jd + self.config = Config(self) + self.linkgrabber = Linkgrabber(self) + self.captcha = Captcha(self) + self.downloads = Downloads(self) + self.downloadcontroller = DownloadController(self) + self.extensions = Extension(self) + self.jd = Jd(self) + self.system = System(self) + + async def ping(self): + return await self.action("/device/ping") + + async def action(self, path, params=()): + response = await self.myjd.request_api(path, params) + if response is None: + raise (MYJDConnectionException("No connection established\n")) + return response["data"] + + +class MyJdApi: + + def __init__(self): + self.__api_url = "http://127.0.0.1:3128" + self._http_session = None + self.device = Jddevice(self) + + def _session(self): + if self._http_session is not None: + return self._http_session + + transport = AsyncHTTPTransport(retries=10, verify=False) + + self._http_session = AsyncClient( + base_url=self.__api_url, + transport=transport, + headers={"Content-Type": "application/json; charset=utf-8"}, + timeout=Timeout(connect=60, read=60, write=60, pool=None), + follow_redirects=True, + verify=False, + ) + + return self._http_session + + async def close(self): + if self._http_session is not None: + await self._http_session.aclose() + self._http_session = None + + async def request_api(self, path, params=None): + session = self._session() + params_request = params if params is not None else [] + params_request = { + "params": params_request, + } + try: + res = await session.post( + path, + json=params_request, + ) + except RequestError: + return None + try: + response = res.json() + except JSONDecodeError as exc: + raise MYJDDecodeException( + "Failed to decode response: {}", response + ) from exc + if res.status_code != 200: + msg = ( + "\n\tSOURCE: " + + response.get("src", "UNKNOWN_SOURCE") + + "\n\tTYPE: " + + response.get("type", "UNKNOWN_TYPE") + + "\n------\nREQUEST_URL: " + + self.__api_url + + path + ) + msg += "\n" + if params_request is not None: + msg += "DATA:\n" + params_request + raise ( + MYJDApiException.get_exception( + response.get("src", "UNKNOWN_SOURCE"), + response.get("type", "UNKNOWN_TYPE"), + msg, + ) + ) + return response diff --git a/qBittorrent/config/qBittorrent.conf b/qBittorrent/config/qBittorrent.conf new file mode 100644 index 0000000000000000000000000000000000000000..ddc33b66ded8c30ac9a36040443a6808dfab7d45 --- /dev/null +++ b/qBittorrent/config/qBittorrent.conf @@ -0,0 +1,66 @@ +[Application] +MemoryWorkingSetLimit=512 + +[BitTorrent] +Session\AddExtensionToIncompleteFiles=false +Session\AddTrackersEnabled=false +Session\AnnounceToAllTrackers=true +Session\AnonymousModeEnabled=false +Session\AsyncIOThreadsCount=16 +Session\ConnectionSpeed=-1 +Session\DHTEnabled=true +Session\DiskCacheSize=-1 +Session\GlobalDLSpeedLimit=0 +Session\GlobalMaxRatio=-1 +Session\GlobalMaxSeedingMinutes=-1 +Session\GlobalUPSpeedLimit=0 +Session\HashingThreadsCount=1 +Session\IgnoreSlowTorrentsForQueueing=true +Session\IncludeOverheadInLimits=false +Session\LSDEnabled=true +Session\MaxActiveCheckingTorrents=3 +Session\MaxActiveDownloads=1000 +Session\MaxActiveTorrents=1000 +Session\MaxActiveUploads=1000 +Session\MaxConnections=-1 +Session\MaxConnectionsPerTorrent=-1 +Session\MaxRatioAction=0 +Session\MaxUploads=-1 +Session\MaxUploadsPerTorrent=-1 +Session\MultiConnectionsPerIp=true +Session\PexEnabled=true +Session\PerformanceWarning=true +Session\Preallocation=true +Session\QueueingSystemEnabled=false +Session\SlowTorrentsDownloadRate=2 +Session\SlowTorrentsInactivityTimer=600 +Session\SlowTorrentsUploadRate=2 +Session\StopTrackerTimeout=5 +TrackerEnabled=true + +[LegalNotice] +Accepted=true + +[Meta] +MigrationVersion=8 + +[Preferences] +Advanced\DisableRecursiveDownload=false +Advanced\RecheckOnCompletion=true +Advanced\trackerPortForwarding=true +General\PreventFromSuspendWhenDownloading=true +General\PreventFromSuspendWhenSeeding=true +Search\SearchEnabled=true +WebUI\Address=* +WebUI\BanDuration=3600 +WebUI\CSRFProtection=false +WebUI\ClickjackingProtection=false +WebUI\Enabled=true +WebUI\HTTPS\Enabled=false +WebUI\HostHeaderValidation=false +WebUI\LocalHostAuth=false +WebUI\MaxAuthenticationFailCount=1000 +WebUI\Port=8090 +WebUI\SecureCookie=false +WebUI\UseUPnP=false +WebUI\Username=mltb diff --git a/requirements-cli.txt b/requirements-cli.txt new file mode 100644 index 0000000000000000000000000000000000000000..f105cbee85f96c55d346541af8b5ddd2ad698ff4 --- /dev/null +++ b/requirements-cli.txt @@ -0,0 +1,7 @@ +oauth2client +google-api-python-client +progress +progressbar2 +httplib2shim +google_auth_oauthlib +kurigram diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..628b09cbd6c0a233deaf666deb6a4542ae43e9a9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,34 @@ +asyncio +aiofiles +aioshutil +anytree +apscheduler +aioaria2 +aioqbt +cloudscraper +dnspython +fastapi +feedparser +google-api-python-client +google-auth-httplib2 +google-auth-oauthlib +gunicorn +httpx +jinja2 +lxml +natsort +par2cmdline-turbo +pillow +psutil +pymongo +kurigram +python-magic +requests +telegraph +tenacity +tgcrypto +urllib3 +uvicorn +uvloop +xattr +yt-dlp[default,curl-cffi] diff --git a/sabnzbd/SABnzbd.ini b/sabnzbd/SABnzbd.ini new file mode 100644 index 0000000000000000000000000000000000000000..1c1408309a4da222b4d8edb0e5236e79f8b46e69 --- /dev/null +++ b/sabnzbd/SABnzbd.ini @@ -0,0 +1,287 @@ +__version__ = 19 +__encoding__ = utf-8 +[misc] +helpful_warnings = 0 +queue_complete = "" +queue_complete_pers = 0 +bandwidth_perc = 100 +refresh_rate = 0 +interface_settings = "" +queue_limit = 20 +config_lock = 0 +fixed_ports = 1 +notified_new_skin = 0 +direct_unpack_tested = 0 +sorters_converted = 1 +check_new_rel = 1 +auto_browser = 1 +language = en +enable_https_verification = 0 +host = :: +port = 8070 +https_port = "" +username = "mltb" +password = "mltbmltb" +bandwidth_max = "" +cache_limit = "" +web_dir = Glitter +web_color = Auto +https_cert = server.cert +https_key = server.key +https_chain = "" +enable_https = 0 +inet_exposure = 4 +api_key = mltb +nzb_key = "" +socks5_proxy_url = "" +permissions = "" +download_dir = /usr/src/app/downloads +download_free = "" +complete_dir = /usr/src/app/downloads +complete_free = "" +fulldisk_autoresume = 0 +script_dir = "" +nzb_backup_dir = "" +admin_dir = admin +backup_dir = "" +dirscan_dir = "" +dirscan_speed = 5 +password_file = "" +log_dir = logs +max_art_tries = 3 +top_only = 0 +sfv_check = 1 +script_can_fail = 0 +enable_recursive = 1 +flat_unpack = 0 +par_option = "" +pre_check = 0 +nice = "" +win_process_prio = 3 +ionice = "" +fail_hopeless_jobs = 1 +fast_fail = 1 +auto_disconnect = 1 +pre_script = None +end_queue_script = None +no_dupes = 3 +no_series_dupes = 0 +no_smart_dupes = 0 +dupes_propercheck = 1 +pause_on_pwrar = 0 +ignore_samples = 0 +deobfuscate_final_filenames = 1 +auto_sort = "" +direct_unpack = 0 +propagation_delay = 0 +folder_rename = 1 +replace_spaces = 0 +replace_underscores = 0 +replace_dots = 0 +safe_postproc = 1 +pause_on_post_processing = 0 +enable_all_par = 0 +sanitize_safe = 0 +cleanup_list = , +unwanted_extensions = , +action_on_unwanted_extensions = 0 +unwanted_extensions_mode = 0 +new_nzb_on_failure = 0 +history_retention = 0 +quota_size = "" +quota_day = "" +quota_resume = 0 +quota_period = m +enable_tv_sorting = 0 +tv_sort_string = "" +tv_categories = tv, +enable_movie_sorting = 0 +movie_sort_string = "" +movie_sort_extra = -cd%1 +movie_categories = movies, +enable_date_sorting = 0 +date_sort_string = "" +date_categories = tv, +schedlines = , +rss_rate = 60 +ampm = 0 +start_paused = 0 +preserve_paused_state = 0 +enable_par_cleanup = 1 +process_unpacked_par2 = 1 +enable_multipar = 1 +enable_unrar = 1 +enable_7zip = 1 +enable_filejoin = 1 +enable_tsjoin = 1 +overwrite_files = 0 +ignore_unrar_dates = 0 +backup_for_duplicates = 0 +empty_postproc = 0 +wait_for_dfolder = 0 +rss_filenames = 0 +api_logging = 1 +html_login = 1 +warn_dupl_jobs = 0 +keep_awake = 1 +tray_icon = 1 +allow_incomplete_nzb = 0 +enable_broadcast = 1 +ipv6_hosting = 0 +api_warnings = 0 +no_penalties = 0 +x_frame_options = 1 +allow_old_ssl_tls = 0 +enable_season_sorting = 1 +verify_xff_header = 0 +rss_odd_titles = nzbindex.nl/, nzbindex.com/, nzbclub.com/ +quick_check_ext_ignore = nfo, sfv, srr +req_completion_rate = 100.2 +selftest_host = self-test.sabnzbd.org +movie_rename_limit = 100M +episode_rename_limit = 20M +size_limit = 0 +direct_unpack_threads = 3 +history_limit = 10 +wait_ext_drive = 5 +max_foldername_length = 246 +nomedia_marker = "" +ipv6_servers = 1 +url_base = /sabnzbd +host_whitelist = , +local_ranges = , +max_url_retries = 10 +downloader_sleep_time = 10 +receive_threads = 2 +switchinterval = 0.005 +ssdp_broadcast_interval = 15 +ext_rename_ignore = , +email_server = "" +email_to = , +email_from = "" +email_account = "" +email_pwd = "" +email_endjob = 0 +email_full = 0 +email_dir = "" +email_rss = 0 +email_cats = *, +[logging] +log_level = 1 +max_log_size = 5242880 +log_backups = 5 +[ncenter] +ncenter_enable = 0 +ncenter_cats = *, +ncenter_prio_startup = 0 +ncenter_prio_download = 0 +ncenter_prio_pause_resume = 0 +ncenter_prio_pp = 0 +ncenter_prio_complete = 1 +ncenter_prio_failed = 1 +ncenter_prio_disk_full = 1 +ncenter_prio_new_login = 0 +ncenter_prio_warning = 0 +ncenter_prio_error = 0 +ncenter_prio_queue_done = 0 +ncenter_prio_other = 1 +[acenter] +acenter_enable = 0 +acenter_cats = *, +acenter_prio_startup = 0 +acenter_prio_download = 0 +acenter_prio_pause_resume = 0 +acenter_prio_pp = 0 +acenter_prio_complete = 1 +acenter_prio_failed = 1 +acenter_prio_disk_full = 1 +acenter_prio_new_login = 0 +acenter_prio_warning = 0 +acenter_prio_error = 0 +acenter_prio_queue_done = 0 +acenter_prio_other = 1 +[ntfosd] +ntfosd_enable = 1 +ntfosd_cats = *, +ntfosd_prio_startup = 0 +ntfosd_prio_download = 0 +ntfosd_prio_pause_resume = 0 +ntfosd_prio_pp = 0 +ntfosd_prio_complete = 1 +ntfosd_prio_failed = 1 +ntfosd_prio_disk_full = 1 +ntfosd_prio_new_login = 0 +ntfosd_prio_warning = 0 +ntfosd_prio_error = 0 +ntfosd_prio_queue_done = 0 +ntfosd_prio_other = 1 +[prowl] +prowl_enable = 0 +prowl_cats = *, +prowl_apikey = "" +prowl_prio_startup = -3 +prowl_prio_download = -3 +prowl_prio_pause_resume = -3 +prowl_prio_pp = -3 +prowl_prio_complete = 0 +prowl_prio_failed = 1 +prowl_prio_disk_full = 1 +prowl_prio_new_login = -3 +prowl_prio_warning = -3 +prowl_prio_error = -3 +prowl_prio_queue_done = -3 +prowl_prio_other = 0 +[pushover] +pushover_token = "" +pushover_userkey = "" +pushover_device = "" +pushover_emergency_expire = 3600 +pushover_emergency_retry = 60 +pushover_enable = 0 +pushover_cats = *, +pushover_prio_startup = -3 +pushover_prio_download = -2 +pushover_prio_pause_resume = -2 +pushover_prio_pp = -3 +pushover_prio_complete = -1 +pushover_prio_failed = -1 +pushover_prio_disk_full = 1 +pushover_prio_new_login = -3 +pushover_prio_warning = 1 +pushover_prio_error = 1 +pushover_prio_queue_done = -3 +pushover_prio_other = -1 +[pushbullet] +pushbullet_enable = 0 +pushbullet_cats = *, +pushbullet_apikey = "" +pushbullet_device = "" +pushbullet_prio_startup = 0 +pushbullet_prio_download = 0 +pushbullet_prio_pause_resume = 0 +pushbullet_prio_pp = 0 +pushbullet_prio_complete = 1 +pushbullet_prio_failed = 1 +pushbullet_prio_disk_full = 1 +pushbullet_prio_new_login = 0 +pushbullet_prio_warning = 0 +pushbullet_prio_error = 0 +pushbullet_prio_queue_done = 0 +pushbullet_prio_other = 1 +[nscript] +nscript_enable = 0 +nscript_cats = *, +nscript_script = "" +nscript_parameters = "" +nscript_prio_startup = 0 +nscript_prio_download = 0 +nscript_prio_pause_resume = 0 +nscript_prio_pp = 0 +nscript_prio_complete = 1 +nscript_prio_failed = 1 +nscript_prio_disk_full = 1 +nscript_prio_new_login = 0 +nscript_prio_warning = 0 +nscript_prio_error = 0 +nscript_prio_queue_done = 0 +nscript_prio_other = 1 \ No newline at end of file diff --git a/sabnzbdapi/__init__.py b/sabnzbdapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d99b2ab2a7896fee856d631c81fcdfe59151b824 --- /dev/null +++ b/sabnzbdapi/__init__.py @@ -0,0 +1,3 @@ +from sabnzbdapi.requests import SabnzbdClient + +__all__ = ["SabnzbdClient"] diff --git a/sabnzbdapi/bound_methods.py b/sabnzbdapi/bound_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..d76697f882565907bf861826886d9e4323cddacf --- /dev/null +++ b/sabnzbdapi/bound_methods.py @@ -0,0 +1,33 @@ +class SubFunctions: + + async def check_login(self): + res = await self.get_config("servers") + return res["config"] or False + + async def add_server(self, server: dict): + """server = { + "name": "main", + "displayname": "main", + "host": "", + "port": 5126, + "timeout": 60, + "username": "", + "password": "", + "connections": 8, + "ssl": 1, + "ssl_verify": 2, + "ssl_ciphers": "", + "enable": 1, + "required": 0, + "optional": 0, + "retention": 0, + "send_group": 0, + "priority": 0, + }""" + return await self.set_special_config("servers", server) + + async def create_category(self, name: str, dir: str): + return await self.set_special_config("categories", {"name": name, "dir": dir}) + + async def delete_category(self, name: str): + return await self.delete_config("categories", name) diff --git a/sabnzbdapi/exception.py b/sabnzbdapi/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..3374c9decb9c92ac1aa9e4593c9e105d770f5a0d --- /dev/null +++ b/sabnzbdapi/exception.py @@ -0,0 +1,18 @@ +from httpx import RequestError, DecodingError + + +class APIError(Exception): + """Base error for all exceptions from this Client.""" + + +class APIConnectionError(RequestError, APIError): + """Base class for all communications errors including HTTP errors.""" + + +class LoginFailed(DecodingError, APIConnectionError): + """This can technically be raised with any request since log in may be attempted for + any request and could fail.""" + + +class NotLoggedIn(APIConnectionError): + """Raised when login is not successful.""" diff --git a/sabnzbdapi/job_functions.py b/sabnzbdapi/job_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..f695d0b48d84ea60db2d5ffebedece8b9a7d2995 --- /dev/null +++ b/sabnzbdapi/job_functions.py @@ -0,0 +1,508 @@ +from sabnzbdapi.bound_methods import SubFunctions + + +class JobFunctions(SubFunctions): + + async def add_uri( + self, + url: str = "", + file: str = "", + nzbname: str = "", + password: str = "", + cat: str = "*", + script: list = None, + priority: int = 0, + pp: int = 1, + ): + + 'return {"status": True, "nzo_ids": ["SABnzbd_nzo_kyt1f0"]}' + + if file: + name = file + mode = "addlocalfile" + else: + name = url + mode = "addurl" + + return await self.call( + { + "mode": mode, + "name": name, + "nzbname": nzbname, + "password": password, + "cat": cat, + "script": script, + "priority": priority, + "pp": pp, + } + ) + + async def get_downloads( + self, + start: int | None = None, + limit: int | None = None, + search: str | None = None, + category: str | list[str] | None = None, + priority: int | list[str] | None = None, + status: str | list[str] | None = None, + nzo_ids: str | list[str] | None = None, + ): + """return { + "queue": { + "status": "Downloading", + "speedlimit": "9", + "speedlimit_abs": "4718592.0", + "paused": false, + "noofslots_total": 2, + "noofslots": 2, + "limit": 10, + "start": 0, + "timeleft": "0:16:44", + "speed": "1.3 M", + "kbpersec": "1296.02", + "size": "1.2 GB", + "sizeleft": "1.2 GB", + "mb": "1277.65", + "mbleft": "1271.58", + "slots": [ + { + "status": "Downloading", + "index": 0, + "password": "", + "avg_age": "2895d", + "script": "None", + "direct_unpack": "10/30", + "mb": "1277.65", + "mbleft": "1271.59", + "mbmissing": "0.0", + "size": "1.2 GB", + "sizeleft": "1.2 GB", + "filename": "TV.Show.S04E11.720p.HDTV.x264", + "labels": [], + "priority": "Normal", + "cat": "tv", + "timeleft": "0:16:44", + "percentage": "0", + "nzo_id": "SABnzbd_nzo_p86tgx", + "unpackopts": "3" + }, + { + "status": "Paused", + "index": 1, + "password": "", + "avg_age": "2895d", + "script": "None", + "direct_unpack": null, + "mb": "1277.76", + "mbleft": "1277.76", + "mbmissing": "0.0", + "size": "1.2 GB", + "sizeleft": "1.2 GB", + "filename": "TV.Show.S04E12.720p.HDTV.x264", + "labels": [ + "TOO LARGE", + "DUPLICATE" + ], + "priority": "Normal", + "cat": "tv", + "timeleft": "0:00:00", + "percentage": "0", + "nzo_id": "SABnzbd_nzo_ksfai6", + "unpackopts": "3" + } + ], + "diskspace1": "161.16", + "diskspace2": "161.16", + "diskspacetotal1": "465.21", + "diskspacetotal2": "465.21", + "diskspace1_norm": "161.2 G", + "diskspace2_norm": "161.2 G", + "have_warnings": "0", + "pause_int": "0", + "left_quota": "0 ", + "version": "3.x.x", + "finish": 2, + "cache_art": "16", + "cache_size": "6 MB", + "finishaction": null, + "paused_all": false, + "quota": "0 ", + "have_quota": false, + } + }""" + + if nzo_ids: + nzo_ids = nzo_ids if isinstance(nzo_ids, str) else ",".join(nzo_ids) + if status: + status = status if isinstance(status, str) else ",".join(status) + if category: + category = category if isinstance(category, str) else ",".join(category) + if priority: + priority = priority if isinstance(priority, str) else ",".join(priority) + + return await self.call( + { + "mode": "queue", + "start": start, + "limit": limit, + "search": search, + "category": category, + "priority": priority, + "status": status, + "nzo_ids": nzo_ids, + }, + ) + + async def pause_job(self, nzo_id: str): + """return {"status": True, "nzo_ids": ["all effected ids"]}""" + return await self.call({"mode": "queue", "name": "pause", "value": nzo_id}) + + async def resume_job(self, nzo_id: str): + """return {"status": True, "nzo_ids": ["all effected ids"]}""" + return await self.call({"mode": "queue", "name": "resume", "value": nzo_id}) + + async def delete_job(self, nzo_id: str | list[str], delete_files: bool = False): + """return {"status": True, "nzo_ids": ["all effected ids"]}""" + return await self.call( + { + "mode": "queue", + "name": "delete", + "value": nzo_id if isinstance(nzo_id, str) else ",".join(nzo_id), + "del_files": 1 if delete_files else 0, + } + ) + + async def pause_all(self): + """return {"status": True}""" + return await self.call({"mode": "pause"}) + + async def resume_all(self): + """return {"status": True}""" + return await self.call({"mode": "resume"}) + + async def purge_all(self, delete_files: bool = False): + """return {"status": True, "nzo_ids": ["all effected ids"]}""" + return await self.call( + {"mode": "queue", "name": "purge", "del_files": 1 if delete_files else 0} + ) + + async def get_files(self, nzo_id: str): + """ + return { + "files": [ + { + "status": "finished", + "mbleft": "0.00", + "mb": "0.05", + "age": "25d", + "bytes": "52161.00", + "filename": "93a4ec7c37752640deab48dabb46b164.par2", + "nzf_id": "SABnzbd_nzf_1lk0ij", + }, + ..., + ] + } + """ + return await self.call({"mode": "get_files", "value": nzo_id}) + + async def remove_file(self, nzo_id: str, file_ids: str | list[str]): + return await self.call( + { + "mode": "queue", + "name": "delete_nzf", + "value": nzo_id, + "value2": file_ids if isinstance(file_ids, str) else ",".join(file_ids), + } + ) # return nzf_ids of removed file idk how yet + + async def get_history( + self, + start: int | None = None, + limit: int | None = None, + search: str | None = None, + category: str | list[str] | None = None, + archive: int | None = None, + status: str | list[str] | None = None, + nzo_ids: str | list[str] | None = None, + failed_only: bool = False, + last_history_update: int | None = None, + ): + """{ + "history": { + "noofslots": 220, + "ppslots": 1, + "day_size": "1.9 G", + "week_size": "30.4 G", + "month_size": "167.3 G", + "total_size": "678.1 G", + "last_history_update": 1469210913, + "slots": [ + { + "action_line": "", + "duplicate_key": "TV.Show/4/2", + "meta": null, + "fail_message": "", + "loaded": false, + "size": "2.3 GB", + "category": "tv", + "pp": "D", + "retry": 0, + "script": "None", + "nzb_name": "TV.Show.S04E02.720p.BluRay.x264-xHD.nzb", + "download_time": 64, + "storage": "C:\\Users\\xxx\\Videos\\Complete\\TV.Show.S04E02.720p.BluRay.x264-xHD", + "has_rating": false, + "status": "Completed", + "script_line": "", + "completed": 1469172988, + "nzo_id": "SABnzbd_nzo_sdkoun", + "downloaded": 2436906376, + "report": "", + "password": "", + "path": "\\\\?\\C:\\SABnzbd\\TV.Show.S04E02.720p.BluRay.x264-xHD", + "postproc_time": 40, + "name": "TV.Show.S04E02.720p.BluRay.x264-xHD", + "url": "TV.Show.S04E02.720p.BluRay.x264-xHD.nzb", + "md5sum": "d2c16aeecbc1b1921d04422850e93013", + "archive": false, + "bytes": 2436906376, + "url_info": "", + "stage_log": [ + { + "name": "Source", + "actions": [ + "TV.Show.S04E02.720p.BluRay.x264-xHD.nzb" + ] + }, + { + "name": "Download", + "actions": [ + "Downloaded in 1 min 4 seconds at an average of 36.2 MB/s
Age: 550d
10 articles were malformed" + ] + }, + { + "name": "Servers", + "actions": [ + "Frugal=2.3 GB" + ] + }, + { + "name": "Repair", + "actions": [ + "[pA72r5Ac6lW3bmpd20T7Hj1Zg2bymUsINBB50skrI] Repaired in 19 seconds" + ] + }, + { + "name": "Unpack", + "actions": [ + "[pA72r5Ac6lW3bmpd20T7Hj1Zg2bymUsINBB50skrI] Unpacked 1 files/folders in 6 seconds" + ] + } + ] + }, + { + "action_line": "", + "duplicate_key": "TV.Show/4/13", + "meta": null, + "fail_message": "", + "loaded": false, + "size": "2.3 GB", + "category": "tv", + "pp": "D", + "retry": 0, + "script": "None", + "nzb_name": "TV.Show.S04E13.720p.BluRay.x264-xHD.nzb", + "download_time": 60, + "storage": "C:\\Users\\xxx\\Videos\\Complete\\TV.Show.S04E13.720p.BluRay.x264-xHD", + "has_rating": false, + "status": "Completed", + "script_line": "", + "completed": 1469172947, + "nzo_id": "SABnzbd_nzo_gqhp63", + "downloaded": 2491255137, + "report": "", + "password": "", + "path": "\\\\?\\C:\\SABnzbd\\TV.Show.S04E13.720p.BluRay.x264-xHD", + "postproc_time": 82, + "name": "TV.Show.S04E13.720p.BluRay.x264-xHD", + "url": "TV.Show.S04E13.720p.BluRay.x264-xHD.nzb", + "md5sum": "85baf55ec0de0dc732c2af6537c5c01b", + "archive": true, + "bytes": 2491255137, + "url_info": "", + "stage_log": [ + { + "name": "Source", + "actions": [ + "TV.Show.S04E13.720p.BluRay.x264-xHD.nzb" + ] + }, + { + "name": "Download", + "actions": [ + "Downloaded in 1 min at an average of 39.4 MB/s
Age: 558d
15 articles were malformed" + ] + }, + { + "name": "Servers", + "actions": [ + "Frugal=2.3 GB" + ] + }, + { + "name": "Repair", + "actions": [ + "[m0vklMEMKIT5L5XH9z5YTmuquoitCQ3F5LISTLFjT] Repaired in 47 seconds" + ] + }, + { + "name": "Unpack", + "actions": [ + "[m0vklMEMKIT5L5XH9z5YTmuquoitCQ3F5LISTLFjT] Unpacked 1 files/folders in 6 seconds" + ] + } + ] + } + ] + } + }""" + + if nzo_ids: + nzo_ids = nzo_ids if isinstance(nzo_ids, str) else ",".join(nzo_ids) + if status: + status = status if isinstance(status, str) else ",".join(status) + if category: + category = category if isinstance(category, str) else ",".join(category) + + return await self.call( + { + "mode": "history", + "start": start, + "limit": limit, + "archive": archive, + "search": search, + "category": category, + "status": status, + "nzo_ids": nzo_ids, + "failed_only": failed_only, + "last_history_update": last_history_update, + }, + ) + + async def retry_item(self, nzo_id: str, password: str = ""): + """return {"status": True}""" + return await self.call({"mode": "retry", "value": nzo_id, "password": password}) + + async def retry_all(self): + """return {"status": True}""" + return await self.call({"mode": "retry_all"}) + + async def delete_history( + self, nzo_ids: str | list[str], archive: int = 0, delete_files: bool = False + ): + """return {"status": True}""" + return await self.call( + { + "mode": "history", + "name": "delete", + "value": nzo_ids if isinstance(nzo_ids, str) else ",".join(nzo_ids), + "archive": archive, + "del_files": 1 if delete_files else 0, + } + ) + + async def change_job_pp(self, nzo_id: str, pp: int): + """return {"status": True}""" + return await self.call({"mode": "change_opts", "value": nzo_id, "value2": pp}) + + async def set_speedlimit(self, limit: str | int): + """return {"status": True}""" + return await self.call({"mode": "config", "name": "speedlimit", "value": limit}) + + async def delete_config(self, section: str, keyword: str): + """return {"status": True}""" + return await self.call( + {"mode": "del_config", "section": section, "keyword": keyword} + ) + + async def set_config_default(self, keyword: str | list[str]): + """return {"status": True}""" + return await self.call({"mode": "set_config_default", "keyword": keyword}) + + async def get_config(self, section: str = None, keyword: str = None): + """return config as dic""" + return await self.call( + {"mode": "get_config", "section": section, "keyword": keyword} + ) + + async def set_config(self, section: str, keyword: str, value: str): + """Returns the new setting when saved successfully""" + return await self.call( + { + "mode": "set_config", + "section": section, + "keyword": keyword, + "value": value, + } + ) + + async def set_special_config(self, section: str, items: dict): + """Returns the new setting when saved successfully""" + return await self.call( + { + "mode": "set_config", + "section": section, + **items, + } + ) + + async def server_stats(self): + """return { + "day": 2352634799, + "week": 32934490677, + "month": 179983557488, + "total": 728426161290, + "servers": { + "eunews.server.com": { + "week": 19783288936, + "total": 163741252273, + "day": 2352634799, + "month": 90478917031, + "daily": { + "2017-01-28": 1234, + "2017-01-29": 4567 + }, + "articles_tried": 929299, + "articles_success": 8299 + }, + "News.server.net": { + "week": 13151201741, + "total": 165783396295, + "day": 0, + "month": 89499300889, + "daily": { + "2017-01-28": 1234, + "2017-01-29": 4567 + }, + "articles_tried": 520400, + "articles_success": 78881 + } + } + }""" + return await self.call({"mode": "server_stats"}) + + async def version(self): + """return {'version': '4.2.2'}""" + return await self.call({"mode": "version"}) + + async def restart(self): + """return {"status": True}""" + return await self.call({"mode": "restart"}) + + async def restart_repair(self): + """return {"status": True}""" + return await self.call({"mode": "restart_repair"}) + + async def shutdown(self): + """return {"status": True}""" + return await self.call({"mode": "shutdown"}) diff --git a/sabnzbdapi/requests.py b/sabnzbdapi/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf181ea69ef837254652815078cf619950c773c --- /dev/null +++ b/sabnzbdapi/requests.py @@ -0,0 +1,76 @@ +from httpx import AsyncClient, AsyncHTTPTransport, Timeout +from urllib3 import disable_warnings +from urllib3.exceptions import InsecureRequestWarning + +from .job_functions import JobFunctions +from .exception import APIConnectionError + + +class SabnzbdClient(JobFunctions): + + LOGGED_IN = False + + def __init__( + self, + host: str, + api_key: str, + port: str = "8070", + VERIFY_CERTIFICATE: bool = False, + RETRIES: int = 10, + HTTPX_REQUETS_ARGS: dict = None, + ): + if HTTPX_REQUETS_ARGS is None: + HTTPX_REQUETS_ARGS = {} + self._base_url = f"{host.rstrip('/')}:{port}" + self._default_params = {"apikey": api_key, "output": "json"} + self._VERIFY_CERTIFICATE = VERIFY_CERTIFICATE + self._RETRIES = RETRIES + self._HTTPX_REQUETS_ARGS = HTTPX_REQUETS_ARGS + self._http_session = None + if not self._VERIFY_CERTIFICATE: + disable_warnings(InsecureRequestWarning) + super().__init__() + + def _session(self): + if self._http_session is not None: + return self._http_session + + transport = AsyncHTTPTransport( + retries=self._RETRIES, verify=self._VERIFY_CERTIFICATE + ) + + self._http_session = AsyncClient( + base_url=self._base_url, + transport=transport, + timeout=Timeout(connect=60, read=60, write=60, pool=None), + follow_redirects=True, + verify=self._VERIFY_CERTIFICATE, + **self._HTTPX_REQUETS_ARGS, + ) + + return self._http_session + + async def call( + self, + params: dict = None, + requests_args: dict = None, + **kwargs, + ): + if requests_args is None: + requests_args = {} + session = self._session() + params |= kwargs + res = await session.get( + url="/sabnzbd/api", + params={**self._default_params, **params}, + **requests_args, + ) + response = res.json() + if response is None: + raise APIConnectionError("Failed to connect to API!") + return response + + async def close(self): + if self._http_session is not None: + await self._http_session.aclose() + self._http_session = None diff --git a/start.sh b/start.sh new file mode 100644 index 0000000000000000000000000000000000000000..50bd8615769e62a5f5c8272b48bc5e116fa88e3f --- /dev/null +++ b/start.sh @@ -0,0 +1,3 @@ +source mltbenv/bin/activate +python3 update.py +python3 -m bot diff --git a/update.py b/update.py new file mode 100644 index 0000000000000000000000000000000000000000..4242621becb7379248a7c0eb1bf4adad8a6d5e53 --- /dev/null +++ b/update.py @@ -0,0 +1,109 @@ +from sys import exit +from importlib import import_module +from logging import ( + FileHandler, + StreamHandler, + INFO, + basicConfig, + error as log_error, + info as log_info, + getLogger, + ERROR, +) +from os import path, remove, getenv +from pymongo.mongo_client import MongoClient +from pymongo.server_api import ServerApi +from subprocess import run as srun +from typing import Dict, Any + +getLogger("pymongo").setLevel(ERROR) + +if path.exists("log.txt"): + with open("log.txt", "r+") as f: + f.truncate(0) + +if path.exists("rlog.txt"): + remove("rlog.txt") + +basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[FileHandler("log.txt"), StreamHandler()], + level=INFO, +) + + +def load_config() -> Dict[str, Any]: + """Load configuration from config module or environment variables.""" + try: + + settings = import_module("config") + return { + key: value.strip() if isinstance(value, str) else value + for key, value in vars(settings).items() + if not key.startswith("__") + } + except ModuleNotFoundError: + log_info("Config module not found, loading from environment variables...") + return { + "BOT_TOKEN": getenv("BOT_TOKEN", ""), + "DATABASE_URL": getenv("DATABASE_URL", ""), + "DATABASE_NAME": getenv("DATABASE_NAME", "mltb"), + "UPSTREAM_REPO": getenv("UPSTREAM_REPO", ""), + "UPSTREAM_BRANCH": getenv("UPSTREAM_BRANCH", "master"), + } + + +config_file = load_config() + +BOT_TOKEN = config_file.get("BOT_TOKEN", "") +if not BOT_TOKEN: + log_error("BOT_TOKEN variable is missing! Exiting now") + exit(1) + +BOT_ID = BOT_TOKEN.split(":", 1)[0] + +DATABASE_NAME = config_file.get("DATABASE_NAME", "mltb") + +if DATABASE_URL := config_file.get("DATABASE_URL", "").strip(): + try: + conn = MongoClient(DATABASE_URL, server_api=ServerApi("1")) + db = conn[DATABASE_NAME] + old_config = db.settings.deployConfig.find_one({"_id": BOT_ID}, {"_id": 0}) + config_dict = db.settings.config.find_one({"_id": BOT_ID}) + if ( + old_config is not None and old_config == config_file or old_config is None + ) and config_dict is not None: + config_file["UPSTREAM_REPO"] = config_dict["UPSTREAM_REPO"] + config_file["UPSTREAM_BRANCH"] = config_dict["UPSTREAM_BRANCH"] + conn.close() + except Exception as e: + log_error(f"Database ERROR: {e}") + +UPSTREAM_REPO = config_file.get("UPSTREAM_REPO", "").strip() + +UPSTREAM_BRANCH = config_file.get("UPSTREAM_BRANCH", "").strip() or "master" + +if UPSTREAM_REPO: + if path.exists(".git"): + srun(["rm", "-rf", ".git"]) + + update = srun( + [ + f"git init -q \ + && git config --global user.email e.anastayyar@gmail.com \ + && git config --global user.name mltb \ + && git add . \ + && git commit -sm update -q \ + && git remote add origin {UPSTREAM_REPO} \ + && git fetch origin -q \ + && git reset --hard origin/{UPSTREAM_BRANCH} -q" + ], + shell=True, + ) + + if update.returncode == 0: + log_info("Successfully updated with latest commit from UPSTREAM_REPO") + else: + log_error( + "Something went wrong while updating, check UPSTREAM_REPO if valid or not!" + ) diff --git a/web/__init__.py b/web/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/web/__init__.py @@ -0,0 +1 @@ + diff --git a/web/nodes.py b/web/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8a957c19a728c8074a1ef0a5602e74be5f6f4e --- /dev/null +++ b/web/nodes.py @@ -0,0 +1,211 @@ +from anytree import NodeMixin + + +class TorNode(NodeMixin): + def __init__( + self, + name, + is_folder=False, + is_file=False, + parent=None, + size=None, + priority=None, + file_id=None, + progress=None, + ): + super().__init__() + self.name = name + self.is_folder = is_folder + self.is_file = is_file + + if parent is not None: + self.parent = parent + if size is not None: + self.fsize = size + if priority is not None: + self.priority = priority + if file_id is not None: + self.file_id = file_id + if progress is not None: + self.progress = progress + + +def qb_get_folders(path): + return path.split("/") + + +def get_folders(path, root_path): + fs = path.split(root_path)[-1] + return fs.split("/") + + +def make_tree(res, tool, root_path=""): + if tool == "qbittorrent": + parent = TorNode("QBITTORRENT") + folder_id = 0 + for i in res: + folders = qb_get_folders(i.name) + if len(folders) > 1: + previous_node = parent + for j in range(len(folders) - 1): + current_node = next( + (k for k in previous_node.children if k.name == folders[j]), + None, + ) + if current_node is None: + previous_node = TorNode( + folders[j], + is_folder=True, + parent=previous_node, + file_id=folder_id, + ) + folder_id += 1 + else: + previous_node = current_node + TorNode( + folders[-1], + is_file=True, + parent=previous_node, + size=i.size, + priority=i.priority, + file_id=i.index, + progress=round(i.progress * 100, 5), + ) + else: + TorNode( + folders[-1], + is_file=True, + parent=parent, + size=i.size, + priority=i.priority, + file_id=i.index, + progress=round(i.progress * 100, 5), + ) + elif tool == "aria2": + parent = TorNode("ARIA2") + folder_id = 0 + for i in res: + folders = get_folders(i["path"], root_path) + priority = 1 + if i["selected"] == "false": + priority = 0 + if len(folders) > 1: + previous_node = parent + for j in range(len(folders) - 1): + current_node = next( + (k for k in previous_node.children if k.name == folders[j]), + None, + ) + if current_node is None: + previous_node = TorNode( + folders[j], + is_folder=True, + parent=previous_node, + file_id=folder_id, + ) + folder_id += 1 + else: + previous_node = current_node + try: + progress = round( + (int(i["completedLength"]) / int(i["length"])) * 100, 5 + ) + except: + progress = 0 + TorNode( + folders[-1], + is_file=True, + parent=previous_node, + size=int(i["length"]), + priority=priority, + file_id=i["index"], + progress=progress, + ) + else: + try: + progress = round( + (int(i["completedLength"]) / int(i["length"])) * 100, 5 + ) + except: + progress = 0 + TorNode( + folders[-1], + is_file=True, + parent=parent, + size=int(i["length"]), + priority=priority, + file_id=i["index"], + progress=progress, + ) + else: + parent = TorNode("SABNZBD+") + priority = 1 + for i in res["files"]: + TorNode( + i["filename"], + is_file=True, + parent=parent, + size=float(i["mb"]) * 1048576, + priority=priority, + file_id=i["nzf_id"], + progress=round( + ((float(i["mb"]) - float(i["mbleft"])) / float(i["mb"])) * 100, + 5, + ), + ) + + result = create_list(parent) + return {"files": result, "engine": tool} + + +""" +def print_tree(parent): + for pre, _, node in RenderTree(parent): + treestr = u"%s%s" % (pre, node.name) + print(treestr.ljust(8), node.is_folder, node.is_file) +""" + + +def create_list(parent, contents=None): + if contents is None: + contents = [] + for i in parent.children: + if i.is_folder: + children = [] + create_list(i, children) + contents.append( + { + "id": f"folderNode_{i.file_id}", + "name": i.name, + "type": "folder", + "children": children, + } + ) + else: + contents.append( + { + "id": i.file_id, + "name": i.name, + "size": i.fsize, + "type": "file", + "selected": bool(i.priority), + "progress": i.progress, + } + ) + return contents + + +def extract_file_ids(data): + selected_files = [] + unselected_files = [] + for item in data: + if item.get("type") == "file": + if item.get("selected"): + selected_files.append(str(item["id"])) + else: + unselected_files.append(str(item["id"])) + if item.get("children"): + child_selected, child_unselected = extract_file_ids(item["children"]) + selected_files.extend(child_selected) + unselected_files.extend(child_unselected) + return selected_files, unselected_files diff --git a/web/templates/page.html b/web/templates/page.html new file mode 100644 index 0000000000000000000000000000000000000000..0ad44244012770e7f6418631506f32190db31fa7 --- /dev/null +++ b/web/templates/page.html @@ -0,0 +1,960 @@ + + + + + + + Torrent Selector + + + + + + +
+
+
+

🗂 Torrent + File Selector

+
+
+ 🌙 + +
+
+
+
+
+ +
+
+

Enter PIN

+ + +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/web/wserver.py b/web/wserver.py new file mode 100644 index 0000000000000000000000000000000000000000..fad2edf87d1d2ce4ad41365625192dc0ca7bfafe --- /dev/null +++ b/web/wserver.py @@ -0,0 +1,258 @@ +from uvloop import install + +install() +from contextlib import asynccontextmanager +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, JSONResponse +from fastapi.templating import Jinja2Templates +from logging import getLogger, FileHandler, StreamHandler, INFO, basicConfig, WARNING +from asyncio import sleep +from sabnzbdapi import SabnzbdClient +from aioaria2 import Aria2HttpClient +from aioqbt.client import create_client +from aiohttp.client_exceptions import ClientError +from aioqbt.exc import AQError + +from web.nodes import extract_file_ids, make_tree + +getLogger("httpx").setLevel(WARNING) +getLogger("aiohttp").setLevel(WARNING) + +aria2 = None +qbittorrent = None +sabnzbd_client = SabnzbdClient( + host="http://localhost", + api_key="mltb", + port="8070", +) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + global aria2, qbittorrent + aria2 = Aria2HttpClient("http://localhost:6800/jsonrpc") + qbittorrent = await create_client("http://localhost:8090/api/v2/") + yield + await aria2.close() + await qbittorrent.close() + + +app = FastAPI(lifespan=lifespan) + + +templates = Jinja2Templates(directory="web/templates/") + +basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[FileHandler("log.txt"), StreamHandler()], + level=INFO, +) + +LOGGER = getLogger(__name__) + + +async def re_verify(paused, resumed, hash_id): + k = 0 + while True: + res = await qbittorrent.torrents.files(hash_id) + verify = True + for i in res: + if i.index in paused and i.priority != 0: + verify = False + break + if i.index in resumed and i.priority == 0: + verify = False + break + if verify: + break + LOGGER.info("Reverification Failed! Correcting stuff...") + await sleep(0.5) + if paused: + try: + await qbittorrent.torrents.file_prio( + hash=hash_id, id=paused, priority=0 + ) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(f"{e} Errored in reverification paused!") + if resumed: + try: + await qbittorrent.torrents.file_prio( + hash=hash_id, id=resumed, priority=1 + ) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(f"{e} Errored in reverification resumed!") + k += 1 + if k > 5: + return False + LOGGER.info(f"Verified! Hash: {hash_id}") + return True + + +@app.get("/app/files", response_class=HTMLResponse) +async def files(request: Request): + return templates.TemplateResponse("page.html", {"request": request}) + + +@app.api_route( + "/app/files/torrent", methods=["GET", "POST"], response_class=HTMLResponse +) +async def handle_torrent(request: Request): + params = request.query_params + + if not (gid := params.get("gid")): + return JSONResponse( + { + "files": [], + "engine": "", + "error": "GID is missing", + "message": "GID not specified", + } + ) + + if not (pin := params.get("pin")): + return JSONResponse( + { + "files": [], + "engine": "", + "error": "Pin is missing", + "message": "PIN not specified", + } + ) + + code = "".join([nbr for nbr in gid if nbr.isdigit()][:4]) + if code != pin: + return JSONResponse( + { + "files": [], + "engine": "", + "error": "Invalid pin", + "message": "The PIN you entered is incorrect", + } + ) + + if request.method == "POST": + if not (mode := params.get("mode")): + return JSONResponse( + { + "files": [], + "engine": "", + "error": "Mode is not specified", + "message": "Mode is not specified", + } + ) + data = await request.json() + if mode == "rename": + if len(gid) > 20: + await handle_rename(gid, data) + content = { + "files": [], + "engine": "", + "error": "", + "message": "Rename successfully.", + } + else: + content = { + "files": [], + "engine": "", + "error": "Rename failed.", + "message": "Cannot rename aria2c torrent file", + } + else: + selected_files, unselected_files = extract_file_ids(data) + if gid.startswith("SABnzbd_nzo"): + await set_sabnzbd(gid, unselected_files) + elif len(gid) > 20: + await set_qbittorrent(gid, selected_files, unselected_files) + else: + selected_files = ",".join(selected_files) + await set_aria2(gid, selected_files) + content = { + "files": [], + "engine": "", + "error": "", + "message": "Your selection has been submitted successfully.", + } + else: + try: + if gid.startswith("SABnzbd_nzo"): + res = await sabnzbd_client.get_files(gid) + content = make_tree(res, "sabnzbd") + elif len(gid) > 20: + res = await qbittorrent.torrents.files(gid) + content = make_tree(res, "qbittorrent") + else: + res = await aria2.getFiles(gid) + op = await aria2.getOption(gid) + fpath = f"{op['dir']}/" + content = make_tree(res, "aria2", fpath) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(str(e)) + content = { + "files": [], + "engine": "", + "error": "Error getting files", + "message": str(e), + } + return JSONResponse(content) + + +async def handle_rename(gid, data): + try: + _type = data["type"] + del data["type"] + if _type == "file": + await qbittorrent.torrents.rename_file(hash=gid, **data) + else: + await qbittorrent.torrents.rename_folder(hash=gid, **data) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(f"{e} Errored in renaming") + + +async def set_sabnzbd(gid, unselected_files): + await sabnzbd_client.remove_file(gid, unselected_files) + LOGGER.info(f"Verified! nzo_id: {gid}") + + +async def set_qbittorrent(gid, selected_files, unselected_files): + if unselected_files: + try: + await qbittorrent.torrents.file_prio( + hash=gid, id=unselected_files, priority=0 + ) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(f"{e} Errored in paused") + if selected_files: + try: + await qbittorrent.torrents.file_prio( + hash=gid, id=selected_files, priority=1 + ) + except (ClientError, TimeoutError, Exception, AQError) as e: + LOGGER.error(f"{e} Errored in resumed") + await sleep(0.5) + if not await re_verify(unselected_files, selected_files, gid): + LOGGER.error(f"Verification Failed! Hash: {gid}") + + +async def set_aria2(gid, selected_files): + res = await aria2.changeOption(gid, {"select-file": selected_files}) + if res == "OK": + LOGGER.info(f"Verified! Gid: {gid}") + else: + LOGGER.info(f"Verification Failed! Report! Gid: {gid}") + + +@app.get("/", response_class=HTMLResponse) +async def homepage(): + return ( + "

See mirror-leech-telegram-bot " + "@GitHub " + "By Anas

" + ) + + +@app.exception_handler(Exception) +async def page_not_found(_, exc): + return HTMLResponse( + f"

404: Task not found! Mostly wrong input.

Error: {exc}

", + status_code=404, + )