From 332d7ae8e3b9dc18c3d53c390e25fe2cb09f7372 Mon Sep 17 00:00:00 2001
From: tekeayush <83461956+tekeayush@users.noreply.github.com>
Date: Wed, 22 Dec 2021 18:43:05 +0530
Subject: [PATCH] initial commit
Start
---
Dockerfile | 18 +
LICENSE | 674 ++++++++++++++
README.md | 241 +++++
add_to_team_drive.py | 77 ++
alive.py | 29 +
aria.bat | 1 +
aria.sh | 15 +
bot/__init__.py | 418 +++++++++
bot/__main__.py | 215 +++++
bot/helper/__init__.py | 70 ++
bot/helper/custom_filters.py | 23 +
bot/helper/ext_utils/__init__.py | 1 +
bot/helper/ext_utils/bot_utils.py | 265 ++++++
bot/helper/ext_utils/db_handler.py | 75 ++
bot/helper/ext_utils/exceptions.py | 8 +
bot/helper/ext_utils/fs_utils.py | 156 ++++
bot/helper/mirror_utils/__init__.py | 1 +
.../mirror_utils/download_utils/__init__.py | 1 +
.../download_utils/aria2_download.py | 106 +++
.../download_utils/direct_link_generator.py | 416 +++++++++
.../direct_link_generator_license.md | 82 ++
.../download_utils/download_helper.py | 27 +
.../download_utils/mega_downloader.py | 201 ++++
.../download_utils/qbit_downloader.py | 240 +++++
.../download_utils/telegram_downloader.py | 126 +++
.../youtube_dl_download_helper.py | 167 ++++
.../mirror_utils/status_utils/__init__.py | 1 +
.../status_utils/aria_download_status.py | 97 ++
.../mirror_utils/status_utils/clone_status.py | 60 ++
.../status_utils/extract_status.py | 36 +
.../status_utils/gdownload_status.py | 65 ++
.../mirror_utils/status_utils/listeners.py | 30 +
.../status_utils/mega_download_status.py | 62 ++
.../status_utils/qbit_download_status.py | 81 ++
.../mirror_utils/status_utils/status.py | 40 +
.../mirror_utils/status_utils/tar_status.py | 36 +
.../status_utils/telegram_download_status.py | 56 ++
.../status_utils/upload_status.py | 61 ++
.../youtube_dl_download_status.py | 59 ++
.../mirror_utils/upload_utils/__init__.py | 1 +
.../mirror_utils/upload_utils/gdriveTools.py | 867 ++++++++++++++++++
.../mirror_utils/upload_utils/gdtot_helper.py | 80 ++
bot/helper/telegram_helper/__init__.py | 1 +
bot/helper/telegram_helper/bot_commands.py | 35 +
bot/helper/telegram_helper/button_build.py | 20 +
bot/helper/telegram_helper/filters.py | 51 ++
bot/helper/telegram_helper/message_utils.py | 154 ++++
bot/modules/__init__.py | 1 +
bot/modules/authorize.py | 198 ++++
bot/modules/cancel_mirror.py | 77 ++
bot/modules/clone.py | 74 ++
bot/modules/config.py | 221 +++++
bot/modules/count.py | 31 +
bot/modules/delete.py | 29 +
bot/modules/eval.py | 142 +++
bot/modules/list.py | 57 ++
bot/modules/mirror.py | 425 +++++++++
bot/modules/mirror_status.py | 28 +
bot/modules/shell.py | 43 +
bot/modules/speedtest.py | 46 +
bot/modules/torrent_search.py | 339 +++++++
bot/modules/updates.py | 83 ++
bot/modules/watch.py | 68 ++
captain-definition | 4 +
config_sample.env | 61 ++
"d\303\251but.sh" | 11 +
extract | 199 ++++
gen_sa_accounts.py | 365 ++++++++
generate_drive_token.py | 22 +
heroku-guide.md | 48 +
heroku.yml | 5 +
nodes.py | 139 +++
pextract | 200 ++++
qBittorrent.conf | 35 +
requirements-cli.txt | 7 +
requirements.txt | 32 +
wserver.py | 739 +++++++++++++++
77 files changed, 9275 insertions(+)
create mode 100644 Dockerfile
create mode 100644 LICENSE
create mode 100644 README.md
create mode 100644 add_to_team_drive.py
create mode 100644 alive.py
create mode 100644 aria.bat
create mode 100644 aria.sh
create mode 100644 bot/__init__.py
create mode 100644 bot/__main__.py
create mode 100644 bot/helper/__init__.py
create mode 100644 bot/helper/custom_filters.py
create mode 100644 bot/helper/ext_utils/__init__.py
create mode 100644 bot/helper/ext_utils/bot_utils.py
create mode 100644 bot/helper/ext_utils/db_handler.py
create mode 100644 bot/helper/ext_utils/exceptions.py
create mode 100644 bot/helper/ext_utils/fs_utils.py
create mode 100644 bot/helper/mirror_utils/__init__.py
create mode 100644 bot/helper/mirror_utils/download_utils/__init__.py
create mode 100644 bot/helper/mirror_utils/download_utils/aria2_download.py
create mode 100644 bot/helper/mirror_utils/download_utils/direct_link_generator.py
create mode 100644 bot/helper/mirror_utils/download_utils/direct_link_generator_license.md
create mode 100644 bot/helper/mirror_utils/download_utils/download_helper.py
create mode 100644 bot/helper/mirror_utils/download_utils/mega_downloader.py
create mode 100644 bot/helper/mirror_utils/download_utils/qbit_downloader.py
create mode 100644 bot/helper/mirror_utils/download_utils/telegram_downloader.py
create mode 100644 bot/helper/mirror_utils/download_utils/youtube_dl_download_helper.py
create mode 100644 bot/helper/mirror_utils/status_utils/__init__.py
create mode 100644 bot/helper/mirror_utils/status_utils/aria_download_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/clone_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/extract_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/gdownload_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/listeners.py
create mode 100644 bot/helper/mirror_utils/status_utils/mega_download_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/qbit_download_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/status.py
create mode 100644 bot/helper/mirror_utils/status_utils/tar_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/telegram_download_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/upload_status.py
create mode 100644 bot/helper/mirror_utils/status_utils/youtube_dl_download_status.py
create mode 100644 bot/helper/mirror_utils/upload_utils/__init__.py
create mode 100644 bot/helper/mirror_utils/upload_utils/gdriveTools.py
create mode 100644 bot/helper/mirror_utils/upload_utils/gdtot_helper.py
create mode 100644 bot/helper/telegram_helper/__init__.py
create mode 100644 bot/helper/telegram_helper/bot_commands.py
create mode 100644 bot/helper/telegram_helper/button_build.py
create mode 100644 bot/helper/telegram_helper/filters.py
create mode 100644 bot/helper/telegram_helper/message_utils.py
create mode 100644 bot/modules/__init__.py
create mode 100644 bot/modules/authorize.py
create mode 100644 bot/modules/cancel_mirror.py
create mode 100644 bot/modules/clone.py
create mode 100644 bot/modules/config.py
create mode 100644 bot/modules/count.py
create mode 100644 bot/modules/delete.py
create mode 100644 bot/modules/eval.py
create mode 100644 bot/modules/list.py
create mode 100644 bot/modules/mirror.py
create mode 100644 bot/modules/mirror_status.py
create mode 100644 bot/modules/shell.py
create mode 100644 bot/modules/speedtest.py
create mode 100644 bot/modules/torrent_search.py
create mode 100644 bot/modules/updates.py
create mode 100644 bot/modules/watch.py
create mode 100644 captain-definition
create mode 100644 config_sample.env
create mode 100644 "d\303\251but.sh"
create mode 100644 extract
create mode 100644 gen_sa_accounts.py
create mode 100644 generate_drive_token.py
create mode 100644 heroku-guide.md
create mode 100644 heroku.yml
create mode 100644 nodes.py
create mode 100644 pextract
create mode 100644 qBittorrent.conf
create mode 100644 requirements-cli.txt
create mode 100644 requirements.txt
create mode 100644 wserver.py
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..b1b78e6
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,18 @@
+FROM breakdowns/mega-sdk-python:latest
+
+WORKDIR /usr/src/app
+RUN chmod 777 /usr/src/app
+
+COPY extract /usr/local/bin
+COPY pextract /usr/local/bin
+RUN chmod +x /usr/local/bin/extract && chmod +x /usr/local/bin/pextract
+
+COPY requirements.txt .
+RUN pip3 install --no-cache-dir -r requirements.txt
+
+COPY . .
+COPY .netrc /root/.netrc
+RUN chmod 600 /usr/src/app/.netrc
+RUN chmod +x aria.sh
+
+CMD ["bash","début.sh"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a203034
--- /dev/null
+++ b/README.md
@@ -0,0 +1,241 @@
+[![Slam](https://telegra.ph/file/019996f816db9ed576cff.jpg)]
+
+# Mirror Bot
+This is a telegram bot writen in python for mirroring files on the internet to our beloved Google Drive.
+
+## Deploying on Heroku
+Give Star & Fork this repo, then upload **token.pickle** & **credentials.json** to your forks
+
+
+after this click on the below button 👇👇👇👇
+
+
+
+## Features supported:
+
+- Mirroring direct download links to Google Drive
+- qBittorrent supported
+- selection of files before downloading torrent
+- Limiting size Torrent/Direct, Tar/Unzip, Mega, cloning Google Drive support
+- Stop duplicate cloning Google Drive & mirroring Mega support
+- Create Tar Google Drive folder
+- Mirroring Mega.nz links to Google Drive (In development stage)
+- Mirroring Uptobox.com links to Google Drive (Uptobox account must be premium)
+- Copy files from someone's drive to your drive (Using Autorclone)
+- Download/upload progress, speeds and ETAs
+- Docker support
+- Uploading To Team Drives.
+- Index Link support
+- Service account support
+- Heroku config support
+- Extracting **tar.xz** support
+- Mirror all youtube-dl supported links
+- Stop duplicate cloning Google Drive & mirroring Mega support
+- Limiting size Torrent/Direct, Mega, cloning Google Drive support
+- Mirror telegram files
+- Delete files from drive
+- Check Heroku dynos stats
+- Nyaa.si and Sukebei Torrent search
+- Shell and Executor
+- Shortener support
+- Custom Buttons
+- Custom Filename (Only for url, telegram files and ytdl. Not for mega links and magnet/torrents)
+- Speedtest with picture results
+- Extracting password protected files and using custom filename see these examples:
+- [custom file name examples ](https://telegra.ph/Magneto-Python-Aria---Custom-Filename-Examples-01-20)
+- Bot can extract the following types of files
+```
+ZIP, RAR, TAR, 7z, ISO, WIM, CAB, GZIP, BZIP2,
+APM, ARJ, CHM, CPIO, CramFS, DEB, DMG, FAT,
+HFS, LZH, LZMA, LZMA2, MBR, MSI, MSLZ, NSIS,
+NTFS, RPM, SquashFS, UDF, VHD, XAR, Z.
+```
+
+
+
+## How to deploy on vps ?
+Deploying is pretty much straight forward and is divided into several steps as follows:
+
+## Installing requirements
+
+- Clone this repo:
+```
+git clone https://github.com/tekeayush/Mirror-bot/
+cd slam_aria_mirror_bot_HEROKU
+```
+
+- Install requirements
+For Debian based distros
+```
+sudo apt install python3
+sudo snap install docker
+```
+- For Arch and it's derivatives:
+```
+sudo pacman -S docker python
+```
+
+## Setting up config file
+
+ Click here for more details
+
+```
+cp config_sample.env config.env
+```
+- Remove the first line saying:
+```
+_____REMOVE_THIS_LINE_____=True
+```
+Fill up rest of the fields. Meaning of each fields are discussed below:
+### Required Field
+- **BOT_TOKEN**: The Telegram bot token that you get from [@BotFather](https://t.me/BotFather)
+- **TELEGRAM_API**: This is to authenticate to your Telegram account for downloading Telegram files. You can get this from https://my.telegram.org DO NOT put this in quotes.
+- **TELEGRAM_HASH**: This is to authenticate to your Telegram account for downloading Telegram files. You can get this from https://my.telegram.org
+- **OWNER_ID**: The Telegram user ID (not username) of the Owner of the bot
+- **DATABASE_URL**: Your Database URL. See [Generate Database](https://github.com/breakdowns/slam-mirrorbot/tree/master#generate-database) to generate database. (**NOTE**: If you deploying on Heroku using Heroku button, no need to generate database manually, because it will automatic generate database when first deploying)
+- **GDRIVE_FOLDER_ID**: This is the folder ID of the Google Drive Folder to which you want to upload all the mirrors.
+- **DOWNLOAD_DIR**: The path to the local folder where the downloads should be downloaded to
+- **DOWNLOAD_STATUS_UPDATE_INTERVAL**: A short interval of time in seconds after which the Mirror progress message is updated. (I recommend to keep it `5` seconds at least)
+- **AUTO_DELETE_MESSAGE_DURATION**: Interval of time (in seconds), after which the bot deletes it's message (and command message) which is expected to be viewed instantly. (**Note**: Set to `-1` to never automatically delete messages)
+- **UPSTREAM_REPO**: Link for Bot Upstream Repo, if you want default update, fill .
+- **UPSTREAM_BRANCH**: Branch name for Bot Upstream Repo (Recommended using master branch)
+### Optional Field
+- **GDTOT_COOKIES**: add your GDTOT cookies in form of "crypt=eXU2cDlzYWhzRk93eXV4cTQzMXFCeHE2UElEcUtJcEY1U0 ; PHPSESSID=0vt54of2tao357sltquke"
+- **AUTHORIZED_CHATS**: Fill user_id and chat_id of you want to authorize.
+- **IS_TEAM_DRIVE**: Set to `True` if `GDRIVE_FOLDER_ID` is from a Team Drive else `False` or Leave it empty.
+- **USE_SERVICE_ACCOUNTS**: (Leave empty if unsure) Whether to use Service Accounts or not. For this to work see [Using service accounts](https://github.com/breakdowns/slam-mirrorbot#generate-service-accounts-what-is-service-account) section below.
+- **INDEX_URL**: Refer to [Bhadoo Drive Index](https://bdi-generator.hashhackers.com/) The URL should not have any trailing '/'
+- **MEGA_API_KEY**: Mega.nz api key to mirror mega.nz links. Get it from [Mega SDK Page](https://mega.nz/sdk)
+- **MEGA_EMAIL_ID**: Your email id you used to sign up on mega.nz for using premium accounts (Leave th)
+- **MEGA_PASSWORD**: Your password for your mega.nz account
+- **BLOCK_MEGA_FOLDER**: If you want to remove mega.nz folder support, set it to `True`.
+- **BLOCK_MEGA_LINKS**: If you want to remove mega.nz mirror support, set it to `True`.
+- **STOP_DUPLICATE_MIRROR**: (Leave empty if unsure) if this field is set to `True`, bot will check file in Drive, if it is present in Drive, downloading will be stopped. (**Note**: File will be checked using filename, not using filehash, so this feature is not perfect yet)
+- **STOP_DUPLICATE_MEGA**: (Leave empty if unsure) if this field is set to `True`, bot will check file in Drive, if it is present in Drive, downloading Mega will be stopped.
+- **STOP_DUPLICATE_CLONE**: (Leave empty if unsure) if this field is set to `True`, bot will check file in Drive, if it is present in Drive, cloning will be stopped.
+- **CLONE_LIMIT**: To limit cloning Google Drive (leave space between number and unit, Available units is (gb or GB, tb or TB).
+- **MEGA_LIMIT**: To limit downloading Mega (leave space between number and unit, Available units is (gb or GB, tb or TB).
+- **TORRENT_DIRECT_LIMIT**: To limit the Torrent/Direct mirror size, Leave space between number and unit. Available units is (gb or GB, tb or TB).
+- **IMAGE_URL**: Show Image/Logo in /start message. Fill value of image your link image, use telegra.ph or any direct link image.
+- **VIEW_LINK**: View Link button to open file Index Link in browser instead of direct download link, you can figure out if it's compatible with your Index code or not, open any video from you Index and check if the END of link from browser link bar is `?a=view`, if yes make it `True` it will work (Compatible with [Bhadoo Index](https://github.com/ParveenBhadooOfficial/Google-Drive-Index) Code)
+- **UPTOBOX_TOKEN**: Uptobox token to mirror uptobox links. Get it from [Uptobox Premium Account](https://uptobox.com/my_account).
+- **HEROKU_API_KEY**: (Only if you deploying on Heroku) Your Heroku API key, get it from https://dashboard.heroku.com/account.
+- **HEROKU_APP_NAME**: (Only if you deploying on Heroku) Your Heroku app name.
+- **IGNORE_PENDING_REQUESTS**: (Optional field) If you want the bot to ignore pending requests after it restarts, set this to `True`.
+- **SHORTENER_API**: Fill your Shortener api key if you are using Shortener.
+- **SHORTENER**: if you want to use Shortener in Gdrive and index link, fill Shortener url here. Examples:
+```
+exe.io, gplinks.in, shrinkme.io, urlshortx.com, shortzon.com
+```
+
+Above are the supported url Shorteners. Except these only some url Shorteners are supported.
+
+**Note**: You can limit maximum concurrent downloads by changing the value of **MAX_CONCURRENT_DOWNLOADS** in aria.sh. By default, it's set to `4`.
+### Add more buttons (Optional Field)
+Three buttons are already added of Drive Link, Index Link, and View Link, you can add extra buttons, these are optional, if you don't know what are below entries, simply leave them, don't fill anything in them.
+- **BUTTON_FOUR_NAME**:
+- **BUTTON_FOUR_URL**:
+- **BUTTON_FIVE_NAME**:
+- **BUTTON_FIVE_URL**:
+- **BUTTON_SIX_NAME**:
+- **BUTTON_SIX_URL**:
+
+
+
+## Getting GDTOT COOKIES
+- Watch This [Video](https://youtu.be/PjR6KpHJ23s)
+
+## Getting Google OAuth API credential file
+
+- Visit the [Google Cloud Console](https://console.developers.google.com/apis/credentials)
+- Go to the OAuth Consent tab, fill it, and save.
+- Go to the Credentials tab and click Create Credentials -> OAuth Client ID
+- Choose Desktop and Create.
+- Use the download button to download your credentials.
+- clone this repo https://github.com/tekeayush/Mirror-bot
+- Move that file to the root of mirrorbot, and rename it to credentials.json
+- install the requirements-cli.txt file by using
+
+``` pip3 install -r requirements-cli.txt ```
+
+- Visit [Google API page](https://console.developers.google.com/apis/library)
+- Search for Drive and enable it if it is disabled
+- Finally, run the script to generate **token.pickle** file for Google Drive:
+```
+python3 generate_drive_token.py
+```
+
+## Deploying on vps
+
+- Start docker daemon (skip if already running):
+```
+sudo dockerd
+```
+- Build Docker image:
+```
+sudo docker build . -t mirrorbot
+```
+- Run the image:
+```
+sudo docker run mirrorbot
+```
+
+
+## bot commands will be set automatically
+
+## some of the commands are changed because the group members use them without any reason
+
+## Using service accounts for uploading to avoid user rate limit
+For Service Account to work, you must set **USE_SERVICE_ACCOUNTS="True"** in config file or environment variables
+Many thanks to [AutoRClone](https://github.com/xyou365/AutoRclone) for the scripts
+**NOTE**: Using service accounts is only recommended while uploading to a team drive.
+
+## Generate service accounts. [What is service account](https://cloud.google.com/iam/docs/service-accounts)
+
+
+first enable IAM API from cloud console by Visiting [Google API page](https://console.developers.google.com/apis/library)
+
+Let us create only the service accounts that we need.
+**Warning**: abuse of this feature is not the aim of this project and we do **NOT** recommend that you make a lot of projects, just one project and 100 sa allow you plenty of use, its also possible that over abuse might get your projects banned by google.
+
+```
+Note: 1 service account can copy around 750gb a day, 1 project can make 100 service accounts so that's 75tb a day, for most users this should easily suffice.
+```
+
+`python3 gen_sa_accounts.py --quick-setup 1 --new-only`
+
+A folder named accounts will be created which will contain keys for the service accounts
+
+**NOTE**: If you have created SAs in past from this script, you can also just re download the keys by running:
+```
+python3 gen_sa_accounts.py --download-keys project_id
+```
+
+## Add all the service accounts to the Team Drive
+- Run:
+```
+python3 add_to_team_drive.py -d SharedTeamDriveSrcID
+```
+
+## Youtube-dl authentication using .netrc file
+For using your premium accounts in youtube-dl, edit the [.netrc] file according to following format:
+```
+machine host login username password my_youtube_password
+```
+where host is the name of extractor (eg. youtube, twitch). Multiple accounts of different hosts can be added each separated by a new line
+
+## Credits
+
+Thanks to:
+- [out386](https://github.com/out386) heavily inspired from telegram bot which is written in JS
+- [Izzy12](https://github.com/lzzy12/) for original repo
+- [Dank-del](https://github.com/Dank-del/) for base repo
+- [magneto261290](https://github.com/magneto261290/) for some features
+- [SVR666](https://github.com/SVR666/) for some fixes
+- [4amparaboy](https://github.com/4amparaboy/) for some help
+- [WinTenDev](https://github.com/WinTenDev/) for Uptobox support
+- [iamLiquidX](https://github.com/iamLiquidX/) for Speedtest module
+- [ydner](https://github.com/ydner/) for Usage module
+- [breakdowns](https://github.com/breakdowns) for main repo
+- [Jigarvarma2005](https://gitlab.com/Jigarvarma2005) For There GDTOT Code
+
diff --git a/add_to_team_drive.py b/add_to_team_drive.py
new file mode 100644
index 0000000..087c5a5
--- /dev/null
+++ b/add_to_team_drive.py
@@ -0,0 +1,77 @@
+from __future__ import print_function
+from google.oauth2.service_account import Credentials
+import googleapiclient.discovery, json, progress.bar, glob, sys, argparse, time
+from google_auth_oauthlib.flow import InstalledAppFlow
+from google.auth.transport.requests import Request
+import os, pickle
+
+stt = time.time()
+
+parse = argparse.ArgumentParser(
+ description='A tool to add service accounts to a shared drive from a folder containing credential files.')
+parse.add_argument('--path', '-p', default='accounts',
+ help='Specify an alternative path to the service accounts folder.')
+parse.add_argument('--credentials', '-c', default='./credentials.json',
+ help='Specify the relative path for the credentials file.')
+parse.add_argument('--yes', '-y', default=False, action='store_true', help='Skips the sanity prompt.')
+parsereq = parse.add_argument_group('required arguments')
+parsereq.add_argument('--drive-id', '-d', help='The ID of the Shared Drive.', required=True)
+
+args = parse.parse_args()
+acc_dir = args.path
+did = args.drive_id
+credentials = glob.glob(args.credentials)
+
+try:
+ open(credentials[0], 'r')
+ print('>> Found credentials.')
+except IndexError:
+ print('>> No credentials found.')
+ sys.exit(0)
+
+if not args.yes:
+ # input('Make sure the following client id is added to the shared drive as Manager:\n' + json.loads((open(
+ # credentials[0],'r').read()))['installed']['client_id'])
+ input('>> Make sure the **Google account** that has generated credentials.json\n is added into your Team Drive '
+ '(shared drive) as Manager\n>> (Press any key to continue)')
+
+creds = None
+if os.path.exists('token_sa.pickle'):
+ with open('token_sa.pickle', 'rb') as token:
+ creds = pickle.load(token)
+# If there are no (valid) credentials available, let the user log in.
+if not creds or not creds.valid:
+ if creds and creds.expired and creds.refresh_token:
+ creds.refresh(Request())
+ else:
+ flow = InstalledAppFlow.from_client_secrets_file(credentials[0], scopes=[
+ 'https://www.googleapis.com/auth/admin.directory.group',
+ 'https://www.googleapis.com/auth/admin.directory.group.member'
+ ])
+ # creds = flow.run_local_server(port=0)
+ creds = flow.run_console()
+ # Save the credentials for the next run
+ with open('token_sa.pickle', 'wb') as token:
+ pickle.dump(creds, token)
+
+drive = googleapiclient.discovery.build("drive", "v3", credentials=creds)
+batch = drive.new_batch_http_request()
+
+aa = glob.glob('%s/*.json' % acc_dir)
+pbar = progress.bar.Bar("Readying accounts", max=len(aa))
+for i in aa:
+ ce = json.loads(open(i, 'r').read())['client_email']
+ batch.add(drive.permissions().create(fileId=did, supportsAllDrives=True, body={
+ "role": "organizer",
+ "type": "user",
+ "emailAddress": ce
+ }))
+ pbar.next()
+pbar.finish()
+print('Adding...')
+batch.execute()
+
+print('Complete.')
+hours, rem = divmod((time.time() - stt), 3600)
+minutes, sec = divmod(rem, 60)
+print("Elapsed Time:\n{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), sec))
diff --git a/alive.py b/alive.py
new file mode 100644
index 0000000..a939c19
--- /dev/null
+++ b/alive.py
@@ -0,0 +1,29 @@
+
+
+import time
+import requests
+import os
+from dotenv import load_dotenv
+
+load_dotenv('config.env')
+
+try:
+ BASE_URL = os.environ.get('BASE_URL_OF_BOT', None)
+ if len(BASE_URL) == 0:
+ BASE_URL = None
+except KeyError:
+ BASE_URL = None
+
+try:
+ IS_VPS = os.environ.get('IS_VPS', 'False')
+ if IS_VPS.lower() == 'true':
+ IS_VPS = True
+ else:
+ IS_VPS = False
+except KeyError:
+ IS_VPS = False
+
+if not IS_VPS and BASE_URL is not None:
+ while True:
+ time.sleep(1000)
+ status = requests.get(BASE_URL).status_code
diff --git a/aria.bat b/aria.bat
new file mode 100644
index 0000000..3880800
--- /dev/null
+++ b/aria.bat
@@ -0,0 +1 @@
+aria2c --enable-rpc --rpc-listen-all=false --rpc-listen-port 6800 --max-connection-per-server=10 --rpc-max-request-size=1024M --seed-time=0.01 --min-split-size=10M --follow-torrent=mem --split=10 --daemon=true --allow-overwrite=true
diff --git a/aria.sh b/aria.sh
new file mode 100644
index 0000000..aa12693
--- /dev/null
+++ b/aria.sh
@@ -0,0 +1,15 @@
+export MAX_DOWNLOAD_SPEED=0
+tracker_list=$(curl -Ns https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all.txt https://ngosang.github.io/trackerslist/trackers_all_http.txt https://raw.githubusercontent.com/DeSireFire/animeTrackerList/master/AT_all.txt https://raw.githubusercontent.com/hezhijie0327/Trackerslist/main/trackerslist_combine.txt | awk '$0' | tr '\n' ',')
+export MAX_CONCURRENT_DOWNLOADS=4
+
+aria2c --enable-rpc --rpc-listen-all=false --check-certificate=false \
+ --max-connection-per-server=10 --rpc-max-request-size=1024M \
+ --bt-tracker="[$tracker_list]" --bt-max-peers=0 --bt-tracker-connect-timeout=300 --bt-stop-timeout=1200 --min-split-size=10M \
+ --follow-torrent=mem --split=10 \
+ --daemon=true --allow-overwrite=true --max-overall-download-limit=$MAX_DOWNLOAD_SPEED \
+ --max-overall-upload-limit=1K --max-concurrent-downloads=$MAX_CONCURRENT_DOWNLOADS \
+ --peer-id-prefix=-qB4360- --user-agent=qBittorrent/4.3.6 --peer-agent=qBittorrent/4.3.6 \
+ --disk-cache=64M --file-allocation=prealloc --continue=true \
+ --max-file-not-found=0 --max-tries=20 --auto-file-renaming=true \
+ --bt-enable-lpd=true --seed-time=0.01 --seed-ratio=1.0 \
+ --content-disposition-default-utf8=true --http-accept-gzip=true --reuse-uri=true --netrc-path=/usr/src/app/.netrc
diff --git a/bot/__init__.py b/bot/__init__.py
new file mode 100644
index 0000000..bd0081a
--- /dev/null
+++ b/bot/__init__.py
@@ -0,0 +1,418 @@
+import logging
+import os
+import threading
+import time
+import random
+import string
+import subprocess
+import requests
+
+import aria2p
+import qbittorrentapi as qba
+import telegram.ext as tg
+from dotenv import load_dotenv
+from pyrogram import Client
+from telegraph import Telegraph
+
+import psycopg2
+from psycopg2 import Error
+
+import socket
+import faulthandler
+faulthandler.enable()
+
+socket.setdefaulttimeout(600)
+
+botStartTime = time.time()
+if os.path.exists('log.txt'):
+ with open('log.txt', 'r+') as f:
+ f.truncate(0)
+
+logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+ handlers=[logging.FileHandler('log.txt'), logging.StreamHandler()],
+ level=logging.INFO)
+
+LOGGER = logging.getLogger(__name__)
+
+
+CONFIG_FILE_URL = os.environ.get('CONFIG_FILE_URL', None)
+if CONFIG_FILE_URL is not None:
+ res = requests.get(CONFIG_FILE_URL)
+ if res.status_code == 200:
+ with open('config.env', 'wb+') as f:
+ f.write(res.content)
+ f.close()
+ else:
+ logging.error(res.status_code)
+
+load_dotenv('config.env')
+
+
+SERVER_PORT = os.environ.get('SERVER_PORT', None)
+PORT = os.environ.get('PORT', SERVER_PORT)
+web = subprocess.Popen([f"gunicorn wserver:start_server --bind 0.0.0.0:{PORT} --worker-class aiohttp.GunicornWebWorker"], shell=True)
+time.sleep(1)
+alive = subprocess.Popen(["python3", "alive.py"])
+subprocess.run(["mkdir", "-p", "qBittorrent/config"])
+subprocess.run(["cp", "qBittorrent.conf", "qBittorrent/config/qBittorrent.conf"])
+subprocess.run(["qbittorrent-nox", "-d", "--profile=."])
+Interval = []
+DRIVES_NAMES = []
+DRIVES_IDS = []
+INDEX_URL = []
+
+
+def getConfig(name: str):
+ return os.environ[name]
+
+def mktable():
+ try:
+ conn = psycopg2.connect(DB_URI)
+ cur = conn.cursor()
+ sql = "CREATE TABLE users (uid bigint, sudo boolean DEFAULT FALSE);"
+ cur.execute(sql)
+ conn.commit()
+ LOGGER.info("Table Created!")
+ except Error as e:
+ LOGGER.error(e)
+ exit(1)
+
+try:
+ if bool(getConfig('_____REMOVE_THIS_LINE_____')):
+ logging.error('The README.md file there to be read! Exiting now!')
+ exit()
+except KeyError:
+ pass
+
+aria2 = aria2p.API(
+ aria2p.Client(
+ host="http://localhost",
+ port=6800,
+ secret="",
+ )
+)
+
+
+def get_client() -> qba.TorrentsAPIMixIn:
+ qb_client = qba.Client(host="localhost", port=8090, username="admin", password="adminadmin")
+ try:
+ qb_client.auth_log_in()
+ qb_client.application.set_preferences({"disk_cache":64, "incomplete_files_ext":True, "max_connec":3000, "max_connec_per_torrent":300, "async_io_threads":8, "preallocate_all":True, "upnp":True, "dl_limit":-1, "up_limit":-1, "dht":True, "pex":True, "lsd":True, "encryption":0, "queueing_enabled":True, "max_active_downloads":15, "max_active_torrents":50, "dont_count_slow_torrents":True, "bittorrent_protocol":0, "recheck_completed_torrents":True, "enable_multi_connections_from_same_ip":True, "slow_torrent_dl_rate_threshold":100,"slow_torrent_inactive_timer":600})
+ return qb_client
+ except qba.LoginFailed as e:
+ LOGGER.error(str(e))
+ return None
+
+
+DOWNLOAD_DIR = None
+BOT_TOKEN = None
+
+download_dict_lock = threading.Lock()
+status_reply_dict_lock = threading.Lock()
+# Key: update.effective_chat.id
+# Value: telegram.Message
+status_reply_dict = {}
+# Key: update.message.message_id
+# Value: An object of Status
+download_dict = {}
+# Stores list of users and chats the bot is authorized to use in
+AUTHORIZED_CHATS = set()
+SUDO_USERS = set()
+if os.path.exists('authorized_chats.txt'):
+ with open('authorized_chats.txt', 'r+') as f:
+ lines = f.readlines()
+ for line in lines:
+ AUTHORIZED_CHATS.add(int(line.split()[0]))
+if os.path.exists('sudo_users.txt'):
+ with open('sudo_users.txt', 'r+') as f:
+ lines = f.readlines()
+ for line in lines:
+ SUDO_USERS.add(int(line.split()[0]))
+try:
+ achats = getConfig('AUTHORIZED_CHATS')
+ achats = achats.split(" ")
+ for chats in achats:
+ AUTHORIZED_CHATS.add(int(chats))
+except:
+ pass
+try:
+ schats = getConfig('SUDO_USERS')
+ schats = schats.split(" ")
+ for chats in schats:
+ SUDO_USERS.add(int(chats))
+except:
+ pass
+try:
+ BOT_TOKEN = getConfig('BOT_TOKEN')
+ parent_id = getConfig('GDRIVE_FOLDER_ID')
+ DOWNLOAD_DIR = getConfig('DOWNLOAD_DIR')
+ if not DOWNLOAD_DIR.endswith("/"):
+ DOWNLOAD_DIR = DOWNLOAD_DIR + '/'
+ DOWNLOAD_STATUS_UPDATE_INTERVAL = int(getConfig('DOWNLOAD_STATUS_UPDATE_INTERVAL'))
+ OWNER_ID = int(getConfig('OWNER_ID'))
+ AUTO_DELETE_MESSAGE_DURATION = int(getConfig('AUTO_DELETE_MESSAGE_DURATION'))
+ TELEGRAM_API = getConfig('TELEGRAM_API')
+ TELEGRAM_HASH = getConfig('TELEGRAM_HASH')
+ UPSTREAM_REPO = getConfig('UPSTREAM_REPO')
+ UPSTREAM_BRANCH = getConfig('UPSTREAM_BRANCH')
+except KeyError as e:
+ LOGGER.error("One or more env variables missing! Exiting now")
+ exit(1)
+try:
+ DB_URI = getConfig('DATABASE_URL')
+ if len(DB_URI) == 0:
+ raise KeyError
+except KeyError:
+ logging.warning('Database not provided!')
+ DB_URI = None
+if DB_URI is not None:
+ try:
+ conn = psycopg2.connect(DB_URI)
+ cur = conn.cursor()
+ sql = "SELECT * from users;"
+ cur.execute(sql)
+ rows = cur.fetchall() #returns a list ==> (uid, sudo)
+ for row in rows:
+ AUTHORIZED_CHATS.add(row[0])
+ if row[1]:
+ SUDO_USERS.add(row[0])
+ except Error as e:
+ if 'relation "users" does not exist' in str(e):
+ mktable()
+ else:
+ LOGGER.error(e)
+ exit(1)
+ finally:
+ cur.close()
+ conn.close()
+
+LOGGER.info("Generating USER_SESSION_STRING")
+app = Client(':memory:', api_id=int(TELEGRAM_API), api_hash=TELEGRAM_HASH, bot_token=BOT_TOKEN)
+
+# Generate Telegraph Token
+sname = ''.join(random.SystemRandom().choices(string.ascii_letters, k=8))
+LOGGER.info("Generating TELEGRAPH_TOKEN using '" + sname + "' name")
+telegraph = Telegraph()
+telegraph.create_account(short_name=sname)
+telegraph_token = telegraph.get_access_token()
+
+try:
+ STATUS_LIMIT = getConfig('STATUS_LIMIT')
+ if len(STATUS_LIMIT) == 0:
+ raise KeyError
+ else:
+ STATUS_LIMIT = int(getConfig('STATUS_LIMIT'))
+except KeyError:
+ STATUS_LIMIT = None
+try:
+ MEGA_API_KEY = getConfig('MEGA_API_KEY')
+except KeyError:
+ logging.warning('MEGA API KEY not provided!')
+ MEGA_API_KEY = None
+try:
+ MEGA_EMAIL_ID = getConfig('MEGA_EMAIL_ID')
+ MEGA_PASSWORD = getConfig('MEGA_PASSWORD')
+ if len(MEGA_EMAIL_ID) == 0 or len(MEGA_PASSWORD) == 0:
+ raise KeyError
+except KeyError:
+ logging.warning('MEGA Credentials not provided!')
+ MEGA_EMAIL_ID = None
+ MEGA_PASSWORD = None
+try:
+ HEROKU_API_KEY = getConfig('HEROKU_API_KEY')
+except KeyError:
+ logging.warning('HEROKU API KEY not provided!')
+ HEROKU_API_KEY = None
+try:
+ HEROKU_APP_NAME = getConfig('HEROKU_APP_NAME')
+except KeyError:
+ logging.warning('HEROKU APP NAME not provided!')
+ HEROKU_APP_NAME = None
+try:
+ UPTOBOX_TOKEN = getConfig('UPTOBOX_TOKEN')
+except KeyError:
+ logging.warning('UPTOBOX_TOKEN not provided!')
+ UPTOBOX_TOKEN = None
+try:
+ INDEX_URL = getConfig('INDEX_URL')
+ if len(INDEX_URL) == 0:
+ INDEX_URL = None
+except KeyError:
+ INDEX_URL = None
+try:
+ TORRENT_DIRECT_LIMIT = getConfig('TORRENT_DIRECT_LIMIT')
+ if len(TORRENT_DIRECT_LIMIT) == 0:
+ TORRENT_DIRECT_LIMIT = None
+except KeyError:
+ TORRENT_DIRECT_LIMIT = None
+try:
+ CLONE_LIMIT = getConfig('CLONE_LIMIT')
+ if len(CLONE_LIMIT) == 0:
+ CLONE_LIMIT = None
+except KeyError:
+ CLONE_LIMIT = None
+try:
+ MEGA_LIMIT = getConfig('MEGA_LIMIT')
+ if len(MEGA_LIMIT) == 0:
+ MEGA_LIMIT = None
+except KeyError:
+ MEGA_LIMIT = None
+try:
+ TAR_UNZIP_LIMIT = getConfig('TAR_UNZIP_LIMIT')
+ if len(TAR_UNZIP_LIMIT) == 0:
+ TAR_UNZIP_LIMIT = None
+except KeyError:
+ TAR_UNZIP_LIMIT = None
+try:
+ BUTTON_FOUR_NAME = getConfig('BUTTON_FOUR_NAME')
+ BUTTON_FOUR_URL = getConfig('BUTTON_FOUR_URL')
+ if len(BUTTON_FOUR_NAME) == 0 or len(BUTTON_FOUR_URL) == 0:
+ raise KeyError
+except KeyError:
+ BUTTON_FOUR_NAME = None
+ BUTTON_FOUR_URL = None
+try:
+ BUTTON_FIVE_NAME = getConfig('BUTTON_FIVE_NAME')
+ BUTTON_FIVE_URL = getConfig('BUTTON_FIVE_URL')
+ if len(BUTTON_FIVE_NAME) == 0 or len(BUTTON_FIVE_URL) == 0:
+ raise KeyError
+except KeyError:
+ BUTTON_FIVE_NAME = None
+ BUTTON_FIVE_URL = None
+try:
+ BUTTON_SIX_NAME = getConfig('BUTTON_SIX_NAME')
+ BUTTON_SIX_URL = getConfig('BUTTON_SIX_URL')
+ if len(BUTTON_SIX_NAME) == 0 or len(BUTTON_SIX_URL) == 0:
+ raise KeyError
+except KeyError:
+ BUTTON_SIX_NAME = None
+ BUTTON_SIX_URL = None
+try:
+ IMAGE_URL = getConfig('IMAGE_URL')
+ if len(IMAGE_URL) == 0:
+ IMAGE_URL = 'https://telegra.ph/file/019996f816db9ed576cff.jpg'
+except KeyError:
+ IMAGE_URL = 'https://telegra.ph/file/019996f816db9ed576cff.jpg'
+try:
+ STOP_DUPLICATE = getConfig('STOP_DUPLICATE')
+ if STOP_DUPLICATE.lower() == 'true':
+ STOP_DUPLICATE = True
+ else:
+ STOP_DUPLICATE = False
+except KeyError:
+ STOP_DUPLICATE = False
+try:
+ VIEW_LINK = getConfig('VIEW_LINK')
+ if VIEW_LINK.lower() == 'true':
+ VIEW_LINK = True
+ else:
+ VIEW_LINK = False
+except KeyError:
+ VIEW_LINK = False
+try:
+ IS_TEAM_DRIVE = getConfig('IS_TEAM_DRIVE')
+ if IS_TEAM_DRIVE.lower() == 'true':
+ IS_TEAM_DRIVE = True
+ else:
+ IS_TEAM_DRIVE = False
+except KeyError:
+ IS_TEAM_DRIVE = False
+try:
+ USE_SERVICE_ACCOUNTS = getConfig('USE_SERVICE_ACCOUNTS')
+ if USE_SERVICE_ACCOUNTS.lower() == 'true':
+ USE_SERVICE_ACCOUNTS = True
+ else:
+ USE_SERVICE_ACCOUNTS = False
+except KeyError:
+ USE_SERVICE_ACCOUNTS = False
+try:
+ BLOCK_MEGA_FOLDER = getConfig('BLOCK_MEGA_FOLDER')
+ if BLOCK_MEGA_FOLDER.lower() == 'true':
+ BLOCK_MEGA_FOLDER = True
+ else:
+ BLOCK_MEGA_FOLDER = False
+except KeyError:
+ BLOCK_MEGA_FOLDER = False
+try:
+ BLOCK_MEGA_LINKS = getConfig('BLOCK_MEGA_LINKS')
+ if BLOCK_MEGA_LINKS.lower() == 'true':
+ BLOCK_MEGA_LINKS = True
+ else:
+ BLOCK_MEGA_LINKS = False
+except KeyError:
+ BLOCK_MEGA_LINKS = False
+try:
+ SHORTENER = getConfig('SHORTENER')
+ SHORTENER_API = getConfig('SHORTENER_API')
+ if len(SHORTENER) == 0 or len(SHORTENER_API) == 0:
+ raise KeyError
+except KeyError:
+ SHORTENER = None
+ SHORTENER_API = None
+
+IGNORE_PENDING_REQUESTS = False
+try:
+ if getConfig("IGNORE_PENDING_REQUESTS").lower() == "true":
+ IGNORE_PENDING_REQUESTS = True
+except KeyError:
+ pass
+
+try:
+ BASE_URL = getConfig('BASE_URL_OF_BOT')
+ if len(BASE_URL) == 0:
+ BASE_URL = None
+except KeyError:
+ logging.warning('BASE_URL_OF_BOT not provided! Bot will get down soon....')
+ BASE_URL = None
+
+try:
+ IS_VPS = getConfig('IS_VPS')
+ if IS_VPS.lower() == 'true':
+ IS_VPS = True
+ else:
+ IS_VPS = False
+except KeyError:
+ IS_VPS = False
+
+try:
+ SERVER_PORT = getConfig('SERVER_PORT')
+ if len(SERVER_PORT) == 0:
+ SERVER_PORT = None
+except KeyError:
+ logging.warning('SERVER_PORT not provided!')
+ SERVER_PORT = None
+
+try:
+ TOKEN_PICKLE_URL = getConfig('TOKEN_PICKLE_URL')
+ if len(TOKEN_PICKLE_URL) == 0:
+ TOKEN_PICKLE_URL = None
+ else:
+ out = subprocess.run(["wget", "-q", "-O", "token.pickle", TOKEN_PICKLE_URL])
+ if out.returncode != 0:
+ logging.error(out)
+except KeyError:
+ TOKEN_PICKLE_URL = None
+
+try:
+ GDTOT_COOKIES = getConfig('GDTOT_COOKIES')
+except KeyError:
+ logging.warning('GDTOT_COOKIES not provided!')
+ GDTOT_COOKIES = None
+
+try:
+ ACCOUNTS_ZIP_URL = getConfig('ACCOUNTS_ZIP_URL')
+ if len(ACCOUNTS_ZIP_URL) == 0:
+ ACCOUNTS_ZIP_URL = None
+ else:
+ out = subprocess.run(["wget", "-q", "-O", "accounts.zip", ACCOUNTS_ZIP_URL])
+ if out.returncode != 0:
+ logging.error(out)
+ raise KeyError
+ subprocess.run(["unzip", "-q", "-o", "accounts.zip"])
+ os.remove("accounts.zip")
+except KeyError:
+ ACCOUNTS_ZIP_URL = None
+
+updater = tg.Updater(token=BOT_TOKEN)
+bot = updater.bot
+dispatcher = updater.dispatcher
diff --git a/bot/__main__.py b/bot/__main__.py
new file mode 100644
index 0000000..fb53984
--- /dev/null
+++ b/bot/__main__.py
@@ -0,0 +1,215 @@
+import shutil, psutil
+import signal
+import os
+import asyncio
+
+from pyrogram import idle
+from bot import app
+from sys import executable
+
+from telegram import ParseMode
+from telegram.ext import CommandHandler
+from wserver import start_server_async
+from bot import bot, IMAGE_URL, dispatcher, updater, botStartTime, IGNORE_PENDING_REQUESTS, IS_VPS, SERVER_PORT, OWNER_ID, AUTHORIZED_CHATS
+from bot.helper.ext_utils import fs_utils
+from bot.helper.telegram_helper.bot_commands import BotCommands
+from bot.helper.telegram_helper.message_utils import *
+from .helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time
+from .helper.telegram_helper.filters import CustomFilters
+from bot.helper.telegram_helper import button_build
+from .modules import authorize, list, cancel_mirror, mirror_status, mirror, clone, watch, shell, eval, torrent_search, delete, speedtest, count, config, updates
+
+
+def stats(update, context):
+ currentTime = get_readable_time(time.time() - botStartTime)
+ total, used, free = shutil.disk_usage('.')
+ total = get_readable_file_size(total)
+ used = get_readable_file_size(used)
+ free = get_readable_file_size(free)
+ sent = get_readable_file_size(psutil.net_io_counters().bytes_sent)
+ recv = get_readable_file_size(psutil.net_io_counters().bytes_recv)
+ cpuUsage = psutil.cpu_percent(interval=0.5)
+ memory = psutil.virtual_memory().percent
+ disk = psutil.disk_usage('/').percent
+ stats = f'╭──「⭕️ BOT STATISTICS ⭕️」\n' \
+ f'│\n' \
+ f'├ ⏰ Bot Uptime : {currentTime}\n' \
+ f'├ 💾 Total Disk Space : {total}\n' \
+ f'├ 📀 Total Used Space : {used}\n' \
+ f'├ 💿 Total Free Space : {free}\n' \
+ f'├ 🔼 Total Upload : {sent}\n' \
+ f'├ 🔽 Total Download : {recv}\n' \
+ f'├ 🖥️ CPU : {cpuUsage}%\n' \
+ f'├ 🎮 RAM : {memory}%\n' \
+ f'├ 💽 DISK : {disk}%\n' \
+ f'│\n' \
+ f'╰──「 🚸 @AT_BOTs 🚸 」'
+ update.effective_message.reply_photo(IMAGE_URL, stats, parse_mode=ParseMode.HTML)
+
+
+def start(update, context):
+ start_string = f'''
+This bot can mirror all your links to Google Drive!
+Type /{BotCommands.HelpCommand} to get a list of available commands
+'''
+ buttons = button_build.ButtonMaker()
+ buttons.buildbutton("Repo", "https://github.com/ayushteke/slam_aria_mirror_bot")
+ buttons.buildbutton("Channel", "https://t.me/AT_BOTs")
+ reply_markup = InlineKeyboardMarkup(buttons.build_menu(2))
+ LOGGER.info('UID: {} - UN: {} - MSG: {}'.format(update.message.chat.id, update.message.chat.username, update.message.text))
+ uptime = get_readable_time((time.time() - botStartTime))
+ if CustomFilters.authorized_user(update) or CustomFilters.authorized_chat(update):
+ if update.message.chat.type == "private" :
+ sendMessage(f"Hey I'm Alive 🙂\nSince: {uptime}", context.bot, update)
+ else :
+ sendMarkup(IMAGE_URL, start_string, context.bot, update, reply_markup)
+ else :
+ sendMarkup(f"Oops! You are not allowed to use me..", context.bot, update, reply_markup)
+
+
+def restart(update, context):
+ restart_message = sendMessage("Restarting, Please wait!", context.bot, update)
+ # Save restart message object in order to reply to it after restarting
+ with open(".restartmsg", "w") as f:
+ f.truncate(0)
+ f.write(f"{restart_message.chat.id}\n{restart_message.message_id}\n")
+ fs_utils.clean_all()
+ os.execl(executable, executable, "-m", "bot")
+
+
+def ping(update, context):
+ start_time = int(round(time.time() * 1000))
+ reply = sendMessage("Starting Ping", context.bot, update)
+ end_time = int(round(time.time() * 1000))
+ editMessage(f'{end_time - start_time} ms', reply)
+
+
+def log(update, context):
+ sendLogFile(context.bot, update)
+
+
+def bot_help(update, context):
+ help_string_adm = f'''
+/{BotCommands.HelpCommand}: To get this message
+/{BotCommands.MirrorCommand} [download_url][magnet_link]: Start mirroring the link to Google Drive. Use /{BotCommands.MirrorCommand} qb to mirror with qBittorrent, and use /{BotCommands.MirrorCommand} qbs to select files before downloading
+/{BotCommands.TarMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the archived (.tar) version of the download
+/{BotCommands.ZipMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the archived (.zip) version of the download
+/{BotCommands.UnzipMirrorCommand} [download_url][magnet_link]: Starts mirroring and if downloaded file is any archive, extracts it to Google Drive
+/{BotCommands.CloneCommand} [drive_url]: Copy file/folder to Google Drive
+/{BotCommands.CountCommand} [drive_url]: Count file/folder of Google Drive Links
+/{BotCommands.DeleteCommand} [drive_url]: Delete file from Google Drive (Only Owner & Sudo)
+/{BotCommands.WatchCommand} [youtube-dl supported link]: Mirror through youtube-dl. Click /{BotCommands.WatchCommand} for more help
+/{BotCommands.TarWatchCommand} [youtube-dl supported link]: Mirror through youtube-dl and tar before uploading
+/{BotCommands.CancelMirror}: Reply to the message by which the download was initiated and that download will be cancelled
+/{BotCommands.CancelAllCommand}: Cancel all running tasks
+/{BotCommands.ListCommand} [search term]: Searches the search term in the Google Drive, If found replies with the link
+/{BotCommands.StatusCommand}: Shows a status of all the downloads
+/{BotCommands.StatsCommand}: Show Stats of the machine the bot is hosted on
+/{BotCommands.PingCommand}: Check how long it takes to Ping the Bot
+/{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Can only be invoked by Owner & Sudo of the bot)
+/{BotCommands.UnAuthorizeCommand}: Unauthorize a chat or a user to use the bot (Can only be invoked by Owner & Sudo of the bot)
+/{BotCommands.AuthorizedUsersCommand}: Show authorized users (Only Owner & Sudo)
+/{BotCommands.AddSudoCommand}: Add sudo user (Only Owner)
+/{BotCommands.RmSudoCommand}: Remove sudo users (Only Owner)
+/{BotCommands.RestartCommand}: Restart the bot
+/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports
+/{BotCommands.ConfigMenuCommand}: Get Info Menu about bot config (Owner Only)
+/{BotCommands.UpdateCommand}: Update Bot from Upstream Repo (Owner Only)
+/{BotCommands.SpeedCommand}: Check Internet Speed of the Host
+/{BotCommands.ShellCommand}: Run commands in Shell (Terminal)
+/{BotCommands.ExecHelpCommand}: Get help for Executor module (Only Owner)
+/{BotCommands.TsHelpCommand}: Get help for Torrent search module
+'''
+
+ help_string = f'''
+/{BotCommands.HelpCommand}: To get this message
+/{BotCommands.MirrorCommand} [download_url][magnet_link]: Start mirroring the link to Google Drive. Use /{BotCommands.MirrorCommand} qb to mirror with qBittorrent, and use /{BotCommands.MirrorCommand} qbs to select files before downloading
+/{BotCommands.TarMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the archived (.tar) version of the download
+/{BotCommands.ZipMirrorCommand} [download_url][magnet_link]: Start mirroring and upload the archived (.zip) version of the download
+/{BotCommands.UnzipMirrorCommand} [download_url][magnet_link]: Starts mirroring and if downloaded file is any archive, extracts it to Google Drive
+/{BotCommands.CloneCommand} [drive_url]: Copy file/folder to Google Drive
+/{BotCommands.CountCommand} [drive_url]: Count file/folder of Google Drive Links
+/{BotCommands.WatchCommand} [youtube-dl supported link]: Mirror through youtube-dl. Click /{BotCommands.WatchCommand} for more help
+/{BotCommands.TarWatchCommand} [youtube-dl supported link]: Mirror through youtube-dl and tar before uploading
+/{BotCommands.CancelMirror}: Reply to the message by which the download was initiated and that download will be cancelled
+/{BotCommands.ListCommand} [search term]: Searches the search term in the Google Drive, If found replies with the link
+/{BotCommands.StatusCommand}: Shows a status of all the downloads
+/{BotCommands.StatsCommand}: Show Stats of the machine the bot is hosted on
+/{BotCommands.PingCommand}: Check how long it takes to Ping the Bot
+/{BotCommands.TsHelpCommand}: Get help for Torrent search module
+'''
+
+ if CustomFilters.sudo_user(update) or CustomFilters.owner_filter(update):
+ sendMessage(help_string_adm, context.bot, update)
+ else:
+ sendMessage(help_string, context.bot, update)
+
+
+botcmds = [
+ (f'{BotCommands.HelpCommand}','Get Detailed Help'),
+ (f'{BotCommands.MirrorCommand}', 'Start Mirroring'),
+ (f'{BotCommands.TarMirrorCommand}','Start mirroring and upload as .tar'),
+ (f'{BotCommands.UnzipMirrorCommand}','Extract files'),
+ (f'{BotCommands.ZipMirrorCommand}','Start mirroring and upload as .zip'),
+ (f'{BotCommands.CloneCommand}','Copy file/folder to Drive'),
+ (f'{BotCommands.CountCommand}','Count file/folder of Drive link'),
+ (f'{BotCommands.DeleteCommand}','Delete file from Drive'),
+ (f'{BotCommands.WatchCommand}','Mirror Youtube-dl support link'),
+ (f'{BotCommands.TarWatchCommand}','Mirror Youtube playlist link as .tar'),
+ (f'{BotCommands.CancelMirror}','Cancel a task'),
+ (f'{BotCommands.CancelAllCommand}','Cancel all tasks'),
+ (f'{BotCommands.ListCommand}','Searches files in Drive'),
+ (f'{BotCommands.StatusCommand}','Get Mirror Status message'),
+ (f'{BotCommands.StatsCommand}','Bot Usage Stats'),
+ (f'{BotCommands.PingCommand}','Ping the Bot'),
+ (f'{BotCommands.RestartCommand}','Restart the bot [owner/sudo only]'),
+ (f'{BotCommands.LogCommand}','Get the Bot Log [owner/sudo only]'),
+ (f'{BotCommands.TsHelpCommand}','Get help for Torrent search module')
+ ]
+
+
+def main():
+ fs_utils.start_cleanup()
+ if IS_VPS:
+ asyncio.get_event_loop().run_until_complete(start_server_async(PORT))
+ # Check if the bot is restarting
+ if os.path.isfile(".restartmsg"):
+ with open(".restartmsg") as f:
+ chat_id, msg_id = map(int, f)
+ bot.edit_message_text("Restarted successfully!", chat_id, msg_id)
+ os.remove(".restartmsg")
+ elif OWNER_ID:
+ try:
+ text = "Bot Restarted!"
+ bot.sendMessage(chat_id=OWNER_ID, text=text, parse_mode=ParseMode.HTML)
+ if AUTHORIZED_CHATS:
+ for i in AUTHORIZED_CHATS:
+ bot.sendMessage(chat_id=i, text=text, parse_mode=ParseMode.HTML)
+ except Exception as e:
+ LOGGER.warning(e)
+
+ bot.set_my_commands(botcmds)
+
+ start_handler = CommandHandler(BotCommands.StartCommand, start, run_async=True)
+ ping_handler = CommandHandler(BotCommands.PingCommand, ping,
+ filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
+ restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
+ filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True)
+ help_handler = CommandHandler(BotCommands.HelpCommand,
+ bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
+ stats_handler = CommandHandler(BotCommands.StatsCommand,
+ stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
+ log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True)
+ dispatcher.add_handler(start_handler)
+ dispatcher.add_handler(ping_handler)
+ dispatcher.add_handler(restart_handler)
+ dispatcher.add_handler(help_handler)
+ dispatcher.add_handler(stats_handler)
+ dispatcher.add_handler(log_handler)
+ updater.start_polling(drop_pending_updates=IGNORE_PENDING_REQUESTS)
+ LOGGER.info("Bot Started!")
+ signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
+
+app.start()
+main()
+idle()
diff --git a/bot/helper/__init__.py b/bot/helper/__init__.py
new file mode 100644
index 0000000..4d60510
--- /dev/null
+++ b/bot/helper/__init__.py
@@ -0,0 +1,70 @@
+import heroku3
+
+from functools import wraps
+from pyrogram.types import Message
+from bot import HEROKU_API_KEY, HEROKU_APP_NAME
+
+# Implement by https://github.com/jusidama18
+# Setting Message
+
+def get_text(message: Message) -> [None, str]:
+ """Extract Text From Commands"""
+ text_to_return = message.text
+ if message.text is None:
+ return None
+ if " " in text_to_return:
+ try:
+ return message.text.split(None, 1)[1]
+ except IndexError:
+ return None
+ else:
+ return None
+
+# Preparing For Setting Config
+# Implement by https://github.com/jusidama18 and Based on this https://github.com/DevsExpo/FridayUserbot/blob/master/plugins/heroku_helpers.py
+
+heroku_client = None
+if HEROKU_API_KEY:
+ heroku_client = heroku3.from_key(HEROKU_API_KEY)
+
+def check_heroku(func):
+ @wraps(func)
+ async def heroku_cli(client, message):
+ heroku_app = None
+ if not heroku_client:
+ await message.reply_text("`Please Add HEROKU_API_KEY Key For This To Function To Work!`", parse_mode="markdown")
+ elif not HEROKU_APP_NAME:
+ await message.reply_text("`Please Add HEROKU_APP_NAME For This To Function To Work!`", parse_mode="markdown")
+ if HEROKU_APP_NAME and heroku_client:
+ try:
+ heroku_app = heroku_client.app(HEROKU_APP_NAME)
+ except:
+ await message.reply_text(message, "`Heroku Api Key And App Name Doesn't Match!`", parse_mode="markdown")
+ if heroku_app:
+ await func(client, message, heroku_app)
+
+ return heroku_cli
+
+# Preparing For Update Bot
+# Implement by https://github.com/jusidama18 and Based on this https://github.com/DevsExpo/FridayUserbot/blob/master/plugins/updater.py
+
+def fetch_heroku_git_url(api_key, app_name):
+ if not api_key:
+ return None
+ if not app_name:
+ return None
+ heroku = heroku3.from_key(api_key)
+ try:
+ heroku_applications = heroku.apps()
+ except:
+ return None
+ heroku_app = None
+ for app in heroku_applications:
+ if app.name == app_name:
+ heroku_app = app
+ break
+ if not heroku_app:
+ return None
+ return heroku_app.git_url.replace("https://", "https://api:" + api_key + "@")
+
+HEROKU_URL = fetch_heroku_git_url(HEROKU_API_KEY, HEROKU_APP_NAME)
diff --git a/bot/helper/custom_filters.py b/bot/helper/custom_filters.py
new file mode 100644
index 0000000..0b17f44
--- /dev/null
+++ b/bot/helper/custom_filters.py
@@ -0,0 +1,23 @@
+from pyrogram import filters
+
+def callback_data(data):
+ def func(flt, client, callback_query):
+ return callback_query.data in flt.data
+
+ data = data if isinstance(data, list) else [data]
+ return filters.create(
+ func,
+ 'CustomCallbackDataFilter',
+ data=data
+ )
+
+def callback_chat(chats):
+ def func(flt, client, callback_query):
+ return callback_query.message.chat.id in flt.chats
+
+ chats = chats if isinstance(chats, list) else [chats]
+ return filters.create(
+ func,
+ 'CustomCallbackChatsFilter',
+ chats=chats
+ )
diff --git a/bot/helper/ext_utils/__init__.py b/bot/helper/ext_utils/__init__.py
new file mode 100644
index 0000000..bba8f51
--- /dev/null
+++ b/bot/helper/ext_utils/__init__.py
@@ -0,0 +1 @@
+#TEKEAYUSH
\ No newline at end of file
diff --git a/bot/helper/ext_utils/bot_utils.py b/bot/helper/ext_utils/bot_utils.py
new file mode 100644
index 0000000..b4ad005
--- /dev/null
+++ b/bot/helper/ext_utils/bot_utils.py
@@ -0,0 +1,265 @@
+import logging
+import re
+import threading
+import time
+import math
+
+from bot.helper.telegram_helper.bot_commands import BotCommands
+from bot import dispatcher, download_dict, download_dict_lock, STATUS_LIMIT
+from telegram import InlineKeyboardMarkup
+from telegram.ext import CallbackQueryHandler
+from bot.helper.telegram_helper import button_build, message_utils
+
+LOGGER = logging.getLogger(__name__)
+
+MAGNET_REGEX = r"magnet:\?xt=urn:btih:[a-zA-Z0-9]*"
+
+URL_REGEX = r"(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+"
+
+COUNT = 0
+PAGE_NO = 1
+
+
+class MirrorStatus:
+ STATUS_UPLOADING = "Uploading...📤"
+ STATUS_DOWNLOADING = "Downloading...📥"
+ STATUS_CLONING = "Cloning...♻️"
+ STATUS_WAITING = "Queued...📝"
+ STATUS_FAILED = "Failed 🚫. Cleaning Download..."
+ STATUS_PAUSE = "Paused...⭕️"
+ STATUS_ARCHIVING = "Archiving...🔐"
+ STATUS_EXTRACTING = "Extracting...📂"
+
+
+PROGRESS_MAX_SIZE = 100 // 8
+PROGRESS_INCOMPLETE = ['☆', '☆', '☆', '☆', '☆', '☆', '☆']
+
+SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
+
+
+class setInterval:
+ def __init__(self, interval, action):
+ self.interval = interval
+ self.action = action
+ self.stopEvent = threading.Event()
+ thread = threading.Thread(target=self.__setInterval)
+ thread.start()
+
+ def __setInterval(self):
+ nextTime = time.time() + self.interval
+ while not self.stopEvent.wait(nextTime - time.time()):
+ nextTime += self.interval
+ self.action()
+
+ def cancel(self):
+ self.stopEvent.set()
+
+
+def get_readable_file_size(size_in_bytes) -> str:
+ if size_in_bytes is None:
+ return '0B'
+ index = 0
+ while size_in_bytes >= 1024:
+ size_in_bytes /= 1024
+ index += 1
+ try:
+ return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}'
+ except IndexError:
+ return 'File too large'
+
+
+def getDownloadByGid(gid):
+ with download_dict_lock:
+ for dl in download_dict.values():
+ status = dl.status()
+ if status != MirrorStatus.STATUS_ARCHIVING and status != MirrorStatus.STATUS_EXTRACTING:
+ if dl.gid() == gid:
+ return dl
+ return None
+
+
+def getAllDownload():
+ with download_dict_lock:
+ for dlDetails in download_dict.values():
+ if dlDetails.status() == MirrorStatus.STATUS_DOWNLOADING or dlDetails.status() == MirrorStatus.STATUS_WAITING:
+ if dlDetails:
+ return dlDetails
+ return None
+
+
+def get_progress_bar_string(status):
+ completed = status.processed_bytes() / 8
+ total = status.size_raw() / 8
+ if total == 0:
+ p = 0
+ else:
+ p = round(completed * 100 / total)
+ p = min(max(p, 0), 100)
+ cFull = p // 8
+ cPart = p % 8 - 1
+ p_str = '★' * cFull
+ if cPart >= 0:
+ p_str += PROGRESS_INCOMPLETE[cPart]
+ p_str += ' ' * (PROGRESS_MAX_SIZE - cFull)
+ p_str = f"[{p_str}]"
+ return p_str
+
+
+def get_readable_message():
+ with download_dict_lock:
+ msg = ""
+ INDEX = 0
+ if STATUS_LIMIT is not None:
+ dick_no = len(download_dict)
+ global pages
+ pages = math.ceil(dick_no/STATUS_LIMIT)
+ if PAGE_NO > pages and pages != 0:
+ globals()['COUNT'] -= STATUS_LIMIT
+ globals()['PAGE_NO'] -= 1
+ for download in list(download_dict.values()):
+ INDEX += 1
+ if INDEX > COUNT:
+ msg += f"☞ 🗃️Filename :{download.name()}"
+ msg += f"\n☞ 🚦Status :{download.status()}"
+ if download.status() != MirrorStatus.STATUS_ARCHIVING and download.status() != MirrorStatus.STATUS_EXTRACTING:
+ msg += f"\n{get_progress_bar_string(download)} {download.progress()}"
+ if download.status() == MirrorStatus.STATUS_CLONING:
+ msg += f"\n☞ 🚦Cloned:{get_readable_file_size(download.processed_bytes())} of {download.size()}"
+ elif download.status() == MirrorStatus.STATUS_UPLOADING:
+ msg += f"\n☞ 📤Uploaded :{get_readable_file_size(download.processed_bytes())} of {download.size()}"
+ else:
+ msg += f"\n☞ 📥Downloaded :{get_readable_file_size(download.processed_bytes())} of {download.size()}"
+ msg += f"\n☞ ⚡️Speed :{download.speed()}" \
+ f"\n☞ ⏰ETA :{download.eta()} "
+ # if hasattr(download, 'is_torrent'):
+ try:
+ msg += f"\n☞ Seeders :{download.aria_download().num_seeders}" \
+ f" | ☞ Peers :{download.aria_download().connections}"
+ except:
+ pass
+ try:
+ msg += f"\n☞ Seeders :{download.torrent_info().num_seeds}" \
+ f" | ☞ Leechers :{download.torrent_info().num_leechs}"
+ except:
+ pass
+ msg += f"\n☞ To cancel ❌ :/{BotCommands.CancelMirror} {download.gid()}"
+ msg += "\n\n"
+ if STATUS_LIMIT is not None:
+ if INDEX >= COUNT + STATUS_LIMIT:
+ break
+ if STATUS_LIMIT is not None:
+ if INDEX > COUNT + STATUS_LIMIT:
+ return None, None
+ if dick_no > STATUS_LIMIT:
+ msg += f"Page: {PAGE_NO}/{pages} | Tasks: {dick_no}\n"
+ buttons = button_build.ButtonMaker()
+ buttons.sbutton("Previous", "pre")
+ buttons.sbutton("Next", "nex")
+ button = InlineKeyboardMarkup(buttons.build_menu(2))
+ return msg, button
+ return msg, ""
+
+
+def flip(update, context):
+ query = update.callback_query
+ query.answer()
+ global COUNT, PAGE_NO
+ if query.data == "nex":
+ if PAGE_NO == pages:
+ COUNT = 0
+ PAGE_NO = 1
+ else:
+ COUNT += STATUS_LIMIT
+ PAGE_NO += 1
+ elif query.data == "pre":
+ if PAGE_NO == 1:
+ COUNT = STATUS_LIMIT * (pages - 1)
+ PAGE_NO = pages
+ else:
+ COUNT -= STATUS_LIMIT
+ PAGE_NO -= 1
+ message_utils.update_all_messages()
+
+
+def check_limit(size, limit, tar_unzip_limit=None, is_tar_ext=False):
+ LOGGER.info(f"Checking File/Folder Size...")
+ if is_tar_ext and tar_unzip_limit is not None:
+ limit = tar_unzip_limit
+ if limit is not None:
+ limit = limit.split(' ', maxsplit=1)
+ limitint = int(limit[0])
+ if 'G' in limit[1] or 'g' in limit[1]:
+ if size > limitint * 1024**3:
+ return True
+ elif 'T' in limit[1] or 't' in limit[1]:
+ if size > limitint * 1024**4:
+ return True
+
+def get_readable_time(seconds: int) -> str:
+ result = ''
+ (days, remainder) = divmod(seconds, 86400)
+ days = int(days)
+ if days != 0:
+ result += f'{days}d'
+ (hours, remainder) = divmod(remainder, 3600)
+ hours = int(hours)
+ if hours != 0:
+ result += f'{hours}h'
+ (minutes, seconds) = divmod(remainder, 60)
+ minutes = int(minutes)
+ if minutes != 0:
+ result += f'{minutes}m'
+ seconds = int(seconds)
+ result += f'{seconds}s'
+ return result
+
+
+def is_url(url: str):
+ url = re.findall(URL_REGEX, url)
+ if url:
+ return True
+ return False
+
+
+def is_gdrive_link(url: str):
+ return "drive.google.com" in url
+
+
+def is_mega_link(url: str):
+ return "mega.nz" in url or "mega.co.nz" in url
+
+
+def get_mega_link_type(url: str):
+ if "folder" in url:
+ return "folder"
+ elif "file" in url:
+ return "file"
+ elif "/#F!" in url:
+ return "folder"
+ return "file"
+
+
+def is_magnet(url: str):
+ magnet = re.findall(MAGNET_REGEX, url)
+ if magnet:
+ return True
+ return False
+
+
+def new_thread(fn):
+ """To use as decorator to make a function call threaded.
+ Needs import
+ from threading import Thread"""
+
+ def wrapper(*args, **kwargs):
+ thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
+ thread.start()
+ return thread
+
+ return wrapper
+
+
+next_handler = CallbackQueryHandler(flip, pattern="nex", run_async=True)
+previous_handler = CallbackQueryHandler(flip, pattern="pre", run_async=True)
+dispatcher.add_handler(next_handler)
+dispatcher.add_handler(previous_handler)
diff --git a/bot/helper/ext_utils/db_handler.py b/bot/helper/ext_utils/db_handler.py
new file mode 100644
index 0000000..2273942
--- /dev/null
+++ b/bot/helper/ext_utils/db_handler.py
@@ -0,0 +1,75 @@
+import psycopg2
+from psycopg2 import Error
+from bot import AUTHORIZED_CHATS, SUDO_USERS, DB_URI, LOGGER
+
+class DbManger:
+ def __init__(self):
+ self.err = False
+
+ def connect(self):
+ try:
+ self.conn = psycopg2.connect(DB_URI)
+ self.cur = self.conn.cursor()
+ except psycopg2.DatabaseError as error :
+ LOGGER.error("Error in dbMang : ", error)
+ self.err = True
+
+ def disconnect(self):
+ self.cur.close()
+ self.conn.close()
+
+ def db_auth(self,chat_id: int):
+ self.connect()
+ if self.err :
+ return "There's some error check log for details"
+ else:
+ sql = 'INSERT INTO users VALUES ({});'.format(chat_id)
+ self.cur.execute(sql)
+ self.conn.commit()
+ self.disconnect()
+ AUTHORIZED_CHATS.add(chat_id)
+ return 'Authorized successfully'
+
+ def db_unauth(self,chat_id: int):
+ self.connect()
+ if self.err :
+ return "There's some error check log for details"
+ else:
+ sql = 'DELETE from users where uid = {};'.format(chat_id)
+ self.cur.execute(sql)
+ self.conn.commit()
+ self.disconnect()
+ AUTHORIZED_CHATS.remove(chat_id)
+ return 'Unauthorized successfully'
+
+ def db_addsudo(self,chat_id: int):
+ self.connect()
+ if self.err :
+ return "There's some error check log for details"
+ else:
+ if chat_id in AUTHORIZED_CHATS:
+ sql = 'UPDATE users SET sudo = TRUE where uid = {};'.format(chat_id)
+ self.cur.execute(sql)
+ self.conn.commit()
+ self.disconnect()
+ SUDO_USERS.add(chat_id)
+ return 'Successfully promoted as Sudo'
+ else:
+ sql = 'INSERT INTO users VALUES ({},TRUE);'.format(chat_id)
+ self.cur.execute(sql)
+ self.conn.commit()
+ self.disconnect()
+ SUDO_USERS.add(chat_id)
+ return 'Successfully Authorized and promoted as Sudo'
+
+ def db_rmsudo(self,chat_id: int):
+ self.connect()
+ if self.err :
+ return "There's some error check log for details"
+ else:
+ sql = 'UPDATE users SET sudo = FALSE where uid = {};'.format(chat_id)
+ self.cur.execute(sql)
+ self.conn.commit()
+ self.disconnect()
+ SUDO_USERS.remove(chat_id)
+ return 'Successfully removed from Sudo'
diff --git a/bot/helper/ext_utils/exceptions.py b/bot/helper/ext_utils/exceptions.py
new file mode 100644
index 0000000..a2f600c
--- /dev/null
+++ b/bot/helper/ext_utils/exceptions.py
@@ -0,0 +1,8 @@
+class DirectDownloadLinkException(Exception):
+ """Not method found for extracting direct download link from the http link"""
+ pass
+
+
+class NotSupportedExtractionArchive(Exception):
+ """The archive format use is trying to extract is not supported"""
+ pass
diff --git a/bot/helper/ext_utils/fs_utils.py b/bot/helper/ext_utils/fs_utils.py
new file mode 100644
index 0000000..a7e1a4b
--- /dev/null
+++ b/bot/helper/ext_utils/fs_utils.py
@@ -0,0 +1,156 @@
+import sys
+from bot import aria2, LOGGER, DOWNLOAD_DIR, get_client
+import shutil
+import os
+import pathlib
+import magic
+import tarfile
+from .exceptions import NotSupportedExtractionArchive
+
+
+def clean_download(path: str):
+ if os.path.exists(path):
+ LOGGER.info(f"Cleaning download: {path}")
+ shutil.rmtree(path)
+
+
+def start_cleanup():
+ try:
+ shutil.rmtree(DOWNLOAD_DIR)
+ except FileNotFoundError:
+ pass
+
+
+def clean_all():
+ aria2.remove_all(True)
+ get_client().torrents_delete(torrent_hashes="all", delete_files=True)
+ try:
+ shutil.rmtree(DOWNLOAD_DIR)
+ except FileNotFoundError:
+ pass
+
+
+def exit_clean_up(signal, frame):
+ try:
+ LOGGER.info("Please wait, while we clean up the downloads and stop running downloads")
+ clean_all()
+ sys.exit(0)
+ except KeyboardInterrupt:
+ LOGGER.warning("Force Exiting before the cleanup finishes!")
+ sys.exit(1)
+
+
+def get_path_size(path):
+ if os.path.isfile(path):
+ return os.path.getsize(path)
+ total_size = 0
+ for root, dirs, files in os.walk(path):
+ for f in files:
+ abs_path = os.path.join(root, f)
+ total_size += os.path.getsize(abs_path)
+ return total_size
+
+
+def tar(org_path):
+ tar_path = org_path + ".tar"
+ #path = pathlib.PurePath(org_path)
+ LOGGER.info(f'Tar: orig_path: {org_path}, tar_path: {tar_path}')
+ tar = tarfile.open(tar_path, "w")
+ tar.add(org_path, arcname=os.path.basename(org_path))
+ tar.close()
+ return tar_path
+
+
+def zip(name, path):
+ root_dir = os.path.dirname(path)
+ base_dir = os.path.basename(path.strip(os.sep))
+ zip_file = shutil.make_archive(name, "zip", root_dir, base_dir)
+ zip_path = shutil.move(zip_file, root_dir)
+ LOGGER.info(f"Zip: {zip_path}")
+ return zip_path
+
+
+def get_base_name(orig_path: str):
+ if orig_path.endswith(".tar.bz2"):
+ return orig_path.replace(".tar.bz2", "")
+ elif orig_path.endswith(".tar.gz"):
+ return orig_path.replace(".tar.gz", "")
+ elif orig_path.endswith(".bz2"):
+ return orig_path.replace(".bz2", "")
+ elif orig_path.endswith(".gz"):
+ return orig_path.replace(".gz", "")
+ elif orig_path.endswith(".tar.xz"):
+ return orig_path.replace(".tar.xz", "")
+ elif orig_path.endswith(".tar"):
+ return orig_path.replace(".tar", "")
+ elif orig_path.endswith(".tbz2"):
+ return orig_path.replace("tbz2", "")
+ elif orig_path.endswith(".tgz"):
+ return orig_path.replace(".tgz", "")
+ elif orig_path.endswith(".zip"):
+ return orig_path.replace(".zip", "")
+ elif orig_path.endswith(".7z"):
+ return orig_path.replace(".7z", "")
+ elif orig_path.endswith(".Z"):
+ return orig_path.replace(".Z", "")
+ elif orig_path.endswith(".rar"):
+ return orig_path.replace(".rar", "")
+ elif orig_path.endswith(".iso"):
+ return orig_path.replace(".iso", "")
+ elif orig_path.endswith(".wim"):
+ return orig_path.replace(".wim", "")
+ elif orig_path.endswith(".cab"):
+ return orig_path.replace(".cab", "")
+ elif orig_path.endswith(".apm"):
+ return orig_path.replace(".apm", "")
+ elif orig_path.endswith(".arj"):
+ return orig_path.replace(".arj", "")
+ elif orig_path.endswith(".chm"):
+ return orig_path.replace(".chm", "")
+ elif orig_path.endswith(".cpio"):
+ return orig_path.replace(".cpio", "")
+ elif orig_path.endswith(".cramfs"):
+ return orig_path.replace(".cramfs", "")
+ elif orig_path.endswith(".deb"):
+ return orig_path.replace(".deb", "")
+ elif orig_path.endswith(".dmg"):
+ return orig_path.replace(".dmg", "")
+ elif orig_path.endswith(".fat"):
+ return orig_path.replace(".fat", "")
+ elif orig_path.endswith(".hfs"):
+ return orig_path.replace(".hfs", "")
+ elif orig_path.endswith(".lzh"):
+ return orig_path.replace(".lzh", "")
+ elif orig_path.endswith(".lzma"):
+ return orig_path.replace(".lzma", "")
+ elif orig_path.endswith(".lzma2"):
+ return orig_path.replace(".lzma2", "")
+ elif orig_path.endswith(".mbr"):
+ return orig_path.replace(".mbr", "")
+ elif orig_path.endswith(".msi"):
+ return orig_path.replace(".msi", "")
+ elif orig_path.endswith(".mslz"):
+ return orig_path.replace(".mslz", "")
+ elif orig_path.endswith(".nsis"):
+ return orig_path.replace(".nsis", "")
+ elif orig_path.endswith(".ntfs"):
+ return orig_path.replace(".ntfs", "")
+ elif orig_path.endswith(".rpm"):
+ return orig_path.replace(".rpm", "")
+ elif orig_path.endswith(".squashfs"):
+ return orig_path.replace(".squashfs", "")
+ elif orig_path.endswith(".udf"):
+ return orig_path.replace(".udf", "")
+ elif orig_path.endswith(".vhd"):
+ return orig_path.replace(".vhd", "")
+ elif orig_path.endswith(".xar"):
+ return orig_path.replace(".xar", "")
+ else:
+ raise NotSupportedExtractionArchive('File format not supported for extraction')
+
+
+def get_mime_type(file_path):
+ mime = magic.Magic(mime=True)
+ mime_type = mime.from_file(file_path)
+ mime_type = mime_type if mime_type else "text/plain"
+ return mime_type
diff --git a/bot/helper/mirror_utils/__init__.py b/bot/helper/mirror_utils/__init__.py
new file mode 100644
index 0000000..bba8f51
--- /dev/null
+++ b/bot/helper/mirror_utils/__init__.py
@@ -0,0 +1 @@
+#TEKEAYUSH
\ No newline at end of file
diff --git a/bot/helper/mirror_utils/download_utils/__init__.py b/bot/helper/mirror_utils/download_utils/__init__.py
new file mode 100644
index 0000000..bba8f51
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/__init__.py
@@ -0,0 +1 @@
+#TEKEAYUSH
\ No newline at end of file
diff --git a/bot/helper/mirror_utils/download_utils/aria2_download.py b/bot/helper/mirror_utils/download_utils/aria2_download.py
new file mode 100644
index 0000000..a66a0f6
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/aria2_download.py
@@ -0,0 +1,106 @@
+from bot import aria2, download_dict_lock, STOP_DUPLICATE, TORRENT_DIRECT_LIMIT, TAR_UNZIP_LIMIT
+from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper
+from bot.helper.ext_utils.bot_utils import *
+from .download_helper import DownloadHelper
+from bot.helper.mirror_utils.status_utils.aria_download_status import AriaDownloadStatus
+from bot.helper.telegram_helper.message_utils import *
+import threading
+from aria2p import API
+from time import sleep
+
+
+class AriaDownloadHelper(DownloadHelper):
+
+ def __init__(self):
+ super().__init__()
+
+ @new_thread
+ def __onDownloadStarted(self, api, gid):
+ if STOP_DUPLICATE or TORRENT_DIRECT_LIMIT is not None or TAR_UNZIP_LIMIT is not None:
+ sleep(2)
+ dl = getDownloadByGid(gid)
+ download = aria2.get_download(gid)
+ if STOP_DUPLICATE and dl is not None:
+ LOGGER.info(f"Checking File/Folder if already in Drive...")
+ sname = aria2.get_download(gid).name
+ if dl.getListener().isTar:
+ sname = sname + ".tar"
+ if dl.getListener().extract:
+ smsg = None
+ else:
+ gdrive = GoogleDriveHelper(None)
+ smsg, button = gdrive.drive_list(sname)
+ if smsg:
+ dl.getListener().onDownloadError(f'File/Folder already available in Drive.\n\n')
+ aria2.remove([download], force=True)
+ sendMarkup("Here are the search results:", dl.getListener().bot, dl.getListener().update, button)
+ return
+ if (TORRENT_DIRECT_LIMIT is not None or TAR_UNZIP_LIMIT is not None) and dl is not None:
+ size = aria2.get_download(gid).total_length
+ if dl.getListener().isTar or dl.getListener().extract:
+ is_tar_ext = True
+ mssg = f'Tar/Unzip limit is {TAR_UNZIP_LIMIT}'
+ else:
+ is_tar_ext = False
+ mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}'
+ result = check_limit(size, TORRENT_DIRECT_LIMIT, TAR_UNZIP_LIMIT, is_tar_ext)
+ if result:
+ dl.getListener().onDownloadError(f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}')
+ aria2.remove([download], force=True)
+ return
+ update_all_messages()
+
+ def __onDownloadComplete(self, api: API, gid):
+ dl = getDownloadByGid(gid)
+ download = aria2.get_download(gid)
+ if download.followed_by_ids:
+ new_gid = download.followed_by_ids[0]
+ new_download = aria2.get_download(new_gid)
+ if dl is None:
+ dl = getDownloadByGid(new_gid)
+ with download_dict_lock:
+ download_dict[dl.uid()] = AriaDownloadStatus(new_gid, dl.getListener())
+ if new_download.is_torrent:
+ download_dict[dl.uid()].is_torrent = True
+ update_all_messages()
+ LOGGER.info(f'Changed gid from {gid} to {new_gid}')
+ else:
+ if dl:
+ threading.Thread(target=dl.getListener().onDownloadComplete).start()
+
+ @new_thread
+ def __onDownloadStopped(self, api, gid):
+ sleep(4)
+ dl = getDownloadByGid(gid)
+ if dl:
+ dl.getListener().onDownloadError('★ 𝗠𝗔𝗚𝗡𝗘𝗧/𝗧𝗢𝗥𝗥𝗘𝗡𝗧 𝗟𝗜𝗡𝗞 𝗜𝗦 𝗗𝗘𝗔𝗗 ❌ ★')
+
+ @new_thread
+ def __onDownloadError(self, api, gid):
+ LOGGER.info(f"onDownloadError: {gid}")
+ sleep(0.5) # sleep for split second to ensure proper dl gid update from onDownloadComplete
+ dl = getDownloadByGid(gid)
+ download = aria2.get_download(gid)
+ error = download.error_message
+ LOGGER.info(f"Download Error: {error}")
+ if dl:
+ dl.getListener().onDownloadError(error)
+
+ def start_listener(self):
+ aria2.listen_to_notifications(threaded=True, on_download_start=self.__onDownloadStarted,
+ on_download_error=self.__onDownloadError,
+ on_download_stop=self.__onDownloadStopped,
+ on_download_complete=self.__onDownloadComplete,
+ timeout=1)
+
+ def add_download(self, link: str, path, listener, filename):
+ if is_magnet(link):
+ download = aria2.add_magnet(link, {'dir': path, 'out': filename})
+ else:
+ download = aria2.add_uris([link], {'dir': path, 'out': filename})
+ if download.error_message: # no need to proceed further at this point
+ listener.onDownloadError(download.error_message)
+ return
+ with download_dict_lock:
+ download_dict[listener.uid] = AriaDownloadStatus(download.gid, listener)
+ LOGGER.info(f"Started: {download.gid} DIR:{download.dir} ")
diff --git a/bot/helper/mirror_utils/download_utils/direct_link_generator.py b/bot/helper/mirror_utils/download_utils/direct_link_generator.py
new file mode 100644
index 0000000..04a1f89
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/direct_link_generator.py
@@ -0,0 +1,416 @@
+# Copyright (C) 2019 The Raphielscape Company LLC.
+#
+# Licensed under the Raphielscape Public License, Version 1.c (the "License");
+# you may not use this file except in compliance with the License.
+#
+""" Helper Module containing various sites direct links generators. This module is copied and modified as per need
+from https://github.com/AvinashReddy3108/PaperplaneExtended . I hereby take no credit of the following code other
+than the modifications. See https://github.com/AvinashReddy3108/PaperplaneExtended/commits/master/userbot/modules/direct_links.py
+for original authorship. """
+
+from bot import LOGGER, UPTOBOX_TOKEN
+import json
+import math
+import re
+import urllib.parse
+from os import popen
+from random import choice
+from urllib.parse import urlparse
+
+import lk21
+import requests, cfscrape
+from bs4 import BeautifulSoup
+from js2py import EvalJs
+from lk21.extractors.bypasser import Bypass
+from base64 import standard_b64encode
+from bot.helper.telegram_helper.bot_commands import BotCommands
+from bot.helper.ext_utils.exceptions import DirectDownloadLinkException
+
+
+def direct_link_generator(link: str):
+ """ direct links generator """
+ if not link:
+ raise DirectDownloadLinkException("No links found!")
+ elif 'youtube.com' in link or 'youtu.be' in link:
+ raise DirectDownloadLinkException(f"Use /{BotCommands.WatchCommand} to mirror Youtube link\nUse /{BotCommands.TarWatchCommand} to make tar of Youtube playlist")
+ elif 'zippyshare.com' in link:
+ return zippy_share(link)
+ elif 'yadi.sk' in link:
+ return yandex_disk(link)
+ elif 'mediafire.com' in link:
+ return mediafire(link)
+ elif 'uptobox.com' in link:
+ return uptobox(link)
+ elif 'osdn.net' in link:
+ return osdn(link)
+ elif 'github.com' in link:
+ return github(link)
+ elif 'hxfile.co' in link:
+ return hxfile(link)
+ elif 'anonfiles.com' in link:
+ return anonfiles(link)
+ elif 'letsupload.io' in link:
+ return letsupload(link)
+ elif 'fembed.net' in link:
+ return fembed(link)
+ elif 'fembed.com' in link:
+ return fembed(link)
+ elif 'femax20.com' in link:
+ return fembed(link)
+ elif 'fcdn.stream' in link:
+ return fembed(link)
+ elif 'feurl.com' in link:
+ return fembed(link)
+ elif 'naniplay.nanime.in' in link:
+ return fembed(link)
+ elif 'naniplay.nanime.biz' in link:
+ return fembed(link)
+ elif 'naniplay.com' in link:
+ return fembed(link)
+ elif 'layarkacaxxi.icu' in link:
+ return fembed(link)
+ elif 'sbembed.com' in link:
+ return sbembed(link)
+ elif 'streamsb.net' in link:
+ return sbembed(link)
+ elif 'sbplay.org' in link:
+ return sbembed(link)
+ elif '1drv.ms' in link:
+ return onedrive(link)
+ elif 'pixeldrain.com' in link:
+ return pixeldrain(link)
+ elif 'antfiles.com' in link:
+ return antfiles(link)
+ elif 'streamtape.com' in link:
+ return streamtape(link)
+ elif 'bayfiles.com' in link:
+ return anonfiles(link)
+ elif 'racaty.net' in link:
+ return racaty(link)
+ elif '1fichier.com' in link:
+ return fichier(link)
+ elif 'solidfiles.com' in link:
+ return solidfiles(link)
+ else:
+ raise DirectDownloadLinkException(f'No Direct link function found for {link}')
+
+
+def zippy_share(url: str) -> str:
+ """ ZippyShare direct links generator
+ Based on https://github.com/KenHV/Mirror-Bot
+ https://github.com/jovanzers/WinTenCermin """
+ try:
+ link = re.findall(r'\bhttps?://.*zippyshare\.com\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No Zippyshare links found")
+ try:
+ base_url = re.search('http.+.zippyshare.com', link).group()
+ response = requests.get(link).content
+ pages = BeautifulSoup(response, "lxml")
+ try:
+ js_script = pages.find("div", {"class": "center"}).find_all("script")[1]
+ except IndexError:
+ js_script = pages.find("div", {"class": "right"}).find_all("script")[0]
+ js_content = re.findall(r'\.href.=."/(.*?)";', str(js_script))
+ js_content = 'var x = "/' + js_content[0] + '"'
+ evaljs = EvalJs()
+ setattr(evaljs, "x", None)
+ evaljs.execute(js_content)
+ js_content = getattr(evaljs, "x")
+ return base_url + js_content
+ except IndexError:
+ raise DirectDownloadLinkException("ERROR: Can't find download button")
+
+
+def yandex_disk(url: str) -> str:
+ """ Yandex.Disk direct links generator
+ Based on https://github.com/wldhx/yadisk-direct """
+ try:
+ link = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0]
+ except IndexError:
+ reply = "No Yandex.Disk links found\n"
+ return reply
+ api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
+ try:
+ dl_url = requests.get(api.format(link)).json()['href']
+ return dl_url
+ except KeyError:
+ raise DirectDownloadLinkException("ERROR: File not found/Download limit reached\n")
+
+
+def uptobox(url: str) -> str:
+ """ Uptobox direct links generator
+ based on https://github.com/jovanzers/WinTenCermin """
+ try:
+ link = re.findall(r'\bhttps?://.*uptobox\.com\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No Uptobox links found\n")
+ if UPTOBOX_TOKEN is None:
+ LOGGER.error('UPTOBOX_TOKEN not provided!')
+ dl_url = link
+ else:
+ try:
+ link = re.findall(r'\bhttp?://.*uptobox\.com/dl\S+', url)[0]
+ dl_url = link
+ except:
+ file_id = re.findall(r'\bhttps?://.*uptobox\.com/(\w+)', url)[0]
+ file_link = 'https://uptobox.com/api/link?token=%s&file_code=%s' % (UPTOBOX_TOKEN, file_id)
+ req = requests.get(file_link)
+ result = req.json()
+ dl_url = result['data']['dlLink']
+ return dl_url
+
+
+def mediafire(url: str) -> str:
+ """ MediaFire direct links generator """
+ try:
+ link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No MediaFire links found\n")
+ page = BeautifulSoup(requests.get(link).content, 'lxml')
+ info = page.find('a', {'aria-label': 'Download file'})
+ dl_url = info.get('href')
+ return dl_url
+
+
+def osdn(url: str) -> str:
+ """ OSDN direct links generator """
+ osdn_link = 'https://osdn.net'
+ try:
+ link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No OSDN links found\n")
+ page = BeautifulSoup(
+ requests.get(link, allow_redirects=True).content, 'lxml')
+ info = page.find('a', {'class': 'mirror_link'})
+ link = urllib.parse.unquote(osdn_link + info['href'])
+ mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr')
+ urls = []
+ for data in mirrors[1:]:
+ mirror = data.find('input')['value']
+ urls.append(re.sub(r'm=(.*)&f', f'm={mirror}&f', link))
+ return urls[0]
+
+
+def github(url: str) -> str:
+ """ GitHub direct links generator """
+ try:
+ re.findall(r'\bhttps?://.*github\.com.*releases\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No GitHub Releases links found\n")
+ download = requests.get(url, stream=True, allow_redirects=False)
+ try:
+ dl_url = download.headers["location"]
+ return dl_url
+ except KeyError:
+ raise DirectDownloadLinkException("ERROR: Can't extract the link\n")
+
+
+def hxfile(url: str) -> str:
+ """ Hxfile direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_filesIm(url)
+ return dl_url
+
+
+def anonfiles(url: str) -> str:
+ """ Anonfiles direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_anonfiles(url)
+ return dl_url
+
+
+def letsupload(url: str) -> str:
+ """ Letsupload direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ dl_url = ''
+ try:
+ link = re.findall(r'\bhttps?://.*letsupload\.io\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No Letsupload links found\n")
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_url(link)
+ return dl_url
+
+
+def fembed(link: str) -> str:
+ """ Fembed direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_fembed(link)
+ lst_link = []
+ count = len(dl_url)
+ for i in dl_url:
+ lst_link.append(dl_url[i])
+ return lst_link[count-1]
+
+
+def sbembed(link: str) -> str:
+ """ Sbembed direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_sbembed(link)
+ lst_link = []
+ count = len(dl_url)
+ for i in dl_url:
+ lst_link.append(dl_url[i])
+ return lst_link[count-1]
+
+
+def onedrive(link: str) -> str:
+ """ Onedrive direct link generator
+ Based on https://github.com/UsergeTeam/Userge """
+ link_without_query = urlparse(link)._replace(query=None).geturl()
+ direct_link_encoded = str(standard_b64encode(bytes(link_without_query, "utf-8")), "utf-8")
+ direct_link1 = f"https://api.onedrive.com/v1.0/shares/u!{direct_link_encoded}/root/content"
+ resp = requests.head(direct_link1)
+ if resp.status_code != 302:
+ return "ERROR: Unauthorized link, the link may be private"
+ dl_link = resp.next.url
+ file_name = dl_link.rsplit("/", 1)[1]
+ resp2 = requests.head(dl_link)
+ return dl_link
+
+
+def pixeldrain(url: str) -> str:
+ """ Based on https://github.com/yash-dk/TorToolkit-Telegram """
+ url = url.strip("/ ")
+ file_id = url.split("/")[-1]
+ info_link = f"https://pixeldrain.com/api/file/{file_id}/info"
+ dl_link = f"https://pixeldrain.com/api/file/{file_id}"
+ resp = requests.get(info_link).json()
+ if resp["success"]:
+ return dl_link
+ else:
+ raise DirectDownloadLinkException("ERROR: Cant't download due {}.".format(resp.text["value"]))
+
+
+def antfiles(url: str) -> str:
+ """ Antfiles direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_antfiles(url)
+ return dl_url
+
+
+def streamtape(url: str) -> str:
+ """ Streamtape direct link generator
+ Based on https://github.com/zevtyardt/lk21
+ https://github.com/breakdowns/slam-mirrorbot """
+ bypasser = lk21.Bypass()
+ dl_url=bypasser.bypass_streamtape(url)
+ return dl_url
+
+
+def racaty(url: str) -> str:
+ """ Racaty direct links generator
+ based on https://github.com/breakdowns/slam-mirrorbot """
+ dl_url = ''
+ try:
+ link = re.findall(r'\bhttps?://.*racaty\.net\S+', url)[0]
+ except IndexError:
+ raise DirectDownloadLinkException("No Racaty links found\n")
+ scraper = cfscrape.create_scraper()
+ r = scraper.get(url)
+ soup = BeautifulSoup(r.text, "lxml")
+ op = soup.find("input", {"name": "op"})["value"]
+ ids = soup.find("input", {"name": "id"})["value"]
+ rpost = scraper.post(url, data = {"op": op, "id": ids})
+ rsoup = BeautifulSoup(rpost.text, "lxml")
+ dl_url = rsoup.find("a", {"id": "uniqueExpirylink"})["href"].replace(" ", "%20")
+ return dl_url
+
+
+def fichier(link: str) -> str:
+ """ 1Fichier direct links generator
+ Based on https://github.com/Maujar
+ https://github.com/breakdowns/slam-mirrorbot """
+ regex = r"^([http:\/\/|https:\/\/]+)?.*1fichier\.com\/\?.+"
+ gan = re.match(regex, link)
+ if not gan:
+ raise DirectDownloadLinkException("ERROR: The link you entered is wrong!")
+ if "::" in link:
+ pswd = link.split("::")[-1]
+ url = link.split("::")[-2]
+ else:
+ pswd = None
+ url = link
+ try:
+ if pswd is None:
+ req = requests.post(url)
+ else:
+ pw = {"pass": pswd}
+ req = requests.post(url, data=pe)
+ except:
+ raise DirectDownloadLinkException("ERROR: Unable to reach 1fichier server!")
+ if req.status_code == 404:
+ raise DirectDownloadLinkException("ERROR: File not found/The link you entered is wrong!")
+ soup = BeautifulSoup(req.content, 'lxml')
+ if soup.find("a", {"class": "ok btn-general btn-orange"}) is not None:
+ dl_url = soup.find("a", {"class": "ok btn-general btn-orange"})["href"]
+ if dl_url is None:
+ raise DirectDownloadLinkException("ERROR: Unable to generate Direct Link 1fichier!")
+ else:
+ return dl_url
+ else:
+ if len(soup.find_all("div", {"class": "ct_warn"})) == 2:
+ str_2 = soup.find_all("div", {"class": "ct_warn"})[-1]
+ if "you must wait" in str(str_2).lower():
+ numbers = [int(word) for word in str(str_2).split() if word.isdigit()]
+ if len(numbers) == 0:
+ raise DirectDownloadLinkException("ERROR: 1fichier is on a limit. Please wait a few minutes/hour.")
+ else:
+ raise DirectDownloadLinkException(f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute.")
+ elif "protect access" in str(str_2).lower():
+ raise DirectDownloadLinkException("ERROR: This link requires a password!\n\nThis link requires a password!\n- Insert sign :: after the link and write the password after the sign.\n\nExample:\n/mirror https://1fichier.com/?smmtd8twfpm66awbqz04::love you\n\n* No spaces between the signs ::\n* For the password, you can use a space!")
+ else:
+ raise DirectDownloadLinkException("ERROR: Error trying to generate Direct Link from 1fichier!")
+ elif len(soup.find_all("div", {"class": "ct_warn"})) == 3:
+ str_1 = soup.find_all("div", {"class": "ct_warn"})[-2]
+ str_3 = soup.find_all("div", {"class": "ct_warn"})[-1]
+ if "you must wait" in str(str_1).lower():
+ numbers = [int(word) for word in str(str_1).split() if word.isdigit()]
+ if len(numbers) == 0:
+ raise DirectDownloadLinkException("ERROR: 1fichier is on a limit. Please wait a few minutes/hour.")
+ else:
+ raise DirectDownloadLinkException(f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute.")
+ elif "bad password" in str(str_3).lower():
+ raise DirectDownloadLinkException("ERROR: The password you entered is wrong!")
+ else:
+ raise DirectDownloadLinkException("ERROR: Error trying to generate Direct Link from 1fichier!")
+ else:
+ raise DirectDownloadLinkException("ERROR: Error trying to generate Direct Link from 1fichier!")
+
+
+def solidfiles(url: str) -> str:
+ """ Solidfiles direct links generator
+ Based on https://github.com/Xonshiz/SolidFiles-Downloader
+ By https://github.com/Jusidama18 """
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'
+ }
+ pageSource = requests.get(url, headers = headers).text
+ mainOptions = str(re.search(r'viewerOptions\'\,\ (.*?)\)\;', pageSource).group(1))
+ dl_url = json.loads(mainOptions)["downloadUrl"]
+ return dl_url
+
+
+def useragent():
+ """
+ useragent random setter
+ """
+ useragents = BeautifulSoup(
+ requests.get(
+ 'https://developers.whatismybrowser.com/'
+ 'useragents/explore/operating_system_name/android/').content,
+ 'lxml').findAll('td', {'class': 'useragent'})
+ user_agent = choice(useragents)
+ return user_agent.text
diff --git a/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md b/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md
new file mode 100644
index 0000000..c37c0d9
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/direct_link_generator_license.md
@@ -0,0 +1,82 @@
+ RAPHIELSCAPE PUBLIC LICENSE
+ Version 1.c, June 2019
+
+ Copyright (C) 2019 Raphielscape LLC.
+ Copyright (C) 2019 Devscapes Open Source Holding GmbH.
+
+ Everyone is permitted to copy and distribute verbatim or modified
+ copies of this license document, and changing it is allowed as long
+ as the name is changed.
+
+ RAPHIELSCAPE PUBLIC LICENSE
+ A-1. DEFINITIONS
+
+0. “This License” refers to version 1.c of the Raphielscape Public License.
+
+1. “Copyright” also means copyright-like laws that apply to other kinds of works.
+
+2. “The Work" refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”.
+ “Licensees” and “recipients” may be individuals or organizations.
+
+3. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission,
+ other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work
+ or a work “based on” the earlier work.
+
+4. Source Form. The “source form” for a work means the preferred form of the work for making modifications to it.
+ “Object code” means any non-source form of a work.
+
+ The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and
+ (for an executable work) run the object code and to modify the work, including scripts to control those activities.
+
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+ The Corresponding Source for a work in source code form is that same work.
+
+5. "The author" refers to "author" of the code, which is the one that made the particular code which exists inside of
+ the Corresponding Source.
+
+6. "Owner" refers to any parties which is made the early form of the Corresponding Source.
+
+ A-2. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+1. You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+2. You must retain, in the Source form of any Derivative Works that You distribute,
+ this license, all copyright, patent, trademark, authorships and attribution notices
+ from the Source form of the Work; and
+
+3. Respecting the author and owner of works that are distributed in any way.
+
+ You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction,
+or distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+ B. DISCLAIMER OF WARRANTY
+
+ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+ C. REVISED VERSION OF THIS LICENSE
+
+ The Devscapes Open Source Holding GmbH. may publish revised and/or new versions of the
+Raphielscape Public License from time to time. Such new versions will be similar in spirit
+to the present version, but may differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the Program specifies that a
+certain numbered version of the Raphielscape Public License "or any later version" applies to it,
+you have the option of following the terms and conditions either of that numbered version or of
+any later version published by the Devscapes Open Source Holding GmbH. If the Program does not specify a
+version number of the Raphielscape Public License, you may choose any version ever published
+by the Devscapes Open Source Holding GmbH.
+
+ END OF LICENSE
\ No newline at end of file
diff --git a/bot/helper/mirror_utils/download_utils/download_helper.py b/bot/helper/mirror_utils/download_utils/download_helper.py
new file mode 100644
index 0000000..ebcca14
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/download_helper.py
@@ -0,0 +1,27 @@
+# An abstract class which will be inherited by the tool specific classes like aria2_helper or mega_download_helper
+import threading
+
+
+class MethodNotImplementedError(NotImplementedError):
+ def __init__(self):
+ super(self, 'Not implemented method')
+
+
+class DownloadHelper:
+ def __init__(self):
+ self.name = '' # Name of the download; empty string if no download has been started
+ self.size = 0.0 # Size of the download
+ self.downloaded_bytes = 0.0 # Bytes downloaded
+ self.speed = 0.0 # Download speed in bytes per second
+ self.progress = 0.0
+ self.progress_string = '0.00%'
+ self.eta = 0 # Estimated time of download complete
+ self.eta_string = '0s' # A listener class which have event callbacks
+ self._resource_lock = threading.Lock()
+
+ def add_download(self, link: str, path):
+ raise MethodNotImplementedError
+
+ def cancel_download(self):
+ # Returns None if successfully cancelled, else error string
+ raise MethodNotImplementedError
diff --git a/bot/helper/mirror_utils/download_utils/mega_downloader.py b/bot/helper/mirror_utils/download_utils/mega_downloader.py
new file mode 100644
index 0000000..0d0b474
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/mega_downloader.py
@@ -0,0 +1,201 @@
+from bot import LOGGER, MEGA_API_KEY, download_dict_lock, download_dict, MEGA_EMAIL_ID, MEGA_PASSWORD
+import threading
+from mega import (MegaApi, MegaListener, MegaRequest, MegaTransfer, MegaError)
+from bot.helper.telegram_helper.message_utils import *
+import os
+from bot.helper.ext_utils.bot_utils import new_thread, get_mega_link_type, get_readable_file_size, check_limit
+from bot.helper.mirror_utils.status_utils.mega_download_status import MegaDownloadStatus
+from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper
+from bot import MEGA_LIMIT, STOP_DUPLICATE, TAR_UNZIP_LIMIT
+import random
+import string
+
+class MegaDownloaderException(Exception):
+ pass
+
+
+class MegaAppListener(MegaListener):
+ _NO_EVENT_ON = (MegaRequest.TYPE_LOGIN,MegaRequest.TYPE_FETCH_NODES)
+ NO_ERROR = "no error"
+
+ def __init__(self, continue_event: threading.Event, listener):
+ self.continue_event = continue_event
+ self.node = None
+ self.public_node = None
+ self.listener = listener
+ self.uid = listener.uid
+ self.__bytes_transferred = 0
+ self.is_cancelled = False
+ self.__speed = 0
+ self.__name = ''
+ self.__size = 0
+ self.error = None
+ self.gid = ""
+ super(MegaAppListener, self).__init__()
+
+ @property
+ def speed(self):
+ """Returns speed of the download in bytes/second"""
+ return self.__speed
+
+ @property
+ def name(self):
+ """Returns name of the download"""
+ return self.__name
+
+ def setValues(self, name, size, gid):
+ self.__name = name
+ self.__size = size
+ self.gid = gid
+
+ @property
+ def size(self):
+ """Size of download in bytes"""
+ return self.__size
+
+ @property
+ def downloaded_bytes(self):
+ return self.__bytes_transferred
+
+ def onRequestStart(self, api, request):
+ pass
+
+ def onRequestFinish(self, api, request, error):
+ if str(error).lower() != "no error":
+ self.error = error.copy()
+ return
+ request_type = request.getType()
+ if request_type == MegaRequest.TYPE_LOGIN:
+ api.fetchNodes()
+ elif request_type == MegaRequest.TYPE_GET_PUBLIC_NODE:
+ self.public_node = request.getPublicMegaNode()
+ elif request_type == MegaRequest.TYPE_FETCH_NODES:
+ LOGGER.info("Fetching Root Node.")
+ self.node = api.getRootNode()
+ LOGGER.info(f"Node Name: {self.node.getName()}")
+ if request_type not in self._NO_EVENT_ON or self.node and "cloud drive" not in self.node.getName().lower():
+ self.continue_event.set()
+
+ def onRequestTemporaryError(self, api, request, error: MegaError):
+ LOGGER.info(f'Mega Request error in {error}')
+ if not self.is_cancelled:
+ self.listener.onDownloadError("RequestTempError: " + error.toString())
+ self.is_cancelled = True
+ self.error = error.toString()
+ self.continue_event.set()
+
+ def onTransferStart(self, api: MegaApi, transfer: MegaTransfer):
+ pass
+
+ def onTransferUpdate(self, api: MegaApi, transfer: MegaTransfer):
+ if self.is_cancelled:
+ api.cancelTransfer(transfer, None)
+ self.__speed = transfer.getSpeed()
+ self.__bytes_transferred = transfer.getTransferredBytes()
+
+ def onTransferFinish(self, api: MegaApi, transfer: MegaTransfer, error):
+ try:
+ if transfer.isFolderTransfer() and transfer.isFinished() or transfer.getFileName() == self.name and not self.is_cancelled:
+ self.listener.onDownloadComplete()
+ self.continue_event.set()
+ except Exception as e:
+ LOGGER.error(e)
+
+ def onTransferTemporaryError(self, api, transfer, error):
+ filen = transfer.getFileName()
+ state = transfer.getState()
+ errStr = error.toString()
+ LOGGER.info(f'Mega download error in file {transfer} {filen}: {error}')
+
+ if state == 1 or state == 4:
+ # Sometimes MEGA (offical client) can't stream a node either and raises a temp failed error.
+ # Don't break the transfer queue if transfer's in queued (1) or retrying (4) state [causes seg fault]
+ return
+
+ self.error = errStr
+ if not self.is_cancelled:
+ self.is_cancelled = True
+ self.listener.onDownloadError(f"TransferTempError: {errStr} ({filen})")
+
+ def cancel_download(self):
+ self.is_cancelled = True
+ self.listener.onDownloadError("Download Canceled by user")
+
+
+class AsyncExecutor:
+
+ def __init__(self):
+ self.continue_event = threading.Event()
+
+ def do(self, function, args):
+ self.continue_event.clear()
+ function(*args)
+ self.continue_event.wait()
+
+listeners = []
+
+class MegaDownloadHelper:
+ def __init__(self):
+ pass
+
+ @staticmethod
+ @new_thread
+ def add_download(mega_link: str, path: str, listener):
+ if MEGA_API_KEY is None:
+ raise MegaDownloaderException('Mega API KEY not provided! Cannot mirror Mega links')
+ executor = AsyncExecutor()
+ api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
+ global listeners
+ mega_listener = MegaAppListener(executor.continue_event, listener)
+ listeners.append(mega_listener)
+ api.addListener(mega_listener)
+ if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
+ executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
+ link_type = get_mega_link_type(mega_link)
+ if link_type == "file":
+ LOGGER.info("File. If your download didn't start, then check your link if it's available to download")
+ executor.do(api.getPublicNode, (mega_link,))
+ node = mega_listener.public_node
+ else:
+ LOGGER.info("Folder. If your download didn't start, then check your link if it's available to download")
+ folder_api = MegaApi(MEGA_API_KEY,None,None,'TgBot')
+ folder_api.addListener(mega_listener)
+ executor.do(folder_api.loginToFolder, (mega_link,))
+ node = folder_api.authorizeNode(mega_listener.node)
+ if mega_listener.error is not None:
+ return listener.onDownloadError(str(mega_listener.error))
+ if STOP_DUPLICATE:
+ LOGGER.info(f'Checking File/Folder if already in Drive')
+ mname = node.getName()
+ if listener.isTar:
+ mname = mname + ".tar"
+ if listener.extract:
+ smsg = None
+ else:
+ gd = GoogleDriveHelper()
+ smsg, button = gd.drive_list(mname)
+ if smsg:
+ msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
+ sendMarkup(msg1, listener.bot, listener.update, button)
+ executor.continue_event.set()
+ return
+ if MEGA_LIMIT is not None or TAR_UNZIP_LIMIT is not None:
+ size = api.getSize(node)
+ if listener.isTar or listener.extract:
+ is_tar_ext = True
+ msg3 = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
+ else:
+ is_tar_ext = False
+ msg3 = f'Failed, Mega limit is {MEGA_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
+ result = check_limit(size, MEGA_LIMIT, TAR_UNZIP_LIMIT, is_tar_ext)
+ if result:
+ sendMessage(msg3, listener.bot, listener.update)
+ executor.continue_event.set()
+ return
+ with download_dict_lock:
+ download_dict[listener.uid] = MegaDownloadStatus(mega_listener, listener)
+ os.makedirs(path)
+ gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=8))
+ mega_listener.setValues(node.getName(), api.getSize(node), gid)
+ sendStatusMessage(listener.update, listener.bot)
+ executor.do(api.startDownload,(node,path))
diff --git a/bot/helper/mirror_utils/download_utils/qbit_downloader.py b/bot/helper/mirror_utils/download_utils/qbit_downloader.py
new file mode 100644
index 0000000..5d66ede
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/qbit_downloader.py
@@ -0,0 +1,240 @@
+# Implement By - @anasty17 (https://github.com/breakdowns/slam-mirrorbot/commit/0bfba523f095ab1dccad431d72561e0e002e7a59)
+# (c) https://github.com/breakdowns/slam-mirrorbot
+# All rights reserved
+
+import os
+import random
+import string
+import time
+import logging
+import shutil
+
+import qbittorrentapi as qba
+from fnmatch import fnmatch
+from urllib.parse import urlparse, parse_qs
+from torrentool.api import Torrent
+from telegram import InlineKeyboardMarkup
+from telegram.ext import CallbackQueryHandler
+
+from bot import download_dict, download_dict_lock, BASE_URL, dispatcher, get_client, TORRENT_DIRECT_LIMIT, TAR_UNZIP_LIMIT
+from bot.helper.mirror_utils.status_utils.qbit_download_status import QbDownloadStatus
+from bot.helper.telegram_helper.message_utils import *
+from bot.helper.ext_utils.bot_utils import setInterval, new_thread, MirrorStatus, getDownloadByGid, get_readable_file_size, check_limit
+from bot.helper.telegram_helper import button_build
+
+LOGGER = logging.getLogger(__name__)
+
+
+class qbittorrent:
+
+
+ def __init__(self):
+ self.update_interval = 2
+ self.meta_time = time.time()
+ self.stalled_time = time.time()
+ self.checked = False
+
+ @new_thread
+ def add_torrent(self, link, dire, listener, qbitsel):
+ self.client = get_client()
+ self.listener = listener
+ self.dire = dire
+ self.qbitsel = qbitsel
+ is_file = False
+ count = 0
+ pincode = ""
+ try:
+ if os.path.exists(link):
+ is_file = True
+ self.ext_hash = get_hash_file(link)
+ else:
+ self.ext_hash = get_hash_magnet(link)
+ tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
+ if len(tor_info) > 0:
+ sendMessage("This torrent is already in list.", listener.bot, listener.update)
+ return
+ if is_file:
+ op = self.client.torrents_add(torrent_files=[link], save_path=dire)
+ os.remove(link)
+ else:
+ op = self.client.torrents_add(link, save_path=dire)
+ if op.lower() == "ok.":
+ tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
+ if len(tor_info) == 0:
+ while True:
+ if time.time() - self.meta_time >= 300:
+ sendMessage("The torrent was not added. report when u see this error", listener.bot, listener.update)
+ return False
+ tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
+ if len(tor_info) > 0:
+ break
+ else:
+ sendMessage("This is an unsupported/invalid link.", listener.bot, listener.update)
+ return
+ gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=14))
+ with download_dict_lock:
+ download_dict[listener.uid] = QbDownloadStatus(gid, listener, self.ext_hash, self.client)
+ tor_info = tor_info[0]
+ LOGGER.info(f"QbitDownload started: {tor_info.name}")
+ self.updater = setInterval(self.update_interval, self.update)
+ if BASE_URL is not None and qbitsel:
+ if is_file:
+ self.client.torrents_pause(torrent_hashes=self.ext_hash)
+ else:
+ meta = sendMessage("Downloading Metadata...Please wait then you can select files or mirror torrent file if it have low seeders", listener.bot, listener.update)
+ while True:
+ tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
+ if len(tor_info) == 0:
+ deleteMessage(listener.bot, meta)
+ return False
+ try:
+ tor_info = tor_info[0]
+ if tor_info.state == "metaDL" or tor_info.state == "checkingResumeData":
+ time.sleep(0.5)
+ else:
+ self.client.torrents_pause(torrent_hashes=self.ext_hash)
+ deleteMessage(listener.bot, meta)
+ break
+ except:
+ deleteMessage(listener.bot, meta)
+ return False
+ for n in str(self.ext_hash):
+ if n.isdigit():
+ pincode += str(n)
+ count += 1
+ if count == 4:
+ break
+ URL = f"{BASE_URL}/slam/files/{self.ext_hash}"
+ pindata = f"pin {gid} {pincode}"
+ donedata = f"done {gid} {self.ext_hash}"
+ buttons = button_build.ButtonMaker()
+ buttons.buildbutton("Select Files", URL)
+ buttons.sbutton("Pincode", pindata)
+ buttons.sbutton("Done Selecting", donedata)
+ QBBUTTONS = InlineKeyboardMarkup(buttons.build_menu(2))
+ msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
+ sendMarkup(msg, listener.bot, listener.update, QBBUTTONS)
+ else:
+ sendStatusMessage(listener.update, listener.bot)
+ except qba.UnsupportedMediaType415Error as e:
+ LOGGER.error(str(e))
+ sendMessage("This is an unsupported/invalid link. {str(e)}", listener.bot, listener.update)
+ except Exception as e:
+ LOGGER.error(str(e))
+ sendMessage(str(e), listener.bot, listener.update)
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+
+
+ def update(self):
+ tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
+ if len(tor_info) == 0:
+ self.updater.cancel()
+ return
+ try:
+ tor_info = tor_info[0]
+ if tor_info.state == "metaDL":
+ self.stalled_time = time.time()
+ if time.time() - self.meta_time >= 600:
+ self.listener.onDownloadError("Dead Torrent!")
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+ self.updater.cancel()
+ return
+ elif tor_info.state == "downloading":
+ self.stalled_time = time.time()
+ if (TORRENT_DIRECT_LIMIT is not None or TAR_UNZIP_LIMIT is not None) and not self.checked:
+ if self.listener.isTar or self.listener.extract:
+ is_tar_ext = True
+ mssg = f'Tar/Unzip limit is {TAR_UNZIP_LIMIT}'
+ else:
+ is_tar_ext = False
+ mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}'
+ size = tor_info.size
+ result = check_limit(size, TORRENT_DIRECT_LIMIT, TAR_UNZIP_LIMIT, is_tar_ext)
+ self.checked = True
+ if result:
+ self.listener.onDownloadError(f"{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}")
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+ self.updater.cancel()
+ return
+ elif tor_info.state == "stalledDL":
+ if time.time() - self.stalled_time >= 900:
+ self.listener.onDownloadError("Dead Torrent!")
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+ self.updater.cancel()
+ return
+ elif tor_info.state == "error":
+ self.listener.onDownloadError("Error. IDK why, report in support group")
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+ self.updater.cancel()
+ return
+ elif tor_info.state == "uploading" or tor_info.state.lower().endswith("up"):
+ self.client.torrents_pause(torrent_hashes=self.ext_hash)
+ if self.qbitsel:
+ for dirpath, subdir, files in os.walk(f"{self.dire}", topdown=False):
+ for file in files:
+ if fnmatch(file, "*.!qB"):
+ os.remove(os.path.join(dirpath, file))
+ for folder in subdir:
+ if fnmatch(folder, ".unwanted"):
+ shutil.rmtree(os.path.join(dirpath, folder))
+ if not os.listdir(dirpath):
+ os.rmdir(dirpath)
+ self.listener.onDownloadComplete()
+ self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
+ self.updater.cancel()
+ except:
+ self.updater.cancel()
+
+
+def get_confirm(update, context):
+ query = update.callback_query
+ user_id = query.from_user.id
+ data = query.data
+ data = data.split(" ")
+ qdl = getDownloadByGid(data[1])
+ if qdl is not None:
+ if user_id != qdl.listener.message.from_user.id:
+ query.answer(text="Don't waste your time!", show_alert=True)
+ return
+ if data[0] == "pin":
+ query.answer(text=data[2], show_alert=True)
+ elif data[0] == "done":
+ query.answer()
+ qdl.client.torrents_resume(torrent_hashes=data[2])
+ sendStatusMessage(qdl.listener.update, qdl.listener.bot)
+ query.message.delete()
+ else:
+ query.answer(text="This task has been cancelled!", show_alert=True)
+ query.message.delete()
+
+
+def get_hash_magnet(mgt):
+ if mgt.startswith('magnet:'):
+ _, _, _, _, query, _ = urlparse(mgt)
+
+ qs = parse_qs(query)
+ v = qs.get('xt', None)
+
+ if v == None or v == []:
+ LOGGER.error('Invalid magnet URI: no "xt" query parameter.')
+ return False
+
+ v = v[0]
+ if not v.startswith('urn:btih:'):
+ LOGGER.error('Invalid magnet URI: "xt" value not valid for BitTorrent.')
+ return False
+
+ mgt = v[len('urn:btih:'):]
+ return mgt.lower()
+
+
+def get_hash_file(path):
+ tr = Torrent.from_file(path)
+ mgt = tr.magnet_link
+ return get_hash_magnet(mgt)
+
+
+pin_handler = CallbackQueryHandler(get_confirm, pattern="pin", run_async=True)
+done_handler = CallbackQueryHandler(get_confirm, pattern="done", run_async=True)
+dispatcher.add_handler(pin_handler)
+dispatcher.add_handler(done_handler)
diff --git a/bot/helper/mirror_utils/download_utils/telegram_downloader.py b/bot/helper/mirror_utils/download_utils/telegram_downloader.py
new file mode 100644
index 0000000..5721d00
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/telegram_downloader.py
@@ -0,0 +1,126 @@
+import logging
+import threading
+import time
+from bot import LOGGER, download_dict, download_dict_lock, app, STOP_DUPLICATE
+from .download_helper import DownloadHelper
+from ..status_utils.telegram_download_status import TelegramDownloadStatus
+from bot.helper.telegram_helper.message_utils import sendMarkup, sendStatusMessage
+from bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper
+
+global_lock = threading.Lock()
+GLOBAL_GID = set()
+logging.getLogger("pyrogram").setLevel(logging.WARNING)
+
+
+class TelegramDownloadHelper(DownloadHelper):
+ def __init__(self, listener):
+ super().__init__()
+ self.__listener = listener
+ self.__resource_lock = threading.RLock()
+ self.__name = ""
+ self.__start_time = time.time()
+ self.__gid = ""
+ self._bot = app
+ self.__is_cancelled = False
+
+ @property
+ def gid(self):
+ with self.__resource_lock:
+ return self.__gid
+
+ @property
+ def download_speed(self):
+ with self.__resource_lock:
+ return self.downloaded_bytes / (time.time() - self.__start_time)
+
+ def __onDownloadStart(self, name, size, file_id):
+ with download_dict_lock:
+ download_dict[self.__listener.uid] = TelegramDownloadStatus(self, self.__listener)
+ with global_lock:
+ GLOBAL_GID.add(file_id)
+ with self.__resource_lock:
+ self.name = name
+ self.size = size
+ self.__gid = file_id
+ self.__listener.onDownloadStarted()
+
+ def __onDownloadProgress(self, current, total):
+ if self.__is_cancelled:
+ self.__onDownloadError('Cancelled by user!')
+ self._bot.stop_transmission()
+ return
+ with self.__resource_lock:
+ self.downloaded_bytes = current
+ try:
+ self.progress = current / self.size * 100
+ except ZeroDivisionError:
+ self.progress = 0
+
+ def __onDownloadError(self, error):
+ with global_lock:
+ try:
+ GLOBAL_GID.remove(self.gid)
+ except KeyError:
+ pass
+ self.__listener.onDownloadError(error)
+
+ def __onDownloadComplete(self):
+ with global_lock:
+ GLOBAL_GID.remove(self.gid)
+ self.__listener.onDownloadComplete()
+
+ def __download(self, message, path):
+ download = self._bot.download_media(
+ message,
+ progress = self.__onDownloadProgress,
+ file_name = path
+ )
+ if download is not None:
+ self.__onDownloadComplete()
+ else:
+ if not self.__is_cancelled:
+ self.__onDownloadError('Internal error occurred')
+
+ def add_download(self, message, path, filename):
+ _message = self._bot.get_messages(message.chat.id, reply_to_message_ids=message.message_id)
+ media = None
+ media_array = [_message.document, _message.video, _message.audio]
+ for i in media_array:
+ if i is not None:
+ media = i
+ break
+ if media is not None:
+ with global_lock:
+ # For avoiding locking the thread lock for long time unnecessarily
+ download = media.file_id not in GLOBAL_GID
+ if filename == "":
+ name = media.file_name
+ else:
+ name = filename
+ path = path + name
+
+ if download:
+ if STOP_DUPLICATE:
+ LOGGER.info(f"Checking File/Folder if already in Drive...")
+ if self.__listener.isTar:
+ name = name + ".tar"
+ if self.__listener.extract:
+ smsg = None
+ else:
+ gd = GoogleDriveHelper()
+ smsg, button = gd.drive_list(name)
+ if smsg:
+ sendMarkup("File/Folder is already available in Drive.\nHere are the search results:", self.__listener.bot, self.__listener.update, button)
+ return
+ sendStatusMessage(self.__listener.update, self.__listener.bot)
+ self.__onDownloadStart(name, media.file_size, media.file_id)
+ LOGGER.info(f'Downloading Telegram file with id: {media.file_id}')
+ threading.Thread(target=self.__download, args=(_message, path)).start()
+ else:
+ self.__onDownloadError('File already being downloaded!')
+ else:
+ self.__onDownloadError('No document in the replied message')
+
+ def cancel_download(self):
+ LOGGER.info(f'Cancelling download on user request: {self.gid}')
+ self.__is_cancelled = True
diff --git a/bot/helper/mirror_utils/download_utils/youtube_dl_download_helper.py b/bot/helper/mirror_utils/download_utils/youtube_dl_download_helper.py
new file mode 100644
index 0000000..6997ce0
--- /dev/null
+++ b/bot/helper/mirror_utils/download_utils/youtube_dl_download_helper.py
@@ -0,0 +1,167 @@
+from .download_helper import DownloadHelper
+import time
+from yt_dlp import YoutubeDL, DownloadError
+from bot import download_dict_lock, download_dict
+from ..status_utils.youtube_dl_download_status import YoutubeDLDownloadStatus
+import logging
+import re
+import threading
+
+LOGGER = logging.getLogger(__name__)
+
+
+class MyLogger:
+ def __init__(self, obj):
+ self.obj = obj
+
+ def debug(self, msg):
+ LOGGER.debug(msg)
+ match = re.search(r'.ffmpeg..Merging formats into..(.*?).$', msg)
+ if match and not self.obj.is_playlist:
+ newname = match.group(1)
+ newname = newname.split("/")
+ newname = newname[-1]
+ self.obj.name = newname
+
+ @staticmethod
+ def warning(msg):
+ LOGGER.warning(msg)
+
+ @staticmethod
+ def error(msg):
+ LOGGER.error(msg)
+
+
+class YoutubeDLHelper(DownloadHelper):
+ def __init__(self, listener):
+ super().__init__()
+ self.name = ""
+ self.__start_time = time.time()
+ self.__listener = listener
+ self.__gid = ""
+ self.opts = {
+ 'progress_hooks': [self.__onDownloadProgress],
+ 'logger': MyLogger(self),
+ 'usenetrc': True
+ }
+ self.__download_speed = 0
+ self.downloaded_bytes = 0
+ self.size = 0
+ self.is_playlist = False
+ self.last_downloaded = 0
+ self.is_cancelled = False
+ self.vid_id = ''
+ self.__resource_lock = threading.RLock()
+
+ @property
+ def download_speed(self):
+ with self.__resource_lock:
+ return self.__download_speed
+
+ @property
+ def gid(self):
+ with self.__resource_lock:
+ return self.__gid
+
+ def __onDownloadProgress(self, d):
+ if self.is_cancelled:
+ raise ValueError("Cancelling Download..")
+ if d['status'] == "finished":
+ if self.is_playlist:
+ self.last_downloaded = 0
+ elif d['status'] == "downloading":
+ with self.__resource_lock:
+ self.__download_speed = d['speed']
+ try:
+ tbyte = d['total_bytes']
+ except KeyError:
+ tbyte = d['total_bytes_estimate']
+ if self.is_playlist:
+ progress = d['downloaded_bytes'] / tbyte
+ chunk_size = d['downloaded_bytes'] - self.last_downloaded
+ self.last_downloaded = tbyte * progress
+ self.downloaded_bytes += chunk_size
+ else:
+ self.size = tbyte
+ self.downloaded_bytes = d['downloaded_bytes']
+ try:
+ self.progress = (self.downloaded_bytes / self.size) * 100
+ except ZeroDivisionError:
+ pass
+
+ def __onDownloadStart(self):
+ with download_dict_lock:
+ download_dict[self.__listener.uid] = YoutubeDLDownloadStatus(self, self.__listener)
+
+ def __onDownloadComplete(self):
+ self.__listener.onDownloadComplete()
+
+ def onDownloadError(self, error):
+ self.__listener.onDownloadError(error)
+
+ def extractMetaData(self, link, qual, name):
+ if "hotstar" in link or "sonyliv" in link:
+ self.opts['geo_bypass_country'] = 'IN'
+
+ with YoutubeDL(self.opts) as ydl:
+ try:
+ result = ydl.extract_info(link, download=False)
+ name = ydl.prepare_filename(result) if name == "" else name
+ if qual == "audio":
+ name = name.replace(".mp4", ".mp3").replace(".webm", ".mp3")
+ except DownloadError as e:
+ self.onDownloadError(str(e))
+ return
+ if result.get('direct'):
+ return None
+ if 'entries' in result:
+ video = result['entries'][0]
+ for v in result['entries']:
+ if v and v.get('filesize'):
+ self.size += float(v['filesize'])
+ # For playlists, ydl.prepare-filename returns the following format: -.NA
+ self.name = name.split(f"-{result['id']}")[0]
+ self.vid_id = video.get('id')
+ self.is_playlist = True
+ else:
+ video = result
+ if video.get('filesize'):
+ self.size = float(video.get('filesize'))
+ self.name = name
+ self.vid_id = video.get('id')
+ return video
+
+ def __download(self, link):
+ try:
+ with YoutubeDL(self.opts) as ydl:
+ try:
+ ydl.download([link])
+ except DownloadError as e:
+ self.onDownloadError(str(e))
+ return
+ self.__onDownloadComplete()
+ except ValueError:
+ LOGGER.info("Download Cancelled by User!")
+ self.onDownloadError("Download Cancelled by User!")
+
+ def add_download(self, link, path, qual, name):
+ pattern = '^.*(youtu\.be\/|youtube.com\/)(playlist?)'
+ if re.match(pattern, link):
+ self.opts['ignoreerrors'] = True
+ self.__onDownloadStart()
+ self.extractMetaData(link, qual, name)
+ LOGGER.info(f"Downloading with YT-DLP: {link}")
+ self.__gid = f"{self.vid_id}{self.__listener.uid}"
+ if qual == "audio":
+ self.opts['format'] = 'bestaudio/best'
+ self.opts['postprocessors'] = [{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3','preferredquality': '320',}]
+ else:
+ self.opts['format'] = qual
+ if not self.is_playlist:
+ self.opts['outtmpl'] = f"{path}/{self.name}"
+ else:
+ self.opts['outtmpl'] = f"{path}/{self.name}/%(title)s.%(ext)s"
+ self.__download(link)
+
+ def cancel_download(self):
+ self.is_cancelled = True
diff --git a/bot/helper/mirror_utils/status_utils/__init__.py b/bot/helper/mirror_utils/status_utils/__init__.py
new file mode 100644
index 0000000..bba8f51
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/__init__.py
@@ -0,0 +1 @@
+#TEKEAYUSH
\ No newline at end of file
diff --git a/bot/helper/mirror_utils/status_utils/aria_download_status.py b/bot/helper/mirror_utils/status_utils/aria_download_status.py
new file mode 100644
index 0000000..e0e449c
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/aria_download_status.py
@@ -0,0 +1,97 @@
+from bot import aria2, DOWNLOAD_DIR, LOGGER
+from bot.helper.ext_utils.bot_utils import MirrorStatus
+from .status import Status
+
+def get_download(gid):
+ return aria2.get_download(gid)
+
+
+class AriaDownloadStatus(Status):
+
+ def __init__(self, gid, listener):
+ super().__init__()
+ self.upload_name = None
+ self.__gid = gid
+ self.__download = get_download(self.__gid)
+ self.__uid = listener.uid
+ self.__listener = listener
+ self.message = listener.message
+
+ def __update(self):
+ self.__download = get_download(self.__gid)
+ download = self.__download
+ if download.followed_by_ids:
+ self.__gid = download.followed_by_ids[0]
+
+ def progress(self):
+ """
+ Calculates the progress of the mirror (upload or download)
+ :return: returns progress in percentage
+ """
+ self.__update()
+ return self.__download.progress_string()
+
+ def size_raw(self):
+ """
+ Gets total size of the mirror file/folder
+ :return: total size of mirror
+ """
+ return self.aria_download().total_length
+
+ def processed_bytes(self):
+ return self.aria_download().completed_length
+
+ def speed(self):
+ return self.aria_download().download_speed_string()
+
+ def name(self):
+ return self.aria_download().name
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.__uid}"
+
+ def size(self):
+ return self.aria_download().total_length_string()
+
+ def eta(self):
+ return self.aria_download().eta_string()
+
+ def status(self):
+ download = self.aria_download()
+ if download.is_waiting:
+ status = MirrorStatus.STATUS_WAITING
+ elif download.has_failed:
+ status = MirrorStatus.STATUS_FAILED
+ else:
+ status = MirrorStatus.STATUS_DOWNLOADING
+ return status
+
+ def aria_download(self):
+ self.__update()
+ return self.__download
+
+ def download(self):
+ return self
+
+ def getListener(self):
+ return self.__listener
+
+ def uid(self):
+ return self.__uid
+
+ def gid(self):
+ self.__update()
+ return self.__gid
+
+ def cancel_download(self):
+ LOGGER.info(f"Cancelling Download: {self.name()}")
+ download = self.aria_download()
+ if download.is_waiting:
+ self.__listener.onDownloadError("★ 𝗗𝗼𝘄𝗻𝗹𝗼𝗮𝗱 𝗖𝗮𝗻𝗰𝗲𝗹𝗹𝗲𝗱 𝗕𝘆 𝗨𝘀𝗲𝗿!! ★")
+ aria2.remove([download], force=True)
+ return
+ if len(download.followed_by_ids) != 0:
+ downloads = aria2.get_downloads(download.followed_by_ids)
+ aria2.remove(downloads, force=True)
+ self.__listener.onDownloadError('★ 𝗗𝗼𝘄𝗻𝗹𝗼𝗮𝗱 𝗖𝗮𝗻𝗰𝗲𝗹𝗹𝗲𝗱 𝗕𝘆 𝗨𝘀𝗲𝗿!! ★')
+ aria2.remove([download], force=True)
diff --git a/bot/helper/mirror_utils/status_utils/clone_status.py b/bot/helper/mirror_utils/status_utils/clone_status.py
new file mode 100644
index 0000000..a712265
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/clone_status.py
@@ -0,0 +1,60 @@
+# Implement By - @anasty17 (https://github.com/breakdowns/slam-mirrorbot/commit/80d33430715b4296cd253f62cefc089a81937ebf)
+# (c) https://github.com/breakdowns/slam-mirrorbot
+# All rights reserved
+
+from .status import Status
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+
+
+class CloneStatus(Status):
+ def __init__(self, obj, size, update, gid):
+ self.cobj = obj
+ self.__csize = size
+ self.message = update.message
+ self.__cgid = gid
+
+ def processed_bytes(self):
+ return self.cobj.transferred_size
+
+ def size_raw(self):
+ return self.__csize
+
+ def size(self):
+ return get_readable_file_size(self.__csize)
+
+ def status(self):
+ return MirrorStatus.STATUS_CLONING
+
+ def name(self):
+ return self.cobj.name
+
+ def gid(self) -> str:
+ return self.__cgid
+
+ def progress_raw(self):
+ try:
+ return self.cobj.transferred_size / self.__csize * 100
+ except ZeroDivisionError:
+ return 0
+
+ def progress(self):
+ return f'{round(self.progress_raw(), 2)}%'
+
+ def speed_raw(self):
+ """
+ :return: Download speed in Bytes/Seconds
+ """
+ return self.cobj.cspeed()
+
+ def speed(self):
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def eta(self):
+ try:
+ seconds = (self.__csize - self.cobj.transferred_size) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except ZeroDivisionError:
+ return '-'
+
+ def download(self):
+ return self.cobj
diff --git a/bot/helper/mirror_utils/status_utils/extract_status.py b/bot/helper/mirror_utils/status_utils/extract_status.py
new file mode 100644
index 0000000..41b6ff5
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/extract_status.py
@@ -0,0 +1,36 @@
+from .status import Status
+from bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus
+
+
+class ExtractStatus(Status):
+ def __init__(self, name, path, size):
+ self.__name = name
+ self.__path = path
+ self.__size = size
+
+ # The progress of extract function cannot be tracked. So we just return dummy values.
+ # If this is possible in future,we should implement it
+
+ def progress(self):
+ return '0'
+
+ def speed(self):
+ return '0'
+
+ def name(self):
+ return self.__name
+
+ def path(self):
+ return self.__path
+
+ def size(self):
+ return get_readable_file_size(self.__size)
+
+ def eta(self):
+ return '0s'
+
+ def status(self):
+ return MirrorStatus.STATUS_EXTRACTING
+
+ def processed_bytes(self):
+ return 0
diff --git a/bot/helper/mirror_utils/status_utils/gdownload_status.py b/bot/helper/mirror_utils/status_utils/gdownload_status.py
new file mode 100644
index 0000000..eebb3aa
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/gdownload_status.py
@@ -0,0 +1,65 @@
+# Implement By - @anasty17 (https://github.com/breakdowns/slam-mirrorbot/pull/220)
+# (c) https://github.com/breakdowns/slam-mirrorbot
+# All rights reserved
+
+from .status import Status
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+from bot import DOWNLOAD_DIR
+
+
+class DownloadStatus(Status):
+ def __init__(self, obj, size, listener, gid):
+ self.dobj = obj
+ self.__dsize = size
+ self.uid = listener.uid
+ self.message = listener.message
+ self.__dgid = gid
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.uid}"
+
+ def processed_bytes(self):
+ return self.dobj.downloaded_bytes
+
+ def size_raw(self):
+ return self.__dsize
+
+ def size(self):
+ return get_readable_file_size(self.__dsize)
+
+ def status(self):
+ return MirrorStatus.STATUS_DOWNLOADING
+
+ def name(self):
+ return self.dobj.name
+
+ def gid(self) -> str:
+ return self.__dgid
+
+ def progress_raw(self):
+ try:
+ return self.dobj.downloaded_bytes / self.__dsize * 100
+ except ZeroDivisionError:
+ return 0
+
+ def progress(self):
+ return f'{round(self.progress_raw(), 2)}%'
+
+ def speed_raw(self):
+ """
+ :return: Download speed in Bytes/Seconds
+ """
+ return self.dobj.dspeed()
+
+ def speed(self):
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def eta(self):
+ try:
+ seconds = (self.__dsize - self.dobj.downloaded_bytes) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except ZeroDivisionError:
+ return '-'
+
+ def download(self):
+ return self.dobj
diff --git a/bot/helper/mirror_utils/status_utils/listeners.py b/bot/helper/mirror_utils/status_utils/listeners.py
new file mode 100644
index 0000000..9c824b7
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/listeners.py
@@ -0,0 +1,30 @@
+class MirrorListeners:
+ def __init__(self, context, update):
+ self.bot = context
+ self.update = update
+ self.message = update.message
+ self.uid = self.message.message_id
+
+ def onDownloadStarted(self):
+ raise NotImplementedError
+
+ def onDownloadProgress(self):
+ raise NotImplementedError
+
+ def onDownloadComplete(self):
+ raise NotImplementedError
+
+ def onDownloadError(self, error: str):
+ raise NotImplementedError
+
+ def onUploadStarted(self):
+ raise NotImplementedError
+
+ def onUploadProgress(self):
+ raise NotImplementedError
+
+ def onUploadComplete(self, link: str):
+ raise NotImplementedError
+
+ def onUploadError(self, error: str):
+ raise NotImplementedError
diff --git a/bot/helper/mirror_utils/status_utils/mega_download_status.py b/bot/helper/mirror_utils/status_utils/mega_download_status.py
new file mode 100644
index 0000000..e4f5656
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/mega_download_status.py
@@ -0,0 +1,62 @@
+from bot.helper.ext_utils.bot_utils import get_readable_file_size,MirrorStatus, get_readable_time
+from bot import DOWNLOAD_DIR
+from .status import Status
+
+
+class MegaDownloadStatus(Status):
+
+ def __init__(self, obj, listener):
+ self.uid = obj.uid
+ self.listener = listener
+ self.obj = obj
+ self.message = listener.message
+
+ def name(self) -> str:
+ return self.obj.name
+
+ def progress_raw(self):
+ try:
+ return round(self.processed_bytes() / self.obj.size * 100,2)
+ except ZeroDivisionError:
+ return 0.0
+
+ def progress(self):
+ """Progress of download in percentage"""
+ return f"{self.progress_raw()}%"
+
+ def status(self) -> str:
+ return MirrorStatus.STATUS_DOWNLOADING
+
+ def processed_bytes(self):
+ return self.obj.downloaded_bytes
+
+ def eta(self):
+ try:
+ seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except ZeroDivisionError:
+ return '-'
+
+ def size_raw(self):
+ return self.obj.size
+
+ def size(self) -> str:
+ return get_readable_file_size(self.size_raw())
+
+ def downloaded(self) -> str:
+ return get_readable_file_size(self.obj.downloadedBytes)
+
+ def speed_raw(self):
+ return self.obj.speed
+
+ def speed(self) -> str:
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def gid(self) -> str:
+ return self.obj.gid
+
+ def path(self) -> str:
+ return f"{DOWNLOAD_DIR}{self.uid}"
+
+ def download(self):
+ return self.obj
diff --git a/bot/helper/mirror_utils/status_utils/qbit_download_status.py b/bot/helper/mirror_utils/status_utils/qbit_download_status.py
new file mode 100644
index 0000000..ea93755
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/qbit_download_status.py
@@ -0,0 +1,81 @@
+# Implement By - @anasty17 (https://github.com/breakdowns/slam-mirrorbot/commit/0bfba523f095ab1dccad431d72561e0e002e7a59)
+# (c) https://github.com/breakdowns/slam-mirrorbot
+# All rights reserved
+
+from bot import DOWNLOAD_DIR, LOGGER, get_client
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+from .status import Status
+
+
+class QbDownloadStatus(Status):
+
+ def __init__(self, gid, listener, qbhash, client):
+ super().__init__()
+ self.__gid = gid
+ self.__hash = qbhash
+ self.client = client
+ self.__uid = listener.uid
+ self.listener = listener
+ self.message = listener.message
+
+
+ def progress(self):
+ """
+ Calculates the progress of the mirror (upload or download)
+ :return: returns progress in percentage
+ """
+ return f'{round(self.torrent_info().progress*100,2)}%'
+
+ def size_raw(self):
+ """
+ Gets total size of the mirror file/folder
+ :return: total size of mirror
+ """
+ return self.torrent_info().size
+
+ def processed_bytes(self):
+ return self.torrent_info().downloaded
+
+ def speed(self):
+ return f"{get_readable_file_size(self.torrent_info().dlspeed)}/s"
+
+ def name(self):
+ return self.torrent_info().name
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.__uid}"
+
+ def size(self):
+ return get_readable_file_size(self.torrent_info().size)
+
+ def eta(self):
+ return get_readable_time(self.torrent_info().eta)
+
+ def status(self):
+ download = self.torrent_info().state
+ if download == "queuedDL":
+ status = MirrorStatus.STATUS_WAITING
+ elif download == "metaDL" or download == "checkingResumeData":
+ status = MirrorStatus.STATUS_DOWNLOADING + " (Metadata)"
+ elif download == "pausedDL":
+ status = MirrorStatus.STATUS_PAUSE
+ else:
+ status = MirrorStatus.STATUS_DOWNLOADING
+ return status
+
+ def torrent_info(self):
+ return self.client.torrents_info(torrent_hashes=self.__hash)[0]
+
+ def download(self):
+ return self
+
+ def uid(self):
+ return self.__uid
+
+ def gid(self):
+ return self.__gid
+
+ def cancel_download(self):
+ LOGGER.info(f"Cancelling Download: {self.name()}")
+ self.listener.onDownloadError('Download stopped by user!')
+ self.client.torrents_delete(torrent_hashes=self.__hash, delete_files=True)
diff --git a/bot/helper/mirror_utils/status_utils/status.py b/bot/helper/mirror_utils/status_utils/status.py
new file mode 100644
index 0000000..8e42d13
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/status.py
@@ -0,0 +1,40 @@
+# Generic status class. All other status classes must inherit this class
+
+
+class Status:
+
+ def progress(self):
+ """
+ Calculates the progress of the mirror (upload or download)
+ :return: progress in percentage
+ """
+ raise NotImplementedError
+
+ def speed(self):
+ """:return: speed in bytes per second"""
+ raise NotImplementedError
+
+ def name(self):
+ """:return name of file/directory being processed"""
+ raise NotImplementedError
+
+ def path(self):
+ """:return path of the file/directory"""
+ raise NotImplementedError
+
+ def size(self):
+ """:return Size of file folder"""
+ raise NotImplementedError
+
+ def eta(self):
+ """:return ETA of the process to complete"""
+ raise NotImplementedError
+
+ def status(self):
+ """:return String describing what is the object of this class will be tracking (upload/download/something
+ else) """
+ raise NotImplementedError
+
+ def processed_bytes(self):
+ """:return The size of file that has been processed (downloaded/uploaded/archived)"""
+ raise NotImplementedError
diff --git a/bot/helper/mirror_utils/status_utils/tar_status.py b/bot/helper/mirror_utils/status_utils/tar_status.py
new file mode 100644
index 0000000..efc0895
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/tar_status.py
@@ -0,0 +1,36 @@
+from .status import Status
+from bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus
+
+
+class TarStatus(Status):
+ def __init__(self, name, path, size):
+ self.__name = name
+ self.__path = path
+ self.__size = size
+
+ # The progress of Tar function cannot be tracked. So we just return dummy values.
+ # If this is possible in future,we should implement it
+
+ def progress(self):
+ return '0'
+
+ def speed(self):
+ return '0'
+
+ def name(self):
+ return self.__name
+
+ def path(self):
+ return self.__path
+
+ def size(self):
+ return get_readable_file_size(self.__size)
+
+ def eta(self):
+ return '0s'
+
+ def status(self):
+ return MirrorStatus.STATUS_ARCHIVING
+
+ def processed_bytes(self):
+ return 0
diff --git a/bot/helper/mirror_utils/status_utils/telegram_download_status.py b/bot/helper/mirror_utils/status_utils/telegram_download_status.py
new file mode 100644
index 0000000..89f3d52
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/telegram_download_status.py
@@ -0,0 +1,56 @@
+from bot import DOWNLOAD_DIR
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+from .status import Status
+
+
+class TelegramDownloadStatus(Status):
+ def __init__(self, obj, listener):
+ self.obj = obj
+ self.uid = listener.uid
+ self.message = listener.message
+
+ def gid(self):
+ return self.obj.gid
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.uid}"
+
+ def processed_bytes(self):
+ return self.obj.downloaded_bytes
+
+ def size_raw(self):
+ return self.obj.size
+
+ def size(self):
+ return get_readable_file_size(self.size_raw())
+
+ def status(self):
+ return MirrorStatus.STATUS_DOWNLOADING
+
+ def name(self):
+ return self.obj.name
+
+ def progress_raw(self):
+ return self.obj.progress
+
+ def progress(self):
+ return f'{round(self.progress_raw(), 2)}%'
+
+ def speed_raw(self):
+ """
+ :return: Download speed in Bytes/Seconds
+ """
+ return self.obj.download_speed
+
+ def speed(self):
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def eta(self):
+ try:
+ seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except ZeroDivisionError:
+ return '-'
+
+ def download(self):
+ return self.obj
diff --git a/bot/helper/mirror_utils/status_utils/upload_status.py b/bot/helper/mirror_utils/status_utils/upload_status.py
new file mode 100644
index 0000000..46be352
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/upload_status.py
@@ -0,0 +1,61 @@
+from .status import Status
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+from bot import DOWNLOAD_DIR
+
+
+class UploadStatus(Status):
+ def __init__(self, obj, size, gid, listener):
+ self.obj = obj
+ self.__size = size
+ self.uid = listener.uid
+ self.message = listener.message
+ self.__gid = gid
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.uid}"
+
+ def processed_bytes(self):
+ return self.obj.uploaded_bytes
+
+ def size_raw(self):
+ return self.__size
+
+ def size(self):
+ return get_readable_file_size(self.__size)
+
+ def status(self):
+ return MirrorStatus.STATUS_UPLOADING
+
+ def name(self):
+ return self.obj.name
+
+ def progress_raw(self):
+ try:
+ return self.obj.uploaded_bytes / self.__size * 100
+ except ZeroDivisionError:
+ return 0
+
+ def progress(self):
+ return f'{round(self.progress_raw(), 2)}%'
+
+ def speed_raw(self):
+ """
+ :return: Upload speed in Bytes/Seconds
+ """
+ return self.obj.speed()
+
+ def speed(self):
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def eta(self):
+ try:
+ seconds = (self.__size - self.obj.uploaded_bytes) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except ZeroDivisionError:
+ return '-'
+
+ def gid(self) -> str:
+ return self.__gid
+
+ def download(self):
+ return self.obj
diff --git a/bot/helper/mirror_utils/status_utils/youtube_dl_download_status.py b/bot/helper/mirror_utils/status_utils/youtube_dl_download_status.py
new file mode 100644
index 0000000..3950bad
--- /dev/null
+++ b/bot/helper/mirror_utils/status_utils/youtube_dl_download_status.py
@@ -0,0 +1,59 @@
+from bot import DOWNLOAD_DIR
+from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time
+from .status import Status
+from bot.helper.ext_utils.fs_utils import get_path_size
+
+class YoutubeDLDownloadStatus(Status):
+ def __init__(self, obj, listener):
+ self.obj = obj
+ self.uid = listener.uid
+ self.message = listener.message
+
+ def gid(self):
+ return self.obj.gid
+
+ def path(self):
+ return f"{DOWNLOAD_DIR}{self.uid}"
+
+ def processed_bytes(self):
+ if self.obj.downloaded_bytes != 0:
+ return self.obj.downloaded_bytes
+ else:
+ return get_path_size(f"{DOWNLOAD_DIR}{self.uid}")
+
+ def size_raw(self):
+ return self.obj.size
+
+ def size(self):
+ return get_readable_file_size(self.size_raw())
+
+ def status(self):
+ return MirrorStatus.STATUS_DOWNLOADING
+
+ def name(self):
+ return self.obj.name
+
+ def progress_raw(self):
+ return self.obj.progress
+
+ def progress(self):
+ return f'{round(self.progress_raw(), 2)}%'
+
+ def speed_raw(self):
+ """
+ :return: Download speed in Bytes/Seconds
+ """
+ return self.obj.download_speed
+
+ def speed(self):
+ return f'{get_readable_file_size(self.speed_raw())}/s'
+
+ def eta(self):
+ try:
+ seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()
+ return f'{get_readable_time(seconds)}'
+ except:
+ return '-'
+
+ def download(self):
+ return self.obj
diff --git a/bot/helper/mirror_utils/upload_utils/__init__.py b/bot/helper/mirror_utils/upload_utils/__init__.py
new file mode 100644
index 0000000..bba8f51
--- /dev/null
+++ b/bot/helper/mirror_utils/upload_utils/__init__.py
@@ -0,0 +1 @@
+#TEKEAYUSH
\ No newline at end of file
diff --git a/bot/helper/mirror_utils/upload_utils/gdriveTools.py b/bot/helper/mirror_utils/upload_utils/gdriveTools.py
new file mode 100644
index 0000000..21038da
--- /dev/null
+++ b/bot/helper/mirror_utils/upload_utils/gdriveTools.py
@@ -0,0 +1,867 @@
+import os
+import io
+import pickle
+import urllib.parse as urlparse
+from urllib.parse import parse_qs
+
+import re
+import json
+import requests
+import logging
+from random import randrange
+
+from google.auth.transport.requests import Request
+from google.oauth2 import service_account
+from google_auth_oauthlib.flow import InstalledAppFlow
+from googleapiclient.discovery import build
+from googleapiclient.errors import HttpError
+from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
+from tenacity import *
+
+from telegram import InlineKeyboardMarkup
+from bot.helper.telegram_helper import button_build
+from telegraph import Telegraph
+from bot import parent_id, IMAGE_URL, DOWNLOAD_DIR, IS_TEAM_DRIVE, INDEX_URL, \
+ USE_SERVICE_ACCOUNTS, telegraph_token, BUTTON_FOUR_NAME, BUTTON_FOUR_URL, BUTTON_FIVE_NAME, BUTTON_FIVE_URL, BUTTON_SIX_NAME, BUTTON_SIX_URL, SHORTENER, SHORTENER_API, VIEW_LINK
+from bot.helper.ext_utils.bot_utils import *
+from bot.helper.ext_utils.fs_utils import get_mime_type, get_path_size
+
+LOGGER = logging.getLogger(__name__)
+logging.getLogger('googleapiclient.discovery').setLevel(logging.ERROR)
+if USE_SERVICE_ACCOUNTS:
+ SERVICE_ACCOUNT_INDEX = randrange(len(os.listdir("accounts")))
+TELEGRAPHLIMIT = 80
+
+class GoogleDriveHelper:
+ def __init__(self, name=None, listener=None):
+ self.__G_DRIVE_TOKEN_FILE = "token.pickle"
+ # Check https://developers.google.com/drive/scopes for all available scopes
+ self.__OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive']
+ # Redirect URI for installed apps, can be left as is
+ self.__REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"
+ self.__G_DRIVE_DIR_MIME_TYPE = "application/vnd.google-apps.folder"
+ self.__G_DRIVE_BASE_DOWNLOAD_URL = "https://drive.google.com/uc?id={}&export=download"
+ self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL = "https://drive.google.com/drive/folders/{}"
+ self.__listener = listener
+ self.__service = self.authorize()
+ self._file_uploaded_bytes = 0
+ self._file_downloaded_bytes = 0
+ self.uploaded_bytes = 0
+ self.downloaded_bytes = 0
+ self.start_time = 0
+ self.total_time = 0
+ self.dtotal_time = 0
+ self.is_uploading = False
+ self.is_downloading = False
+ self.is_cloning = False
+ self.is_cancelled = False
+ self.status = None
+ self.dstatus = None
+ self.updater = None
+ self.name = name
+ self.update_interval = 3
+ self.telegraph_content = []
+ self.path = []
+ self.total_bytes = 0
+ self.total_files = 0
+ self.total_folders = 0
+ self.transferred_size = 0
+ self.sa_count = 0
+
+ def speed(self):
+ """
+ It calculates the average upload speed and returns it in bytes/seconds unit
+ :return: Upload speed in bytes/second
+ """
+ try:
+ return self.uploaded_bytes / self.total_time
+ except ZeroDivisionError:
+ return 0
+
+ def dspeed(self):
+ try:
+ return self.downloaded_bytes / self.dtotal_time
+ except ZeroDivisionError:
+ return 0
+
+ def cspeed(self):
+ try:
+ return self.transferred_size / int(time.time() - self.start_time)
+ except ZeroDivisionError:
+ return 0
+
+ @staticmethod
+ def getIdFromUrl(link: str):
+ if "folders" in link or "file" in link:
+ regex = r"https://drive\.google\.com/(drive)?/?u?/?\d?/?(mobile)?/?(file)?(folders)?/?d?/([-\w]+)[?+]?/?(w+)?"
+ res = re.search(regex,link)
+ if res is None:
+ raise IndexError("G-Drive ID not found.")
+ return res.group(5)
+ parsed = urlparse.urlparse(link)
+ return parse_qs(parsed.query)['id'][0]
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def _on_upload_progress(self):
+ if self.status is not None:
+ chunk_size = self.status.total_size * self.status.progress() - self._file_uploaded_bytes
+ self._file_uploaded_bytes = self.status.total_size * self.status.progress()
+ LOGGER.debug(f'Uploading {self.name}, chunk size: {get_readable_file_size(chunk_size)}')
+ self.uploaded_bytes += chunk_size
+ self.total_time += self.update_interval
+
+ def __upload_empty_file(self, path, file_name, mime_type, parent_id=None):
+ media_body = MediaFileUpload(path,
+ mimetype=mime_type,
+ resumable=False)
+ file_metadata = {
+ 'name': file_name,
+ 'description': 'Uploaded using AT_BOTs Mirrorbot',
+ 'mimeType': mime_type,
+ }
+ if parent_id is not None:
+ file_metadata['parents'] = [parent_id]
+ return self.__service.files().create(supportsTeamDrives=True,
+ body=file_metadata, media_body=media_body).execute()
+ def deletefile(self, link: str):
+ try:
+ file_id = self.getIdFromUrl(link)
+ except (KeyError,IndexError):
+ msg = "Google Drive ID could not be found in the provided link"
+ return msg
+ msg = ''
+ try:
+ res = self.__service.files().delete(fileId=file_id, supportsTeamDrives=IS_TEAM_DRIVE).execute()
+ msg = "Successfully deleted"
+ except HttpError as err:
+ LOGGER.error(str(err))
+ if "File not found" in str(err):
+ msg = "No such file exist"
+ else:
+ msg = "Something went wrong check log"
+ finally:
+ return msg
+
+ def switchServiceAccount(self):
+ global SERVICE_ACCOUNT_INDEX
+ service_account_count = len(os.listdir("accounts"))
+ if SERVICE_ACCOUNT_INDEX == service_account_count - 1:
+ SERVICE_ACCOUNT_INDEX = 0
+ self.sa_count += 1
+ SERVICE_ACCOUNT_INDEX += 1
+ LOGGER.info(f"Switching to {SERVICE_ACCOUNT_INDEX}.json service account")
+ self.__service = self.authorize()
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def __set_permission(self, drive_id):
+ permissions = {
+ 'role': 'reader',
+ 'type': 'anyone',
+ 'value': None,
+ 'withLink': True
+ }
+ return self.__service.permissions().create(supportsTeamDrives=True, fileId=drive_id,
+ body=permissions).execute()
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def upload_file(self, file_path, file_name, mime_type, parent_id):
+ # File body description
+ file_metadata = {
+ 'name': file_name,
+ 'description': 'Uploaded using AT_BOTs Mirrorbot',
+ 'mimeType': mime_type,
+ }
+ try:
+ self.typee = file_metadata['mimeType']
+ except:
+ self.typee = 'File'
+ if parent_id is not None:
+ file_metadata['parents'] = [parent_id]
+
+ if os.path.getsize(file_path) == 0:
+ media_body = MediaFileUpload(file_path,
+ mimetype=mime_type,
+ resumable=False)
+ response = self.__service.files().create(supportsTeamDrives=True,
+ body=file_metadata, media_body=media_body).execute()
+ if not IS_TEAM_DRIVE:
+ self.__set_permission(response['id'])
+
+ drive_file = self.__service.files().get(supportsTeamDrives=True,
+ fileId=response['id']).execute()
+ download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))
+ return download_url
+ media_body = MediaFileUpload(file_path,
+ mimetype=mime_type,
+ resumable=True,
+ chunksize=50 * 1024 * 1024)
+
+ # Insert a file
+ drive_file = self.__service.files().create(supportsTeamDrives=True,
+ body=file_metadata, media_body=media_body)
+ response = None
+ while response is None:
+ if self.is_cancelled:
+ break
+ try:
+ self.status, response = drive_file.next_chunk()
+ except HttpError as err:
+ if err.resp.get('content-type', '').startswith('application/json'):
+ reason = json.loads(err.content).get('error').get('errors')[0].get('reason')
+ if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':
+ if USE_SERVICE_ACCOUNTS:
+ self.switchServiceAccount()
+ LOGGER.info(f"Got: {reason}, Trying Again.")
+ return self.upload_file(file_path, file_name, mime_type, parent_id)
+ else:
+ self.is_cancelled = True
+ LOGGER.info(f"Got: {reason}")
+ raise err
+ else:
+ raise err
+ if self.is_cancelled:
+ return
+ self._file_uploaded_bytes = 0
+ # Insert new permissions
+ if not IS_TEAM_DRIVE:
+ self.__set_permission(response['id'])
+ # Define file instance and get url for download
+ drive_file = self.__service.files().get(supportsTeamDrives=True, fileId=response['id']).execute()
+ download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))
+ return download_url
+
+ def upload(self, file_name: str):
+ self.is_downloading = False
+ self.is_uploading = True
+ if USE_SERVICE_ACCOUNTS:
+ self.service_account_count = len(os.listdir("accounts"))
+ self.__listener.onUploadStarted()
+ file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}"
+ file_path = f"{file_dir}/{file_name}"
+ size = get_readable_file_size(get_path_size(file_path))
+ LOGGER.info("Uploading File: " + file_path)
+ self.updater = setInterval(self.update_interval, self._on_upload_progress)
+ if os.path.isfile(file_path):
+ try:
+ mime_type = get_mime_type(file_path)
+ link = self.upload_file(file_path, file_name, mime_type, parent_id)
+ if self.is_cancelled:
+ return
+ if link is None:
+ raise Exception('Upload has been manually cancelled')
+ LOGGER.info("Uploaded To G-Drive: " + file_path)
+ except Exception as e:
+ if isinstance(e, RetryError):
+ LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
+ err = e.last_attempt.exception()
+ else:
+ err = e
+ LOGGER.error(err)
+ self.__listener.onUploadError(str(err))
+ return
+ finally:
+ self.updater.cancel()
+ if self.is_cancelled:
+ return
+ else:
+ try:
+ dir_id = self.create_directory(os.path.basename(os.path.abspath(file_name)), parent_id)
+ result = self.upload_dir(file_path, dir_id)
+ if result is None:
+ raise Exception('Upload has been manually cancelled!')
+ link = f"https://drive.google.com/folderview?id={dir_id}"
+ if self.is_cancelled:
+ LOGGER.info("Deleting uploaded data from Drive...")
+ msg = self.deletefile(link)
+ LOGGER.info(f"{msg}")
+ return
+ LOGGER.info("Uploaded To G-Drive: " + file_name)
+ except Exception as e:
+ if isinstance(e, RetryError):
+ LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
+ err = e.last_attempt.exception()
+ else:
+ err = e
+ LOGGER.error(err)
+ self.__listener.onUploadError(str(err))
+ return
+ finally:
+ self.updater.cancel()
+ if self.is_cancelled:
+ return
+ files = self.total_files
+ folders = self.total_folders
+ typ = self.typee
+ self.__listener.onUploadComplete(link, size, files, folders, typ)
+ return link
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def copyFile(self, file_id, dest_id):
+ body = {
+ 'parents': [dest_id]
+ }
+
+ try:
+ res = self.__service.files().copy(supportsAllDrives=True,fileId=file_id,body=body).execute()
+ return res
+ except HttpError as err:
+ if err.resp.get('content-type', '').startswith('application/json'):
+ reason = json.loads(err.content).get('error').get('errors')[0].get('reason')
+ if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':
+ if USE_SERVICE_ACCOUNTS:
+ if self.sa_count == self.service_account_count:
+ self.is_cancelled = True
+ raise err
+ else:
+ self.switchServiceAccount()
+ return self.copyFile(file_id,dest_id)
+ else:
+ self.is_cancelled = True
+ LOGGER.info(f"Got: {reason}")
+ raise err
+ else:
+ raise err
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def getFileMetadata(self,file_id):
+ return self.__service.files().get(supportsAllDrives=True, fileId=file_id,
+ fields="name,id,mimeType,size").execute()
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def getFilesByFolderId(self,folder_id):
+ page_token = None
+ q = f"'{folder_id}' in parents"
+ files = []
+ while True:
+ response = self.__service.files().list(supportsTeamDrives=True,
+ includeTeamDriveItems=True,
+ q=q,
+ spaces='drive',
+ pageSize=200,
+ fields='nextPageToken, files(id, name, mimeType,size)', corpora='allDrives', orderBy='folder, name',
+ pageToken=page_token).execute()
+ for file in response.get('files', []):
+ files.append(file)
+ page_token = response.get('nextPageToken', None)
+ if page_token is None:
+ break
+ return files
+
+ def clone(self, link):
+ self.is_cloning = True
+ self.start_time = time.time()
+ self.total_files = 0
+ self.total_folders = 0
+ if USE_SERVICE_ACCOUNTS:
+ self.service_account_count = len(os.listdir("accounts"))
+ try:
+ file_id = self.getIdFromUrl(link)
+ except (KeyError,IndexError):
+ msg = "Google Drive ID could not be found in the provided link"
+ return msg
+ msg = ""
+ LOGGER.info(f"File ID: {file_id}")
+ try:
+ meta = self.getFileMetadata(file_id)
+ if meta.get("mimeType") == self.__G_DRIVE_DIR_MIME_TYPE:
+ dir_id = self.create_directory(meta.get('name'), parent_id)
+ self.cloneFolder(meta.get('name'), meta.get('name'), meta.get('id'), dir_id)
+ durl = self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id)
+ if self.is_cancelled:
+ LOGGER.info("Deleting cloned data from Drive...")
+ msg = self.deletefile(durl)
+ LOGGER.info(f"{msg}")
+ return "your clone has been stopped and cloned data has been deleted!", "cancelled"
+ msg += f'☞ 📂Filename : {meta.get("name")}\nSize: {get_readable_file_size(self.transferred_size)}'
+ msg += f'\n☞ 🌀Type : Folder'
+ msg += f'\n☞ Powerd by : @AT_BOTs'
+ buttons = button_build.ButtonMaker()
+ if SHORTENER is not None and SHORTENER_API is not None:
+ surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={durl}&format=text').text
+ buttons.buildbutton("🌠 Drive Link 🌠", surl)
+ else:
+ buttons.buildbutton("🌠 Drive Link 🌠", durl)
+ if INDEX_URL is not None:
+ url_path = requests.utils.quote(f'{meta.get("name")}')
+ url = f'{INDEX_URL}/{url_path}/'
+ if SHORTENER is not None and SHORTENER_API is not None:
+ siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text
+ buttons.buildbutton("☄️ Index Link ☄️", siurl)
+ else:
+ buttons.buildbutton("☄️ Index Link ☄️", url)
+ if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:
+ buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}")
+ if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:
+ buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}")
+ if BUTTON_SIX_NAME is not None and BUTTON_SIX_URL is not None:
+ buttons.buildbutton(f"{BUTTON_SIX_NAME}", f"{BUTTON_SIX_URL}")
+ else:
+ file = self.copyFile(meta.get('id'), parent_id)
+ msg += f'☞ 📂Filename : {file.get("name")}'
+ durl = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(file.get("id"))
+ buttons = button_build.ButtonMaker()
+ if SHORTENER is not None and SHORTENER_API is not None:
+ surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={durl}&format=text').text
+ buttons.buildbutton("🌠 Drive Link 🌠", surl)
+ else:
+ buttons.buildbutton("🌠 Drive Link 🌠", durl)
+ try:
+ typeee = file.get('mimeType')
+ except:
+ typeee = 'File'
+ try:
+ msg += f'\n☞ 📦Size : {get_readable_file_size(int(meta.get("size")))}'
+ msg += f'\n☞ 🗳Powerd by : @AT_BOTS '
+ except TypeError:
+ pass
+ if INDEX_URL is not None:
+ url_path = requests.utils.quote(f'{file.get("name")}')
+ url = f'{INDEX_URL}/{url_path}'
+ urls = f'{INDEX_URL}/{url_path}?a=view'
+ if SHORTENER is not None and SHORTENER_API is not None:
+ siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text
+ siurls = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={urls}&format=text').text
+ buttons.buildbutton("☄️ Index Link ☄️", siurl)
+ if VIEW_LINK:
+ buttons.buildbutton(" View Link", siurls)
+ else:
+ buttons.buildbutton("☄️ Index Link ☄️", url)
+ if VIEW_LINK:
+ buttons.buildbutton(" View Link", urls)
+ if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:
+ buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}")
+ if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:
+ buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}")
+ if BUTTON_SIX_NAME is not None and BUTTON_SIX_URL is not None:
+ buttons.buildbutton(f"{BUTTON_SIX_NAME}", f"{BUTTON_SIX_URL}")
+ 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)
+ if "User rate limit exceeded" in str(err):
+ msg = "User rate limit exceeded."
+ elif "File not found" in str(err):
+ msg = "File not found."
+ else:
+ msg = f"Error.\n{err}"
+ return msg, ""
+ return msg, InlineKeyboardMarkup(buttons.build_menu(2))
+
+ def cloneFolder(self, name, local_path, folder_id, parent_id):
+ LOGGER.info(f"Syncing: {local_path}")
+ files = self.getFilesByFolderId(folder_id)
+ new_id = None
+ if len(files) == 0:
+ return parent_id
+ for file in files:
+ if file.get('mimeType') == self.__G_DRIVE_DIR_MIME_TYPE:
+ self.total_folders += 1
+ file_path = os.path.join(local_path, file.get('name'))
+ current_dir_id = self.create_directory(file.get('name'), parent_id)
+ new_id = self.cloneFolder(file.get('name'), file_path, file.get('id'), current_dir_id)
+ else:
+ try:
+ self.total_files += 1
+ self.transferred_size += int(file.get('size'))
+ except TypeError:
+ pass
+ self.copyFile(file.get('id'), parent_id)
+ new_id = parent_id
+ if self.is_cancelled:
+ break
+
+ @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
+ retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
+ def create_directory(self, directory_name, parent_id):
+ file_metadata = {
+ "name": directory_name,
+ "mimeType": self.__G_DRIVE_DIR_MIME_TYPE
+ }
+ if parent_id is not None:
+ file_metadata["parents"] = [parent_id]
+ file = self.__service.files().create(supportsTeamDrives=True, body=file_metadata).execute()
+ file_id = file.get("id")
+ if not IS_TEAM_DRIVE:
+ self.__set_permission(file_id)
+ LOGGER.info("Created G-Drive Folder:\nName: {}\nID: {} ".format(file.get("name"), file_id))
+ return file_id
+
+ def upload_dir(self, input_directory, parent_id):
+ list_dirs = os.listdir(input_directory)
+ if len(list_dirs) == 0:
+ return parent_id
+ new_id = None
+ for item in list_dirs:
+ current_file_name = os.path.join(input_directory, item)
+ if os.path.isdir(current_file_name):
+ current_dir_id = self.create_directory(item, parent_id)
+ new_id = self.upload_dir(current_file_name, current_dir_id)
+ self.total_folders += 1
+ else:
+ mime_type = get_mime_type(current_file_name)
+ file_name = current_file_name.split("/")[-1]
+ # current_file_name will have the full path
+ self.upload_file(current_file_name, file_name, mime_type, parent_id)
+ self.total_files += 1
+ new_id = parent_id
+ if self.is_cancelled:
+ break
+ return new_id
+
+ def authorize(self):
+ # Get credentials
+ credentials = None
+ if not USE_SERVICE_ACCOUNTS:
+ if os.path.exists(self.__G_DRIVE_TOKEN_FILE):
+ with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f:
+ credentials = pickle.load(f)
+ if credentials is None or not credentials.valid:
+ if credentials and credentials.expired and credentials.refresh_token:
+ credentials.refresh(Request())
+ else:
+ flow = InstalledAppFlow.from_client_secrets_file(
+ 'credentials.json', self.__OAUTH_SCOPE)
+ LOGGER.info(flow)
+ credentials = flow.run_console(port=0)
+
+ # Save the credentials for the next run
+ with open(self.__G_DRIVE_TOKEN_FILE, 'wb') as token:
+ pickle.dump(credentials, token)
+ else:
+ LOGGER.info(f"Authorizing with {SERVICE_ACCOUNT_INDEX}.json service account")
+ credentials = service_account.Credentials.from_service_account_file(
+ f'accounts/{SERVICE_ACCOUNT_INDEX}.json',
+ scopes=self.__OAUTH_SCOPE)
+ return build('drive', 'v3', credentials=credentials, cache_discovery=False)
+ def edit_telegraph(self):
+ nxt_page = 1
+ prev_page = 0
+ for content in self.telegraph_content :
+ if nxt_page == 1 :
+ content += f'Next'
+ nxt_page += 1
+ else :
+ if prev_page <= self.num_of_path:
+ content += f'Prev'
+ prev_page += 1
+ if nxt_page < self.num_of_path:
+ content += f' | Next'
+ nxt_page += 1
+ Telegraph(access_token=telegraph_token).edit_page(path = self.path[prev_page],
+ title = 'AT_BOTs Mirror bot search',
+ author_name='AT_BOTs',
+ author_url='https://t.me/AT_BOTs',
+ html_content=content)
+ return
+
+ def escapes(self, str):
+ chars = ['\\', "'", '"', r'\a', r'\b', r'\f', r'\n', r'\r', r'\t']
+ for char in chars:
+ str = str.replace(char, '\\'+char)
+ return str
+
+ def drive_list(self, fileName):
+ msg = ""
+ fileName = self.escapes(str(fileName))
+ # Create Search Query for API request.
+ query = f"'{parent_id}' in parents and (name contains '{fileName}')"
+ response = self.__service.files().list(supportsTeamDrives=True,
+ includeTeamDriveItems=True,
+ q=query,
+ spaces='drive',
+ pageSize=200,
+ fields='files(id, name, mimeType, size)',
+ orderBy='name asc').execute()
+ content_count = 0
+ if response["files"]:
+ msg += f'
{len(response["files"])} Results: {fileName}
'
+ for file in response.get('files', []):
+ if file.get('mimeType') == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File.
+ furl = f"https://drive.google.com/drive/folders/{file.get('id')}"
+ msg += f"📁 {file.get('name')} (folder) "
+ if SHORTENER is not None and SHORTENER_API is not None:
+ sfurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={furl}&format=text').text
+ msg += f"Drive Link"
+ else:
+ msg += f"Drive Link"
+ if INDEX_URL is not None:
+ url_path = requests.utils.quote(f'{file.get("name")}')
+ url = f'{INDEX_URL}/{url_path}/'
+ if SHORTENER is not None and SHORTENER_API is not None:
+ siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text
+ msg += f' | Index Link'
+ else:
+ msg += f' | Index Link'
+ elif file.get('mimeType') == 'application/vnd.google-apps.shortcut':
+ msg += f"⁍{file.get('name')}" \
+ f" (shortcut)"
+ # Excluded index link as indexes cant download or open these shortcuts
+ else:
+ furl = f"https://drive.google.com/uc?id={file.get('id')}&export=download"
+ msg += f"📄 {file.get('name')} ({get_readable_file_size(int(file.get('size')))}) "
+ if SHORTENER is not None and SHORTENER_API is not None:
+ sfurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={furl}&format=text').text
+ msg += f"Drive Link"
+ else:
+ msg += f"Drive Link"
+ if INDEX_URL is not None:
+ url_path = requests.utils.quote(f'{file.get("name")}')
+ url = f'{INDEX_URL}/{url_path}'
+ urls = f'{INDEX_URL}/{url_path}?a=view'
+ if SHORTENER is not None and SHORTENER_API is not None:
+ siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text
+ siurls = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={urls}&format=text').text
+ msg += f' | Index Link'
+ if VIEW_LINK:
+ msg += f' | View Link'
+ else:
+ msg += f' | Index Link'
+ if VIEW_LINK:
+ msg += f' | View Link'
+ msg += '