[
  {
    "path": ".github/workflows/release.yml",
    "content": "name: MirrorX Release\n\non:\n  push:\n    tags:\n      - \"v*.*.*\"\n\njobs:\n  BuildWheel:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - name: Setup Python\n        uses: actions/setup-python@v1\n        with:\n          python-version: 3.8.12\n      - name: Get the version\n        id: get_version\n        run: echo ::set-output name=VERSION::${GITHUB_REF/refs\\/tags\\//}\n      - name: Install deps fro Pypi Release\n        run: |\n          pip -q install setuptools wheel twine\n          pip -q install -r requirements.txt\n      - name: Publish to pypi\n        env:\n          TWINE_USERNAME: __token__\n          TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}\n        run: |\n          python setup.py sdist bdist_wheel\n          twine upload dist/* || exit 0\n      - name: Upload all the data files to github Release\n        uses: softprops/action-gh-release@v1\n        with:\n          name: MirrorX Release ${{ steps.get_version.outputs.VERSION }}\n          files: |\n            dist/*\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n      - name: Sleep\n        run: sleep 60\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v1\n        with:\n          platforms: arm64\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v1\n      - name: Login to GitHub Container Registry\n        uses: docker/login-action@v1 \n        with:\n          registry: ghcr.io\n          username: token\n          password: ${{ secrets.GH_TOKEN }}\n      - name: Docker meta\n        id: metaraw\n        uses: docker/metadata-action@v3\n        with:\n          images: ghcr.io/iamliquidx/mirrorx\n          tags: |\n            type=semver,pattern={{version}}\n      - name: Build and push Docker images\n        uses: docker/build-push-action@v2\n        with:\n          context: .\n          file: ./Dockerfile\n          platforms: linux/amd64, linux/arm64/v8\n          push: true\n          tags: ${{ steps.metaraw.outputs.tags }}\n          labels: ${{ steps.metaraw.outputs.labels }}\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3.9-slim\n\nWORKDIR /\n# Deps\n\nSHELL [ \"/usr/bin/bash\" , \"-cel\" ]\n\nRUN \\\n[[ ${valid_arch:-aarch64 amd64 x86_64} =~ ${HOST_CPU_ARCH:=$(uname -m)} ]] \\\n  || echo 'unsupported cpu arch' && exit 1\n\nRUN \\\nexport HOST_CPU_ARCH=$(uname -m) \\\nsed -i 's/main/main non-free/g' /etc/apt/sources.list && \\\napt-get -qq update && \\\napt-get -qq install -y tzdata curl aria2 p7zip-full p7zip-rar wget xz-utils libmagic-dev gcc libffi-dev nscd && \\\napt-get -y autoremove && rm -rf /var/lib/apt/lists/* && apt-get clean && \\\nwget -q https://github.com/yzop/gg/raw/main/ffmpeg-git-${HOST_CPU_ARCH}-static.tar.xz && \\\ntar -xf ff*.tar.xz && rm -rf *.tar.xz && \\\nmv ff*/ff* /usr/local/bin/ && rm -rf ff* && \\\nwget -q https://github.com/viswanathbalusu/megasdkrest/releases/latest/download/megasdkrest-${HOST_CPU_ARCH} -O /usr/local/bin/megasdkrest && \\\nchmod a+x /usr/local/bin/megasdkrest && mkdir /app/ && chmod 777 /app/ && \\\npip3 install --no-cache-dir MirrorX && \\\napt-get purge -yqq gcc && apt-get -y autoremove && rm -rf /var/lib/apt/lists/* && apt-get clean\n\nWORKDIR /app\n\nCMD [\"MirrorX\"]\n\n###\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": " <p align=\"center\">\n  <img width=\"200\" src=\"https://media4.giphy.com/media/1jWAx072bAJwMebcl7/200w.gif?cid=82a1493bnsutnhqk7gyyjf1k0m8rbad3qp6t6gan3zf9vr6b&rid=200w.gif\" alt=\"Material Bread logo\">\n</p> \n\n\n<p align=\"center\">\n\n# This Is A Telegram Bot Written In Python For Mirroring Files On The Internet To Our Beloved Google Drive.\n</p>\n\nHere Are Some Things To Get You Started.👇\n\n\n## 👉[All The Feature Of This Bot Or What This Bot Can Do For You.](https://github.com/iamLiquidX/MirrorX/wiki/Feature-Or-What-This-Bot-Can-Do)\n\n## 👉[How To Deploy](https://github.com/iamLiquidX/MirrorX/wiki/How-To-Deploy)\n\n## 👉[Commands To Use The Bot](https://github.com/iamLiquidX/MirrorX/wiki/Commands-To-Use-This-Bot)\n\n## 👉[Modification Guide](https://github.com/iamLiquidX/MirrorX/wiki/Modification)\n\n\nFor The Most Recent Changes, Please Check The Changelog.👇\n\n## 👉[Changelog](https://github.com/iamLiquidX/MirrorX/wiki/Changelog)\n\n\n\n# Credits 👇\n\n1. [Shivam Jha aka lzzy12](https://github.com/lzzy12) & [JaskaranSM aka Zero Cool](https://github.com/jaskaranSM) - They Built This Bot From Scratch. \n2. [Sreeraj V R](https://github.com/SVR666)- Added Inline Button, Added Support For Deleting File/Folders From GDrive, Search Results On Telegra.ph.\n3. [Archie](https://github.com/archie9211) - Added Support For Extraction Of Archives, Fixed SSL Handshake Error, Update Trackers Dynamically.\n4. [Magneto](https://github.com/magneto261290) - Added Alot Of Customization, Support For Custom File Names, Support For Password Protected Archives, Quality Selection Option In YTDL And Much More.\n5. [KenHV](https://github.com/KenHV) - Many Fixes And Imporovements.\n6. [Anos](https://github.com/destiny6520) - Modification/Customization Guide.\n7. [Viswanath](https://github.com/nenokkadine) - Fixes & Improvements, Dockerfile Clean Up, DHT Support In Aria.  \n8. [breakdowns](https://github.com/breakdowns) - Source Code For Count,Zip/Unzip GDrive Links & Fembed.\n"
  },
  {
    "path": "bin/MirrorX",
    "content": "#!/bin/bash\npip3 install -U MirrorX\nMirrorXBot"
  },
  {
    "path": "bin/extract",
    "content": "#!/bin/bash\n\nif [ $# -lt 1 ]; then\n  echo \"Usage: $(basename $0) FILES\"\n  exit 1\nfi\n\nextract() {\n  arg=\"$1\"\n  cd \"$(dirname \"$arg\")\" || exit\n  case \"$arg\" in\n  *.tar.bz2)\n    tar xjf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.tar.gz)\n    tar xzf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.bz2)\n    bunzip2 \"$arg\"\n    local code=$?\n    ;;\n  *.gz)\n    gunzip \"$arg\"\n    local code=$?\n    ;;\n  *.tar)\n    tar xf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.tbz2)\n    (tar xjf \"$arg\" --one-top-level)\n    local code=$?\n    ;;\n  *.tgz)\n    tar xzf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.zip)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).zip')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.7z)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).7z')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.Z)\n    uncompress \"$arg\"\n    local code=$?\n    ;;\n  *.rar)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).rar')\n    mkdir \"$a_dir\"\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.iso)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).iso')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.wim)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).wim')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.cab)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cab')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.apm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).apm')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.arj)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).arj')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.chm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).chm')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.cpio)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cpio')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.cramfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cramfs')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.deb)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).deb')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.dmg)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).dmg')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.fat)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).fat')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.hfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).hfs')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.lzh)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzh')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.lzma)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzma')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.lzma2)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzma2')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.mbr)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).mbr')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.msi)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).msi')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.mslz)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).mslz')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.nsis)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).nsis')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.ntfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).ntfs')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.rpm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).rpm')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.squashfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).squashfs')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.udf)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).udf')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.vhd)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).vhd')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *.xar)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).xar')\n    7z x \"$arg\" -o\"$a_dir\"\n    local code=$?\n    ;;\n  *)\n    echo \"'$arg' cannot be extracted via extract()\" 1>&2\n    exit 1\n    ;;\n  esac\n  cd - || exit $?\n  exit $code\n}\n\nextract \"$1\"\n"
  },
  {
    "path": "bin/pextract",
    "content": "#!/bin/bash\n\nif [ $# -lt 1 ]; then\n  echo \"Usage: $(basename $0) FILES\"\n  exit 1\nfi\n\nextract() {\n  arg=\"$1\"\n  pswd=\"$2\"\n  cd \"$(dirname \"$arg\")\" || exit\n  case \"$arg\" in\n  *.tar.bz2)\n    tar xjf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.tar.gz)\n    tar xzf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.bz2)\n    bunzip2 \"$arg\"\n    local code=$?\n    ;;\n  *.gz)\n    gunzip \"$arg\"\n    local code=$?\n    ;;\n  *.tar)\n    tar xf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.tbz2)\n    (tar xjf \"$arg\" --one-top-level)\n    local code=$?\n    ;;\n  *.tgz)\n    tar xzf \"$arg\" --one-top-level\n    local code=$?\n    ;;\n  *.zip)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).zip')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.7z)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).7z')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.Z)\n    uncompress \"$arg\"\n    local code=$?\n    ;;\n  *.rar)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).rar')\n    mkdir \"$a_dir\"\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.iso)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).iso')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.wim)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).wim')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.cab)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cab')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.apm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).apm')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.arj)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).arj')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.chm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).chm')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.cpio)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cpio')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.cramfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).cramfs')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.deb)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).deb')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.dmg)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).dmg')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.fat)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).fat')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.hfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).hfs')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.lzh)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzh')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.lzma)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzma')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.lzma2)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).lzma2')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.mbr)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).mbr')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.msi)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).msi')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.mslz)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).mslz')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.nsis)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).nsis')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.ntfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).ntfs')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.rpm)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).rpm')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.squashfs)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).squashfs')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.udf)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).udf')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.vhd)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).vhd')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *.xar)\n    a_dir=$(expr \"$arg\" : '\\(.*\\).xar')\n    7z x \"$arg\" -o\"$a_dir\" -p\"$pswd\"\n    local code=$?\n    ;;\n  *)\n    echo \"'$arg' cannot be extracted via extract()\" 1>&2\n    exit 1\n    ;;\n  esac\n  cd - || exit $?\n  exit $code\n}\n\nextract \"$1\" \"$2\""
  },
  {
    "path": "bot/__init__.py",
    "content": "import logging\nimport os\nimport threading\nimport time\nimport random\nimport string\nimport subprocess\nimport pkgutil\nimport pathlib\nimport sys\n\nimport aria2p\nimport requests\nimport telegram.ext as tg\nfrom dotenv import load_dotenv\nfrom pyrogram import Client\nfrom telegraph import Telegraph\nfrom megasdkrestclient import MegaSdkRestClient, errors as mega_err\n\nimport socket\nimport faulthandler\nfaulthandler.enable()\n\nsocket.setdefaulttimeout(600)\n\nbotStartTime = time.time()\nif os.path.exists('log.txt'):\n    with open('log.txt', 'r+') as f:\n        f.truncate(0)\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n                    handlers=[logging.FileHandler('log.txt'), logging.StreamHandler()],\n                    level=logging.INFO)\n\nload_dotenv('config.env')\n\nInterval = []\n\n\ndef getConfig(name: str):\n    return os.environ[name]\n\n\nLOGGER = logging.getLogger(__name__)\n\ntry:\n    if bool(getConfig('_____REMOVE_THIS_LINE_____')):\n        logging.error('The README.md file there to be read! Exiting now!')\n        exit()\nexcept KeyError:\n    pass\nCWD = os.getcwd()\nariaconfig = pkgutil.get_data(\"bot\", \"data/aria.conf\").decode()\ndhtfile = pkgutil.get_data(\"bot\", \"data/dht.dat\")\ndht6file = pkgutil.get_data(\"bot\", \"data/dht6.dat\")\nwith open(\"dht.dat\", \"wb+\") as dht:\n    dht.write(dhtfile)\nwith open(\"dht6.dat\", \"wb+\") as dht6:\n    dht6.write(dhtfile)\nariaconfig = ariaconfig.replace(\"/currentwd\", str(CWD))\ntry:\n    max_dl = getConfig(\"MAX_CONCURRENT_DOWNLOADS\")\nexcept KeyError:\n    max_dl = \"4\"\ntracker_list = requests.get(\"https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all_aria2.txt\").text\nariaconfig += f\"\\nmax-concurrent-downloads={max_dl}\\nbt-tracker={tracker_list}\"\n\nwith open(\"aria.conf\", \"w+\") as ariaconf:\n    ariaconf.write(ariaconfig)\n\nARIA_CHILD_PROC = None\ntry:\n    ARIA_CHILD_PROC = subprocess.Popen([\"aria2c\", f\"--conf-path={CWD}/aria.conf\"])\nexcept FileNotFoundError:\n    LOGGER.error(\"Please install Aria2c, Exiting..\")\n    sys.exit(0)\nexcept OSError:\n    LOGGER.error(\"Aria2c Binary might have got damaged, Please Check and reinstall..\")\n    sys.exit(0)\ntime.sleep(1)\n\naria2 = aria2p.API(\n    aria2p.Client(\n        host=\"http://localhost\",\n        port=6800,\n        secret=\"\",\n    )\n)\n\nDOWNLOAD_DIR = None\nBOT_TOKEN = None\n\ndownload_dict_lock = threading.Lock()\nstatus_reply_dict_lock = threading.Lock()\n# Key: update.effective_chat.id\n# Value: telegram.Message\nstatus_reply_dict = {}\n# Key: update.message.message_id\n# Value: An object of Status\ndownload_dict = {}\n# Stores list of users and chats the bot is authorized to use in\nAUTHORIZED_CHATS = set()\nif os.path.exists('authorized_chats.txt'):\n    with open('authorized_chats.txt', 'r+') as f:\n        lines = f.readlines()\n        for line in lines:\n            #    LOGGER.info(line.split())\n            AUTHORIZED_CHATS.add(int(line.split()[0]))\ntry:\n    achats = getConfig('AUTHORIZED_CHATS')\n    achats = achats.split(\" \")\n    for chats in achats:\n        AUTHORIZED_CHATS.add(int(chats))\nexcept:\n    pass\n\ntry:\n    BOT_TOKEN = getConfig('BOT_TOKEN')\n    parent_id = getConfig('GDRIVE_FOLDER_ID')\n    DOWNLOAD_DIR = getConfig('DOWNLOAD_DIR')\n    if not DOWNLOAD_DIR.endswith(\"/\"):\n        DOWNLOAD_DIR = DOWNLOAD_DIR + '/'\n    if not os.path.exists(DOWNLOAD_DIR):\n        os.makedirs(DOWNLOAD_DIR, 0o777)\n    DOWNLOAD_STATUS_UPDATE_INTERVAL = int(getConfig('DOWNLOAD_STATUS_UPDATE_INTERVAL'))\n    OWNER_ID = int(getConfig('OWNER_ID'))\n    AUTO_DELETE_MESSAGE_DURATION = int(getConfig('AUTO_DELETE_MESSAGE_DURATION'))\n    TELEGRAM_API = getConfig('TELEGRAM_API')\n    TELEGRAM_HASH = getConfig('TELEGRAM_HASH')\nexcept KeyError as e:\n    LOGGER.error(\"One or more env variables missing! Exiting now\")\n    sys.exit()\n    # exit()\n\nLOGGER.info(\"Generating USER_SESSION_STRING\")\napp = Client(':memory:', api_id=int(TELEGRAM_API), api_hash=TELEGRAM_HASH, bot_token=BOT_TOKEN)\n\n#Generate Telegraph Token\nsname = ''.join(random.SystemRandom().choices(string.ascii_letters, k=8))\nLOGGER.info(\"Generating Telegraph Token using '\" + sname + \"' name\")\ntelegraph = Telegraph()\ntelegraph.create_account(short_name=sname)\ntelegraph_token = telegraph.get_access_token()\nLOGGER.info(\"Telegraph Token Generated: '\" + telegraph_token + \"'\")\n\ntry:\n    UPTOBOX_TOKEN = getConfig('UPTOBOX_TOKEN')\nexcept KeyError:\n    logging.warning('UPTOBOX_TOKEN not provided!')\n    UPTOBOX_TOKEN = None\n\ntry:\n    MEGA_KEY = getConfig('MEGA_KEY')\nexcept KeyError:\n    MEGA_KEY = None\n    LOGGER.info('MEGA API KEY NOT AVAILABLE')\nMEGA_CHILD_PROC = None\nif MEGA_KEY is not None:\n    try:\n        MEGA_CHILD_PROC = subprocess.Popen([\"megasdkrest\", \"--apikey\", MEGA_KEY])\n    except FileNotFoundError:\n        LOGGER.error(\"Please install Megasdkrest Binary, Exiting..\")\n        sys.exit(0)\n    except OSError:\n        LOGGER.error(\"Megasdkrest Binary might have got damaged, Please Check ..\")\n        sys.exit(0)\n    time.sleep(3)\n    mega_client = MegaSdkRestClient('http://localhost:6090')\n    try:\n        MEGA_USERNAME = getConfig('MEGA_USERNAME')\n        MEGA_PASSWORD = getConfig('MEGA_PASSWORD')\n        if len(MEGA_USERNAME) > 0 and len(MEGA_PASSWORD) > 0:\n            try:\n                mega_client.login(MEGA_USERNAME, MEGA_PASSWORD)\n            except mega_err.MegaSdkRestClientException as e:\n                logging.error(e.message['message'])\n                exit(0)\n        else:\n            LOGGER.info(\"Mega API KEY provided but credentials not provided. Starting mega in anonymous mode!\")\n            MEGA_USERNAME = None\n            MEGA_PASSWORD = None\n    except KeyError:\n        LOGGER.info(\"Mega API KEY provided but credentials not provided. Starting mega in anonymous mode!\")\n        MEGA_USERNAME = None\n        MEGA_PASSWORD = None\nelse:\n    MEGA_USERNAME = None\n    MEGA_PASSWORD = None\ntry:\n    INDEX_URL = getConfig('INDEX_URL')\n    if len(INDEX_URL) == 0:\n        INDEX_URL = None\nexcept KeyError:\n    INDEX_URL = None\ntry:\n    BUTTON_THREE_NAME = getConfig('BUTTON_THREE_NAME')\n    BUTTON_THREE_URL = getConfig('BUTTON_THREE_URL')\n    if len(BUTTON_THREE_NAME) == 0 or len(BUTTON_THREE_URL) == 0:\n        raise KeyError\nexcept KeyError:\n    BUTTON_THREE_NAME = None\n    BUTTON_THREE_URL = None\ntry:\n    BUTTON_FOUR_NAME = getConfig('BUTTON_FOUR_NAME')\n    BUTTON_FOUR_URL = getConfig('BUTTON_FOUR_URL')\n    if len(BUTTON_FOUR_NAME) == 0 or len(BUTTON_FOUR_URL) == 0:\n        raise KeyError\nexcept KeyError:\n    BUTTON_FOUR_NAME = None\n    BUTTON_FOUR_URL = None\ntry:\n    BUTTON_FIVE_NAME = getConfig('BUTTON_FIVE_NAME')\n    BUTTON_FIVE_URL = getConfig('BUTTON_FIVE_URL')\n    if len(BUTTON_FIVE_NAME) == 0 or len(BUTTON_FIVE_URL) == 0:\n        raise KeyError\nexcept KeyError:\n    BUTTON_FIVE_NAME = None\n    BUTTON_FIVE_URL = None\ntry:\n    STOP_DUPLICATE_MIRROR = getConfig('STOP_DUPLICATE_MIRROR')\n    if STOP_DUPLICATE_MIRROR.lower() == 'true':\n        STOP_DUPLICATE_MIRROR = True\n    else:\n        STOP_DUPLICATE_MIRROR = False\nexcept KeyError:\n    STOP_DUPLICATE_MIRROR = False\ntry:\n    IS_TEAM_DRIVE = getConfig('IS_TEAM_DRIVE')\n    if IS_TEAM_DRIVE.lower() == 'true':\n        IS_TEAM_DRIVE = True\n    else:\n        IS_TEAM_DRIVE = False\nexcept KeyError:\n    IS_TEAM_DRIVE = False\n\ntry:\n    USE_SERVICE_ACCOUNTS = getConfig('USE_SERVICE_ACCOUNTS')\n    if USE_SERVICE_ACCOUNTS.lower() == 'true':\n        USE_SERVICE_ACCOUNTS = True\n    else:\n        USE_SERVICE_ACCOUNTS = False\nexcept KeyError:\n    USE_SERVICE_ACCOUNTS = False\n\ntry:\n    BLOCK_MEGA_LINKS = getConfig('BLOCK_MEGA_LINKS')\n    if BLOCK_MEGA_LINKS.lower() == 'true':\n        BLOCK_MEGA_LINKS = True\n    else:\n        BLOCK_MEGA_LINKS = False\nexcept KeyError:\n    BLOCK_MEGA_LINKS = False\n\ntry:\n    SHORTENER = getConfig('SHORTENER')\n    SHORTENER_API = getConfig('SHORTENER_API')\n    if len(SHORTENER) == 0 or len(SHORTENER_API) == 0:\n        raise KeyError\nexcept KeyError:\n    SHORTENER = None\n    SHORTENER_API = None\n\nupdater = tg.Updater(token=BOT_TOKEN)\nbot = updater.bot\ndispatcher = updater.dispatcher\n"
  },
  {
    "path": "bot/__main__.py",
    "content": "import os\nimport shutil, psutil\nimport signal\n\nfrom sys import executable\nimport time\n\nfrom telegram.ext import CommandHandler\nfrom bot import bot, dispatcher, updater, botStartTime\nfrom bot.helper.ext_utils import fs_utils\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.telegram_helper.message_utils import *\nfrom .helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time\nfrom .helper.telegram_helper.filters import CustomFilters\nfrom .modules import authorize, list, cancel_mirror, mirror_status, mirror, clone, watch, delete, speedtest, count\n\nfrom pyrogram import idle\nfrom bot import app\n\n\ndef stats(update, context):\n    currentTime = get_readable_time(time.time() - botStartTime)\n    total, used, free = shutil.disk_usage('.')\n    total = get_readable_file_size(total)\n    used = get_readable_file_size(used)\n    free = get_readable_file_size(free)\n    sent = get_readable_file_size(psutil.net_io_counters().bytes_sent)\n    recv = get_readable_file_size(psutil.net_io_counters().bytes_recv)\n    cpuUsage = psutil.cpu_percent(interval=0.5)\n    memory = psutil.virtual_memory().percent\n    disk = psutil.disk_usage('/').percent\n    stats = f'<b>Bot Uptime:-</b> {currentTime}\\n' \\\n            f'<b>Total Disk Space:-</b> {total}\\n' \\\n            f'<b>Used:-</b> {used}  ' \\\n            f'<b>Free:-</b> {free}\\n\\n' \\\n            f'Data Usage\\n<b>Up:-</b> {sent}\\n' \\\n            f'<b>Down:-</b> {recv}\\n\\n' \\\n            f'<b>CPU:</b> {cpuUsage}% ' \\\n            f'<b>RAM:</b> {memory}% ' \\\n            f'<b>Disk:</b> {disk}%'\n    sendMessage(stats, context.bot, update)\n\n\ndef start(update, context):\n    start_string = f'''\nThis is a bot which can mirror all your links to Google drive!\nType /{BotCommands.HelpCommand} to get a list of available commands\n'''\n    sendMessage(start_string, context.bot, update)\n\n\ndef restart(update, context):\n    restart_message = sendMessage(\"Restarting, Please wait!\", context.bot, update)\n    # Save restart message ID and chat ID in order to edit it after restarting\n    with open(\".restartmsg\", \"w\") as f:\n        f.truncate(0)\n        f.write(f\"{restart_message.chat.id}\\n{restart_message.message_id}\\n\")\n    fs_utils.clean_all()\n    os.execl(executable, executable, \"-m\", \"bot\")\n\n\ndef ping(update, context):\n    start_time = int(round(time.time() * 1000))\n    reply = sendMessage(\"Starting Ping\", context.bot, update)\n    end_time = int(round(time.time() * 1000))\n    editMessage(f'{end_time - start_time} ms', reply)\n\n\ndef log(update, context):\n    sendLogFile(context.bot, update)\n\n\ndef bot_help(update, context):\n    help_string = f'''\n/{BotCommands.HelpCommand}: To get this message\n\n/{BotCommands.MirrorCommand} [download_url][magnet_link]: Start mirroring the link to google drive.\\n\n\n/{BotCommands.UnzipMirrorCommand} [download_url][magnet_link] : starts mirroring and if downloaded file is any archive , extracts it to google drive\n\n/{BotCommands.CountCommand}: Count files/folders of G-Drive Links\n\n/{BotCommands.TarMirrorCommand} [download_url][magnet_link]: start mirroring and upload the archived (.tar) version of the download\n\n/{BotCommands.WatchCommand} [youtube-dl supported link]: Mirror through youtube-dl. Click /{BotCommands.WatchCommand} for more help.\n\n/{BotCommands.TarWatchCommand} [youtube-dl supported link]: Mirror through youtube-dl and tar before uploading\n\n/{BotCommands.CancelMirror} : Reply to the message by which the download was initiated and that download will be cancelled\n\n/{BotCommands.StatusCommand}: Shows a status of all the downloads\n\n/{BotCommands.ListCommand} [search term]: Searches the search term in the Google drive, if found replies with the link\n\n/{BotCommands.StatsCommand}: Show Stats of the machine the bot is hosted on\n\n/{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Can only be invoked by owner of the bot)\n\n/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports\n\n/{BotCommands.SpeedCommand} : Check Internet Speed Of The Host\n\n'''\n    sendMessage(help_string, context.bot, update)\n\n\ndef main():\n    fs_utils.start_cleanup()\n    # Check if the bot is restarting\n    if os.path.isfile(\".restartmsg\"):\n        with open(\".restartmsg\") as f:\n            chat_id, msg_id = map(int, f)\n        bot.edit_message_text(\"Restarted successfully!\", chat_id, msg_id)\n        os.remove(\".restartmsg\")\n\n    start_handler = CommandHandler(BotCommands.StartCommand, start,\n                                   filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\n    ping_handler = CommandHandler(BotCommands.PingCommand, ping,\n                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\n    restart_handler = CommandHandler(BotCommands.RestartCommand, restart,\n                                     filters=CustomFilters.owner_filter| CustomFilters.authorized_user, run_async=True)\n    help_handler = CommandHandler(BotCommands.HelpCommand,\n                                  bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\n    stats_handler = CommandHandler(BotCommands.StatsCommand,\n                                   stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\n    log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter, run_async=True)\n    dispatcher.add_handler(start_handler)\n    dispatcher.add_handler(ping_handler)\n    dispatcher.add_handler(restart_handler)\n    dispatcher.add_handler(help_handler)\n    dispatcher.add_handler(stats_handler)\n    dispatcher.add_handler(log_handler)\n    updater.start_polling()\n    LOGGER.info(\"Bot Started!\")\n    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)\n\napp.start()\nmain()\nidle()\n"
  },
  {
    "path": "bot/helper/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/ext_utils/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/ext_utils/bot_utils.py",
    "content": "import logging\nimport re\nimport threading\nimport time\n\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot import download_dict, download_dict_lock\n\nLOGGER = logging.getLogger(__name__)\n\nMAGNET_REGEX = r\"magnet:\\?xt=urn:btih:[a-zA-Z0-9]*\"\n\nURL_REGEX = r\"(?:(?:https?|ftp):\\/\\/)?[\\w/\\-?=%.]+\\.[\\w/\\-?=%.]+\"\n\n\nclass MirrorStatus:\n    STATUS_UPLOADING = \"Uploading\"\n    STATUS_DOWNLOADING = \"Downloading\"\n    STATUS_WAITING = \"Queued\"\n    STATUS_FAILED = \"Failed.Cleaning download\"\n    STATUS_CANCELLED = \"Cancelled \"\n    STATUS_ARCHIVING = \"Archiving\"\n    STATUS_EXTRACTING = \"Extracting\"\n\n\nPROGRESS_MAX_SIZE = 100 // 8\nPROGRESS_INCOMPLETE = ['█', '█', '█', '█', '█', '█', '█']\n\nSIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\n\n\nclass setInterval:\n    def __init__(self, interval, action):\n        self.interval = interval\n        self.action = action\n        self.stopEvent = threading.Event()\n        thread = threading.Thread(target=self.__setInterval)\n        thread.start()\n\n    def __setInterval(self):\n        nextTime = time.time() + self.interval\n        while not self.stopEvent.wait(nextTime - time.time()):\n            nextTime += self.interval\n            self.action()\n\n    def cancel(self):\n        self.stopEvent.set()\n\n\ndef get_readable_file_size(size_in_bytes) -> str:\n    if size_in_bytes is None:\n        return '0B'\n    index = 0\n    while size_in_bytes >= 1024:\n        size_in_bytes /= 1024\n        index += 1\n    try:\n        return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}'\n    except IndexError:\n        return 'File too large'\n\n\ndef getDownloadByGid(gid):\n    with download_dict_lock:\n        for dl in download_dict.values():\n            status = dl.status()\n            if status != MirrorStatus.STATUS_UPLOADING and status != MirrorStatus.STATUS_ARCHIVING \\\n                    and status != MirrorStatus.STATUS_EXTRACTING:\n                if dl.gid() == gid:\n                    return dl\n    return None\n\n\ndef get_progress_bar_string(status):\n    completed = status.processed_bytes() / 8\n    total = status.size_raw() / 8\n    if total == 0:\n        p = 0\n    else:\n        p = round(completed * 100 / total)\n    p = min(max(p, 0), 100)\n    cFull = p // 8\n    cPart = p % 8 - 1\n    p_str = '█' * cFull\n    if cPart >= 0:\n        p_str += PROGRESS_INCOMPLETE[cPart]\n    p_str += '░' * (PROGRESS_MAX_SIZE - cFull)\n    p_str = f\"[{p_str}]\"\n    return p_str\n\n\ndef get_readable_message():\n    with download_dict_lock:\n        msg = \"\"\n        for download in list(download_dict.values()):\n            msg += f\"<b>Name:-</b> <code>{download.name()}</code>\"\n            msg += f\"\\n<b>Status:-</b> <i>{download.status()}</i>\"\n            if download.status() != MirrorStatus.STATUS_ARCHIVING and download.status() != MirrorStatus.STATUS_EXTRACTING:\n                msg += f\"\\n<code>{get_progress_bar_string(download)} {download.progress()}</code>\"\n                if download.status() == MirrorStatus.STATUS_DOWNLOADING:\n                    msg += f\"\\n<b>Downloaded:-</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}\"\n                else:\n                    msg += f\"\\n<b>Uploaded:-</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}\"\n                msg += f\"\\n<b>Speed:-</b> {download.speed()}, \\n<b>ETA:- </b> {download.eta()} \"\n                # if hasattr(download, 'is_torrent'):\n                try:\n                    msg += f\"\\n<b>Info: Seeders:-</b> {download.aria_download().num_seeders}\" \\\n                        f\" & <b>Peers:-</b> {download.aria_download().connections}\"\n                except:\n                    pass\n            if download.status() == MirrorStatus.STATUS_DOWNLOADING:\n                msg += f\"\\n<b>To Stop:-</b> <code>/{BotCommands.CancelMirror} {download.gid()}</code>\"                 \n            msg += \"\\n\\n\"\n        return msg\n\n\ndef get_readable_time(seconds: int) -> str:\n    result = ''\n    (days, remainder) = divmod(seconds, 86400)\n    days = int(days)\n    if days != 0:\n        result += f'{days}d'\n    (hours, remainder) = divmod(remainder, 3600)\n    hours = int(hours)\n    if hours != 0:\n        result += f'{hours}h'\n    (minutes, seconds) = divmod(remainder, 60)\n    minutes = int(minutes)\n    if minutes != 0:\n        result += f'{minutes}m'\n    seconds = int(seconds)\n    result += f'{seconds}s'\n    return result\n\n\ndef is_url(url: str):\n    url = re.findall(URL_REGEX, url)\n    if url:\n        return True\n    return False\n\n\ndef is_magnet(url: str):\n    magnet = re.findall(MAGNET_REGEX, url)\n    if magnet:\n        return True\n    return False\n\ndef is_gdrive_link(url: str):\n    return \"drive.google.com\" in url\n\ndef is_mega_link(url: str):\n    return \"mega.nz\" in url\n\ndef get_mega_link_type(url: str):\n    if \"folder\" in url:\n        return \"folder\"\n    elif \"file\" in url:\n        return \"file\"\n    elif \"/#F!\" in url:\n        return \"folder\"\n    return \"file\"\n\n\ndef new_thread(fn):\n    \"\"\"To use as decorator to make a function call threaded.\n    Needs import\n    from threading import Thread\"\"\"\n\n    def wrapper(*args, **kwargs):\n        thread = threading.Thread(target=fn, args=args, kwargs=kwargs)\n        thread.start()\n        return thread\n\n    return wrapper\n"
  },
  {
    "path": "bot/helper/ext_utils/exceptions.py",
    "content": "class DirectDownloadLinkException(Exception):\n    \"\"\"Not method found for extracting direct download link from the http link\"\"\"\n    pass\n\n\nclass NotSupportedExtractionArchive(Exception):\n    \"\"\"The archive format use is trying to extract is not supported\"\"\"\n    pass\n"
  },
  {
    "path": "bot/helper/ext_utils/fs_utils.py",
    "content": "import sys\nfrom bot import aria2, LOGGER, DOWNLOAD_DIR, ARIA_CHILD_PROC, MEGA_CHILD_PROC\nimport shutil\nimport os\nimport pathlib\nimport magic\nimport tarfile\nfrom .exceptions import NotSupportedExtractionArchive\n\n\ndef clean_download(path: str):\n    if os.path.exists(path):\n        LOGGER.info(f\"Cleaning download: {path}\")\n        shutil.rmtree(path)\n\n\ndef start_cleanup():\n    try:\n        shutil.rmtree(DOWNLOAD_DIR)\n    except FileNotFoundError:\n        pass\n\n\ndef clean_all():\n    aria2.remove_all(True)\n    try:\n        shutil.rmtree(DOWNLOAD_DIR)\n    except FileNotFoundError:\n        pass\n\n\ndef exit_clean_up(signal, frame):\n    try:\n        LOGGER.info(\"Please wait, while we clean up the downloads and stop running downloads\")\n        clean_all()\n        ARIA_CHILD_PROC.kill()\n        MEGA_CHILD_PROC.kill()\n        sys.exit(0)\n    except KeyboardInterrupt:\n        LOGGER.warning(\"Force Exiting before the cleanup finishes!\")\n        ARIA_CHILD_PROC.kill()\n        MEGA_CHILD_PROC.kill()\n        sys.exit(1)\n\n\ndef get_path_size(path):\n    if os.path.isfile(path):\n        return os.path.getsize(path)\n    total_size = 0\n    for root, dirs, files in os.walk(path):\n        for f in files:\n            abs_path = os.path.join(root, f)\n            total_size += os.path.getsize(abs_path)\n    return total_size\n\n\ndef tar(org_path):\n    tar_path = org_path + \".tar\"\n    path = pathlib.PurePath(org_path)\n    LOGGER.info(f'Tar: orig_path: {org_path}, tar_path: {tar_path}')\n    tar = tarfile.open(tar_path, \"w\")\n    tar.add(org_path, arcname=path.name)\n    tar.close()\n    return tar_path\n\n\ndef get_base_name(orig_path: str):\n    if orig_path.endswith(\".tar.bz2\"):\n        return orig_path.replace(\".tar.bz2\", \"\")\n    elif orig_path.endswith(\".tar.gz\"):\n        return orig_path.replace(\".tar.gz\", \"\")\n    elif orig_path.endswith(\".bz2\"):\n        return orig_path.replace(\".bz2\", \"\")\n    elif orig_path.endswith(\".gz\"):\n        return orig_path.replace(\".gz\", \"\")\n    elif orig_path.endswith(\".tar\"):\n        return orig_path.replace(\".tar\", \"\")\n    elif orig_path.endswith(\".tbz2\"):\n        return orig_path.replace(\"tbz2\", \"\")\n    elif orig_path.endswith(\".tgz\"):\n        return orig_path.replace(\".tgz\", \"\")\n    elif orig_path.endswith(\".zip\"):\n        return orig_path.replace(\".zip\", \"\")\n    elif orig_path.endswith(\".7z\"):\n        return orig_path.replace(\".7z\", \"\")\n    elif orig_path.endswith(\".Z\"):\n        return orig_path.replace(\".Z\", \"\")\n    elif orig_path.endswith(\".rar\"):\n        return orig_path.replace(\".rar\", \"\")\n    elif orig_path.endswith(\".iso\"):\n        return orig_path.replace(\".iso\", \"\")\n    elif orig_path.endswith(\".wim\"):\n        return orig_path.replace(\".wim\", \"\")\n    elif orig_path.endswith(\".cab\"):\n        return orig_path.replace(\".cab\", \"\")\n    elif orig_path.endswith(\".apm\"):\n        return orig_path.replace(\".apm\", \"\")\n    elif orig_path.endswith(\".arj\"):\n        return orig_path.replace(\".arj\", \"\")\n    elif orig_path.endswith(\".chm\"):\n        return orig_path.replace(\".chm\", \"\")\n    elif orig_path.endswith(\".cpio\"):\n        return orig_path.replace(\".cpio\", \"\")\n    elif orig_path.endswith(\".cramfs\"):\n        return orig_path.replace(\".cramfs\", \"\")\n    elif orig_path.endswith(\".deb\"):\n        return orig_path.replace(\".deb\", \"\")\n    elif orig_path.endswith(\".dmg\"):\n        return orig_path.replace(\".dmg\", \"\")\n    elif orig_path.endswith(\".fat\"):\n        return orig_path.replace(\".fat\", \"\")\n    elif orig_path.endswith(\".hfs\"):\n        return orig_path.replace(\".hfs\", \"\")\n    elif orig_path.endswith(\".lzh\"):\n        return orig_path.replace(\".lzh\", \"\")\n    elif orig_path.endswith(\".lzma\"):\n        return orig_path.replace(\".lzma\", \"\")\n    elif orig_path.endswith(\".lzma2\"):\n        return orig_path.replace(\".lzma2\", \"\")\n    elif orig_path.endswith(\".mbr\"):\n        return orig_path.replace(\".mbr\", \"\")\n    elif orig_path.endswith(\".msi\"):\n        return orig_path.replace(\".msi\", \"\")\n    elif orig_path.endswith(\".mslz\"):\n        return orig_path.replace(\".mslz\", \"\")\n    elif orig_path.endswith(\".nsis\"):\n        return orig_path.replace(\".nsis\", \"\")\n    elif orig_path.endswith(\".ntfs\"):\n        return orig_path.replace(\".ntfs\", \"\")\n    elif orig_path.endswith(\".rpm\"):\n        return orig_path.replace(\".rpm\", \"\")\n    elif orig_path.endswith(\".squashfs\"):\n        return orig_path.replace(\".squashfs\", \"\")\n    elif orig_path.endswith(\".udf\"):\n        return orig_path.replace(\".udf\", \"\")\n    elif orig_path.endswith(\".vhd\"):\n        return orig_path.replace(\".vhd\", \"\")\n    elif orig_path.endswith(\".xar\"):\n        return orig_path.replace(\".xar\", \"\")\n    else:\n        raise NotSupportedExtractionArchive('File format not supported for extraction')\n\n\ndef get_mime_type(file_path):\n    mime = magic.Magic(mime=True)\n    mime_type = mime.from_file(file_path)\n    mime_type = mime_type if mime_type else \"text/plain\"\n    return mime_type\n"
  },
  {
    "path": "bot/helper/mirror_utils/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/aria2_download.py",
    "content": "from bot import aria2, download_dict_lock, STOP_DUPLICATE_MIRROR\nfrom bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper\nfrom bot.helper.ext_utils.bot_utils import *\nfrom .download_helper import DownloadHelper\nfrom bot.helper.mirror_utils.status_utils.aria_download_status import AriaDownloadStatus\nfrom bot.helper.telegram_helper.message_utils import *\nimport threading\nfrom aria2p import API\nfrom time import sleep\n\n\nclass AriaDownloadHelper(DownloadHelper):\n\n    def __init__(self):\n        super().__init__()\n\n    @new_thread\n    def __onDownloadStarted(self, api, gid):\n        sleep(1)\n        LOGGER.info(f\"onDownloadStart: {gid}\")\n        dl = getDownloadByGid(gid)\n        download = api.get_download(gid)\n        self.name = download.name\n        sname = download.name\n        if STOP_DUPLICATE_MIRROR:\n          if dl.getListener().isTar == True:\n            sname = sname + \".tar\"\n          if dl.getListener().extract == True:\n            smsg = None\n          else:\n            gdrive = GoogleDriveHelper(None)\n            smsg, button = gdrive.drive_list(sname)\n          if smsg:\n              dl.getListener().onDownloadError(f'File is already available in drive.This download has been stopped.\\n\\n')\n              sendMarkup(\"Here are the search results:\", dl.getListener().bot, dl.getListener().update, button)\n              aria2.remove([download])\n          return\n        update_all_messages()\n    def __onDownloadComplete(self, api: API, gid):\n        LOGGER.info(f\"onDownloadComplete: {gid}\")\n        dl = getDownloadByGid(gid)\n        download = api.get_download(gid)\n        if download.followed_by_ids:\n            new_gid = download.followed_by_ids[0]\n            new_download = api.get_download(new_gid)\n            with download_dict_lock:\n                download_dict[dl.uid()] = AriaDownloadStatus(new_gid, dl.getListener())\n                if new_download.is_torrent:\n                    download_dict[dl.uid()].is_torrent = True\n            update_all_messages()\n            LOGGER.info(f'Changed gid from {gid} to {new_gid}')\n        else:\n            if dl: threading.Thread(target=dl.getListener().onDownloadComplete).start()\n\n    @new_thread\n    def __onDownloadPause(self, api, gid):\n        LOGGER.info(f\"onDownloadPause: {gid}\")\n        dl = getDownloadByGid(gid)\n        dl.getListener().onDownloadError('Download stopped by user!')\n\n    @new_thread\n    def __onDownloadStopped(self, api, gid):\n        LOGGER.info(f\"onDownloadStop: {gid}\")\n        dl = getDownloadByGid(gid)\n        if dl: dl.getListener().onDownloadError('Your torrent has no seeds.Download stopped automatically.')\n\n    @new_thread\n    def __onDownloadError(self, api, gid):\n        sleep(0.5) #sleep for split second to ensure proper dl gid update from onDownloadComplete\n        LOGGER.info(f\"onDownloadError: {gid}\")\n        dl = getDownloadByGid(gid)\n        download = api.get_download(gid)\n        error = download.error_message\n        LOGGER.info(f\"Download Error: {error}\")\n        if dl: dl.getListener().onDownloadError(error)\n\n    def start_listener(self):\n        aria2.listen_to_notifications(threaded=True, on_download_start=self.__onDownloadStarted,\n                                      on_download_error=self.__onDownloadError,\n                                      on_download_pause=self.__onDownloadPause,\n                                      on_download_stop=self.__onDownloadStopped,\n                                      on_download_complete=self.__onDownloadComplete)\n\n\n    def add_download(self, link: str, path, listener, filename):\n        if is_magnet(link):\n            download = aria2.add_magnet(link, {'dir': path, 'out': filename})\n        else:\n            download = aria2.add_uris([link], {'dir': path, 'out': filename})\n        if download.error_message: #no need to proceed further at this point\n            listener.onDownloadError(download.error_message)\n            return \n        with download_dict_lock:\n            download_dict[listener.uid] = AriaDownloadStatus(download.gid,listener)\n            LOGGER.info(f\"Started: {download.gid} DIR:{download.dir} \")\n\n\n"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/direct_link_generator.py",
    "content": "# Copyright (C) 2019 The Raphielscape Company LLC.\n#\n# Licensed under the Raphielscape Public License, Version 1.c (the \"License\");\n# you may not use this file except in compliance with the License.\n#\n\"\"\" Helper Module containing various sites direct links generators. This module is copied and modified as per need\nfrom https://github.com/AvinashReddy3108/PaperplaneExtended . I hereby take no credit of the following code other\nthan the modifications. See https://github.com/AvinashReddy3108/PaperplaneExtended/commits/master/userbot/modules/direct_links.py\nfor original authorship. \"\"\"\n\nimport json\nimport re\nimport math \nimport urllib.parse\nfrom os import popen\nfrom random import choice\nfrom urllib.parse import urlparse\n\nimport lk21\nimport requests\nimport logging\nfrom bot import UPTOBOX_TOKEN\nfrom bs4 import BeautifulSoup\nfrom lk21.extractors.bypasser import Bypass\nfrom base64 import standard_b64encode\nfrom js2py import EvalJs\n\nfrom bot.helper.ext_utils.exceptions import DirectDownloadLinkException\n\n\ndef direct_link_generator(link: str):\n    \"\"\" direct links generator \"\"\"\n    if not link:\n        raise DirectDownloadLinkException(\"`No links found!`\")\n    elif 'zippyshare.com' in link:\n        return zippy_share(link)\n    elif 'yadi.sk' in link:\n        return yandex_disk(link)\n    elif 'cloud.mail.ru' in link:\n        return cm_ru(link)\n    elif 'mediafire.com' in link:\n        return mediafire(link)\n    elif 'uptobox.com' in link:\n        return uptobox(link)\n    elif 'osdn.net' in link:\n        return osdn(link)\n    elif 'github.com' in link:\n        return github(link)\n    elif 'fembed.com' in link:\n        return fembed(link)\n    elif 'femax20.com' in link:\n        return fembed(link)\n    elif 'feurl.com' in link:\n        return fembed(link)\n    else:\n        raise DirectDownloadLinkException(f'No Direct link function found for {link}')\n\n\ndef zippy_share(url: str) -> str:\n    link = re.findall(\"https:/.(.*?).zippyshare\", url)[0]\n    response_content = (requests.get(url)).content\n    bs_obj = BeautifulSoup(response_content, \"lxml\")\n\n    try:\n        js_script = bs_obj.find(\"div\", {\"class\": \"center\",}).find_all(\n            \"script\"\n        )[1]\n    except:\n        js_script = bs_obj.find(\"div\", {\"class\": \"right\",}).find_all(\n            \"script\"\n        )[0]\n\n    js_content = re.findall(r'\\.href.=.\"/(.*?)\";', str(js_script))\n    js_content = 'var x = \"/' + js_content[0] + '\"'\n\n    evaljs = EvalJs()\n    setattr(evaljs, \"x\", None)\n    evaljs.execute(js_content)\n    js_content = getattr(evaljs, \"x\")\n\n    return f\"https://{link}.zippyshare.com{js_content}\"\n\n\ndef yandex_disk(url: str) -> str:\n    \"\"\" Yandex.Disk direct links generator\n    Based on https://github.com/wldhx/yadisk-direct\"\"\"\n    try:\n        link = re.findall(r'\\bhttps?://.*yadi\\.sk\\S+', url)[0]\n    except IndexError:\n        reply = \"`No Yandex.Disk links found`\\n\"\n        return reply\n    api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'\n    try:\n        dl_url = requests.get(api.format(link)).json()['href']\n        return dl_url\n    except KeyError:\n        raise DirectDownloadLinkException(\"`Error: File not found / Download limit reached`\\n\")\n\n\ndef cm_ru(url: str) -> str:\n    \"\"\" cloud.mail.ru direct links generator\n    Using https://github.com/JrMasterModelBuilder/cmrudl.py\"\"\"\n    reply = ''\n    try:\n        link = re.findall(r'\\bhttps?://.*cloud\\.mail\\.ru\\S+', url)[0]\n    except IndexError:\n        raise DirectDownloadLinkException(\"`No cloud.mail.ru links found`\\n\")\n    command = f'vendor/cmrudl.py/cmrudl -s {link}'\n    result = popen(command).read()\n    result = result.splitlines()[-1]\n    try:\n        data = json.loads(result)\n    except json.decoder.JSONDecodeError:\n        raise DirectDownloadLinkException(\"`Error: Can't extract the link`\\n\")\n    dl_url = data['download']\n    return dl_url\n\n\ndef mediafire(url: str) -> str:\n    \"\"\" MediaFire direct links generator \"\"\"\n    try:\n        link = re.findall(r'\\bhttps?://.*mediafire\\.com\\S+', url)[0]\n    except IndexError:\n        raise DirectDownloadLinkException(\"`No MediaFire links found`\\n\")\n    page = BeautifulSoup(requests.get(link).content, 'lxml')\n    info = page.find('a', {'aria-label': 'Download file'})\n    dl_url = info.get('href')\n    return dl_url\n\n\ndef uptobox(url: str) -> str:\n    try:\n        link = re.findall(r'\\bhttps?://.*uptobox\\.com\\S+', url)[0]\n    except IndexError:\n        raise DirectDownloadLinkException(\"`No Uptobox links found`\\n\")\n    if UPTOBOX_TOKEN is None:\n        logging.error('UPTOBOX_TOKEN not provided!')\n    else:\n        check = 'https://uptobox.com/api/user/me?token=%s' % (UPTOBOX_TOKEN)\n        request = requests.get(check)\n        info = request.json()\n        premium = info[\"data\"][\"premium\"]\n        try:\n            link = re.findall(r'\\bhttp?://.*uptobox\\.com/dl\\S+', url)[0]\n            logging.info('Uptobox direct link')\n            dl_url = url\n        except:\n            if premium == 1:\n                file_id = re.findall(r'\\bhttps?://.*uptobox\\.com/(\\w+)', url)[0]\n                file_link = 'https://uptobox.com/api/link?token=%s&file_code=%s' % (UPTOBOX_TOKEN, file_id)\n                req = requests.get(file_link)\n                result = req.json()\n                dl_url = result['data']['dlLink']\n            else:\n                file_id = re.findall(r'\\bhttps?://.*uptobox\\.com/(\\w+)', url)[0]\n                file_link = 'https://uptobox.com/api/link?token=%s&file_code=%s' % (UPTOBOX_TOKEN, file_id)\n                req = requests.get(file_link)\n                result = req.json()\n                waiting_time = result[\"data\"][\"waiting\"] + 1\n                waiting_token = result[\"data\"][\"waitingToken\"]\n                _countdown(waiting_time)\n                file_link = 'https://uptobox.com/api/link?token=%s&file_code=%s&waitingToken=%s' % (UPTOBOX_TOKEN, file_id, waiting_token)\n                req = requests.get(file_link)\n                result = req.json()\n                dl_url = result['data']['dlLink']\n    return dl_url\n\n\ndef osdn(url: str) -> str:\n    \"\"\" OSDN direct links generator \"\"\"\n    osdn_link = 'https://osdn.net'\n    try:\n        link = re.findall(r'\\bhttps?://.*osdn\\.net\\S+', url)[0]\n    except IndexError:\n        raise DirectDownloadLinkException(\"`No OSDN links found`\\n\")\n    page = BeautifulSoup(\n        requests.get(link, allow_redirects=True).content, 'lxml')\n    info = page.find('a', {'class': 'mirror_link'})\n    link = urllib.parse.unquote(osdn_link + info['href'])\n    mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr')\n    urls = []\n    for data in mirrors[1:]:\n        mirror = data.find('input')['value']\n        urls.append(re.sub(r'm=(.*)&f', f'm={mirror}&f', link))\n    return urls[0]\n\n\ndef github(url: str) -> str:\n    \"\"\" GitHub direct links generator \"\"\"\n    try:\n        re.findall(r'\\bhttps?://.*github\\.com.*releases\\S+', url)[0]\n    except IndexError:\n        raise DirectDownloadLinkException(\"`No GitHub Releases links found`\\n\")\n    download = requests.get(url, stream=True, allow_redirects=False)\n    try:\n        dl_url = download.headers[\"location\"]\n        return dl_url\n    except KeyError:\n        raise DirectDownloadLinkException(\"`Error: Can't extract the link`\\n\")\n\n\ndef useragent():\n    \"\"\"\n    useragent random setter\n    \"\"\"\n    useragents = BeautifulSoup(\n        requests.get(\n            'https://developers.whatismybrowser.com/'\n            'useragents/explore/operating_system_name/android/').content,\n        'lxml').findAll('td', {'class': 'useragent'})\n    user_agent = choice(useragents)\n    return user_agent.text\n\ndef fembed(link: str) -> str:\n    \"\"\" Fembed direct link generator\n    Based on https://github.com/breakdowns/slam-mirrorbot \"\"\"\n    bypasser = lk21.Bypass()\n    dl_url=bypasser.bypass_fembed(link)\n    lst_link = []\n    count = len(dl_url)\n    for i in dl_url:\n        lst_link.append(dl_url[i])\n    return lst_link[count-1]\n"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/direct_link_generator_license.md",
    "content": "                        RAPHIELSCAPE PUBLIC LICENSE \n                          Version 1.c, June 2019 \n\n Copyright (C) 2019 Raphielscape LLC.\n Copyright (C) 2019 Devscapes Open Source Holding GmbH.\n\n  Everyone is permitted to copy and distribute verbatim or modified \n copies of this license document, and changing it is allowed as long \n as the name is changed. \n\n                        RAPHIELSCAPE PUBLIC LICENSE \n                            A-1. DEFINITIONS\n\n0. “This License” refers to version 1.c of the Raphielscape Public License.\n\n1. “Copyright” also means copyright-like laws that apply to other kinds of works.\n\n2. “The Work\" refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. \n   “Licensees” and “recipients” may be individuals or organizations.\n\n3. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, \n   other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work \n   or a work “based on” the earlier work.\n\n4. Source Form. The “source form” for a work means the preferred form of the work for making modifications to it. \n   “Object code” means any non-source form of a work.\n\n  The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and \n  (for an executable work) run the object code and to modify the work, including scripts to control those activities.\n\n  The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\n  The Corresponding Source for a work in source code form is that same work.\n\n5. \"The author\" refers to \"author\" of the code, which is the one that made the particular code which exists inside of \n   the Corresponding Source.\n\n6. \"Owner\" refers to any parties which is made the early form of the Corresponding Source.\n\n     A-2. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION \n\n0. You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n1. You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n2. You must retain, in the Source form of any Derivative Works that You distribute, \n   this license, all copyright, patent, trademark, authorships and attribution notices \n   from the Source form of the Work; and\n\n3. Respecting the author and owner of works that are distributed in any way.\n\n You may add Your own copyright statement to Your modifications and may provide \nadditional or different license terms and conditions for use, reproduction, \nor distribution of Your modifications, or for any such Derivative Works as a whole, \nprovided Your use, reproduction, and distribution of the Work otherwise complies \nwith the conditions stated in this License.\n\n                        B. DISCLAIMER OF WARRANTY\n                        \n  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR \nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS \nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, \nOR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT \nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n                   C. REVISED VERSION OF THIS LICENSE\n\n  The Devscapes Open Source Holding GmbH. may publish revised and/or new versions of the \nRaphielscape Public License from time to time.  Such new versions will be similar in spirit \nto the present version, but may differ in detail to address new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the Program specifies that a \ncertain numbered version of the Raphielscape Public License \"or any later version\" applies to it, \nyou have the option of following the terms and conditions either of that numbered version or of \nany later version published by the Devscapes Open Source Holding GmbH.  If the Program does not specify a \nversion number of the Raphielscape Public License, you may choose any version ever published\nby the Devscapes Open Source Holding GmbH.\n\n                             END OF LICENSE"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/download_helper.py",
    "content": "# An abstract class which will be inherited by the tool specific classes like aria2_helper or mega_download_helper\nimport threading\n\n\nclass MethodNotImplementedError(NotImplementedError):\n    def __init__(self):\n        super(self, 'Not implemented method')\n\n\nclass DownloadHelper:\n    def __init__(self):\n        self.__name = ''  # Name of the download; empty string if no download has been started\n        self.__size = 0.0  # Size of the download\n        self.downloaded_bytes = 0.0  # Bytes downloaded\n        self.speed = 0.0  # Download speed in bytes per second\n        self.progress = 0.0\n        self.progress_string = '0.00%'\n        self.eta = 0  # Estimated time of download complete\n        self.eta_string = '0s'  # A listener class which have event callbacks\n        self._resource_lock = threading.Lock()\n\n    def add_download(self, link: str, path):\n        raise MethodNotImplementedError\n\n    def cancel_download(self):\n        # Returns None if successfully cancelled, else error string\n        raise MethodNotImplementedError\n"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/mega_download.py",
    "content": "import threading\nfrom bot import LOGGER, download_dict, download_dict_lock\nfrom .download_helper import DownloadHelper\nfrom ..status_utils.mega_status import MegaDownloadStatus\nfrom megasdkrestclient import MegaSdkRestClient, constants\nfrom bot.helper.ext_utils.bot_utils import setInterval\nfrom pathlib import Path\n\n\nclass MegaDownloader:\n    POLLING_INTERVAL = 2\n\n    def __init__(self, listener):\n        super().__init__()\n        self.__listener = listener\n        self.__name = \"\"\n        self.__gid = ''\n        self.__resource_lock = threading.Lock()\n        self.__mega_client = MegaSdkRestClient('http://localhost:6090')\n        self.__periodic = None\n        self.__downloaded_bytes = 0\n        self.__progress = 0\n        self.__size = 0\n\n    @property\n    def progress(self):\n        with self.__resource_lock:\n            return self.__progress\n\n    @property\n    def downloaded_bytes(self):\n        with self.__resource_lock:\n            return self.__downloaded_bytes\n\n    @property\n    def size(self):\n        with self.__resource_lock:\n            return self.__size\n\n    @property\n    def gid(self):\n        with self.__resource_lock:\n            return self.__gid\n\n    @property\n    def name(self):\n        with self.__resource_lock:\n            return self.__name\n\n    @property\n    def download_speed(self):\n        if self.gid is not None:\n            return self.__mega_client.getDownloadInfo(self.gid)['speed']\n\n    def __onDownloadStart(self, name, size, gid):\n        self.__periodic = setInterval(self.POLLING_INTERVAL, self.__onInterval)\n        with download_dict_lock:\n            download_dict[self.__listener.uid] = MegaDownloadStatus(self, self.__listener)\n        with self.__resource_lock:\n            self.__name = name\n            self.__size = size\n            self.__gid = gid\n        self.__listener.onDownloadStarted()\n\n    def __onInterval(self):\n        dlInfo = self.__mega_client.getDownloadInfo(self.gid)\n        if (dlInfo['state'] == constants.State.TYPE_STATE_COMPLETED or dlInfo[\n            'state'] == constants.State.TYPE_STATE_CANCELED or dlInfo[\n                'state'] == constants.State.TYPE_STATE_FAILED) and self.__periodic is not None:\n            self.__periodic.cancel()\n        if dlInfo['state'] == constants.State.TYPE_STATE_COMPLETED:\n            self.__onDownloadComplete()\n            return\n        if dlInfo['state'] == constants.State.TYPE_STATE_CANCELED:\n            self.__onDownloadError('Cancelled by user')\n            return\n        if dlInfo['state'] == constants.State.TYPE_STATE_FAILED:\n            self.__onDownloadError(dlInfo['error_string'])\n            return\n        self.__onDownloadProgress(dlInfo['completed_length'], dlInfo['total_length'])\n\n    def __onDownloadProgress(self, current, total):\n        with self.__resource_lock:\n            self.__downloaded_bytes = current\n            try:\n                self.__progress = current / total * 100\n            except ZeroDivisionError:\n                self.__progress = 0\n\n    def __onDownloadError(self, error):\n        self.__listener.onDownloadError(error)\n\n    def __onDownloadComplete(self):\n        self.__listener.onDownloadComplete()\n\n    def add_download(self, link, path):\n        Path(path).mkdir(parents=True, exist_ok=True)\n        dl = self.__mega_client.addDl(link, path)\n        gid = dl['gid']\n        info = self.__mega_client.getDownloadInfo(gid)\n        file_name = info['name']\n        file_size = info['total_length']\n        self.__onDownloadStart(file_name, file_size, gid)\n        LOGGER.info(f'Started mega download with gid: {gid}')\n\n    def cancel_download(self):\n        LOGGER.info(f'Cancelling download on user request: {self.gid}')\n        self.__mega_client.cancelDl(self.gid)"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/telegram_downloader.py",
    "content": "import logging\nimport threading\nimport time\n\nfrom bot import LOGGER, download_dict, download_dict_lock, app\nfrom .download_helper import DownloadHelper\nfrom ..status_utils.telegram_download_status import TelegramDownloadStatus\n\nglobal_lock = threading.Lock()\nGLOBAL_GID = set()\n\nlogging.getLogger(\"pyrogram\").setLevel(logging.WARNING)\n\n\nclass TelegramDownloadHelper(DownloadHelper):\n    def __init__(self, listener):\n        super().__init__()\n        self.__listener = listener\n        self.__resource_lock = threading.RLock()\n        self.__name = \"\"\n        self.__gid = ''\n        self.__start_time = time.time()\n        self.__user_bot = app\n        self.__is_cancelled = False\n\n    @property\n    def gid(self):\n        with self.__resource_lock:\n            return self.__gid\n\n    @property\n    def download_speed(self):\n        with self.__resource_lock:\n            return self.downloaded_bytes / (time.time() - self.__start_time)\n\n    def __onDownloadStart(self, name, size, file_id):\n        with download_dict_lock:\n            download_dict[self.__listener.uid] = TelegramDownloadStatus(self, self.__listener)\n        with global_lock:\n            GLOBAL_GID.add(file_id)\n        with self.__resource_lock:\n            self.name = name\n            self.size = size\n            self.__gid = file_id\n        self.__listener.onDownloadStarted()\n\n    def __onDownloadProgress(self, current, total):\n        if self.__is_cancelled:\n            self.__onDownloadError('Cancelled by user!')\n            self.__user_bot.stop_transmission()\n            return\n        with self.__resource_lock:\n            self.downloaded_bytes = current\n            try:\n                self.progress = current / self.size * 100\n            except ZeroDivisionError:\n                self.progress = 0\n\n    def __onDownloadError(self, error):\n        with global_lock:\n            try:\n                GLOBAL_GID.remove(self.gid)\n            except KeyError:\n                pass\n        self.__listener.onDownloadError(error)\n\n    def __onDownloadComplete(self):\n        with global_lock:\n            GLOBAL_GID.remove(self.gid)\n        self.__listener.onDownloadComplete()\n\n    def __download(self, message, path):\n        download = self.__user_bot.download_media(message,\n                                                  progress=self.__onDownloadProgress, file_name=path)\n        if download is not None:\n            self.__onDownloadComplete()\n        else:\n            if not self.__is_cancelled:\n                self.__onDownloadError('Internal error occurred')\n\n    def add_download(self, message, path, filename):\n        _message = self.__user_bot.get_messages(message.chat.id, message.message_id)\n        media = None\n        media_array = [_message.document, _message.video, _message.audio]\n        for i in media_array:\n            if i is not None:\n                media = i\n                break\n        if media is not None:\n            with global_lock:\n                # For avoiding locking the thread lock for long time unnecessarily\n                download = media.file_id not in GLOBAL_GID\n            if filename == \"\":\n                name = media.file_name\n            else:\n                name = filename\n                path = path + name\n            if download:\n                self.__onDownloadStart(name, media.file_size, media.file_id)\n                LOGGER.info(f'Downloading telegram file with id: {media.file_id}')\n                threading.Thread(target=self.__download, args=(_message, path)).start()\n            else:\n                self.__onDownloadError('File already being downloaded!')\n        else:\n            self.__onDownloadError('No document in the replied message')\n\n    def cancel_download(self):\n        LOGGER.info(f'Cancelling download on user request: {self.gid}')\n        self.__is_cancelled = True\n"
  },
  {
    "path": "bot/helper/mirror_utils/download_utils/youtube_dl_download_helper.py",
    "content": "from .download_helper import DownloadHelper\nimport time\nfrom yt_dlp import YoutubeDL, DownloadError\nfrom bot import download_dict_lock, download_dict\nfrom ..status_utils.youtube_dl_download_status import YoutubeDLDownloadStatus\nimport logging\nimport re\nimport threading\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass MyLogger:\n    def __init__(self, obj):\n        self.obj = obj\n\n    def debug(self, msg):\n        LOGGER.debug(msg)\n        # Hack to fix changing changing extension\n        match = re.search(r'.ffmpeg..Merging formats into..(.*?).$', msg)\n        if match and not self.obj.is_playlist:\n            newname = match.group(1)\n            newname = newname.split(\"/\")\n            newname = newname[-1]\n            self.obj.name = newname\n\n    @staticmethod\n    def warning(msg):\n        LOGGER.warning(msg)\n\n    @staticmethod\n    def error(msg):\n        LOGGER.error(msg)\n\n\nclass YoutubeDLHelper(DownloadHelper):\n    def __init__(self, listener):\n        super().__init__()\n        self.name = \"\"\n        self.__start_time = time.time()\n        self.__listener = listener\n        self.__gid = \"\"\n        self.opts = {\n            'progress_hooks': [self.__onDownloadProgress],\n            'logger': MyLogger(self),\n            'usenetrc': True\n        }\n        self.__download_speed = 0\n        self.download_speed_readable = ''\n        self.downloaded_bytes = 0\n        self.size = 0\n        self.is_playlist = False\n        self.last_downloaded = 0\n        self.is_cancelled = False\n        self.vid_id = ''\n        self.__resource_lock = threading.RLock()\n\n    @property\n    def download_speed(self):\n        with self.__resource_lock:\n            return self.__download_speed\n\n    @property\n    def gid(self):\n        with self.__resource_lock:\n            return self.__gid\n\n    def __onDownloadProgress(self, d):\n        if self.is_cancelled:\n            raise ValueError(\"Cancelling Download..\")\n        if d['status'] == \"finished\":\n            if self.is_playlist:\n                self.last_downloaded = 0\n        elif d['status'] == \"downloading\":\n            with self.__resource_lock:\n                self.__download_speed = d['speed']\n                try:\n                    tbyte = d['total_bytes']\n                except KeyError:\n                    tbyte = d['total_bytes_estimate']\n                if self.is_playlist:\n                    progress = d['downloaded_bytes'] / tbyte\n                    chunk_size = d['downloaded_bytes'] - self.last_downloaded\n                    self.last_downloaded = tbyte * progress\n                    self.downloaded_bytes += chunk_size\n                    try:\n                        self.progress = (self.downloaded_bytes / self.size) * 100\n                    except ZeroDivisionError:\n                        pass\n                else:\n                    self.download_speed_readable = d['_speed_str']\n                    self.downloaded_bytes = d['downloaded_bytes']\n\n    def __onDownloadStart(self):\n        with download_dict_lock:\n            download_dict[self.__listener.uid] = YoutubeDLDownloadStatus(self, self.__listener)\n\n    def __onDownloadComplete(self):\n        self.__listener.onDownloadComplete()\n\n    def onDownloadError(self, error):\n        self.__listener.onDownloadError(error)\n\n    def extractMetaData(self, link, qual, name):\n        if \"hotstar\" in link or \"sonyliv\" in link:\n            self.opts['geo_bypass_country'] = 'IN'\n\n        with YoutubeDL(self.opts) as ydl:\n            try:\n                result = ydl.extract_info(link, download=False)\n                if name == \"\":\n                    name = ydl.prepare_filename(result)\n                else:\n                    name = name\n                # noobway hack for changing extension after converting to mp3\n                if qual == \"audio\":\n                  name = name.replace(\".mp4\", \".mp3\").replace(\".webm\", \".mp3\")\n            except DownloadError as e:\n                self.onDownloadError(str(e))\n                return\n        if result.get('direct'):\n            return None\n        if 'entries' in result:\n            video = result['entries'][0]\n            for v in result['entries']:\n                if v and v.get('filesize'):\n                    self.size += float(v['filesize'])\n            # For playlists, ydl.prepare-filename returns the following format: <Playlist Name>-<Id of playlist>.NA\n            self.name = name.split(f\"-{result['id']}\")[0]\n            self.vid_id = video.get('id')\n            self.is_playlist = True\n        else:\n            video = result\n            if video.get('filesize'):\n                self.size = float(video.get('filesize'))\n            self.name = name\n            self.vid_id = video.get('id')\n        return video\n\n    def __download(self, link):\n        try:\n            with YoutubeDL(self.opts) as ydl:\n                try:\n                    ydl.download([link])\n                except DownloadError as e:\n                    self.onDownloadError(str(e))\n                    return\n            self.__onDownloadComplete()\n        except ValueError:\n            LOGGER.info(\"Download Cancelled by User!\")\n            self.onDownloadError(\"Download Cancelled by User!\")\n\n    def add_download(self, link, path, qual, name):\n        pattern = '^.*(youtu\\.be\\/|youtube.com\\/)(playlist?)'\n        if re.match(pattern, link):\n            self.opts['ignoreerrors'] = True\n        self.__onDownloadStart()\n        self.extractMetaData(link, qual, name)\n        LOGGER.info(f\"Downloading with YT-DL: {link}\")\n        self.__gid = f\"{self.vid_id}{self.__listener.uid}\"\n        if qual == \"audio\":\n          self.opts['format'] = 'bestaudio/best'\n          self.opts['postprocessors'] = [{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3','preferredquality': '192',}]\n        else:\n          self.opts['format'] = qual\n        if not self.is_playlist:\n            self.opts['outtmpl'] = f\"{path}/{self.name}\"\n        else:\n            self.opts['outtmpl'] = f\"{path}/{self.name}/%(title)s.%(ext)s\"\n        self.__download(link)\n\n    def cancel_download(self):\n        self.is_cancelled = True\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/aria_download_status.py",
    "content": "from bot import aria2, DOWNLOAD_DIR, LOGGER\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus\nfrom .status import Status\n\n\ndef get_download(gid):\n    return aria2.get_download(gid)\n\n\nclass AriaDownloadStatus(Status):\n\n    def __init__(self, gid, listener):\n        super().__init__()\n        self.upload_name = None\n        self.is_archiving = False\n        self.__gid = gid\n        self.__download = get_download(self.__gid)\n        self.__uid = listener.uid\n        self.__listener = listener\n        self.message = listener.message\n        self.last = None\n        self.is_waiting = False\n        self.is_extracting = False\n\n    def __update(self):\n        self.__download = get_download(self.__gid)\n\n    def progress(self):\n        \"\"\"\n        Calculates the progress of the mirror (upload or download)\n        :return: returns progress in percentage\n        \"\"\"\n        self.__update()\n        return self.__download.progress_string()\n\n    def size_raw(self):\n        \"\"\"\n        Gets total size of the mirror file/folder\n        :return: total size of mirror\n        \"\"\"\n        return self.aria_download().total_length\n\n    def processed_bytes(self):\n        return self.aria_download().completed_length\n\n    def speed(self):\n        return self.aria_download().download_speed_string()\n\n    def name(self):\n        return self.aria_download().name\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.__uid}\"\n\n    def size(self):\n        return self.aria_download().total_length_string()\n\n    def eta(self):\n        return self.aria_download().eta_string()\n\n    def status(self):\n        download = self.aria_download()\n        if download.is_waiting:\n            status = MirrorStatus.STATUS_WAITING\n        elif download.is_paused:\n            status = MirrorStatus.STATUS_CANCELLED\n        elif download.has_failed:\n            status = MirrorStatus.STATUS_FAILED\n        else:\n            status = MirrorStatus.STATUS_DOWNLOADING\n        return status\n\n    def aria_download(self):\n        self.__update()\n        return self.__download\n\n    def download(self):\n        return self\n\n    def updateName(self,name):\n        self.__name = name\n\n    def updateGid(self,gid):\n        self.__gid = gid\n\n    def getListener(self):\n        return self.__listener\n    \n    def uid(self):\n        return self.__uid\n\n    def gid(self):\n        self.__update()\n        return self.__gid\n\n    def cancel_download(self):\n        LOGGER.info(f\"Cancelling Download: {self.name()}\")\n        download = self.aria_download()\n        if download.is_waiting:\n            aria2.remove([download])\n            self.__listener.onDownloadError(\"Cancelled by user\")\n            return\n        if len(download.followed_by_ids) != 0:\n            downloads = aria2.get_downloads(download.followed_by_ids)\n            aria2.pause(downloads)\n        aria2.pause([download])\n\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/extract_status.py",
    "content": "from .status import Status\nfrom bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus\n\n\nclass ExtractStatus(Status):\n    def __init__(self, name, path, size):\n        self.__name = name\n        self.__path = path\n        self.__size = size\n\n    # The progress of extract function cannot be tracked. So we just return dummy values.\n    # If this is possible in future,we should implement it\n\n    def progress(self):\n        return '0'\n\n    def speed(self):\n        return '0'\n\n    def name(self):\n        return self.__name\n\n    def path(self):\n        return self.__path\n\n    def size(self):\n        return get_readable_file_size(self.__size)\n\n    def eta(self):\n        return '0s'\n\n    def status(self):\n        return MirrorStatus.STATUS_EXTRACTING\n\n    def processed_bytes(self):\n        return 0\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/gdownload_status.py",
    "content": "import bot\n\nfrom .status import Status\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time\nfrom bot import DOWNLOAD_DIR\n\n\nclass DownloadStatus(Status):\n    def __init__(self, obj, size, listener, gid):\n        self.dobj = obj\n        self.__dsize = size\n        self.uid = listener.uid\n        self.message = listener.message\n        self.__dgid = gid\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.uid}\"\n\n    def processed_bytes(self):\n        return self.dobj.downloaded_bytes\n\n    def size_raw(self):\n        return self.__dsize\n\n    def size(self):\n        return get_readable_file_size(self.__dsize)\n\n    def status(self):\n        return MirrorStatus.STATUS_DOWNLOADING\n\n    def name(self):\n        return self.dobj.name\n\n    def gid(self) -> str:\n        return self.__dgid\n\n    def progress_raw(self):\n        try:\n            return self.dobj.downloaded_bytes / self.__dsize * 100\n        except ZeroDivisionError:\n            return 0\n\n    def progress(self):\n        return f'{round(self.progress_raw(), 2)}%'\n\n    def speed_raw(self):\n        \"\"\"\n        :return: Download speed in Bytes/Seconds\n        \"\"\"\n        return self.dobj.dspeed()\n\n    def speed(self):\n        return f'{get_readable_file_size(self.speed_raw())}/s'\n\n    def eta(self):\n        try:\n            seconds = (self.__dsize - self.dobj.downloaded_bytes) / self.speed_raw()\n            return f'{get_readable_time(seconds)}'\n        except ZeroDivisionError:\n            return '-'\n\n    def download(self):\n        return self.dobj"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/listeners.py",
    "content": "class MirrorListeners:\n    def __init__(self, context, update):\n        self.bot = context\n        self.update = update\n        self.message = update.message\n        self.uid = self.message.message_id\n\n    def onDownloadStarted(self):\n        raise NotImplementedError\n\n    def onDownloadProgress(self):\n        raise NotImplementedError\n    \n    def onDownloadComplete(self):\n        raise NotImplementedError\n\n    def onDownloadError(self, error: str):\n        raise NotImplementedError\n\n    def onUploadStarted(self):\n        raise NotImplementedError\n\n    def onUploadProgress(self):\n        raise NotImplementedError\n\n    def onUploadComplete(self, link: str):\n        raise NotImplementedError\n\n    def onUploadError(self, error: str):\n        raise NotImplementedError\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/mega_status.py",
    "content": "from bot import DOWNLOAD_DIR\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time\nfrom .status import Status\n\n\nclass MegaDownloadStatus(Status):\n    def __init__(self, obj, listener):\n        self.obj = obj\n        self.uid = listener.uid\n        self.message = listener.message\n\n    def gid(self):\n        return self.obj.gid\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.uid}\"\n\n    def processed_bytes(self):\n        return self.obj.downloaded_bytes\n\n    def size_raw(self):\n        return self.obj.size\n\n    def size(self):\n        return get_readable_file_size(self.size_raw())\n\n    def status(self):\n        return MirrorStatus.STATUS_DOWNLOADING\n\n    def name(self):\n        return self.obj.name\n\n    def progress_raw(self):\n        return self.obj.progress\n\n    def progress(self):\n        return f'{round(self.progress_raw(), 2)}%'\n\n    def speed_raw(self):\n        \"\"\"\n        :return: Download speed in Bytes/Seconds\n        \"\"\"\n        return self.obj.download_speed\n\n    def speed(self):\n        return f'{get_readable_file_size(self.speed_raw())}/s'\n\n    def eta(self):\n        try:\n            seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()\n            return f'{get_readable_time(seconds)}'\n        except ZeroDivisionError:\n            return '-'\n\n    def download(self):\n        return self.obj"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/status.py",
    "content": "# Generic status class. All other status classes must inherit this class\n\n\nclass Status:\n\n    def progress(self):\n        \"\"\"\n        Calculates the progress of the mirror (upload or download)\n        :return: progress in percentage\n        \"\"\"\n        raise NotImplementedError\n\n    def speed(self):\n        \"\"\":return: speed in bytes per second\"\"\"\n        raise NotImplementedError\n\n    def name(self):\n        \"\"\":return name of file/directory being processed\"\"\"\n        raise NotImplementedError\n\n    def path(self):\n        \"\"\":return path of the file/directory\"\"\"\n        raise NotImplementedError\n\n    def size(self):\n        \"\"\":return Size of file folder\"\"\"\n        raise NotImplementedError\n\n    def eta(self):\n        \"\"\":return ETA of the process to complete\"\"\"\n        raise NotImplementedError\n\n    def status(self):\n        \"\"\":return String describing what is the object of this class will be tracking (upload/download/something\n        else) \"\"\"\n        raise NotImplementedError\n\n    def processed_bytes(self):\n        \"\"\":return The size of file that has been processed (downloaded/uploaded/archived)\"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/tar_status.py",
    "content": "from .status import Status\nfrom bot.helper.ext_utils.bot_utils import get_readable_file_size, MirrorStatus\n\n\nclass TarStatus(Status):\n    def __init__(self, name, path, size):\n        self.__name = name\n        self.__path = path\n        self.__size = size\n\n    # The progress of Tar function cannot be tracked. So we just return dummy values.\n    # If this is possible in future,we should implement it\n\n    def progress(self):\n        return '0'\n\n    def speed(self):\n        return '0'\n\n    def name(self):\n        return self.__name\n\n    def path(self):\n        return self.__path\n\n    def size(self):\n        return get_readable_file_size(self.__size)\n\n    def eta(self):\n        return '0s'\n\n    def status(self):\n        return MirrorStatus.STATUS_ARCHIVING\n\n    def processed_bytes(self):\n        return 0\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/telegram_download_status.py",
    "content": "from bot import DOWNLOAD_DIR\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time\nfrom .status import Status\n\n\nclass TelegramDownloadStatus(Status):\n    def __init__(self, obj, listener):\n        self.obj = obj\n        self.uid = listener.uid\n        self.message = listener.message\n\n    def gid(self):\n        return self.obj.gid\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.uid}\"\n\n    def processed_bytes(self):\n        return self.obj.downloaded_bytes\n\n    def size_raw(self):\n        return self.obj.size\n\n    def size(self):\n        return get_readable_file_size(self.size_raw())\n\n    def status(self):\n        return MirrorStatus.STATUS_DOWNLOADING\n\n    def name(self):\n        return self.obj.name\n\n    def progress_raw(self):\n        return self.obj.progress\n\n    def progress(self):\n        return f'{round(self.progress_raw(), 2)}%'\n\n    def speed_raw(self):\n        \"\"\"\n        :return: Download speed in Bytes/Seconds\n        \"\"\"\n        return self.obj.download_speed\n\n    def speed(self):\n        return f'{get_readable_file_size(self.speed_raw())}/s'\n\n    def eta(self):\n        try:\n            seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()\n            return f'{get_readable_time(seconds)}'\n        except ZeroDivisionError:\n            return '-'\n\n    def download(self):\n        return self.obj\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/upload_status.py",
    "content": "from .status import Status\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time\nfrom bot import DOWNLOAD_DIR\n\n\nclass UploadStatus(Status):\n    def __init__(self, obj, size, listener):\n        self.obj = obj\n        self.__size = size\n        self.uid = listener.uid\n        self.message = listener.message\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.uid}\"\n\n    def processed_bytes(self):\n        return self.obj.uploaded_bytes\n\n    def size_raw(self):\n        return self.__size\n\n    def size(self):\n        return get_readable_file_size(self.__size)\n\n    def status(self):\n        return MirrorStatus.STATUS_UPLOADING\n\n    def name(self):\n        return self.obj.name\n\n    def progress_raw(self):\n        try:\n            return self.obj.uploaded_bytes / self.__size * 100\n        except ZeroDivisionError:\n            return 0\n\n    def progress(self):\n        return f'{round(self.progress_raw(), 2)}%'\n\n    def speed_raw(self):\n        \"\"\"\n        :return: Upload speed in Bytes/Seconds\n        \"\"\"\n        return self.obj.speed()\n\n    def speed(self):\n        return f'{get_readable_file_size(self.speed_raw())}/s'\n\n    def eta(self):\n        try:\n            seconds = (self.__size - self.obj.uploaded_bytes) / self.speed_raw()\n            return f'{get_readable_time(seconds)}'\n        except ZeroDivisionError:\n            return '-'\n"
  },
  {
    "path": "bot/helper/mirror_utils/status_utils/youtube_dl_download_status.py",
    "content": "from bot import DOWNLOAD_DIR\nfrom bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time\nfrom .status import Status\nfrom bot.helper.ext_utils.fs_utils import get_path_size\n\nclass YoutubeDLDownloadStatus(Status):\n    def __init__(self, obj, listener):\n        self.obj = obj\n        self.uid = listener.uid\n        self.message = listener.message\n\n    def gid(self):\n        return self.obj.gid\n\n    def path(self):\n        return f\"{DOWNLOAD_DIR}{self.uid}\"\n\n    def processed_bytes(self):\n        if self.obj.downloaded_bytes != 0:\n          return self.obj.downloaded_bytes\n        else:\n          return get_path_size(f\"{DOWNLOAD_DIR}{self.uid}\")\n\n    def size_raw(self):\n        return self.obj.size\n\n    def size(self):\n        return get_readable_file_size(self.size_raw())\n\n    def status(self):\n        return MirrorStatus.STATUS_DOWNLOADING\n\n    def name(self):\n        return self.obj.name\n\n    def progress_raw(self):\n        return self.obj.progress\n\n    def progress(self):\n        return f'{round(self.progress_raw(), 2)}%'\n\n    def speed_raw(self):\n        \"\"\"\n        :return: Download speed in Bytes/Seconds\n        \"\"\"\n        return self.obj.download_speed\n\n    def speed(self):\n        return f'{get_readable_file_size(self.speed_raw())}/s'\n\n    def eta(self):\n        try:\n            seconds = (self.size_raw() - self.processed_bytes()) / self.speed_raw()\n            return f'{get_readable_time(seconds)}'\n        except:\n            return '-'\n\n    def download(self):\n        return self.obj\n"
  },
  {
    "path": "bot/helper/mirror_utils/upload_utils/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/mirror_utils/upload_utils/gdriveTools.py",
    "content": "import os\nimport io\nimport pickle\nimport urllib.parse as urlparse\nfrom urllib.parse import parse_qs\n\nimport re\nimport json\nimport requests\nimport logging\nfrom random import randrange\n\nfrom google.auth.transport.requests import Request\nfrom google.oauth2 import service_account\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom googleapiclient.http import MediaFileUpload, MediaIoBaseDownload\nfrom tenacity import *\n\nfrom telegram import InlineKeyboardMarkup\nfrom bot.helper.telegram_helper import button_build\nfrom telegraph import Telegraph\n\nfrom bot import parent_id, DOWNLOAD_DIR, IS_TEAM_DRIVE, INDEX_URL, \\\n    USE_SERVICE_ACCOUNTS, download_dict, telegraph_token, BUTTON_THREE_NAME, BUTTON_THREE_URL, BUTTON_FOUR_NAME, BUTTON_FOUR_URL, BUTTON_FIVE_NAME, BUTTON_FIVE_URL, SHORTENER, SHORTENER_API\nfrom bot.helper.ext_utils.bot_utils import *\nfrom bot.helper.ext_utils.fs_utils import get_mime_type, get_path_size\n\nLOGGER = logging.getLogger(__name__)\nlogging.getLogger('googleapiclient.discovery').setLevel(logging.ERROR)\nif USE_SERVICE_ACCOUNTS:\n    SERVICE_ACCOUNT_INDEX = randrange(len(os.listdir(\"accounts\")))\nTELEGRAPHLIMIT = 95\n\n\nclass GoogleDriveHelper:\n    def __init__(self, name=None, listener=None):\n        self.__G_DRIVE_TOKEN_FILE = \"token.pickle\"\n        # Check https://developers.google.com/drive/scopes for all available scopes\n        self.__OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive']\n        # Redirect URI for installed apps, can be left as is\n        self.__REDIRECT_URI = \"urn:ietf:wg:oauth:2.0:oob\"\n        self.__G_DRIVE_DIR_MIME_TYPE = \"application/vnd.google-apps.folder\"\n        self.__G_DRIVE_BASE_DOWNLOAD_URL = \"https://drive.google.com/uc?id={}&export=download\"\n        self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL = \"https://drive.google.com/drive/folders/{}\"\n        self.__listener = listener\n        self.__service = self.authorize()\n        self.__listener = listener\n        self._file_uploaded_bytes = 0\n        self._file_downloaded_bytes = 0\n        self.uploaded_bytes = 0\n        self.downloaded_bytes = 0\n        self.UPDATE_INTERVAL = 5\n        self.start_time = 0\n        self.total_time = 0\n        self.dtotal_time = 0\n        self._should_update = True\n        self.is_uploading = True\n        self.is_cancelled = False\n        self.status = None\n        self.dstatus = None\n        self.updater = None\n        self.name = name\n        self.update_interval = 3\n        self.telegraph_content = []\n        self.path = []\n        self.total_bytes = 0\n        self.total_files = 0\n        self.total_folders = 0\n\n    def cancel(self):\n        self.is_cancelled = True\n        self.is_uploading = False\n\n    def speed(self):\n        \"\"\"\n        It calculates the average upload speed and returns it in bytes/seconds unit\n        :return: Upload speed in bytes/second\n        \"\"\"\n        try:\n            return self.uploaded_bytes / self.total_time\n        except ZeroDivisionError:\n            return 0\n    \n    def dspeed(self):\n        try:\n            return self.downloaded_bytes / self.dtotal_time\n        except ZeroDivisionError:\n            return 0\n\n\n    @staticmethod\n    def getIdFromUrl(link: str):\n        if \"folders\" in link or \"file\" in link:\n            regex = r\"https://drive\\.google\\.com/(drive)?/?u?/?\\d?/?(mobile)?/?(file)?(folders)?/?d?/([-\\w]+)[?+]?/?(w+)?\"\n            res = re.search(regex,link)\n            if res is None:\n                raise IndexError(\"GDrive ID not found.\")\n            return res.group(5)\n        parsed = urlparse.urlparse(link)\n        return parse_qs(parsed.query)['id'][0]\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def _on_upload_progress(self):\n        if self.status is not None:\n            chunk_size = self.status.total_size * self.status.progress() - self._file_uploaded_bytes\n            self._file_uploaded_bytes = self.status.total_size * self.status.progress()\n            LOGGER.debug(f'Uploading {self.name}, chunk size: {get_readable_file_size(chunk_size)}')\n            self.uploaded_bytes += chunk_size\n            self.total_time += self.update_interval\n\n    def __upload_empty_file(self, path, file_name, mime_type, parent_id=None):\n        media_body = MediaFileUpload(path,\n                                     mimetype=mime_type,\n                                     resumable=False)\n        file_metadata = {\n            'name': file_name,\n            'description': 'mirrored',\n            'mimeType': mime_type,\n        }\n        if parent_id is not None:\n            file_metadata['parents'] = [parent_id]\n        return self.__service.files().create(supportsTeamDrives=True,\n                                             body=file_metadata, media_body=media_body).execute()\n\n    def switchServiceAccount(self):\n        global SERVICE_ACCOUNT_INDEX\n        service_account_count = len(os.listdir(\"accounts\"))\n        if SERVICE_ACCOUNT_INDEX == service_account_count - 1:\n            SERVICE_ACCOUNT_INDEX = 0\n        SERVICE_ACCOUNT_INDEX += 1\n        LOGGER.info(f\"Switching to {SERVICE_ACCOUNT_INDEX}.json service account\")\n        self.__service = self.authorize()\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def __set_permission(self, drive_id):\n        permissions = {\n            'role': 'reader',\n            'type': 'anyone',\n            'value': None,\n            'withLink': True\n        }\n        return self.__service.permissions().create(supportsTeamDrives=True, fileId=drive_id,\n                                                   body=permissions).execute()\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def upload_file(self, file_path, file_name, mime_type, parent_id):\n        # File body description\n        file_metadata = {\n            'name': file_name,\n            'description': 'mirror',\n            'mimeType': mime_type,\n        }\n        if parent_id is not None:\n            file_metadata['parents'] = [parent_id]\n\n        if os.path.getsize(file_path) == 0:\n            media_body = MediaFileUpload(file_path,\n                                         mimetype=mime_type,\n                                         resumable=False)\n            response = self.__service.files().create(supportsTeamDrives=True,\n                                                     body=file_metadata, media_body=media_body).execute()\n            if not IS_TEAM_DRIVE:\n                self.__set_permission(response['id'])\n\n            drive_file = self.__service.files().get(supportsTeamDrives=True,\n                                                    fileId=response['id']).execute()\n            download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))\n            return download_url\n        media_body = MediaFileUpload(file_path,\n                                     mimetype=mime_type,\n                                     resumable=True,\n                                     chunksize=50 * 1024 * 1024)\n\n        # Insert a file\n        drive_file = self.__service.files().create(supportsTeamDrives=True,\n                                                   body=file_metadata, media_body=media_body)\n        response = None\n        while response is None:\n            if self.is_cancelled:\n                return None\n            try:\n                self.status, response = drive_file.next_chunk()\n            except HttpError as err:\n                if err.resp.get('content-type', '').startswith('application/json'):\n                    reason = json.loads(err.content).get('error').get('errors')[0].get('reason')\n                    if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':\n                        if USE_SERVICE_ACCOUNTS:\n                            self.switchServiceAccount()\n                            LOGGER.info(f\"Got: {reason}, Trying Again.\")\n                            return self.upload_file(file_path, file_name, mime_type, parent_id)\n                    else:\n                        raise err\n        self._file_uploaded_bytes = 0\n        # Insert new permissions\n        if not IS_TEAM_DRIVE:\n            self.__set_permission(response['id'])\n        # Define file instance and get url for download\n        drive_file = self.__service.files().get(supportsTeamDrives=True, fileId=response['id']).execute()\n        download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))\n        return download_url\n\n    def deletefile(self, link: str):\n        try:\n            file_id = self.getIdFromUrl(link)\n        except (KeyError,IndexError):\n            msg = \"Google drive ID could not be found in the provided link\"\n            return msg\n        msg = ''\n        try:\n            res = self.__service.files().delete(fileId=file_id, supportsTeamDrives=IS_TEAM_DRIVE).execute()\n            msg = \"Successfully deleted\"\n        except HttpError as err:\n            LOGGER.error(str(err))\n            if \"File not found\" in str(err):\n                msg = \"No such file exist\"\n            else:\n                msg = \"Something went wrong check log\"\n        finally:\n            return msg\n\n    def upload(self, file_name: str):\n        if USE_SERVICE_ACCOUNTS:\n            self.service_account_count = len(os.listdir(\"accounts\"))\n        self.__listener.onUploadStarted()\n        file_dir = f\"{DOWNLOAD_DIR}{self.__listener.message.message_id}\"\n        file_path = f\"{file_dir}/{file_name}\"\n        size = get_readable_file_size(get_path_size(file_path))\n        LOGGER.info(\"Uploading File: \" + file_path)\n        self.start_time = time.time()\n        self.updater = setInterval(self.update_interval, self._on_upload_progress)\n        if os.path.isfile(file_path):\n            try:\n                mime_type = get_mime_type(file_path)\n                link = self.upload_file(file_path, file_name, mime_type, parent_id)\n                if link is None:\n                    raise Exception('Upload has been manually cancelled')\n                LOGGER.info(\"Uploaded To G-Drive:- \" + file_path)\n            except Exception as e:\n                if isinstance(e, RetryError):\n                    LOGGER.info(f\"Total Attempts: {e.last_attempt.attempt_number}\")\n                    err = e.last_attempt.exception()\n                else:\n                    err = e\n                LOGGER.error(err)\n                self.__listener.onUploadError(str(err))\n                return\n            finally:\n                self.updater.cancel()\n        else:\n            try:\n                dir_id = self.create_directory(os.path.basename(os.path.abspath(file_name)), parent_id)\n                result = self.upload_dir(file_path, dir_id)\n                if result is None:\n                    raise Exception('Upload has been manually cancelled!')\n                LOGGER.info(\"Uploaded To G-Drive: \" + file_name)\n                link = f\"https://drive.google.com/folderview?id={dir_id}\"\n            except Exception as e:\n                if isinstance(e, RetryError):\n                    LOGGER.info(f\"Total Attempts: {e.last_attempt.attempt_number}\")\n                    err = e.last_attempt.exception()\n                else:\n                    err = e\n                LOGGER.error(err)\n                self.__listener.onUploadError(str(err))\n                return\n            finally:\n                self.updater.cancel()\n        LOGGER.info(download_dict)\n        self.__listener.onUploadComplete(link, size)\n        LOGGER.info(\"Deleting downloaded file/folder..\")\n        return link\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def copyFile(self, file_id, dest_id):\n        body = {\n            'parents': [dest_id]\n        }\n\n        try:\n            res = self.__service.files().copy(supportsAllDrives=True,fileId=file_id,body=body).execute()\n            return res\n        except HttpError as err:\n            if err.resp.get('content-type', '').startswith('application/json'):\n                reason = json.loads(err.content).get('error').get('errors')[0].get('reason')\n                if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':\n                    if USE_SERVICE_ACCOUNTS:\n                        self.switchServiceAccount()\n                        LOGGER.info(f\"Got: {reason}, Trying Again.\")\n                        return self.copyFile(file_id,dest_id)\n                else:\n                    raise err\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def getFileMetadata(self,file_id):\n        return self.__service.files().get(supportsAllDrives=True, fileId=file_id,\n                                              fields=\"name,id,mimeType,size\").execute()\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def getFilesByFolderId(self,folder_id):\n        page_token = None\n        q = f\"'{folder_id}' in parents\"\n        files = []\n        while True:\n            response = self.__service.files().list(supportsTeamDrives=True,\n                                                   includeTeamDriveItems=True,\n                                                   q=q,\n                                                   spaces='drive',\n                                                   pageSize=200,\n                                                   fields='nextPageToken, files(id, name, mimeType,size)',\n                                                   pageToken=page_token).execute()\n            for file in response.get('files', []):\n                files.append(file)\n            page_token = response.get('nextPageToken', None)\n            if page_token is None:\n                break\n        return files\n\n    def clone(self, link):\n        self.transferred_size = 0\n        self.total_files = 0\n        self.total_folders = 0\n        try:\n            file_id = self.getIdFromUrl(link)\n        except (KeyError,IndexError):\n            msg = \"Google drive ID could not be found in the provided link\"\n            return msg, \"\"\n        msg = \"\"\n        LOGGER.info(f\"File ID: {file_id}\")\n        try:\n            meta = self.getFileMetadata(file_id)\n            if meta.get(\"mimeType\") == self.__G_DRIVE_DIR_MIME_TYPE:\n                dir_id = self.create_directory(meta.get('name'), parent_id)\n                result = self.cloneFolder(meta.get('name'), meta.get('name'), meta.get('id'), dir_id)\n                msg += f'<b>Name:- </b><code>{meta.get(\"name\")}</code>\\n<b>Size:- </b>{get_readable_file_size(self.transferred_size)}'\n                durl = self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id)\n                buttons = button_build.ButtonMaker()\n                if SHORTENER is not None and SHORTENER_API is not None:\n                    surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={durl}&format=text').text\n                    buttons.buildbutton(\"Drive Link\", surl)\n                else:\n                    buttons.buildbutton(\"Drive Link\", durl)\n                if INDEX_URL is not None:\n                    url_path = requests.utils.quote(f'{meta.get(\"name\")}')\n                    url = f'{INDEX_URL}/{url_path}/'\n                    if SHORTENER is not None and SHORTENER_API is not None:\n                        siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text\n                        buttons.buildbutton(\"Index Link\", siurl)\n                    else:\n                        buttons.buildbutton(\"Index Link\", url)\n                if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_THREE_NAME}\", f\"{BUTTON_THREE_URL}\")\n                if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_FOUR_NAME}\", f\"{BUTTON_FOUR_URL}\")\n                if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_FIVE_NAME}\", f\"{BUTTON_FIVE_URL}\")\n            else:\n                file = self.copyFile(meta.get('id'), parent_id)\n                msg += f'<b>Name:- </b><code>{file.get(\"name\")}</code>'\n                durl = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(file.get(\"id\"))\n                buttons = button_build.ButtonMaker()\n                if SHORTENER is not None and SHORTENER_API is not None:\n                    surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={durl}&format=text').text\n                    buttons.buildbutton(\"Drive Link\", surl)\n                else:\n                    buttons.buildbutton(\"Drive Link\", durl)\n                try:\n                    msg += f'\\n<b>Size:- </b><code>{get_readable_file_size(int(meta.get(\"size\")))}</code>'\n                except TypeError:\n                    pass\n                if INDEX_URL is not None:\n                    url_path = requests.utils.quote(f'{file.get(\"name\")}')\n                    url = f'{INDEX_URL}/{url_path}'\n                    if SHORTENER is not None and SHORTENER_API is not None:\n                        siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text\n                        buttons.buildbutton(\"Index Link\", siurl)\n                    else:\n                        buttons.buildbutton(\"Index Link\", url)\n                if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_THREE_NAME}\", f\"{BUTTON_THREE_URL}\")\n                if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_FOUR_NAME}\", f\"{BUTTON_FOUR_URL}\")\n                if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:\n                    buttons.buildbutton(f\"{BUTTON_FIVE_NAME}\", f\"{BUTTON_FIVE_URL}\")\n        except Exception as err:\n            if isinstance(err, RetryError):\n                LOGGER.info(f\"Total Attempts:- {err.last_attempt.attempt_number}\")\n                err = err.last_attempt.exception()\n            err = str(err).replace('>', '').replace('<', '')\n            LOGGER.error(err)\n            return err, \"\"\n        return msg, InlineKeyboardMarkup(buttons.build_menu(2))\n\n    def cloneFolder(self, name, local_path, folder_id, parent_id):\n        LOGGER.info(f\"Syncing: {local_path}\")\n        files = self.getFilesByFolderId(folder_id)\n        new_id = None\n        if len(files) == 0:\n            return parent_id\n        for file in files:\n            if file.get('mimeType') == self.__G_DRIVE_DIR_MIME_TYPE:\n                file_path = os.path.join(local_path, file.get('name'))\n                current_dir_id = self.create_directory(file.get('name'), parent_id)\n                new_id = self.cloneFolder(file.get('name'), file_path, file.get('id'), current_dir_id)\n            else:\n                try:\n                    self.transferred_size += int(file.get('size'))\n                except TypeError:\n                    pass\n                try:\n                    self.copyFile(file.get('id'), parent_id)\n                    new_id = parent_id\n                except Exception as e:\n                    if isinstance(e, RetryError):\n                        LOGGER.info(f\"Total Attempts: {e.last_attempt.attempt_number}\")\n                        err = e.last_attempt.exception()\n                    else:\n                        err = e\n                    LOGGER.error(err)\n        return new_id\n\n    @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),\n           retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))\n    def create_directory(self, directory_name, parent_id):\n        file_metadata = {\n            \"name\": directory_name,\n            \"mimeType\": self.__G_DRIVE_DIR_MIME_TYPE\n        }\n        if parent_id is not None:\n            file_metadata[\"parents\"] = [parent_id]\n        file = self.__service.files().create(supportsTeamDrives=True, body=file_metadata).execute()\n        file_id = file.get(\"id\")\n        if not IS_TEAM_DRIVE:\n            self.__set_permission(file_id)\n        LOGGER.info(\"Created Google-Drive Folder:\\nName: {}\\nID: {} \".format(file.get(\"name\"), file_id))\n        return file_id\n\n    def upload_dir(self, input_directory, parent_id):\n        list_dirs = os.listdir(input_directory)\n        if len(list_dirs) == 0:\n            return parent_id\n        new_id = None\n        for item in list_dirs:\n            current_file_name = os.path.join(input_directory, item)\n            if self.is_cancelled:\n                return None\n            if os.path.isdir(current_file_name):\n                current_dir_id = self.create_directory(item, parent_id)\n                new_id = self.upload_dir(current_file_name, current_dir_id)\n            else:\n                mime_type = get_mime_type(current_file_name)\n                file_name = current_file_name.split(\"/\")[-1]\n                # current_file_name will have the full path\n                self.upload_file(current_file_name, file_name, mime_type, parent_id)\n                new_id = parent_id\n        return new_id\n\n    def authorize(self):\n        # Get credentials\n        credentials = None\n        if not USE_SERVICE_ACCOUNTS:\n            if os.path.exists(self.__G_DRIVE_TOKEN_FILE):\n                with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f:\n                    credentials = pickle.load(f)\n            if credentials is None or not credentials.valid:\n                if credentials and credentials.expired and credentials.refresh_token:\n                    credentials.refresh(Request())\n                else:\n                    flow = InstalledAppFlow.from_client_secrets_file(\n                        'credentials.json', self.__OAUTH_SCOPE)\n                    LOGGER.info(flow)\n                    credentials = flow.run_console(port=0)\n\n                # Save the credentials for the next run\n                with open(self.__G_DRIVE_TOKEN_FILE, 'wb') as token:\n                    pickle.dump(credentials, token)\n        else:\n            LOGGER.info(f\"Authorizing with {SERVICE_ACCOUNT_INDEX}.json service account\")\n            credentials = service_account.Credentials.from_service_account_file(\n                f'accounts/{SERVICE_ACCOUNT_INDEX}.json',\n                scopes=self.__OAUTH_SCOPE)\n        return build('drive', 'v3', credentials=credentials, cache_discovery=False)\n\n    def edit_telegraph(self):\n        nxt_page = 1 \n        prev_page = 0\n        for content in self.telegraph_content :\n            if nxt_page == 1 :\n                content += f'<b><a href=\"https://telegra.ph/{self.path[nxt_page]}\">Next</a></b>'\n                nxt_page += 1\n            else :\n                if prev_page <= self.num_of_path:\n                    content += f'<b><a href=\"https://telegra.ph/{self.path[prev_page]}\">Prev</a></b>'\n                    prev_page += 1\n                if nxt_page < self.num_of_path:\n                    content += f'<b> | <a href=\"https://telegra.ph/{self.path[nxt_page]}\">Next</a></b>'\n                    nxt_page += 1\n            Telegraph(access_token=telegraph_token).edit_page(path = self.path[prev_page],\n                                 title = 'MirrorX Search',\n                                 author_name='MirrorX',\n                                 author_url='https://github.com/iamLiquidX',\n                                 html_content=content)\n        return\n\n    def escapes(self, str):\n        chars = ['\\\\', \"'\", '\"', r'\\a', r'\\b', r'\\f', r'\\n', r'\\r', r'\\t']\n        for char in chars:\n            str = str.replace(char, '\\\\'+char)\n        return str\n\n    def drive_list(self, fileName):\n        msg = \"\"\n        fileName = self.escapes(str(fileName))\n        # Create Search Query for API request.\n        query = f\"'{parent_id}' in parents and (name contains '{fileName}')\"\n        response = self.__service.files().list(supportsTeamDrives=True,\n                                               includeTeamDriveItems=True,\n                                               q=query,\n                                               spaces='drive',\n                                               pageSize=200,\n                                               fields='files(id, name, mimeType, size)',\n                                               orderBy='modifiedTime desc').execute()\n\n        content_count = 0\n        if response[\"files\"]:\n            msg += f'<h4>Results : {fileName}</h4><br><br>'\n\n            for file in response.get('files', []):\n                if file.get('mimeType') == \"application/vnd.google-apps.folder\":  # Detect Whether Current Entity is a Folder or File.\n                    furl = f\"https://drive.google.com/drive/folders/{file.get('id')}\"\n                    msg += f\"⁍<code>{file.get('name')}<br>(folder)</code><br>\"\n                    if SHORTENER is not None and SHORTENER_API is not None:\n                        sfurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={furl}&format=text').text\n                        msg += f\"<b><a href={sfurl}>Drive Link</a></b>\"\n                    else:\n                        msg += f\"<b><a href={furl}>Drive Link</a></b>\"\n                    if INDEX_URL is not None:\n                        url_path = requests.utils.quote(f'{file.get(\"name\")}')\n                        url = f'{INDEX_URL}/{url_path}/'\n                        if SHORTENER is not None and SHORTENER_API is not None:\n                            siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text\n                            msg += f' <b>| <a href=\"{siurl}\">Index Link</a></b>'\n                        else:\n                            msg += f' <b>| <a href=\"{url}\">Index Link</a></b>'\n                else:\n                    furl = f\"https://drive.google.com/uc?id={file.get('id')}&export=download\"\n                    msg += f\"⁍<code>{file.get('name')}<br>({get_readable_file_size(int(file.get('size')))})</code><br>\"\n                    if SHORTENER is not None and SHORTENER_API is not None:\n                        sfurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={furl}&format=text').text\n                        msg += f\"<b><a href={sfurl}>Drive Link</a></b>\"\n                    else:\n                        msg += f\"<b><a href={furl}>Drive Link</a></b>\"\n                    if INDEX_URL is not None:\n                        url_path = requests.utils.quote(f'{file.get(\"name\")}')\n                        url = f'{INDEX_URL}/{url_path}'\n                        if SHORTENER is not None and SHORTENER_API is not None:\n                            siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={url}&format=text').text\n                            msg += f' <b>| <a href=\"{siurl}\">Index Link</a></b>'\n                        else:\n                            msg += f' <b>| <a href=\"{url}\">Index Link</a></b>'\n                msg += '<br><br>'\n                content_count += 1\n                if content_count == TELEGRAPHLIMIT :\n                    self.telegraph_content.append(msg)\n                    msg = \"\"\n                    content_count = 0\n\n            if msg != '':\n                self.telegraph_content.append(msg)\n\n            if len(self.telegraph_content) == 0:\n                return \"No Result Found :(\", None\n\n            for content in self.telegraph_content :\n                self.path.append(Telegraph(access_token=telegraph_token).create_page(\n                                                        title = 'MirrorX Search',\n                                                        author_name='MirrorX',\n                                                        author_url='https://github.com/iamLiquidX',\n                                                        html_content=content\n                                                        )['path'])\n\n            self.num_of_path = len(self.path)\n            if self.num_of_path > 1:\n                self.edit_telegraph()\n\n            msg = f\"<b>Search Results For {fileName} 👇</b>\"\n            buttons = button_build.ButtonMaker()   \n            buttons.buildbutton(\"HERE\", f\"https://telegra.ph/{self.path[0]}\")\n\n            return msg, InlineKeyboardMarkup(buttons.build_menu(1))\n\n        else :\n            return '', ''\n\n\n\n    def count(self, link):\n        self.total_bytes = 0\n        self.total_files = 0\n        self.total_folders = 0\n        try:\n            file_id = self.getIdFromUrl(link)\n        except (KeyError,IndexError):\n            msg = \"Google drive ID could not be found in the provided link\"\n            return msg\n        msg = \"\"\n        LOGGER.info(f\"File ID: {file_id}\")\n        try:\n            drive_file = self.__service.files().get(fileId=file_id, fields=\"id, name, mimeType, size\",\n                                                   supportsTeamDrives=True).execute()\n            name = drive_file['name']\n            LOGGER.info(f\"Counting: {name}\")\n            if drive_file['mimeType'] == self.__G_DRIVE_DIR_MIME_TYPE:\n                self.gDrive_directory(**drive_file)\n                msg += f'<b>Name:- </b><code>{name}</code>'\n                msg += f'\\n<b>Size:- </b>{get_readable_file_size(self.total_bytes)}'\n                msg += f\"\\n<b>Type:- </b>Folder\"\n                msg += f\"\\n<b>SubFolders:- </b>{self.total_folders}\"\n                msg += f\"\\n<b>Files:- </b>{self.total_files}\"\n            else:\n                msg += f'<b>Name:- </b><code>{name}</code>'\n                try:\n                    typee = drive_file['mimeType']\n                except:\n                    typee = 'File'    \n                try:\n                    self.total_files += 1\n                    self.gDrive_file(**drive_file)\n                    msg += f'\\n<b>Size:- </b><code>{get_readable_file_size(self.total_bytes)}</code>'\n                    msg += f\"\\n<b>Type:- </b>{typee}\"\n                    msg += f\"\\n<b>Files:- </b>{self.total_files}\"\n                except TypeError:\n                    pass\n        except Exception as err:\n            if isinstance(err, RetryError):\n                LOGGER.info(f\"Total Attempts: {err.last_attempt.attempt_number}\")\n                err = err.last_attempt.exception()\n            err = str(err).replace('>', '').replace('<', '')\n            LOGGER.error(err)\n            return err\n        return msg\n\n    def gDrive_file(self, **kwargs):\n        try:\n            size = int(kwargs['size'])\n        except:\n            size = 0\n        self.total_bytes += size\n\n    def gDrive_directory(self, **kwargs) -> None:\n        files = self.getFilesByFolderId(kwargs['id'])\n        if len(files) == 0:\n            return\n        for file_ in files:\n            if file_['mimeType'] == self.__G_DRIVE_DIR_MIME_TYPE:\n                self.total_folders += 1\n                self.gDrive_directory(**file_)\n            else:\n                self.total_files += 1\n                self.gDrive_file(**file_)\n    \n    def clonehelper(self, link):\n        try:\n            file_id = self.getIdFromUrl(link)\n        except (KeyError,IndexError):\n            msg = \"Google drive ID could not be found in the provided link\"\n            return msg, \"\", \"\"\n        LOGGER.info(f\"File ID: {file_id}\")\n        try:\n            drive_file = self.__service.files().get(fileId=file_id, fields=\"id, name, mimeType, size\",\n                                                   supportsTeamDrives=True).execute()\n            name = drive_file['name']\n            LOGGER.info(f\"Checking: {name}\")\n            if drive_file['mimeType'] == self.__G_DRIVE_DIR_MIME_TYPE:\n                self.gDrive_directory(**drive_file)\n            else:\n                try:\n                    self.total_files += 1\n                    self.gDrive_file(**drive_file)\n                except TypeError:\n                    pass\n            clonesize = self.total_bytes\n        except Exception as err:\n            if isinstance(err, RetryError):\n                LOGGER.info(f\"Total Attempts: {err.last_attempt.attempt_number}\")\n                err = err.last_attempt.exception()\n            err = str(err).replace('>', '').replace('<', '')\n            LOGGER.error(err)\n            if \"File not found\" in str(err):\n                msg = \"File not found.\"\n            else:\n                msg = f\"Error.\\n{err}\"\n            return msg, \"\", \"\"\n        return \"\", clonesize, name\n\n    def download(self, link):\n        self.is_downloading = True\n        file_id = self.getIdFromUrl(link)\n        if USE_SERVICE_ACCOUNTS:\n            self.service_account_count = len(os.listdir(\"accounts\"))\n        self.start_time = time.time()\n        self.updater = setInterval(self.update_interval, self._on_download_progress)\n        try:\n            meta = self.getFileMetadata(file_id)\n            path = f\"{DOWNLOAD_DIR}{self.__listener.uid}/\"\n            if meta.get(\"mimeType\") == self.__G_DRIVE_DIR_MIME_TYPE:\n                self.download_folder(file_id, path, meta.get('name'))\n            else:\n                os.makedirs(path)\n                self.download_file(file_id, path, meta.get('name'), meta.get('mimeType'))\n        except Exception as err:\n            if isinstance(err, RetryError):\n                LOGGER.info(f\"Total Attempts: {err.last_attempt.attempt_number}\")\n                err = err.last_attempt.exception()\n            err = str(err).replace('>', '').replace('<', '')\n            LOGGER.error(err)\n            self.is_cancelled = True\n            self.__listener.onDownloadError(err)\n            return\n        finally:\n            self.updater.cancel()\n            if self.is_cancelled:\n                return\n        self.__listener.onDownloadComplete()\n\n    def download_folder(self, folder_id, path, folder_name):\n        if not os.path.exists(path + folder_name):\n            os.makedirs(path + folder_name)\n        path += folder_name + '/'\n        result = []\n        page_token = None\n        while True:\n            files = self.__service.files().list(\n                    supportsTeamDrives=True,\n                    includeTeamDriveItems=True,\n                    q=f\"'{folder_id}' in parents\",\n                    fields='nextPageToken, files(id, name, mimeType, size, shortcutDetails)',\n                    pageToken=page_token,\n                    pageSize=1000).execute()\n            result.extend(files['files'])\n            page_token = files.get(\"nextPageToken\")\n            if not page_token:\n                break\n\n        result = sorted(result, key=lambda k: k['name'])\n        for item in result:\n            file_id = item['id']\n            filename = item['name']\n            mime_type = item['mimeType']\n            shortcut_details = item.get('shortcutDetails', None)\n            if shortcut_details != None:\n                file_id = shortcut_details['targetId']\n                mime_type = shortcut_details['targetMimeType']\n            if mime_type == 'application/vnd.google-apps.folder':\n                self.download_folder(file_id, path, filename)\n            elif not os.path.isfile(path + filename):\n                self.download_file(file_id, path, filename, mime_type)\n            if self.is_cancelled:\n                break\n                return\n\n    def download_file(self, file_id, path, filename, mime_type):\n        request = self.__service.files().get_media(fileId=file_id)\n        fh = io.FileIO('{}{}'.format(path, filename), 'wb')\n        downloader = MediaIoBaseDownload(fh, request, chunksize = 65 * 1024 * 1024)\n        done = False\n        while done is False:\n            if self.is_cancelled:\n                fh.close()\n                break\n                return\n            try:\n                self.dstatus, done = downloader.next_chunk()\n            except HttpError as err:\n                if err.resp.get('content-type', '').startswith('application/json'):\n                    reason = json.loads(err.content).get('error').get('errors')[0].get('reason')\n                    if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':\n                        if USE_SERVICE_ACCOUNTS:\n                            if not self.switchServiceAccount():\n                                raise err\n                            LOGGER.info(f\"Got: {reason}, Trying Again...\")\n                            return self.download_file(file_id, path, filename, mime_type)\n                        else:\n                            raise err\n                    else:\n                        raise err\n        self._file_downloaded_bytes = 0\n\n    def _on_download_progress(self):\n        if self.dstatus is not None:\n            chunk_size = self.dstatus.total_size * self.dstatus.progress() - self._file_downloaded_bytes\n            self._file_downloaded_bytes = self.dstatus.total_size * self.dstatus.progress()\n            self.downloaded_bytes += chunk_size\n            self.dtotal_time += self.update_interval\n\n    def cancel_download(self):\n        self.is_cancelled = True\n        self.__listener.onDownloadError('Download stopped by user!')\n"
  },
  {
    "path": "bot/helper/telegram_helper/__init__.py",
    "content": ""
  },
  {
    "path": "bot/helper/telegram_helper/bot_commands.py",
    "content": "import os\n\ndef getCommand(name: str, command: str):\n    try:\n        if len(os.environ[name]) == 0:\n            raise KeyError\n        return os.environ[name]\n    except KeyError:\n        return command\nclass _BotCommands:\n    def __init__(self):\n        self.StartCommand = getCommand('START_COMMAND', 'start')\n        self.MirrorCommand = getCommand('MIRROR_COMMAND', 'mirror')\n        self.UnzipMirrorCommand = getCommand('UNZIP_COMMAND', 'unzipmirror')\n        self.TarMirrorCommand = getCommand('TAR_COMMAND', 'tarmirror')\n        self.CancelMirror = getCommand('CANCEL_COMMAND', 'cancel')\n        self.CancelAllCommand = getCommand('CANCELALL_COMMAND', 'cancelall')\n        self.ListCommand = getCommand('LIST_COMMAND', 'list')\n        self.SpeedCommand = getCommand('SPEED_COMMAND', 'speedtest')\n        self.CountCommand = getCommand('COUNT_COMMAND', 'count')\n        self.StatusCommand = getCommand('STATUS_COMMAND', 'status')\n        self.AuthorizeCommand = getCommand('AUTH_COMMAND', 'authorize')\n        self.UnAuthorizeCommand = getCommand('UNAUTH_COMMAND', 'unauthorize')\n        self.PingCommand = getCommand('PING_COMMAND', 'ping')\n        self.RestartCommand = getCommand('RESTART_COMMAND', 'restart')\n        self.StatsCommand = getCommand('STATS_COMMAND', 'stats')\n        self.HelpCommand = getCommand('HELP_COMMAND', 'help')\n        self.LogCommand = getCommand('LOG_COMMAND', 'log')\n        self.CloneCommand = getCommand('CLONE_COMMAND', 'clone')\n        self.WatchCommand = getCommand('WATCH_COMMAND', 'watch')\n        self.TarWatchCommand = getCommand('TARWATCH_COMMAND', 'tarwatch')\n        self.deleteCommand = getCommand('DELETE_COMMAND', 'del')\n\nBotCommands = _BotCommands()\n"
  },
  {
    "path": "bot/helper/telegram_helper/button_build.py",
    "content": "from telegram import InlineKeyboardButton\n\nclass ButtonMaker:\n\tdef __init__(self):\n\t\tself.button = []\n\n\tdef buildbutton(self, key, link):\n\t\tself.button.append(InlineKeyboardButton(text = key, url = link))\n\n\tdef build_menu(self, n_cols, footer_buttons=None, header_buttons=None):\n\t\tmenu = [self.button[i:i + n_cols] for i in range(0, len(self.button), n_cols)]\n\t\tif header_buttons:\n\t\t\tmenu.insert(0, header_buttons)\n\t\tif footer_buttons:\n\t\t\tmenu.append(footer_buttons)\n\t\treturn menu"
  },
  {
    "path": "bot/helper/telegram_helper/filters.py",
    "content": "from telegram.ext import MessageFilter\nfrom telegram import Message\nfrom bot import AUTHORIZED_CHATS, OWNER_ID, download_dict, download_dict_lock\n\n\nclass CustomFilters:\n    class _OwnerFilter(MessageFilter):\n        def filter(self, message):\n            return bool(message.from_user.id == OWNER_ID)\n\n    owner_filter = _OwnerFilter()\n\n    class _AuthorizedUserFilter(MessageFilter):\n        def filter(self, message):\n            id = message.from_user.id\n            return bool(id in AUTHORIZED_CHATS or id == OWNER_ID)\n\n    authorized_user = _AuthorizedUserFilter()\n\n    class _AuthorizedChat(MessageFilter):\n        def filter(self, message):\n            return bool(message.chat.id in AUTHORIZED_CHATS)\n\n    authorized_chat = _AuthorizedChat()\n\n    class _MirrorOwner(MessageFilter):\n        def filter(self, message: Message):\n            user_id = message.from_user.id\n            if user_id == OWNER_ID:\n                return True\n            args = str(message.text).split(' ')\n            if len(args) > 1:\n                # Cancelling by gid\n                with download_dict_lock:\n                    for message_id, status in download_dict.items():\n                        if status.gid() == args[1] and status.message.from_user.id == user_id:\n                            return True\n                    else:\n                        return False\n            # Cancelling by replying to original mirror message\n            reply_user = message.reply_to_message.from_user.id\n            return bool(reply_user == user_id)\n    mirror_owner_filter = _MirrorOwner()\n"
  },
  {
    "path": "bot/helper/telegram_helper/message_utils.py",
    "content": "from telegram import InlineKeyboardMarkup\nfrom telegram.message import Message\nfrom telegram.update import Update\nimport time\nimport psutil\nfrom bot import AUTO_DELETE_MESSAGE_DURATION, LOGGER, bot, \\\n    status_reply_dict, status_reply_dict_lock, download_dict, download_dict_lock\nfrom bot.helper.ext_utils.bot_utils import get_readable_message, get_readable_file_size, MirrorStatus\nfrom telegram.error import TimedOut, BadRequest\n\ndef sendMessage(text: str, bot, update: Update):\n    try:\n        return bot.send_message(update.message.chat_id,\n                            reply_to_message_id=update.message.message_id,\n                            text=text, parse_mode='HTMl')\n    except Exception as e:\n        LOGGER.error(str(e))\n\n\ndef sendMarkup(text: str, bot, update: Update, reply_markup: InlineKeyboardMarkup):\n    try:\n        return bot.send_message(update.message.chat_id,\n                             reply_to_message_id=update.message.message_id,\n                             text=text, reply_markup=reply_markup, parse_mode='HTMl')\n    except Exception as e:\n        LOGGER.error(str(e))\n\n\ndef editMessage(text: str, message: Message, reply_markup=None):\n    try:\n        bot.edit_message_text(text=text, message_id=message.message_id,\n                              chat_id=message.chat.id,reply_markup=reply_markup,\n                              parse_mode='HTMl')\n    except Exception as e:\n        LOGGER.error(str(e))\n\n\ndef deleteMessage(bot, message: Message):\n    try:\n        bot.delete_message(chat_id=message.chat.id,\n                           message_id=message.message_id)\n    except Exception as e:\n        LOGGER.error(str(e))\n\n\ndef sendLogFile(bot, update: Update):\n    with open('log.txt', 'rb') as f:\n        bot.send_document(document=f, filename=f.name,\n                          reply_to_message_id=update.message.message_id,\n                          chat_id=update.message.chat_id)\n\n\ndef auto_delete_message(bot, cmd_message: Message, bot_message: Message):\n    if AUTO_DELETE_MESSAGE_DURATION != -1:\n        time.sleep(AUTO_DELETE_MESSAGE_DURATION)\n        try:\n            # Skip if None is passed meaning we don't want to delete bot xor cmd message\n            deleteMessage(bot, cmd_message)\n            deleteMessage(bot, bot_message)\n        except AttributeError:\n            pass\n\n\ndef delete_all_messages():\n    with status_reply_dict_lock:\n        for message in list(status_reply_dict.values()):\n            try:\n                deleteMessage(bot, message)\n                del status_reply_dict[message.chat.id]\n            except Exception as e:\n                LOGGER.error(str(e))\n\n\ndef update_all_messages():\n    msg = get_readable_message()\n    msg += f\"<b>CPU:-</b> {psutil.cpu_percent()}%\" \\\n           f\" <b>DISK:-</b> {psutil.disk_usage('/').percent}%\" \\\n           f\" <b>RAM:-</b> {psutil.virtual_memory().percent}%\"\n    with download_dict_lock:\n        dlspeed_bytes = 0\n        uldl_bytes = 0\n        for download in list(download_dict.values()):\n            speedy = download.speed()\n            if download.status() == MirrorStatus.STATUS_DOWNLOADING:\n                if 'KiB/s' in speedy:\n                    dlspeed_bytes += float(speedy.split('K')[0]) * 1024\n                elif 'MiB/s' in speedy:\n                    dlspeed_bytes += float(speedy.split('M')[0]) * 1048576 \n            if download.status() == MirrorStatus.STATUS_UPLOADING:\n                if 'KB/s' in speedy:\n            \t    uldl_bytes += float(speedy.split('K')[0]) * 1024\n                elif 'MB/s' in speedy:\n                    uldl_bytes += float(speedy.split('M')[0]) * 1048576\n        dlspeed = get_readable_file_size(dlspeed_bytes)\n        ulspeed = get_readable_file_size(uldl_bytes)\n        msg += f\"\\n<b>DL:</b>{dlspeed}ps | <b>UL:</b>{ulspeed}ps \\n\"\n    with status_reply_dict_lock:\n        for chat_id in list(status_reply_dict.keys()):\n            if status_reply_dict[chat_id] and msg != status_reply_dict[chat_id].text:\n                if len(msg) == 0:\n                    msg = \"Starting DL\"\n                try:\n                    editMessage(msg, status_reply_dict[chat_id])\n                except Exception as e:\n                    LOGGER.error(str(e))\n                status_reply_dict[chat_id].text = msg\n\n\ndef sendStatusMessage(msg, bot):\n    progress = get_readable_message()\n    progress += f\"<b>CPU:</b> {psutil.cpu_percent()}%\" \\\n           f\" <b>DISK:</b> {psutil.disk_usage('/').percent}%\" \\\n           f\" <b>RAM:</b> {psutil.virtual_memory().percent}%\"\n    with download_dict_lock:\n        dlspeed_bytes = 0\n        uldl_bytes = 0\n        for download in list(download_dict.values()):\n            speedy = download.speed()\n            if download.status() == MirrorStatus.STATUS_DOWNLOADING:\n                if 'KiB/s' in speedy:\n                    dlspeed_bytes += float(speedy.split('K')[0]) * 1024\n                elif 'MiB/s' in speedy:\n                    dlspeed_bytes += float(speedy.split('M')[0]) * 1048576 \n            if download.status() == MirrorStatus.STATUS_UPLOADING:\n                if 'KB/s' in speedy:\n            \t    uldl_bytes += float(speedy.split('K')[0]) * 1024\n                elif 'MB/s' in speedy:\n                    uldl_bytes += float(speedy.split('M')[0]) * 1048576\n        dlspeed = get_readable_file_size(dlspeed_bytes)\n        ulspeed = get_readable_file_size(uldl_bytes)\n        progress += f\"\\n<b>DL:</b>{dlspeed}ps | <b>UL:</b>{ulspeed}ps \\n\"\n    with status_reply_dict_lock:\n        if msg.message.chat.id in list(status_reply_dict.keys()):\n            try:\n                message = status_reply_dict[msg.message.chat.id]\n                deleteMessage(bot, message)\n                del status_reply_dict[msg.message.chat.id]\n            except Exception as e:\n                LOGGER.error(str(e))\n                del status_reply_dict[msg.message.chat.id]\n        if len(progress) == 0:\n            progress = \"Starting DL\"\n        message = sendMessage(progress, bot, msg)\n        status_reply_dict[msg.message.chat.id] = message\n"
  },
  {
    "path": "bot/modules/__init__.py",
    "content": ""
  },
  {
    "path": "bot/modules/authorize.py",
    "content": "from bot.helper.telegram_helper.message_utils import sendMessage\nfrom bot import AUTHORIZED_CHATS, dispatcher\nfrom telegram.ext import CommandHandler\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom telegram.ext import Filters\nfrom telegram import Update\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\n\n\ndef authorize(update,context):\n    reply_message = update.message.reply_to_message\n    msg = ''\n    with open('authorized_chats.txt', 'a') as file:\n        if reply_message is None:\n            # Trying to authorize a chat\n            chat_id = update.effective_chat.id\n            if chat_id not in AUTHORIZED_CHATS:\n                file.write(f'{chat_id}\\n')\n                AUTHORIZED_CHATS.add(chat_id)\n                msg = 'Chat authorized'\n            else:\n                msg = 'Already authorized chat'\n        else:\n            # Trying to authorize someone in specific\n            user_id = reply_message.from_user.id\n            if user_id not in AUTHORIZED_CHATS:\n                file.write(f'{user_id}\\n')\n                AUTHORIZED_CHATS.add(user_id)\n                msg = 'Person Authorized to use the bot!'\n            else:\n                msg = 'Person already authorized'\n        sendMessage(msg, context.bot, update)\n\n\ndef unauthorize(update,context):\n    reply_message = update.message.reply_to_message\n    if reply_message is None:\n        # Trying to unauthorize a chat\n        chat_id = update.effective_chat.id\n        if chat_id in AUTHORIZED_CHATS:\n            AUTHORIZED_CHATS.remove(chat_id)\n            msg = 'Chat unauthorized'\n        else:\n            msg = 'Already unauthorized chat'\n    else:\n        # Trying to authorize someone in specific\n        user_id = reply_message.from_user.id\n        if user_id in AUTHORIZED_CHATS:\n            AUTHORIZED_CHATS.remove(user_id)\n            msg = 'Person unauthorized to use the bot!'\n        else:\n            msg = 'Person already unauthorized!'\n    with open('authorized_chats.txt', 'a') as file:\n        file.truncate(0)\n        for i in AUTHORIZED_CHATS:\n            file.write(f'{i}\\n')\n    sendMessage(msg, context.bot, update)\n\n\nauthorize_handler = CommandHandler(command=BotCommands.AuthorizeCommand, callback=authorize,\n                                   filters=CustomFilters.owner_filter & Filters.group, run_async=True)\nunauthorize_handler = CommandHandler(command=BotCommands.UnAuthorizeCommand, callback=unauthorize,\n                                     filters=CustomFilters.owner_filter & Filters.group, run_async=True)\ndispatcher.add_handler(authorize_handler)\ndispatcher.add_handler(unauthorize_handler)\n\n"
  },
  {
    "path": "bot/modules/cancel_mirror.py",
    "content": "from telegram.ext import CommandHandler\n\nfrom bot import download_dict, dispatcher, download_dict_lock, DOWNLOAD_DIR\nfrom bot.helper.ext_utils.fs_utils import clean_download\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.message_utils import *\n\nfrom time import sleep\nfrom bot.helper.ext_utils.bot_utils import getDownloadByGid, MirrorStatus\n\n\ndef cancel_mirror(update, context):\n    args = update.message.text.split(\" \", maxsplit=1)\n    mirror_message = None\n    if len(args) > 1:\n        gid = args[1]\n        dl = getDownloadByGid(gid)\n        if not dl:\n            sendMessage(f\"GID: <code>{gid}</code> not found.\", context.bot, update)\n            return\n        with download_dict_lock:\n            keys = list(download_dict.keys())\n        mirror_message = dl.message\n    elif update.message.reply_to_message:\n        mirror_message = update.message.reply_to_message\n        with download_dict_lock:\n            keys = list(download_dict.keys())\n            dl = download_dict[mirror_message.message_id]\n    if len(args) == 1:\n        if mirror_message is None or mirror_message.message_id not in keys:\n            if BotCommands.MirrorCommand in mirror_message.text or \\\n                    BotCommands.TarMirrorCommand in mirror_message.text:\n                msg = \"Mirror already have been cancelled\"\n                sendMessage(msg, context.bot, update)\n                return\n            else:\n                msg = \"Please reply to the /mirror message which was used to start the download or /cancel gid to cancel it!\"\n                sendMessage(msg, context.bot, update)\n                return\n    if dl.status() == \"Uploading\":\n        sendMessage(\"Upload in Progress, Don't Cancel it.\", context.bot, update)\n        return\n    elif dl.status() == \"Archiving\":\n        sendMessage(\"Archival in Progress, Don't Cancel it.\", context.bot, update)\n        return\n    else:\n        dl.download().cancel_download()\n    sleep(1)  # Wait a Second For Aria2 To free Resources.\n    clean_download(f'{DOWNLOAD_DIR}{mirror_message.message_id}/')\n\n\ndef cancel_all(update, context):\n    with download_dict_lock:\n        count = 0\n        for dlDetails in list(download_dict.values()):\n            if dlDetails.status() == MirrorStatus.STATUS_DOWNLOADING \\\n                    or dlDetails.status() == MirrorStatus.STATUS_WAITING:\n                dlDetails.download().cancel_download()\n                count += 1\n    delete_all_messages()\n    sendMessage(f'Cancelled {count} downloads!', context.bot, update)\n\n\ncancel_mirror_handler = CommandHandler(BotCommands.CancelMirror, cancel_mirror,\n                                       filters=(CustomFilters.authorized_chat | CustomFilters.authorized_user) & CustomFilters.mirror_owner_filter, run_async=True)\ncancel_all_handler = CommandHandler(BotCommands.CancelAllCommand, cancel_all,\n                                    filters=CustomFilters.owner_filter, run_async=True)\ndispatcher.add_handler(cancel_all_handler)\ndispatcher.add_handler(cancel_mirror_handler)\n"
  },
  {
    "path": "bot/modules/clone.py",
    "content": "from telegram.ext import CommandHandler\nfrom bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper\nfrom bot.helper.telegram_helper.message_utils import *\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.ext_utils.bot_utils import new_thread\nfrom bot import dispatcher\n\n\ndef cloneNode(update,context):\n    args = update.message.text.split(\" \",maxsplit=1)\n    if len(args) > 1:\n        link = args[1]\n        msg = sendMessage(f\"Cloning: <code>{link}</code>\",context.bot,update)\n        gd = GoogleDriveHelper()\n        result, button = gd.clone(link)\n        deleteMessage(context.bot,msg)\n        if button == \"\":\n            sendMessage(result,context.bot,update)\n        else:\n            if update.message.from_user.username:\n                uname = f'@{update.message.from_user.username}'\n            else:\n                uname = f'<a href=\"tg://user?id={update.message.from_user.id}\">{update.message.from_user.first_name}</a>'\n            if uname is not None:\n                cc = f'\\n\\nReq. By: {uname}'\n            sendMarkup(result + cc, context.bot, update, button)\n    else:\n        sendMessage(\"Provide G-Drive Shareable Link to Clone.\",context.bot,update)\n\nclone_handler = CommandHandler(BotCommands.CloneCommand,cloneNode,filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(clone_handler)\n"
  },
  {
    "path": "bot/modules/count.py",
    "content": "import bot\n\nfrom telegram.ext import CommandHandler\nfrom bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper\nfrom bot.helper.telegram_helper.message_utils import deleteMessage, sendMessage\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot import dispatcher, AUTHORIZED_CHATS\n\ndef countNode(update,context):\n    args = update.message.text.split(\" \",maxsplit=1)\n    if len(args) > 1:\n        link = args[1]\n        msg = sendMessage(f\"Counting: <code>{link}</code>\",context.bot,update)\n        gd = GoogleDriveHelper()\n        result = gd.count(link)\n        deleteMessage(context.bot,msg)\n        if update.message.from_user.username:\n            uname = f'@{update.message.from_user.username}'\n        else:\n            uname = f'<a href=\"tg://user?id={update.message.from_user.id}\">{update.message.from_user.first_name}</a>'\n        if uname is not None:\n            cc = f'\\n\\nReq. By: {uname}'\n        sendMessage(result + cc, context.bot, update)\n    else:\n        sendMessage(\"Provide G-Drive Shareable Link to Count.\",context.bot,update)\n\ncount_handler = CommandHandler(BotCommands.CountCommand,countNode,filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(count_handler)"
  },
  {
    "path": "bot/modules/delete.py",
    "content": "from telegram.ext import CommandHandler\nimport threading\nfrom telegram import Update\nfrom bot import dispatcher, LOGGER\nfrom bot.helper.telegram_helper.message_utils import auto_delete_message, sendMessage\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.mirror_utils.upload_utils import gdriveTools\n\ndef deletefile(update, context):\n\tmsg_args = update.message.text.split(None, 1)\n\tmsg = ''\n\ttry:\n\t\tlink = msg_args[1]\n\t\tLOGGER.info(msg_args[1])\n\texcept IndexError:\n\t\tmsg = 'send a link along with command'\n\n\tif msg == '' : \n\t\tdrive = gdriveTools.GoogleDriveHelper()\n\t\tmsg = drive.deletefile(link)\n\tLOGGER.info(f\"this is msg : {msg}\")\n\treply_message = sendMessage(msg, context.bot, update)\n\n\tthreading.Thread(target=auto_delete_message, args=(context.bot, update.message, reply_message)).start()\n\ndelete_handler = CommandHandler(command=BotCommands.deleteCommand, callback=deletefile,\n\t\t\t\t\t\t\t\t\tfilters=CustomFilters.owner_filter, run_async=True)\ndispatcher.add_handler(delete_handler)\n"
  },
  {
    "path": "bot/modules/list.py",
    "content": "from telegram.ext import CommandHandler\nfrom bot.helper.mirror_utils.upload_utils.gdriveTools import GoogleDriveHelper\nfrom bot import LOGGER, dispatcher\nfrom bot.helper.telegram_helper.message_utils import sendMessage, sendMarkup, editMessage\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\n\ndef list_drive(update,context):\n    try:\n        search = update.message.text.split(' ',maxsplit=1)[1]\n        LOGGER.info(f\"Searching: {search}\")\n        reply = sendMessage('Searching..... Please wait!', context.bot, update)\n        gdrive = GoogleDriveHelper(None)\n        msg, button = gdrive.drive_list(search)\n\n        if button:\n            editMessage(msg, reply, button)\n        else:\n            editMessage('No result found', reply, button)\n\n    except IndexError:\n        sendMessage('send a search key along with command', context.bot, update)\n    except AttributeError:\n        pass\n\n\nlist_handler = CommandHandler(BotCommands.ListCommand, list_drive,filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(list_handler)\n"
  },
  {
    "path": "bot/modules/mirror.py",
    "content": "import requests\nfrom telegram.ext import CommandHandler\nfrom telegram import InlineKeyboardMarkup\n\nfrom bot import Interval, INDEX_URL, BUTTON_THREE_NAME, BUTTON_THREE_URL, BUTTON_FOUR_NAME, BUTTON_FOUR_URL, BUTTON_FIVE_NAME, BUTTON_FIVE_URL, BLOCK_MEGA_LINKS, MEGA_KEY\nfrom bot import dispatcher, DOWNLOAD_DIR, DOWNLOAD_STATUS_UPDATE_INTERVAL, download_dict, download_dict_lock, SHORTENER, SHORTENER_API\nfrom bot.helper.ext_utils import fs_utils, bot_utils\nfrom bot.helper.ext_utils.bot_utils import setInterval\nfrom bot.helper.ext_utils.exceptions import DirectDownloadLinkException, NotSupportedExtractionArchive\nfrom bot.helper.mirror_utils.download_utils.aria2_download import AriaDownloadHelper\nfrom bot.helper.mirror_utils.download_utils.mega_download import MegaDownloader\nfrom bot.helper.mirror_utils.download_utils.direct_link_generator import direct_link_generator\nfrom bot.helper.mirror_utils.download_utils.telegram_downloader import TelegramDownloadHelper\nfrom bot.helper.mirror_utils.status_utils import listeners\nfrom bot.helper.mirror_utils.status_utils.extract_status import ExtractStatus\nfrom bot.helper.mirror_utils.status_utils.tar_status import TarStatus\nfrom bot.helper.mirror_utils.status_utils.upload_status import UploadStatus\nfrom bot.helper.mirror_utils.status_utils.gdownload_status import DownloadStatus\nfrom bot.helper.mirror_utils.upload_utils import gdriveTools\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.message_utils import *\nfrom bot.helper.telegram_helper import button_build\nimport urllib\nimport pathlib\nimport os\nimport subprocess\nimport threading\nimport re\nimport random\nimport string\n\nariaDlManager = AriaDownloadHelper()\nariaDlManager.start_listener()\n\n\nclass MirrorListener(listeners.MirrorListeners):\n    def __init__(self, bot, update, pswd, isTar=False, tag=None, extract=False):\n        super().__init__(bot, update)\n        self.isTar = isTar\n        self.tag = tag\n        self.extract = extract\n        self.pswd = pswd\n\n    def onDownloadStarted(self):\n        pass\n\n    def onDownloadProgress(self):\n        # We are handling this on our own!\n        pass\n\n    def clean(self):\n        try:\n            Interval[0].cancel()\n            del Interval[0]\n            delete_all_messages()\n        except IndexError:\n            pass\n\n    def onDownloadComplete(self):\n        with download_dict_lock:\n            LOGGER.info(f\"Download completed: {download_dict[self.uid].name()}\")\n            download = download_dict[self.uid]\n            name = download.name()\n            size = download.size_raw()\n            if name is None: # when pyrogram's media.file_name is of NoneType\n                name = os.listdir(f'{DOWNLOAD_DIR}{self.uid}')[0]\n            m_path = f'{DOWNLOAD_DIR}{self.uid}/{name}'\n        if self.isTar:\n            download.is_archiving = True\n            try:\n                with download_dict_lock:\n                    download_dict[self.uid] = TarStatus(name, m_path, size)\n                path = fs_utils.tar(m_path)\n            except FileNotFoundError:\n                LOGGER.info('File to archive not found!')\n                self.onUploadError('Internal error occurred!!')\n                return\n        elif self.extract:\n            download.is_extracting = True\n            try:\n                path = fs_utils.get_base_name(m_path)\n                LOGGER.info(\n                    f\"Extracting : {name} \"\n                )\n                with download_dict_lock:\n                    download_dict[self.uid] = ExtractStatus(name, m_path, size)\n                pswd = self.pswd\n                if pswd is not None:\n                    archive_result = subprocess.run([\"pextract\", m_path, pswd])\n                else:\n                    archive_result = subprocess.run([\"extract\", m_path])\n                if archive_result.returncode == 0:\n                    threading.Thread(target=os.remove, args=(m_path,)).start()\n                    LOGGER.info(f\"Deleting archive : {m_path}\")\n                else:\n                    LOGGER.warning('Unable to extract archive! Uploading anyway')\n                    path = f'{DOWNLOAD_DIR}{self.uid}/{name}'\n                LOGGER.info(\n                    f'got path : {path}'\n                )\n\n            except NotSupportedExtractionArchive:\n                LOGGER.info(\"Not any valid archive, uploading file as it is.\")\n                path = f'{DOWNLOAD_DIR}{self.uid}/{name}'\n        else:\n            path = f'{DOWNLOAD_DIR}{self.uid}/{name}'\n        up_name = pathlib.PurePath(path).name\n        if up_name == \"None\":\n            up_name = \"\".join(os.listdir(f'{DOWNLOAD_DIR}{self.uid}/'))\n        up_path = f'{DOWNLOAD_DIR}{self.uid}/{up_name}'\n        LOGGER.info(f\"Upload Name : {up_name}\")\n        drive = gdriveTools.GoogleDriveHelper(up_name, self)\n        size = fs_utils.get_path_size(up_path)\n        upload_status = UploadStatus(drive, size, self)\n        with download_dict_lock:\n            download_dict[self.uid] = upload_status\n        update_all_messages()\n        drive.upload(up_name)\n\n    def onDownloadError(self, error):\n        error = error.replace('<', ' ')\n        error = error.replace('>', ' ')\n        LOGGER.info(self.update.effective_chat.id)\n        with download_dict_lock:\n            try:\n                download = download_dict[self.uid]\n                del download_dict[self.uid]\n                LOGGER.info(f\"Deleting folder: {download.path()}\")\n                fs_utils.clean_download(download.path())\n                LOGGER.info(str(download_dict))\n            except Exception as e:\n                LOGGER.error(str(e))\n                pass\n            count = len(download_dict)\n        if self.message.from_user.username:\n            uname = f\"@{self.message.from_user.username}\"\n        else:\n            uname = f'<a href=\"tg://user?id={self.message.from_user.id}\">{self.message.from_user.first_name}</a>'\n        msg = f\"{uname} your download has been stopped due to: {error}\"\n        sendMessage(msg, self.bot, self.update)\n        if count == 0:\n            self.clean()\n        else:\n            update_all_messages()\n\n    def onUploadStarted(self):\n        pass\n\n    def onUploadProgress(self):\n        pass\n\n    def onUploadComplete(self, link: str, size):\n        with download_dict_lock:\n            msg = f'<b>Name:- </b><code>{download_dict[self.uid].name()}</code>\\n<b>Size:- </b><code>{size}</code>'\n            buttons = button_build.ButtonMaker()\n            if SHORTENER is not None and SHORTENER_API is not None:\n                surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={link}&format=text').text\n                buttons.buildbutton(\"Drive Link\", surl)\n            else:\n                buttons.buildbutton(\"Drive Link\", link)\n            LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}')\n            if INDEX_URL is not None:\n                url_path = requests.utils.quote(f'{download_dict[self.uid].name()}')\n                share_url = f'{INDEX_URL}/{url_path}'\n                if os.path.isdir(f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}'):\n                    share_url += '/'\n                if SHORTENER is not None and SHORTENER_API is not None:\n                    siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={share_url}&format=text').text\n                    buttons.buildbutton(\"Index Link\", siurl)\n                else:\n                    buttons.buildbutton(\"Index Link\", share_url)\n            if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None:\n                buttons.buildbutton(f\"{BUTTON_THREE_NAME}\", f\"{BUTTON_THREE_URL}\")\n            if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:\n                buttons.buildbutton(f\"{BUTTON_FOUR_NAME}\", f\"{BUTTON_FOUR_URL}\")\n            if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:\n                buttons.buildbutton(f\"{BUTTON_FIVE_NAME}\", f\"{BUTTON_FIVE_URL}\")\n            if self.message.from_user.username:\n                uname = f\"@{self.message.from_user.username}\"\n            else:\n                uname = f'<a href=\"tg://user?id={self.message.from_user.id}\">{self.message.from_user.first_name}</a>'\n            if uname is not None:\n                msg += f'\\n\\nReq. By:- {uname}'\n            try:\n                fs_utils.clean_download(download_dict[self.uid].path())\n            except FileNotFoundError:\n                pass\n            del download_dict[self.uid]\n            count = len(download_dict)\n        sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2)))\n        if count == 0:\n            self.clean()\n        else:\n            update_all_messages()\n\n    def onUploadError(self, error):\n        e_str = error.replace('<', '').replace('>', '')\n        with download_dict_lock:\n            try:\n                fs_utils.clean_download(download_dict[self.uid].path())\n            except FileNotFoundError:\n                pass\n            del download_dict[self.message.message_id]\n            count = len(download_dict)\n        sendMessage(e_str, self.bot, self.update)\n        if count == 0:\n            self.clean()\n        else:\n            update_all_messages()\n\n\ndef _mirror(bot, update, isTar=False, extract=False):\n    mesg = update.message.text.split('\\n')\n    message_args = mesg[0].split(' ')\n    name_args = mesg[0].split('|')\n    try:\n        link = message_args[1]\n        print(link)\n        if link.startswith(\"|\") or link.startswith(\"pswd: \"):\n            link = ''\n    except IndexError:\n        link = ''\n    try:\n        name = name_args[1]\n        name = name.strip()\n        if name.startswith(\"pswd: \"):\n            name = ''\n    except IndexError:\n        name = ''\n    try:\n        ussr = urllib.parse.quote(mesg[1], safe='')\n        pssw = urllib.parse.quote(mesg[2], safe='')\n    except:\n        ussr = ''\n        pssw = ''\n    if ussr != '' and pssw != '':\n        link = link.split(\"://\", maxsplit=1)\n        link = f'{link[0]}://{ussr}:{pssw}@{link[1]}'\n    pswd = re.search('(?<=pswd: )(.*)', update.message.text)\n    if pswd is not None:\n      pswd = pswd.groups()\n      pswd = \" \".join(pswd)\n    LOGGER.info(link)\n    link = link.strip()\n    reply_to = update.message.reply_to_message\n    if reply_to is not None:\n        file = None\n        tag = reply_to.from_user.username\n        media_array = [reply_to.document, reply_to.video, reply_to.audio]\n        for i in media_array:\n            if i is not None:\n                file = i\n                break\n\n        if not bot_utils.is_url(link) and not bot_utils.is_magnet(link) or len(link) == 0:\n            if file is not None:\n                if file.mime_type != \"application/x-bittorrent\":\n                    listener = MirrorListener(bot, update, pswd, isTar, tag, extract)\n                    tg_downloader = TelegramDownloadHelper(listener)\n                    tg_downloader.add_download(reply_to, f'{DOWNLOAD_DIR}{listener.uid}/', name)\n                    sendStatusMessage(update, bot)\n                    if len(Interval) == 0:\n                        Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))\n                    return\n                else:\n                    link = file.get_file().file_path\n    else:\n        tag = None\n    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):\n        sendMessage('No download source provided', bot, update)\n        return\n\n    try:\n        link = direct_link_generator(link)\n    except DirectDownloadLinkException as e:\n        LOGGER.info(f'{link}: {e}')\n    listener = MirrorListener(bot, update, pswd, isTar, tag, extract)\n    if bot_utils.is_gdrive_link(link):\n        if not isTar and not extract:\n            sendMessage(f\"Use /{BotCommands.CloneCommand} To Copy File/Folder\", bot, update)\n            return\n        res, size, name = gdriveTools.GoogleDriveHelper().clonehelper(link)\n        if res != \"\":\n            sendMessage(res, bot, update)\n            return\n        LOGGER.info(f\"Download Name : {name}\")\n        drive = gdriveTools.GoogleDriveHelper(name, listener)\n        gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=12))\n        download_status = DownloadStatus(drive, size, listener, gid)\n        with download_dict_lock:\n            download_dict[listener.uid] = download_status\n        if len(Interval) == 0:\n            Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))\n        sendStatusMessage(update, bot)\n        drive.download(link)\n\n    elif bot_utils.is_mega_link(link) and MEGA_KEY is not None:\n        if BLOCK_MEGA_LINKS:\n            sendMessage(\"Mega Links Are Blocked.\", bot, update)\n        else:\n            mega_dl = MegaDownloader(listener)\n            mega_dl.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/')\n            sendStatusMessage(update, bot)\n    else:\n        ariaDlManager.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/', listener, name)\n        sendStatusMessage(update, bot)\n    if len(Interval) == 0:\n        Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))\n\n\ndef mirror(update, context):\n    _mirror(context.bot, update)\n\n\ndef tar_mirror(update, context):\n    _mirror(context.bot, update, True)\n\n\ndef unzip_mirror(update, context):\n    _mirror(context.bot, update, extract=True)\n\n\nmirror_handler = CommandHandler(BotCommands.MirrorCommand, mirror,\n                                filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ntar_mirror_handler = CommandHandler(BotCommands.TarMirrorCommand, tar_mirror,\n                                    filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\nunzip_mirror_handler = CommandHandler(BotCommands.UnzipMirrorCommand, unzip_mirror,\n                                      filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(mirror_handler)\ndispatcher.add_handler(tar_mirror_handler)\ndispatcher.add_handler(unzip_mirror_handler)\n"
  },
  {
    "path": "bot/modules/mirror_status.py",
    "content": "from telegram.ext import CommandHandler\nfrom bot import dispatcher, status_reply_dict, DOWNLOAD_STATUS_UPDATE_INTERVAL, status_reply_dict_lock\nfrom bot.helper.telegram_helper.message_utils import *\nfrom time import sleep\nfrom bot.helper.ext_utils.bot_utils import get_readable_message\nfrom telegram.error import BadRequest\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nimport threading\n\ndef mirror_status(update,context):\n    message = get_readable_message()\n    if len(message) == 0:\n        message = \"No active downloads\"\n        reply_message = sendMessage(message, context.bot, update)\n        threading.Thread(target=auto_delete_message, args=(bot, update.message, reply_message)).start()\n        return\n    index = update.effective_chat.id\n    with status_reply_dict_lock:\n        if index in status_reply_dict.keys():\n            deleteMessage(bot, status_reply_dict[index])\n            del status_reply_dict[index]\n    sendStatusMessage(update,context.bot)\n    deleteMessage(context.bot,update.message)\n\n\nmirror_status_handler = CommandHandler(BotCommands.StatusCommand, mirror_status,\n                                       filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(mirror_status_handler)\n"
  },
  {
    "path": "bot/modules/speedtest.py",
    "content": "import speedtest\nimport bot\n\nfrom bot.helper.telegram_helper.filters import CustomFilters\nfrom bot import dispatcher, AUTHORIZED_CHATS\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode\nfrom telegram.ext import CallbackContext, Filters, CommandHandler\n\n\n\ndef speedtst(update, context):\n    message = update.effective_message\n    ed_msg = message.reply_text(\"Running Speed Test . . . 💨\")\n    test = speedtest.Speedtest()\n    test.get_best_server()\n    test.download()\n    test.upload()\n    test.results.share()\n    result = test.results.dict()\n    context.bot.editMessageText(\n        \"🔻 Download Speed : \"\n        f\"{speed_convert(result['download'])}\\n\"\n        \"🔺 Upload Speed : \"\n        f\"{speed_convert(result['upload'])}\\n\"\n        \"📶 Ping : \"\n        f\"{result['ping']}\\n\"\n        \"🏬 ISP : \"\n        f\"{result['client']['isp']}\",\n        update.effective_chat.id,\n        ed_msg.message_id,\n    )\n\ndef speed_convert(size):\n    \"\"\"Hi human, you can't read bytes?\"\"\"\n    power = 2 ** 10\n    zero = 0\n    units = {0: \"\", 1: \"Kb/s\", 2: \"Mb/s\", 3: \"Gb/s\", 4: \"Tb/s\"}\n    while size > power:\n        size /= power\n        zero += 1\n    return f\"{round(size, 2)} {units[zero]}\"\n\n\nSPEED_HANDLER = CommandHandler(BotCommands.SpeedCommand, speedtst, \n                                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\n\ndispatcher.add_handler(SPEED_HANDLER)\n"
  },
  {
    "path": "bot/modules/watch.py",
    "content": "from telegram.ext import CommandHandler\nfrom telegram import Bot, Update\nfrom bot import Interval, DOWNLOAD_DIR, DOWNLOAD_STATUS_UPDATE_INTERVAL, dispatcher, LOGGER\nfrom bot.helper.ext_utils.bot_utils import setInterval\nfrom bot.helper.telegram_helper.message_utils import update_all_messages, sendMessage, sendStatusMessage\nfrom .mirror import MirrorListener\nfrom bot.helper.mirror_utils.download_utils.youtube_dl_download_helper import YoutubeDLHelper\nfrom bot.helper.telegram_helper.bot_commands import BotCommands\nfrom bot.helper.telegram_helper.filters import CustomFilters\nimport threading\n\n\ndef _watch(bot: Bot, update, isTar=False):\n    mssg = update.message.text\n    message_args = mssg.split(' ')\n    name_args = mssg.split('|')\n    try:\n        link = message_args[1]\n    except IndexError:\n        msg = f\"/{BotCommands.WatchCommand} [yt_dl supported link] [quality] |[CustomName] to mirror with youtube_dl.\\n\\n\"\n        msg += \"<b>Note :- Quality and custom name are optional</b>\\n\\nExample of quality :- audio, 144, 240, 360, 480, 720, 1080, 2160.\"\n        msg += \"\\n\\nIf you want to use custom filename, plz enter it after |\"\n        msg += f\"\\n\\nExample :-\\n<code>/{BotCommands.WatchCommand} https://youtu.be/ocX2FN1nguA 720 |My video bro</code>\\n\\n\"\n        msg += \"This file will be downloaded in 720p quality and it's name will be <b>My video bro</b>\"\n        sendMessage(msg, bot, update)\n        return\n    try:\n      if \"|\" in mssg:\n        mssg = mssg.split(\"|\")\n        qual = mssg[0].split(\" \")[2]\n        if qual == \"\":\n          raise IndexError\n      else:\n        qual = message_args[2]\n      if qual != \"audio\":\n        qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'\n    except IndexError:\n      qual = \"bestvideo+bestaudio/best\"\n    try:\n      name = name_args[1]\n    except IndexError:\n      name = \"\"\n    reply_to = update.message.reply_to_message\n    if reply_to is not None:\n        tag = reply_to.from_user.username\n    else:\n        tag = None\n    pswd = \"\"\n    listener = MirrorListener(bot, update, pswd, isTar, tag)\n    ydl = YoutubeDLHelper(listener)\n    threading.Thread(target=ydl.add_download,args=(link, f'{DOWNLOAD_DIR}{listener.uid}', qual, name)).start()\n    sendStatusMessage(update, bot)\n    if len(Interval) == 0:\n        Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))\n\n\ndef watchTar(update, context):\n    _watch(context.bot, update, True)\n\n\ndef watch(update, context):\n    _watch(context.bot, update)\n\n\nmirror_handler = CommandHandler(BotCommands.WatchCommand, watch,\n                                filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ntar_mirror_handler = CommandHandler(BotCommands.TarWatchCommand, watchTar,\n                                    filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)\ndispatcher.add_handler(mirror_handler)\ndispatcher.add_handler(tar_mirror_handler)\n"
  },
  {
    "path": "config_sample.env",
    "content": "#Remove this line before deploying\n_____REMOVE_THIS_LINE_____=True\n\n## Telegram\nBOT_TOKEN = \"\" # ENTER BOT TOKEN (Get your BOT_TOKEN by talking to @botfather)\nOWNER_ID =\nDOWNLOAD_STATUS_UPDATE_INTERVAL = 5\nAUTO_DELETE_MESSAGE_DURATION = 20\nTELEGRAM_API = \nTELEGRAM_HASH = \"\"\nAUTHORIZED_CHATS = \"\" #Separated by space\nMAX_CONCURRENT_DOWNLOADS = 4\n\n## Drive\nGDRIVE_FOLDER_ID = \"\"\nIS_TEAM_DRIVE = \"\"\nINDEX_URL = \"\"\nDOWNLOAD_DIR = \"/app/downloads\" #   Dont change this if you are using Docker compose\nUSE_SERVICE_ACCOUNTS = \"\"\n\n## Optional config\nUPTOBOX_TOKEN = \"\"\n\nMEGA_KEY = \"\"  # Get this from https://mega.nz/sdk\nMEGA_USERNAME = \"\"\nMEGA_PASSWORD = \"\"\nBLOCK_MEGA_LINKS = \"\"\n\nSTOP_DUPLICATE_MIRROR = \"\"\n\nSHORTENER = \"\"\nSHORTENER_API = \"\"\n\n# Add more buttons (two buttons are already added of file link and index link, you can add extra buttons too, these are optional)\n# If you don't know what are below entries, simply leave them, Don't fill anything in them.\nBUTTON_THREE_NAME = \"\"\nBUTTON_THREE_URL = \"\"\nBUTTON_FOUR_NAME = \"\"\nBUTTON_FOUR_URL = \"\"\nBUTTON_FIVE_NAME = \"\"\nBUTTON_FIVE_URL = \"\"\n\n\n# Commands Customization (Completely Optional)\n# If you want to change\nSTART_COMMAND = \"\"\nMIRROR_COMMAND = \"\"\nUNZIP_COMMAND = \"\"\nTAR_COMMAND = \"\"\nCANCEL_COMMAND = \"\"\nCANCELALL_COMMAND = \"\"\nLIST_COMMAND = \"\"\nSPEED_COMMAND = \"\"\nCOUNT_COMMAND = \"\"\nSTATUS_COMMAND = \"\"\nAUTH_COMMAND = \"\"\nUNAUTH_COMMAND = \"\"\nPING_COMMAND = \"\"\nRESTART_COMMAND = \"\"\nSTATS_COMMAND = \"\"\nHELP_COMMAND = \"\"\nLOG_COMMAND = \"\"\nCLONE_COMMAND = \"\"\nWATCH_COMMAND = \"\"\nTARWATCH_COMMAND = \"\"\nDELETE_COMMAND = \"\""
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3.9\"\n\nservices:\n  mirrorx:\n    image: ghcr.io/iamliquidx/mirrorx:latest\n    container_name: mirrorx\n    env_file:\n        # Should be filled up and should be kept in the same directory\n        - config.env\n    volumes:\n        # Make a folder in the host OS and keep SA(accounts folder) or token there\n        # syntax \"host OS path\":\"where it should be mounted inside container\" \n        - /home/someuser/mirrorx/accounts:/app/accounts\n        # for Service Accounts ex: /home/someuser/mirrorx/accounts:/app/accounts \n        # for token and credential.json\n        # - /home/someuser/mirrorx/token.pickle:/app/token.pickle\n        # - /home/someuser/mirrorx/credential.json:/app/credentials.json\n        # Incase you want to add a netrc file to youtube-dl\n        # - /home/someuser/mirrorx/netrc:/root/.netrc\n        # Dont edit the Container Directory (i.e Right Side one) as the bot runs in the same directory\n\n    restart: unless-stopped\n    # Restart policy, if container exits due to some error it will restart again"
  },
  {
    "path": "netrc",
    "content": ""
  },
  {
    "path": "requirements.txt",
    "content": "requests==2.26.0\nappdirs==1.4.4\naria2p==0.10.4\nprogress==1.6\npsutil==5.8.0\npython-telegram-bot==13.7\ngoogle-api-python-client==2.11.0\ngoogle-auth-httplib2==0.1.0\ngoogle-auth-oauthlib==0.4.5\njs2py==0.71\npython-dotenv==0.19.0\ntenacity==8.0.1\npython-magic==0.4.24\nbeautifulsoup4==4.9.3\nPyrogram\nTgCrypto\nyt-dlp\nlxml==4.6.3\ntelegraph==1.4.1\nspeedtest-cli==2.1.3\nmessages==0.5.0\npybase64==1.1.4\nlk21==1.6.0\nmegasdkrestclient"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup, find_packages\nimport pathlib\n\nCWD = pathlib.Path(__file__).parent\n\nREADME = (CWD / \"README.md\").read_text()\n\nsetup(\n    name='MirrorX',\n    version='6.0.13',\n    packages=find_packages(),\n    long_description=README,\n    long_description_content_type=\"text/markdown\",\n    url='https://github.com/iamliquidx/mirrorx',\n    license='GPL3.0',\n    author='',\n    author_email='',\n    include_package_data=True,\n    description='Telegram Mirror Bot',\n    platforms=\"any\",\n    install_requires=[\n        \"requests==2.26.0\",\n        \"appdirs==1.4.4\",\n        \"aria2p==0.10.4\",\n        \"progress==1.6\",\n        \"psutil==5.8.0\",\n        \"python-telegram-bot==13.7\",\n        \"google-api-python-client==2.11.0\",\n        \"google-auth-httplib2==0.1.0\",\n        \"google-auth-oauthlib==0.4.5\",\n        \"js2py==0.71\",\n        \"python-dotenv==0.19.0\",\n        \"tenacity==8.0.1\",\n        \"python-magic==0.4.24\",\n        \"beautifulsoup4==4.9.3\",\n        \"Pyrogram\",\n        \"TgCrypto\",\n        \"yt-dlp\",\n        \"lxml==4.6.3\",\n        \"telegraph==1.4.1\",\n        \"speedtest-cli==2.1.3\",\n        \"messages==0.5.0\",\n        \"pybase64==1.1.4\",\n        \"lk21==1.6.0\",\n        \"megasdkrestclient\"\n    ],\n    classifiers=[\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.7\",\n        \"Programming Language :: Python :: 3.8\",\n        \"Programming Language :: Python :: 3.9\",\n        \"License :: OSI Approved :: GNU General Public License (GPL)\",\n        \"Operating System :: POSIX :: Linux\",\n        \"Development Status :: 5 - Production/Stable\"\n    ],\n    python_requires=\">=3.7\",\n    entry_points={\n        \"console_scripts\":[\n            \"MirrorXBot = bot.__main__:main\"\n        ]\n\n    },\n    package_data={\n        \"\": [\"data/*.dat\", \"data/aria.conf\"],\n    },\n    scripts=['bin/extract', 'bin/pextract', 'bin/MirrorX'],\n)\n"
  },
  {
    "path": "utils/add_to_team_drive.py",
    "content": "from google.oauth2.service_account import Credentials\nimport googleapiclient.discovery, json, progress.bar, glob, sys, argparse, time\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport os, pickle\n\nstt = time.time()\n\nparse = argparse.ArgumentParser(\n    description='A tool to add service accounts to a shared drive from a folder containing credential files.')\nparse.add_argument('--path', '-p', default='accounts',\n                   help='Specify an alternative path to the service accounts folder.')\nparse.add_argument('--credentials', '-c', default='./credentials.json',\n                   help='Specify the relative path for the credentials file.')\nparse.add_argument('--yes', '-y', default=False, action='store_true', help='Skips the sanity prompt.')\nparsereq = parse.add_argument_group('required arguments')\nparsereq.add_argument('--drive-id', '-d', help='The ID of the Shared Drive.', required=True)\n\nargs = parse.parse_args()\nacc_dir = args.path\ndid = args.drive_id\ncredentials = glob.glob(args.credentials)\n\ntry:\n    open(credentials[0])\n    print('>> Found credentials.')\nexcept IndexError:\n    print('>> No credentials found.')\n    sys.exit(0)\n\nif not args.yes:\n    # input('Make sure the following client id is added to the shared drive as Manager:\\n' + json.loads((open(\n    # credentials[0],'r').read()))['installed']['client_id'])\n    input('>> Make sure the **Google account** that has generated credentials.json\\n   is added into your Team Drive '\n          '(shared drive) as Manager\\n>> (Press any key to continue)')\n\ncreds = None\nif os.path.exists('token_sa.pickle'):\n    with open('token_sa.pickle', 'rb') as token:\n        creds = pickle.load(token)\n# If there are no (valid) credentials available, let the user log in.\nif not creds or not creds.valid:\n    if creds and creds.expired and creds.refresh_token:\n        creds.refresh(Request())\n    else:\n        flow = InstalledAppFlow.from_client_secrets_file(credentials[0], scopes=[\n            'https://www.googleapis.com/auth/admin.directory.group',\n            'https://www.googleapis.com/auth/admin.directory.group.member'\n        ])\n        # creds = flow.run_local_server(port=0)\n        creds = flow.run_console()\n    # Save the credentials for the next run\n    with open('token_sa.pickle', 'wb') as token:\n        pickle.dump(creds, token)\n\ndrive = googleapiclient.discovery.build(\"drive\", \"v3\", credentials=creds)\nbatch = drive.new_batch_http_request()\n\naa = glob.glob('%s/*.json' % acc_dir)\npbar = progress.bar.Bar(\"Readying accounts\", max=len(aa))\nfor i in aa:\n    ce = json.loads(open(i).read())['client_email']\n    batch.add(drive.permissions().create(fileId=did, supportsAllDrives=True, body={\n        \"role\": \"fileOrganizer\",\n        \"type\": \"user\",\n        \"emailAddress\": ce\n    }))\n    pbar.next()\npbar.finish()\nprint('Adding...')\nbatch.execute()\n\nprint('Complete.')\nhours, rem = divmod((time.time() - stt), 3600)\nminutes, sec = divmod(rem, 60)\nprint(\"Elapsed Time:\\n{:0>2}:{:0>2}:{:05.2f}\".format(int(hours), int(minutes), sec))"
  },
  {
    "path": "utils/gen_sa_accounts.py",
    "content": "import errno\nimport os\nimport pickle\nimport sys\nfrom argparse import ArgumentParser\nfrom base64 import b64decode\nfrom glob import glob\nfrom json import loads\nfrom random import choice\nfrom time import sleep\n\nfrom google.auth.transport.requests import Request\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\nSCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/cloud-platform',\n          'https://www.googleapis.com/auth/iam']\nproject_create_ops = []\ncurrent_key_dump = []\nsleep_time = 30\n\n\n# Create count SAs in project\ndef _create_accounts(service, project, count):\n    batch = service.new_batch_http_request(callback=_def_batch_resp)\n    for i in range(count):\n        aid = _generate_id('mfc-')\n        batch.add(service.projects().serviceAccounts().create(name='projects/' + project, body={'accountId': aid,\n                                                                                                'serviceAccount': {\n                                                                                                    'displayName': aid}}))\n    batch.execute()\n\n\n# Create accounts needed to fill project\ndef _create_remaining_accounts(iam, project):\n    print('Creating accounts in %s' % project)\n    sa_count = len(_list_sas(iam, project))\n    while sa_count != 100:\n        _create_accounts(iam, project, 100 - sa_count)\n        sa_count = len(_list_sas(iam, project))\n\n\n# Generate a random id\ndef _generate_id(prefix='saf-'):\n    chars = '-abcdefghijklmnopqrstuvwxyz1234567890'\n    return prefix + ''.join(choice(chars) for _ in range(25)) + choice(chars[1:])\n\n\n# List projects using service\ndef _get_projects(service):\n    return [i['projectId'] for i in service.projects().list().execute()['projects']]\n\n\n# Default batch callback handler\ndef _def_batch_resp(id, resp, exception):\n    if exception is not None:\n        if str(exception).startswith('<HttpError 429'):\n            sleep(sleep_time / 100)\n        else:\n            print(str(exception))\n\n\n# Project Creation Batch Handler\ndef _pc_resp(id, resp, exception):\n    global project_create_ops\n    if exception is not None:\n        print(str(exception))\n    else:\n        for i in resp.values():\n            project_create_ops.append(i)\n\n\n# Project Creation\ndef _create_projects(cloud, count):\n    global project_create_ops\n    batch = cloud.new_batch_http_request(callback=_pc_resp)\n    new_projs = []\n    for i in range(count):\n        new_proj = _generate_id()\n        new_projs.append(new_proj)\n        batch.add(cloud.projects().create(body={'project_id': new_proj}))\n    batch.execute()\n\n    for i in project_create_ops:\n        while True:\n            resp = cloud.operations().get(name=i).execute()\n            if 'done' in resp and resp['done']:\n                break\n            sleep(3)\n    return new_projs\n\n\n# Enable services ste for projects in projects\ndef _enable_services(service, projects, ste):\n    batch = service.new_batch_http_request(callback=_def_batch_resp)\n    for i in projects:\n        for j in ste:\n            batch.add(service.services().enable(name=f'projects/{i}/services/{j}'))\n    batch.execute()\n\n\n# List SAs in project\ndef _list_sas(iam, project):\n    resp = iam.projects().serviceAccounts().list(name='projects/' + project, pageSize=100).execute()\n    if 'accounts' in resp:\n        return resp['accounts']\n    return []\n\n\n# Create Keys Batch Handler\ndef _batch_keys_resp(id, resp, exception):\n    global current_key_dump\n    if exception is not None:\n        current_key_dump = None\n        sleep(sleep_time / 100)\n    elif current_key_dump is None:\n        sleep(sleep_time / 100)\n    else:\n        current_key_dump.append((\n            resp['name'][resp['name'].rfind('/'):],\n            b64decode(resp['privateKeyData']).decode('utf-8')\n        ))\n\n\n# Create Keys\ndef _create_sa_keys(iam, projects, path):\n    global current_key_dump\n    for i in projects:\n        current_key_dump = []\n        print('Downloading keys from %s' % i)\n        while current_key_dump is None or len(current_key_dump) != 100:\n            batch = iam.new_batch_http_request(callback=_batch_keys_resp)\n            total_sas = _list_sas(iam, i)\n            for j in total_sas:\n                batch.add(iam.projects().serviceAccounts().keys().create(\n                    name='projects/{}/serviceAccounts/{}'.format(i, j['uniqueId']),\n                    body={\n                        'privateKeyType': 'TYPE_GOOGLE_CREDENTIALS_FILE',\n                        'keyAlgorithm': 'KEY_ALG_RSA_2048'\n                    }\n                ))\n            batch.execute()\n            if current_key_dump is None:\n                print('Redownloading keys from %s' % i)\n                current_key_dump = []\n            else:\n                index = 0\n                for j in current_key_dump:\n                    with open(f'{path}/{index}.json', 'w+') as f:\n                        f.write(j[1])\n                    index += 1\n\n\n# Delete Service Accounts\ndef _delete_sas(iam, project):\n    sas = _list_sas(iam, project)\n    batch = iam.new_batch_http_request(callback=_def_batch_resp)\n    for i in sas:\n        batch.add(iam.projects().serviceAccounts().delete(name=i['name']))\n    batch.execute()\n\n\ndef serviceaccountfactory(\n        credentials='credentials.json',\n        token='token_sa.pickle',\n        path=None,\n        list_projects=False,\n        list_sas=None,\n        create_projects=None,\n        max_projects=12,\n        enable_services=None,\n        services=['iam', 'drive'],\n        create_sas=None,\n        delete_sas=None,\n        download_keys=None\n):\n    selected_projects = []\n    proj_id = loads(open(credentials).read())['installed']['project_id']\n    creds = None\n    if os.path.exists(token):\n        with open(token, 'rb') as t:\n            creds = pickle.load(t)\n    if not creds or not creds.valid:\n        if creds and creds.expired and creds.refresh_token:\n            creds.refresh(Request())\n        else:\n            flow = InstalledAppFlow.from_client_secrets_file(credentials, SCOPES)\n\n            # creds = flow.run_local_server(port=0)\n            creds = flow.run_console()\n\n        with open(token, 'wb') as t:\n            pickle.dump(creds, t)\n\n    cloud = build('cloudresourcemanager', 'v1', credentials=creds)\n    iam = build('iam', 'v1', credentials=creds)\n    serviceusage = build('serviceusage', 'v1', credentials=creds)\n\n    projs = None\n    while projs == None:\n        try:\n            projs = _get_projects(cloud)\n        except HttpError as e:\n            if loads(e.content.decode('utf-8'))['error']['status'] == 'PERMISSION_DENIED':\n                try:\n                    serviceusage.services().enable(\n                        name='projects/%s/services/cloudresourcemanager.googleapis.com' % proj_id).execute()\n                except HttpError as e:\n                    print(e._get_reason())\n                    input('Press Enter to retry.')\n    if list_projects:\n        return _get_projects(cloud)\n    if list_sas:\n        return _list_sas(iam, list_sas)\n    if create_projects:\n        print(f\"creat projects: {create_projects}\")\n        if create_projects > 0:\n            current_count = len(_get_projects(cloud))\n            if current_count + create_projects <= max_projects:\n                print('Creating %d projects' % (create_projects))\n                nprjs = _create_projects(cloud, create_projects)\n                selected_projects = nprjs\n            else:\n                sys.exit('No, you cannot create %d new project (s).\\n'\n                         'Please reduce value of --quick-setup.\\n'\n                         'Remember that you can totally create %d projects (%d already).\\n'\n                         'Please do not delete existing projects unless you know what you are doing' % (\n                             create_projects, max_projects, current_count))\n        else:\n            print('Will overwrite all service accounts in existing projects.\\n'\n                  'So make sure you have some projects already.')\n            input(\"Press Enter to continue...\")\n\n    if enable_services:\n        ste = []\n        ste.append(enable_services)\n        if enable_services == '~':\n            ste = selected_projects\n        elif enable_services == '*':\n            ste = _get_projects(cloud)\n        services = [i + '.googleapis.com' for i in services]\n        print('Enabling services')\n        _enable_services(serviceusage, ste, services)\n    if create_sas:\n        stc = []\n        stc.append(create_sas)\n        if create_sas == '~':\n            stc = selected_projects\n        elif create_sas == '*':\n            stc = _get_projects(cloud)\n        for i in stc:\n            _create_remaining_accounts(iam, i)\n    if download_keys:\n        try:\n            os.mkdir(path)\n        except OSError as e:\n            if e.errno == errno.EEXIST:\n                pass\n            else:\n                raise\n        std = []\n        std.append(download_keys)\n        if download_keys == '~':\n            std = selected_projects\n        elif download_keys == '*':\n            std = _get_projects(cloud)\n        _create_sa_keys(iam, std, path)\n    if delete_sas:\n        std = []\n        std.append(delete_sas)\n        if delete_sas == '~':\n            std = selected_projects\n        elif delete_sas == '*':\n            std = _get_projects(cloud)\n        for i in std:\n            print('Deleting service accounts in %s' % i)\n            _delete_sas(iam, i)\n\n\nif __name__ == '__main__':\n    parse = ArgumentParser(description='A tool to create Google service accounts.')\n    parse.add_argument('--path', '-p', default='accounts',\n                       help='Specify an alternate directory to output the credential files.')\n    parse.add_argument('--token', default='token_sa.pickle', help='Specify the pickle token file path.')\n    parse.add_argument('--credentials', default='credentials.json', help='Specify the credentials file path.')\n    parse.add_argument('--list-projects', default=False, action='store_true',\n                       help='List projects viewable by the user.')\n    parse.add_argument('--list-sas', default=False, help='List service accounts in a project.')\n    parse.add_argument('--create-projects', type=int, default=None, help='Creates up to N projects.')\n    parse.add_argument('--max-projects', type=int, default=12, help='Max amount of project allowed. Default: 12')\n    parse.add_argument('--enable-services', default=None,\n                       help='Enables services on the project. Default: IAM and Drive')\n    parse.add_argument('--services', nargs='+', default=['iam', 'drive'],\n                       help='Specify a different set of services to enable. Overrides the default.')\n    parse.add_argument('--create-sas', default=None, help='Create service accounts in a project.')\n    parse.add_argument('--delete-sas', default=None, help='Delete service accounts in a project.')\n    parse.add_argument('--download-keys', default=None, help='Download keys for all the service accounts in a project.')\n    parse.add_argument('--quick-setup', default=None, type=int,\n                       help='Create projects, enable services, create service accounts and download keys. ')\n    parse.add_argument('--new-only', default=False, action='store_true', help='Do not use exisiting projects.')\n    args = parse.parse_args()\n    # If credentials file is invalid, search for one.\n    if not os.path.exists(args.credentials):\n        options = glob('*.json')\n        print('No credentials found at %s. Please enable the Drive API in:\\n'\n              'https://developers.google.com/drive/api/v3/quickstart/python\\n'\n              'and save the json file as credentials.json' % args.credentials)\n        if len(options) < 1:\n            exit(-1)\n        else:\n            i = 0\n            print('Select a credentials file below.')\n            inp_options = [str(i) for i in list(range(1, len(options) + 1))] + options\n            while i < len(options):\n                print('  %d) %s' % (i + 1, options[i]))\n                i += 1\n            inp = None\n            while True:\n                inp = input('> ')\n                if inp in inp_options:\n                    break\n            if inp in options:\n                args.credentials = inp\n            else:\n                args.credentials = options[int(inp) - 1]\n            print('Use --credentials %s next time to use this credentials file.' % args.credentials)\n    if args.quick_setup:\n        opt = '*'\n        if args.new_only:\n            opt = '~'\n        args.services = ['iam', 'drive']\n        args.create_projects = args.quick_setup\n        args.enable_services = opt\n        args.create_sas = opt\n        args.download_keys = opt\n    resp = serviceaccountfactory(\n        path=args.path,\n        token=args.token,\n        credentials=args.credentials,\n        list_projects=args.list_projects,\n        list_sas=args.list_sas,\n        create_projects=args.create_projects,\n        max_projects=args.max_projects,\n        create_sas=args.create_sas,\n        delete_sas=args.delete_sas,\n        enable_services=args.enable_services,\n        services=args.services,\n        download_keys=args.download_keys\n    )\n    if resp is not None:\n        if args.list_projects:\n            if resp:\n                print('Projects (%d):' % len(resp))\n                for i in resp:\n                    print('  ' + i)\n            else:\n                print('No projects.')\n        elif args.list_sas:\n            if resp:\n                print('Service accounts in %s (%d):' % (args.list_sas, len(resp)))\n                for i in resp:\n                    print('  {} ({})'.format(i['email'], i['uniqueId']))\n            else:\n                print('No service accounts.')\n"
  },
  {
    "path": "utils/generate_drive_token.py",
    "content": "import pickle\nimport os\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\ncredentials = None\n__G_DRIVE_TOKEN_FILE = \"token.pickle\"\n__OAUTH_SCOPE = [\"https://www.googleapis.com/auth/drive\"]\nif os.path.exists(__G_DRIVE_TOKEN_FILE):\n    with open(__G_DRIVE_TOKEN_FILE, 'rb') as f:\n        credentials = pickle.load(f)\n        if credentials is None or not credentials.valid:\n            if credentials and credentials.expired and credentials.refresh_token:\n                credentials.refresh(Request())\nelse:\n    flow = InstalledAppFlow.from_client_secrets_file(\n        'credentials.json', __OAUTH_SCOPE)\n    credentials = flow.run_console(port=0)\n\n# Save the credentials for the next run\nwith open(__G_DRIVE_TOKEN_FILE, 'wb') as token:\n    pickle.dump(credentials, token)"
  }
]