diff --git a/.all-contributorsrc b/.all-contributorsrc new file mode 100644 index 0000000..eb40f3d --- /dev/null +++ b/.all-contributorsrc @@ -0,0 +1,29 @@ +{ + "files": [ + "README.md" + ], + "imageSize": 100, + "commit": false, + "commitType": "docs", + "commitConvention": "angular", + "contributors": [ + { + "login": "bushig", + "name": "Bogdan", + "avatar_url": "https://avatars.githubusercontent.com/u/2815779?v=4", + "profile": "https://github.com/bushig", + "contributions": [ + "code" + ] + } + ], + "contributorsPerLine": 7, + "skipCi": true, + "repoType": "github", + "repoHost": "https://github.com", + "projectName": "QBittorrentBot", + "projectOwner": "ch3p4ll3" +} + "projectName": "QBittorrentBot", + "projectOwner": "ch3p4ll3" +} diff --git a/.github/workflows/deploy_retype.yml b/.github/workflows/deploy_retype.yml new file mode 100644 index 0000000..7eb835e --- /dev/null +++ b/.github/workflows/deploy_retype.yml @@ -0,0 +1,26 @@ +name: Publish Retype powered website to GitHub Pages +on: + workflow_dispatch: + push: + branches: + - main + +jobs: + publish: + name: Publish to retype branch + + runs-on: ubuntu-latest + + permissions: + contents: write + + steps: + - uses: actions/checkout@v2 + + - uses: retypeapp/action-build@latest + with: + config: docs/retype.yml + + - uses: retypeapp/action-github-pages@latest + with: + update-branch: true \ No newline at end of file diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index e92d406..561fabd 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -13,6 +13,11 @@ jobs: runs-on: ubuntu-latest steps: + - name: "Set current date as env variable" + run: | + echo "builddate=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT + id: version # this is used on variable path + - name: Checkout uses: actions/checkout@v3 - @@ -36,4 +41,6 @@ jobs: context: . file: ./Dockerfile push: true - tags: ${{ secrets.DOCKER_HUB_USERNAME }}/qbittorrent-bot:latest + tags: | + ${{ secrets.DOCKER_HUB_USERNAME }}/qbittorrent-bot:${{ steps.version.outputs.builddate }} + ${{ secrets.DOCKER_HUB_USERNAME }}/qbittorrent-bot:latest diff --git a/.gitignore b/.gitignore index 78fc413..f9de277 100644 --- a/.gitignore +++ b/.gitignore @@ -165,4 +165,5 @@ config.json *.session *.session-journal -*.sqlite \ No newline at end of file +*.sqlite +/docker_folder diff --git a/LICENSE b/LICENSE index fc7dccd..f288702 100755 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,674 @@ -MIT License - -Copyright (c) 2019 Mattia - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index a85bc55..677d775 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/259099080ca24e029a910e3249d32041)](https://app.codacy.com/gh/ch3p4ll3/QBittorrentBot?utm_source=github.com&utm_medium=referral&utm_content=ch3p4ll3/QBittorrentBot&utm_campaign=Badge_Grade) + +[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-) + # QBittorrentBot @@ -10,6 +13,9 @@ magnet:?xt=... ``` You can also pause, resume, delete and add/remove and modify categories. +## Warning! +Since version V2, the mapping of the configuration file has been changed. Make sure you have modified it correctly before starting the bot + ## Configuration ### Retrieve Telegram API ID and API HASH With the change of library to [pyrogram](https://docs.pyrogram.org/) you will need the API_ID and API_HASH. Check [here](https://docs.pyrogram.org/intro/quickstart) to find out how to recover them. @@ -19,8 +25,9 @@ The config file is stored in the mounted /app/config/ volume ``` { - "qbittorrent": { - "ip": "192.168.178.102", + "client": { + "type": "qbittorrent", + "host": "192.168.178.102", "port": 8080, "user": "admin", "password": "admin" @@ -34,11 +41,13 @@ The config file is stored in the mounted /app/config/ volume "users": [ { "user_id": 123456, - "notify": false + "notify": false, + "role": "administrator" }, { "user_id": 12345678, - "notify": true + "notify": true, + "role": "manager" } ] } @@ -58,7 +67,6 @@ Pull and run the image with: `docker run -d -v /home/user/docker/QBittorrentBot: - Move in the project directory - Install dependencies with `pip3 install -r requirements.txt` - Create a config.json file -- Edit in the file /src/config.py the location of the file 'config.json' - Start the bot with `python3 main.py` ## How to enable the qBittorrent Web UI @@ -71,3 +79,24 @@ You can activate it by going on the menu bar, go to **Tools > Options** qBittorr - Set username and password (by default username: admin / password: adminadmin) Click on Ok to save settings. + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + +
Bogdan
Bogdan

💻
+ + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/config.json.template b/config.json.template index ebd14a2..f2afd73 100644 --- a/config.json.template +++ b/config.json.template @@ -1,6 +1,7 @@ { - "qbittorrent": { - "ip": "192.168.178.102", + "client": { + "type": "qbittorrent", + "host": "192.168.178.102", "port": 8080, "user": "admin", "password": "admin" @@ -14,7 +15,8 @@ "users": [ { "user_id": 123456, - "notify": false + "notify": false, + "role": "administrator" } ] } \ No newline at end of file diff --git a/docs/advanced/add_entries_configuration.md b/docs/advanced/add_entries_configuration.md new file mode 100644 index 0000000..3981114 --- /dev/null +++ b/docs/advanced/add_entries_configuration.md @@ -0,0 +1,35 @@ +--- +order: -10 +--- +# Add new entries in configuration file + +Adding a new entry to the QBittorrentBot configuration file involves several steps: + +- **Clone the repository**: `git clone https://github.com/ch3p4ll3/QBittorrentBot.git` + +- **Navigate to the folder**: `src/configs` + +- **Modify the pydantic class**: + Identify the pydantic class where the new entry should be added. + Add a new attribute to the class to represent the new entry. + +- **Create a validation function (if necessary)**: + If the new entry requires additional validation beyond the type provided by pydantic, create a validation function. + The validation function should inspect the value of the new entry and check for any constraints or rules that need to be enforced. + +- **Add the new entry to the config file**: + Open the configuration file (usually `config.json`). + Add a new property to the configuration object for the new entry. + Set the value of the new property to the desired initial value. + +- **Update the convert_type_from_string function (if necessary)**: + If the new entry type requires a custom conversion from a string representation, add the conversion function to the `utils` file. + The function should take a string representation of the new entry type and return the corresponding data type. + +- **Update the bot code (if necessary)**: + If the new entry is being used by the bot code, update the relevant parts of the code to handle the new entry type and its values. + +- Build the docker image +- Start the docker container + +You can now use the bot with the new entry, have fun🥳 diff --git a/docs/advanced/add_new_client_manager.md b/docs/advanced/add_new_client_manager.md new file mode 100644 index 0000000..0c67cd4 --- /dev/null +++ b/docs/advanced/add_new_client_manager.md @@ -0,0 +1,78 @@ +--- +order: 0 +--- +# Add new client manager + +Adding a new client manager to QBittorrentBot involves creating a new class that implements the `ClientManager` interface. This interface defines the methods that the bot uses to interact with the client, such as adding, removing, pausing, and resuming torrents. + +To do this you need to follow a couple of steps: + +- Clone the repository locally using the command: `git clone https://github.com/ch3p4ll3/QBittorrentBot.git` +- Navigate to the folder `src/client_manager` +- Create a new file for your client manager class. Name the file something like `_manager.py`. For example, if you are writing a manager for utorrent the name will be `utorrent_manager.py` +- Define your client manager class. The class should inherit from the `ClientManager` class and implement all of its methods. For example, the `utorrent_manager.py` file might look like this: +```python +from typing import Union, List +from .client_manager import ClientManager + + +class UtorrentManager(ClientManager): + @classmethod + def add_magnet(cls, magnet_link: Union[str, List[str]], category: str = None) -> None: + # Implement your code to add a magnet to the utorrent client + pass + + @classmethod + def add_torrent(cls, file_name: str, category: str = None) -> None: + # Implement your code to add a torrent to the utorrent client + pass +... +``` +- Navigate to the `src/configs/` folder and edit the `enums.py` file by adding to the `ClientTypeEnum` class an enum for your client. For example, if we wanted to add a manager for utorrent the class would become like this: +```python +class ClientTypeEnum(str, Enum): + QBittorrent = 'qbittorrent' + Utorrent = 'utorrent' +``` +- Return to the `src/client_manager` folder and edit the `client_repo.py` file by adding to the dictionary named `repositories` an entry associating the newly created enum with the new manager. Example: +```python +from ..configs.enums import ClientTypeEnum +from .qbittorrent_manager import QbittorrentManager, ClientManager + + +class ClientRepo: + repositories = { + ClientTypeEnum.QBittorrent: QbittorrentManager, + ClientTypeEnum.Utorrent: UtorrentManager + } +... +``` +- Register your client manager in the config file. The config file is a JSON file that defines the configuration for the QBittorrentBot. You can add your new client manager to the client section of the config file. For example, the config file might look like this: +```json +{ + "client": { + "type": "utorrent", + "host": "192.168.178.102", + "port": 8080, + "user": "admin", + "password": "admin" + }, + "telegram": { + "bot_token": "1111111:AAAAAAAA-BBBBBBBBB", + "api_id": 1111, + "api_hash": "aaaaaaaa" + }, + + "users": [ + { + "user_id": 123456, + "notify": false, + "role": "administrator" + } + ] +} +``` +- Build the docker image +- Start the docker container + +You can now use the bot with the new client, have fun:partying_face: \ No newline at end of file diff --git a/docs/advanced/index.md b/docs/advanced/index.md new file mode 100644 index 0000000..250f34d --- /dev/null +++ b/docs/advanced/index.md @@ -0,0 +1,3 @@ +# Advanced + +This section will speigate the advanced functions of the bot, such as creating new client managers, and managing user roles \ No newline at end of file diff --git a/docs/advanced/index.yml b/docs/advanced/index.yml new file mode 100644 index 0000000..4d66b6e --- /dev/null +++ b/docs/advanced/index.yml @@ -0,0 +1 @@ +order: -10 \ No newline at end of file diff --git a/docs/advanced/manager_user_roles.md b/docs/advanced/manager_user_roles.md new file mode 100644 index 0000000..27020c2 --- /dev/null +++ b/docs/advanced/manager_user_roles.md @@ -0,0 +1,20 @@ +--- +order: -20 +--- +# Managing users roles + +QBittorrentBot provides a user role management system to control access to different actions and functionalities within the bot. The system defines three roles: Reader, Manager, and Admin, each with increasing permissions and capabilities. + +## Reader + +The Reader role grants basic access to view the list of active torrents and inspect the details of individual torrents. Users with the Reader role can view the torrent name, download speed, upload speed, progress, and file size. They can also view the category to which each torrent belongs. + +## Manager + +The Manager role extends the Reader role with additional permissions, allowing users to perform actions beyond mere observation. Manager-level users can download new torrents by sending magnet links or torrent files to the bot. They can also add or edit categories to organize their torrents effectively. Additionally, Manager users can set torrent priorities, enabling them to manage the download order and prioritize specific torrents. Moreover, they can pause or resume ongoing downloads, providing flexibility in managing their torrent activity. + +## Admin + +The Admin role, the most privileged, grants the user full control over the bot's functionalities. In addition to the capabilities of the Manager role, Admin users can remove torrents from their download lists, eliminating unwanted downloads. They can also remove categories, streamlining their torrent organization structure. And, as the highest-level role, Admin users have the authority to edit the bot's configuration files, modifying its settings and behavior. + +This role management system ensures that users are granted access appropriate to their needs and responsibilities. Readers can observe and manage their torrent activity, Managers can perform more extensive actions, and Admins have full control over the bot's operation. This structure enhances security and prevents unauthorized users from modifying configuration files or deleting torrents. \ No newline at end of file diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..36d47ef --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,64 @@ +--- +order: -20 +--- +# FAQ + +### What is QBittorrentBot? + +QBittorrentBot is a Telegram bot that allows you to control your qBittorrent downloads from within the Telegram app. It can add torrents, manage your torrent list, and much more. + +### What are the benefits of using QBittorrentBot? + +There are several benefits to using QBittorrentBot, including: + +* **Convenience:** You can control your torrents from anywhere, without having to open the qBittorrent app. +* **Efficiency:** You can manage your torrents without switching between apps. +* **Organization:** You can categorize your torrents for better organization and accessibility. +* **Docker Support:** You can deploy and manage the bot seamlessly using Docker containers. + +### How do I add QBittorrentBot to my Telegram account? + +Follow this guide to start using QBittorrentBot +[!ref Getting Started](getting_started) + +### How do I edit the configuration for the QBittorrentBot? + +The QBittorrentBot configuration file is located at config.json. This file stores the bot's settings, such as the connection details for the qBittorrent client, the API IDs and hashes, and the list of authorized users. To edit the configuration file, you can open it in a text editor and make the necessary changes. + +### How do I check the status of my torrents? + +You can check the status of your torrents by using the list torrents button. This command will display a list of all your active torrents, including their name, status, progress, and download/upload speed. + +### What is the difference between a magnet link and a torrent file? + +A magnet link is a URI scheme that allows you to download a torrent without having to download the entire torrent file. A torrent file is a file that contains metadata about the torrent, such as the filename, file size, and number of pieces. + +### What are the different user roles available in QBittorrentBot? + +QBittorrentBot supports three user roles: Reader, Manager, and Admin. Each role has different permissions, as follows: + +* **Reader:** Can view lists of active torrents and view individual torrent details. +* **Manager:** Can perform all Reader actions, plus add/edit categories, set torrent priorities, and pause/resume downloads. +* **Admin:** Can perform all Manager actions, plus remove torrents, remove categories, and edit configs. + +### How do I change the user role for a user? + +You can change the user role for a user by editing the `config.json` file. Open the file and find the user's entry. Change the `role` field to the desired role (e.g., "reader", "manager", or "admin"). Save the file and restart the bot or, if you are an admin you can reload the configuration from the bot. + +### How do I install QBittorrentBot on my server? + +You can install QBittorrentBot on your server using Docker. First, install Docker on your server. Then, create a Docker image from the QBittorrentBot Dockerfile. Finally, run the Docker image to start the bot. + +### How do I add a new manager to my QBittorrentBot? + +Please follow this guide +[!ref Add new client manager](advanced/add_new_client_manager) + +### How do I add a new entry to the QBittorrentBot configuration file? + +Please follow this guide +[!ref Add new entries in configuration file](advanced/add_entries_configuration) + +### How do I contribute to the development of QBittorrentBot? + +QBittorrentBot is an open-source project. You can contribute to the development by reporting bugs, suggesting improvements, or submitting pull requests. The project's code is hosted on [GitHub](https://github.com/ch3p4ll3/QBittorrentBot). \ No newline at end of file diff --git a/docs/getting_started/configuration_file.md b/docs/getting_started/configuration_file.md new file mode 100644 index 0000000..194202d --- /dev/null +++ b/docs/getting_started/configuration_file.md @@ -0,0 +1,92 @@ +# Configuration File + +The configuration file serves as a central repository for all the necessary information that the QBittorrentBot needs to operate effectively. It defines the connection parameters, credentials, and user settings that the bot utilizes to interact with the qBittorrent server and Telegram API. + +Below you can find an example of the configuration file: + +```json5 +{ + "client": { + "type": "qbittorrent", + "host": "192.168.178.102", + "port": 8080, + "user": "admin", + "password": "admin" + }, + "telegram": { + "bot_token": "1111111:AAAAAAAA-BBBBBBBBB", + "api_id": 1111, + "api_hash": "aaaaaaaa" + }, + + "users": [ + { + "user_id": 123456, + "notify": false, + "role": "administrator" + } + ] +} +``` + +Here's a brief overview of the configuration file and its key sections: + +- **Clients Section**: Establishes the connection details for the qBittorrent server, including the hostname, port number, username, and password. This enables the bot to interact with the qBittorrent server and manage torrents. + +- **Telegram Section**: Contains the bot token, API ID, and API hash, which are essential for authenticating the bot with the Telegram API. These credentials allow the bot to communicate with the Telegram server and receive user commands. Click [here](https://docs.pyrogram.org/intro/quickstart) to find out how to retrive your API ID and API Hash + +- **Users Section**: Lists the authorized users of the QBittorrentBot, along with their Telegram user IDs, notification preferences, and user roles. This section defines the users who can interact with the bot, receive notifications, and manage torrents. + +## Client + +This section defines the configuration for the qBittorrent client that the bot will be interacting with. + +Name | Type | Value +--- | --- | --- +type | [ClientTypeEnum](#clienttypeenum) | The type of client. +host | [IPvAnyAddress](#ipvanyaddress) | The IP address of the qBittorrent server. +port | int | The port number of the qBittorrent server. +user | str | The username for the qBittorrent server. +password | str | The password for the qBittorrent server. + +## Telegram + +This section defines the configuration for the Telegram bot that the QBittorrentBot will be communicating with. + +Name | Type | Value +--- | --- | --- +bot_token | str | The bot token for the QBittorrentBot. This is a unique identifier that is used to authenticate the bot with the Telegram API. +api_id | int | The API ID for the QBittorrentBot. This is a unique identifier that is used to identify the bot to the Telegram API. +api_hash |str | The API hash for the QBittorrentBot. This is a string of characters that is used to verify the authenticity of the bot's requests to the Telegram API. + + +## Users + +This section defines the list of users who are authorized to use the QBittorrentBot. Each user is defined by their Telegram user ID, whether or not they should be notified about completed torrents, and their role. + +Name | Type | Value +--- | --- |--- +user_id | int |The Telegram user ID of the user. This is a unique identifier that is used to identify the user to the Telegram API. +notify | bool |Whether or not the user should be notified about new torrents. +role | [UserRolesEnum](#userrolesenum) |The role of the user. + + +## Enums + +### ClientTypeEnum + +Name | Type | Value(to be used in json) +--- | --- |--- +QBittorrent | str | qbittorrent + +### UserRolesEnum +Name | Type | Value(to be used in json) | Remarks +--- | --- |--- | +Reader | str | reader | Can perform only reading operations(view torrents) +Manager | str | manager | Can perform only managing operations(view torrents + can download files + can add/edit categories + set torrent priority + can stop/start downloads) +Administrator| str | administrator | Can perform all operations (Manager + remove torrent + remove category + edit configs) + +## Other types + +### IPvAnyAddress +This type allows either an IPv4Address or an IPv6Address \ No newline at end of file diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md new file mode 100644 index 0000000..e68510c --- /dev/null +++ b/docs/getting_started/index.md @@ -0,0 +1,29 @@ +# Getting Started + +In order to start using the bot, you must first create a folder where the bot will fish for settings and where it will save logs + +For example: let's create a folder called `QBittorrentBot` in the home of the user `user`. The path to the folder will then be `/home/user/docker/QBittorrentBot`. + +Before starting the bot you need to place the configuration file in this folder. You can rename the `config.json.template` file to `config.json` and change the parameters as desired. Go [here](configuration_file.md) to read more about the configuration file. + +Once that is done you can start the bot using docker, you can use either docker or docker compose. + ++++ Docker +Open your terminal and execute the following command to start the bot container: + +`docker run -d -v /home/user/docker/QBittorrentBot:/app/config:rw --name qbittorrent-bot ch3p4ll3/qbittorrent-bot:latest` ++++ Docker compose +Create a file named `docker-compose.yml` inside a directory with the following content: +``` +version: '3.9' +services: + qbittorrent-bot: + image: 'ch3p4ll3/qbittorrent-bot:latest' + container_name: qbittorrent-bot + restart: unless-stopped + volumes: + - '/home/user/docker/QBittorrentBot:/app/config:rw' +``` + +Run the following command to start the bot using Docker Compose: +`docker compose up -d` \ No newline at end of file diff --git a/docs/getting_started/migrating_to_v2.md b/docs/getting_started/migrating_to_v2.md new file mode 100644 index 0000000..68e3480 --- /dev/null +++ b/docs/getting_started/migrating_to_v2.md @@ -0,0 +1,76 @@ +# Migrating to V2 + +Much has changed with the new version, especially the management of the configuration file. Some fields have been added, while others have changed names, so first check that you have all the fields in the json with the correct name. + +## New fields + +Two new fields were introduced: `type` and `role` in the `client` and `users` sections, respectively. + +The `type` field determines the type of torrent client you want to use(currently only qbittorrent is supported, so its value must be `qbittorrent`) + +The `role` field, on the other hand, determines the role of a particular user. Currently there are 3 roles: +- Reader +- Manager +- Administrator + +You can find more information [here](configuration_file/#enums) + +## Changed names + +There are 2 changes to the field names, the first is the name of the `qbittorrent` section which has been renamed to `client`. While the second is the `ip` field inside che `client` section which has been renamed to `host` + +## V1 vs V2 +configurations in comparison + +||| V1 + +```json +{ + "qbittorrent": { + "ip": "192.168.178.102", + "port": 8080, + "user": "admin", + "password": "admin" + }, + "telegram": { + "bot_token": "1111111:AAAAAAAA-BBBBBBBBB", + "api_id": 1111, + "api_hash": "aaaaaaaa" + }, + + "users": [ + { + "user_id": 123456, + "notify": false + } + ] +} +``` + +||| V2 + +```json +{ + "client": { + "type": "qbittorrent", + "host": "192.168.178.102", + "port": 8080, + "user": "admin", + "password": "admin" + }, + "telegram": { + "bot_token": "1111111:AAAAAAAA-BBBBBBBBB", + "api_id": 1111, + "api_hash": "aaaaaaaa" + }, + + "users": [ + { + "user_id": 123456, + "notify": false, + "role": "administrator" + } + ] +} +``` +||| \ No newline at end of file diff --git a/docs/images/administrator.png b/docs/images/administrator.png new file mode 100644 index 0000000..8cab98e Binary files /dev/null and b/docs/images/administrator.png differ diff --git a/docs/images/administrator_qbittorrent_settings.png b/docs/images/administrator_qbittorrent_settings.png new file mode 100644 index 0000000..4c95268 Binary files /dev/null and b/docs/images/administrator_qbittorrent_settings.png differ diff --git a/docs/images/administrator_settings.png b/docs/images/administrator_settings.png new file mode 100644 index 0000000..0f5cda6 Binary files /dev/null and b/docs/images/administrator_settings.png differ diff --git a/docs/images/list_torrents.png b/docs/images/list_torrents.png new file mode 100644 index 0000000..e3c6552 Binary files /dev/null and b/docs/images/list_torrents.png differ diff --git a/docs/images/torrent_info.png b/docs/images/torrent_info.png new file mode 100644 index 0000000..7374196 Binary files /dev/null and b/docs/images/torrent_info.png differ diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..8f43633 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,33 @@ +# QBittorrentBot + +QBittorrentBot is a Telegram bot that allows you to control your qBittorrent downloads from your Telegram account. + +This means that you can add, remove, pause, resume, and delete torrents, as well as view a list of your active downloads, all without having to open the qBittorrent application. + +!!!warning Warning +A lot has changed from version 2, if you have any errors, please take a look [here](getting_started/migrating_to_v2). +!!! + +## Features +Here are some of the things you can do with QBittorrentBot: + +- **Add torrents**: You can add torrents to your qBittorrent download queue by sending magnet links or torrent files to the bot. +- **List active downloads**: You can get a list of your current downloads, including their progress, status, and estimated completion time. +- **Pause/Resume downloads**: You can pause or resume ongoing downloads with a single command. +- **Delete torrents**: You can remove unwanted downloads from your queue with a single command. +- **Add/Remove/Edit categories**: You can categorize your torrents for better organization and accessibility. +- **Edit settings**: You can edit user and torrent client settings directly from the bot +- **Check client connection**: You can check the connection with the client directly from the bot + +## Benefits + +Here are some of the benefits of using QBittorrentBot: + +- **Security**: You can add multiple users who have access to the bot and each of them can have different permissions(reader, manager, administrator) +- **Convenience**: You can manage your torrents from anywhere, as long as you have your Telegram app with you. +- **Efficiency**: You don't have to switch between apps to control your torrents. +- **Organization**: You can categorize your torrents for better organization and accessibility. +- **Docker support**: You can deploy and manage the bot seamlessly using Docker for enhanced isolation, security, and flexibility. + + +QBittorrentBot is an open-source project, so you can contribute to its development if you want to make it even more powerful and user-friendly. diff --git a/docs/retype.yml b/docs/retype.yml new file mode 100644 index 0000000..72ac7d1 --- /dev/null +++ b/docs/retype.yml @@ -0,0 +1,11 @@ +input: . +output: .retype +url: # Add your website address here +branding: + title: QBittorrentBot + label: Docs +links: +- text: Getting Started + link: getting_started/ +footer: + copyright: "© Copyright {{ year }}. All rights reserved." \ No newline at end of file diff --git a/docs/screenshots/index.md b/docs/screenshots/index.md new file mode 100644 index 0000000..6a5e28c --- /dev/null +++ b/docs/screenshots/index.md @@ -0,0 +1,10 @@ +# Screenshots + +![Main Menu (Administrator view)](/images/administrator.png) + +![List and filter torrents](/images/list_torrents.png) +![View torrent info](/images/torrent_info.png) + +## Administrator section +![Administrator Settings](/images/administrator_settings.png) +![Edit Client Settings](/images/administrator_qbittorrent_settings.png) \ No newline at end of file diff --git a/docs/screenshots/index.yml b/docs/screenshots/index.yml new file mode 100644 index 0000000..0d38165 --- /dev/null +++ b/docs/screenshots/index.yml @@ -0,0 +1 @@ +order: -20 \ No newline at end of file diff --git a/logs/.gitignore b/logs/.gitignore new file mode 100644 index 0000000..86d0cb2 --- /dev/null +++ b/logs/.gitignore @@ -0,0 +1,4 @@ +# Ignore everything in this directory +* +# Except this file +!.gitignore \ No newline at end of file diff --git a/main.py b/main.py index f1b163b..b377446 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,28 @@ -from src.qbittorrent_bot import app, scheduler +from src.bot import app, scheduler +import logging +from logging import handlers +from src.configs import Configs +from os.path import exists +from os import mkdir + + +if not exists(Configs.log_folder): + mkdir(Configs.log_folder) + +# Create a file handler +handler = logging.handlers.TimedRotatingFileHandler( + f'{Configs.log_folder}/QbittorrentBot.log', + when='midnight', + backupCount=10 +) + +# Create a format +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +handler.setFormatter(formatter) + +logging.getLogger().addHandler(handler) +# Set logging level to DEBUG +logging.getLogger().setLevel(logging.DEBUG) if __name__ == '__main__': scheduler.start() diff --git a/requirements.txt b/requirements.txt index 6b75ca4..5fbd17e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,25 +1,26 @@ annotated-types==0.6.0 APScheduler==3.10.4 async-lru==2.0.4 -certifi==2023.7.22 -charset-normalizer==3.3.1 -idna==3.4 +certifi==2023.11.17 +charset-normalizer==3.3.2 +idna==3.6 packaging==23.2 pony==0.7.17 psutil==5.9.6 pyaes==1.6.1 -pydantic==2.4.2 -pydantic_core==2.10.1 +pydantic==2.5.2 +pydantic_core==2.14.5 Pyrogram==2.0.106 PySocks==1.7.1 pytz==2023.3.post1 pytz-deprecation-shim==0.1.0.post0 -qbittorrent-api==2023.10.54 +qbittorrent-api==2023.11.57 requests==2.31.0 six==1.16.0 TgCrypto==1.2.5 -typing_extensions==4.8.0 +tqdm==4.66.1 +typing_extensions==4.9.0 tzdata==2023.3 tzlocal==5.2 -urllib3==2.0.7 +urllib3==2.1.0 uvloop==0.19.0 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/bot/__init__.py b/src/bot/__init__.py new file mode 100644 index 0000000..1194ff8 --- /dev/null +++ b/src/bot/__init__.py @@ -0,0 +1,25 @@ +from pyrogram import Client +from pyrogram.enums.parse_mode import ParseMode +from apscheduler.schedulers.asyncio import AsyncIOScheduler +from src.utils import torrent_finished +from ..configs import Configs + + +BOT_CONFIGS = Configs.config + + +plugins = dict( + root="src.bot.plugins" +) + +app = Client( + "qbittorrent_bot", + api_id=BOT_CONFIGS.telegram.api_id, + api_hash=BOT_CONFIGS.telegram.api_hash, + bot_token=BOT_CONFIGS.telegram.bot_token, + parse_mode=ParseMode.MARKDOWN, + plugins=plugins +) + +scheduler = AsyncIOScheduler() +scheduler.add_job(torrent_finished, "interval", args=[app], seconds=60) diff --git a/src/bot/__main__.py b/src/bot/__main__.py new file mode 100644 index 0000000..1d669db --- /dev/null +++ b/src/bot/__main__.py @@ -0,0 +1,3 @@ +from . import app + +app.run() \ No newline at end of file diff --git a/src/bot/custom_filters.py b/src/bot/custom_filters.py new file mode 100644 index 0000000..3479187 --- /dev/null +++ b/src/bot/custom_filters.py @@ -0,0 +1,61 @@ +from pyrogram import filters +from ..configs import Configs +from ..utils import get_user_from_config +from ..configs.enums import UserRolesEnum + + +# Authorization filters +check_user_filter = filters.create(lambda _, __, message: message.from_user.id in [i.user_id for i in Configs.config.users]) + +user_is_reader = filters.create(lambda _, __, query: get_user_from_config(query.from_user.id).role == UserRolesEnum.Reader) +user_is_manager = filters.create(lambda _, __, query: get_user_from_config(query.from_user.id).role == UserRolesEnum.Manager) +user_is_administrator = filters.create(lambda _, __, query: get_user_from_config(query.from_user.id).role == UserRolesEnum.Administrator) + +# Categories filters +menu_category_filter = filters.regex(r"^menu_categories$") +add_category_filter = filters.regex(r"^add_category$") +remove_category_filter = filters.regex(r'^remove_category(#.+|$)?$') +modify_category_filter = filters.regex(r'^modify_category(#.+|$)?$') +category_filter = filters.regex(r'^category(#.+|$)?$') +select_category_filter = filters.regex(r'^select_category(#.+|$)?$') + +# Add filters +add_magnet_filter = filters.regex(r'^add_magnet(#.+|$)?$') +add_torrent_filter = filters.regex(r'^add_torrent(#.+|$)?$') + +# Pause/Resume filters +menu_pause_resume_filter = filters.regex(r"^menu_pause_resume$") +pause_all_filter = filters.regex(r"^pause_all$") +resume_all_filter = filters.regex(r"^resume_all$") +pause_filter = filters.regex(r'^pause(#.+|$)?$') +resume_filter = filters.regex(r'^resume(#.+|$)?$') + +# Delete filers +menu_delete_filter = filters.regex(r"^menu_delete$") +delete_one_filter = filters.regex(r'^delete_one(#.+|$)?$') +delete_one_no_data_filter = filters.regex(r'^delete_one_no_data(#.+|$)?$') +delete_one_data_filter = filters.regex(r'^delete_one_data(#.+|$)?$') +delete_all_filter = filters.regex(r'^delete_all(#.+|$)?$') +delete_all_no_data_filter = filters.regex(r"^delete_all_no_data$") +delete_all_data_filter = filters.regex(r"^delete_all_data$") + +# Settings filters +settings_filter = filters.regex(r"^settings$") +get_users_filter = filters.regex(r"^get_users$") +user_info_filter = filters.regex(r'^user_info(#.+|$)?$') +edit_user_filter = filters.regex(r'^edit_user(#.+|$)?$') +toggle_user_var_filter = filters.regex(r'^toggle_user_var(#.+|$)?$') +edit_client_settings_filter = filters.regex(r"^edit_client$") +list_client_settings_filter = filters.regex(r"^lst_client$") +check_connection_filter = filters.regex(r"^check_connection$") +edit_client_setting_filter = filters.regex(r'^edit_clt(#.+|$)?$') +reload_settings_filter = filters.regex(r"^reload_settings$") +toggle_speed_limit_filter = filters.regex(r"^toggle_speed_limit$") + + +# Other +export_filter = filters.regex(r'^export(#.+|$)?$') +torrentInfo_filter = filters.regex(r'^torrentInfo(#.+|$)?$') +menu_filter = filters.regex(r"^menu$") +list_filter = filters.regex(r"^list$") +list_by_status_filter = filters.regex(r'^by_status_list(#.+|$)?$') diff --git a/src/bot/plugins/__init__.py b/src/bot/plugins/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/bot/plugins/callbacks/__init__.py b/src/bot/plugins/callbacks/__init__.py new file mode 100644 index 0000000..eb03b23 --- /dev/null +++ b/src/bot/plugins/callbacks/__init__.py @@ -0,0 +1,8 @@ +from .add_torrents_callbacks import * +from src.bot.plugins.callbacks.category.category_callbacks import * +from src.bot.plugins.callbacks.delete.delete_all_callbacks import * +from src.bot.plugins.callbacks.delete.delete_single_callbacks import * +from .list_callbacks import * +from .pause_resume.pause_callbacks import * +from .pause_resume.resume_callbacks import * +from .torrent_info import * diff --git a/src/bot/plugins/callbacks/add_torrents_callbacks.py b/src/bot/plugins/callbacks/add_torrents_callbacks.py new file mode 100644 index 0000000..2035a55 --- /dev/null +++ b/src/bot/plugins/callbacks/add_torrents_callbacks.py @@ -0,0 +1,16 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery +from .... import db_management +from ... import custom_filters + + +@Client.on_callback_query(custom_filters.add_magnet_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def add_magnet_callback(client: Client, callback_query: CallbackQuery) -> None: + db_management.write_support(f"magnet#{callback_query.data.split('#')[1]}", callback_query.from_user.id) + await client.answer_callback_query(callback_query.id, "Send a magnet link") + + +@Client.on_callback_query(custom_filters.add_torrent_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def add_torrent_callback(client: Client, callback_query: CallbackQuery) -> None: + db_management.write_support(f"torrent#{callback_query.data.split('#')[1]}", callback_query.from_user.id) + await client.answer_callback_query(callback_query.id, "Send a torrent file") diff --git a/src/bot/plugins/callbacks/category/__init__.py b/src/bot/plugins/callbacks/category/__init__.py new file mode 100644 index 0000000..534d78a --- /dev/null +++ b/src/bot/plugins/callbacks/category/__init__.py @@ -0,0 +1,31 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton + +from .... import custom_filters + + +@Client.on_callback_query(custom_filters.menu_category_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def menu_category_callback(client: Client, callback_query: CallbackQuery) -> None: + await callback_query.edit_message_text( + "Pause/Resume a download", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("➕ Add Category", "add_category"), + ], + [ + InlineKeyboardButton("🗑 Remove Category", "select_category#remove_category") + ], + [ + InlineKeyboardButton("📝 Modify Category", "select_category#modify_category")], + [ + InlineKeyboardButton("🔙 Menu", "menu") + ] + ] + ) + ) + + + + + diff --git a/src/bot/plugins/callbacks/category/category_callbacks.py b/src/bot/plugins/callbacks/category/category_callbacks.py new file mode 100644 index 0000000..0ecf5d0 --- /dev/null +++ b/src/bot/plugins/callbacks/category/category_callbacks.py @@ -0,0 +1,98 @@ +from pyrogram import Client +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery +from pyrogram.errors.exceptions import MessageIdInvalid + +from ...callbacks import add_magnet_callback, add_torrent_callback +from ..... import db_management +from .... import custom_filters +from .....client_manager import ClientRepo +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.add_category_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def add_category_callback(client: Client, callback_query: CallbackQuery) -> None: + db_management.write_support("category_name", callback_query.from_user.id) + button = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Menu", "menu")]]) + try: + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + "Send the category name", reply_markup=button) + except MessageIdInvalid: + await client.send_message(callback_query.from_user.id, "Send the category name", reply_markup=button) + + +@Client.on_callback_query(custom_filters.select_category_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def list_categories(client: Client, callback_query: CallbackQuery): + buttons = [] + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + categories = repository.get_categories() + + if categories is None: + buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + "There are no categories", reply_markup=InlineKeyboardMarkup(buttons)) + return + + for key, i in enumerate(categories): + buttons.append([InlineKeyboardButton(i, f"{callback_query.data.split('#')[1]}#{i}")]) + + buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) + + try: + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + "Choose a category:", reply_markup=InlineKeyboardMarkup(buttons)) + except MessageIdInvalid: + await client.send_message(callback_query.from_user.id, "Choose a category:", + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.remove_category_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def remove_category_callback(client: Client, callback_query: CallbackQuery) -> None: + buttons = [[InlineKeyboardButton("🔙 Menu", "menu")]] + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.remove_category(callback_query.data.split("#")[1]) + + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + f"The category {callback_query.data.split('#')[1]} has been removed", + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.modify_category_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def modify_category_callback(client: Client, callback_query: CallbackQuery) -> None: + buttons = [[InlineKeyboardButton("🔙 Menu", "menu")]] + + db_management.write_support(f"category_dir_modify#{callback_query.data.split('#')[1]}", callback_query.from_user.id) + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + f"Send new path for category {callback_query.data.split('#')[1]}", + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.category_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def category(client: Client, callback_query: CallbackQuery) -> None: + buttons = [] + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + categories = repository.get_categories() + + if categories is None: + if "magnet" in callback_query.data: + await add_magnet_callback(client, callback_query) + + else: + await add_torrent_callback(client, callback_query) + + return + + for key, i in enumerate(categories): + buttons.append([InlineKeyboardButton(i, f"{callback_query.data.split('#')[1]}#{i}")]) + + buttons.append([InlineKeyboardButton("None", f"{callback_query.data.split('#')[1]}#None")]) + buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) + + try: + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, + "Choose a category:", reply_markup=InlineKeyboardMarkup(buttons)) + except MessageIdInvalid: + await client.send_message(callback_query.from_user.id, "Choose a category:", + reply_markup=InlineKeyboardMarkup(buttons)) diff --git a/src/bot/plugins/callbacks/delete/__init__.py b/src/bot/plugins/callbacks/delete/__init__.py new file mode 100644 index 0000000..9fb3661 --- /dev/null +++ b/src/bot/plugins/callbacks/delete/__init__.py @@ -0,0 +1,24 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton + +from .... import custom_filters + + +@Client.on_callback_query(custom_filters.menu_delete_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def menu_delete_callback(client: Client, callback_query: CallbackQuery) -> None: + await callback_query.edit_message_text( + "Delete a torrent", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("🗑 Delete", "delete_one") + ], + [ + InlineKeyboardButton("🗑 Delete All", "delete_all") + ], + [ + InlineKeyboardButton("🔙 Menu", "menu") + ] + ] + ) + ) diff --git a/src/bot/plugins/callbacks/delete/delete_all_callbacks.py b/src/bot/plugins/callbacks/delete/delete_all_callbacks.py new file mode 100644 index 0000000..1d7ed41 --- /dev/null +++ b/src/bot/plugins/callbacks/delete/delete_all_callbacks.py @@ -0,0 +1,34 @@ +from pyrogram import Client +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery + +from .... import custom_filters +from .....client_manager import ClientRepo +from ...common import send_menu +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.delete_all_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_all_callback(client: Client, callback_query: CallbackQuery) -> None: + buttons = [[InlineKeyboardButton("🗑 Delete all torrents", "delete_all_no_data")], + [InlineKeyboardButton("🗑 Delete all torrents and data", "delete_all_data")], + [InlineKeyboardButton("🔙 Menu", "menu")]] + await client.edit_message_reply_markup(callback_query.from_user.id, callback_query.message.id, + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.delete_all_no_data_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_all_with_no_data_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.delete_all_no_data() + + await client.answer_callback_query(callback_query.id, "Deleted only torrents") + await send_menu(client, callback_query.message.id, callback_query.from_user.id) + + +@Client.on_callback_query(custom_filters.delete_all_data_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_all_with_data_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.delete_all_data() + + await client.answer_callback_query(callback_query.id, "Deleted All+Torrents") + await send_menu(client, callback_query.message.id, callback_query.from_user.id) diff --git a/src/bot/plugins/callbacks/delete/delete_single_callbacks.py b/src/bot/plugins/callbacks/delete/delete_single_callbacks.py new file mode 100644 index 0000000..f11c2ca --- /dev/null +++ b/src/bot/plugins/callbacks/delete/delete_single_callbacks.py @@ -0,0 +1,47 @@ +from pyrogram import Client +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery + +from .... import custom_filters +from .....client_manager import ClientRepo +from ...common import send_menu, list_active_torrents +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.delete_one_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_callback(client: Client, callback_query: CallbackQuery) -> None: + if callback_query.data.find("#") == -1: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, "delete_one") + + else: + + buttons = [ + [InlineKeyboardButton("🗑 Delete torrent", f"delete_one_no_data#{callback_query.data.split('#')[1]}")], + [InlineKeyboardButton("🗑 Delete torrent and data", f"delete_one_data#{callback_query.data.split('#')[1]}")], + [InlineKeyboardButton("🔙 Menu", "menu")]] + + await client.edit_message_reply_markup(callback_query.from_user.id, callback_query.message.id, + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.delete_one_no_data_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_no_data_callback(client: Client, callback_query: CallbackQuery) -> None: + if callback_query.data.find("#") == -1: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, "delete_one_no_data") + + else: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.delete_one_no_data(torrent_hash=callback_query.data.split("#")[1]) + + await send_menu(client, callback_query.message.id, callback_query.from_user.id) + + +@Client.on_callback_query(custom_filters.delete_one_data_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def delete_with_data_callback(client: Client, callback_query: CallbackQuery) -> None: + if callback_query.data.find("#") == -1: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, "delete_one_data") + + else: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.delete_one_data(torrent_hash=callback_query.data.split("#")[1]) + + await send_menu(client, callback_query.message.id, callback_query.from_user.id) diff --git a/src/bot/plugins/callbacks/list_callbacks.py b/src/bot/plugins/callbacks/list_callbacks.py new file mode 100644 index 0000000..ecdce05 --- /dev/null +++ b/src/bot/plugins/callbacks/list_callbacks.py @@ -0,0 +1,21 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery +from ... import custom_filters +from .... import db_management +from ..common import list_active_torrents, send_menu + + +@Client.on_callback_query(custom_filters.list_filter & custom_filters.check_user_filter) +async def list_callback(client: Client, callback_query: CallbackQuery) -> None: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id) + + +@Client.on_callback_query(custom_filters.list_by_status_filter & custom_filters.check_user_filter) +async def list_by_status_callback(client: Client, callback_query: CallbackQuery) -> None: + status_filter = callback_query.data.split("#")[1] + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, status_filter=status_filter) + + +@Client.on_callback_query(custom_filters.menu_filter & custom_filters.check_user_filter) +async def menu_callback(client: Client, callback_query: CallbackQuery) -> None: + await send_menu(client, callback_query.message.id, callback_query.from_user.id) diff --git a/src/bot/plugins/callbacks/pause_resume/__init__.py b/src/bot/plugins/callbacks/pause_resume/__init__.py new file mode 100644 index 0000000..0ca1890 --- /dev/null +++ b/src/bot/plugins/callbacks/pause_resume/__init__.py @@ -0,0 +1,25 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton +from .... import custom_filters + + +@Client.on_callback_query(custom_filters.menu_pause_resume_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def menu_pause_resume_callback(client: Client, callback_query: CallbackQuery) -> None: + await callback_query.edit_message_text( + "Pause/Resume a torrent", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("⏸ Pause", "pause"), + InlineKeyboardButton("▶️ Resume", "resume") + ], + [ + InlineKeyboardButton("⏸ Pause All", "pause_all"), + InlineKeyboardButton("▶️ Resume All", "resume_all") + ], + [ + InlineKeyboardButton("🔙 Menu", "menu") + ] + ] + ) + ) diff --git a/src/bot/plugins/callbacks/pause_resume/pause_callbacks.py b/src/bot/plugins/callbacks/pause_resume/pause_callbacks.py new file mode 100644 index 0000000..263a26d --- /dev/null +++ b/src/bot/plugins/callbacks/pause_resume/pause_callbacks.py @@ -0,0 +1,25 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery + +from .... import custom_filters +from .....client_manager import ClientRepo +from ...common import list_active_torrents, send_menu +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.pause_all_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def pause_all_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.pause_all() + await client.answer_callback_query(callback_query.id, "Paused all torrents") + + +@Client.on_callback_query(custom_filters.pause_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def pause_callback(client: Client, callback_query: CallbackQuery) -> None: + if callback_query.data.find("#") == -1: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, "pause") + + else: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.pause(torrent_hash=callback_query.data.split("#")[1]) + await callback_query.answer("Torrent Paused") diff --git a/src/bot/plugins/callbacks/pause_resume/resume_callbacks.py b/src/bot/plugins/callbacks/pause_resume/resume_callbacks.py new file mode 100644 index 0000000..8dd1428 --- /dev/null +++ b/src/bot/plugins/callbacks/pause_resume/resume_callbacks.py @@ -0,0 +1,25 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery + +from .... import custom_filters +from .....client_manager import ClientRepo +from ...common import list_active_torrents, send_menu +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.resume_all_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def resume_all_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.resume_all() + await client.answer_callback_query(callback_query.id, "Resumed all torrents") + + +@Client.on_callback_query(custom_filters.resume_filter & custom_filters.check_user_filter & (custom_filters.user_is_administrator | custom_filters.user_is_manager)) +async def resume_callback(client: Client, callback_query: CallbackQuery) -> None: + if callback_query.data.find("#") == -1: + await list_active_torrents(client, callback_query.from_user.id, callback_query.message.id, "resume") + + else: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + repository.resume(torrent_hash=callback_query.data.split("#")[1]) + await callback_query.answer("Torrent Resumed") diff --git a/src/bot/plugins/callbacks/settings/__init__.py b/src/bot/plugins/callbacks/settings/__init__.py new file mode 100644 index 0000000..b021c8c --- /dev/null +++ b/src/bot/plugins/callbacks/settings/__init__.py @@ -0,0 +1,29 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton +from .... import custom_filters + + +@Client.on_callback_query(custom_filters.settings_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def settings_callback(client: Client, callback_query: CallbackQuery) -> None: + await callback_query.edit_message_text( + "QBittorrentBot Settings", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("🫂 Users Settings", "get_users") + ], + [ + InlineKeyboardButton("📥 Client Settings", "edit_client") + ], + [ + InlineKeyboardButton("🇮🇹 Language Settings", "menu") + ], + [ + InlineKeyboardButton("🔄 Reload Settings", "reload_settings") + ], + [ + InlineKeyboardButton("🔙 Menu", "menu") + ] + ] + ) + ) diff --git a/src/bot/plugins/callbacks/settings/client_settings_callbacks.py b/src/bot/plugins/callbacks/settings/client_settings_callbacks.py new file mode 100644 index 0000000..0c119b9 --- /dev/null +++ b/src/bot/plugins/callbacks/settings/client_settings_callbacks.py @@ -0,0 +1,121 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton + +from .... import custom_filters +from .....configs import Configs +from .....client_manager import ClientRepo +from .....utils import convert_type_from_string +from .....db_management import write_support + + +@Client.on_callback_query(custom_filters.edit_client_settings_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def edit_client_settings_callback(client: Client, callback_query: CallbackQuery) -> None: + confs = '\n- '.join(iter([f"**{key.capitalize()}:** {item}" for key, item in Configs.config.client.model_dump().items()])) + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + speed_limit = repository.get_speed_limit_mode() + + confs += f"\n\n**Speed Limit**: {'Enabled' if speed_limit else 'Disabled'}" + + await callback_query.edit_message_text( + f"Edit Qbittorrent Client Settings \n\n**Current Settings:**\n- {confs}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("📝 Edit Client Settings", "lst_client") + ], + [ + InlineKeyboardButton("🐢 Toggle Speed Limit", "toggle_speed_limit") + ], + [ + InlineKeyboardButton("✅ Check Client connection", "check_connection") + ], + [ + InlineKeyboardButton("🔙 Settings", "settings") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.toggle_speed_limit_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def toggle_speed_limit_callback(client: Client, callback_query: CallbackQuery) -> None: + confs = '\n- '.join(iter([f"**{key.capitalize()}:** {item}" for key, item in Configs.config.client.model_dump().items()])) + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + speed_limit = repository.toggle_speed_limit() + + confs += f"\n\n**Speed Limit**: {'Enabled' if speed_limit else 'Disabled'}" + + await callback_query.edit_message_text( + f"Edit Qbittorrent Client Settings \n\n**Current Settings:**\n- {confs}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("📝 Edit Client Settings", "lst_client") + ], + [ + InlineKeyboardButton("🐢 Toggle Speed Limit", "toggle_speed_limit") + ], + [ + InlineKeyboardButton("✅ Check Client connection", "check_connection") + ], + [ + InlineKeyboardButton("🔙 Settings", "settings") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.check_connection_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def check_connection_callback(client: Client, callback_query: CallbackQuery) -> None: + try: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + version = repository.check_connection() + + await callback_query.answer(f"✅ The connection works. QBittorrent version: {version}", show_alert=True) + except Exception: + await callback_query.answer("❌ Unable to establish connection with QBittorrent", show_alert=True) + + +@Client.on_callback_query(custom_filters.list_client_settings_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def list_client_settings_callback(client: Client, callback_query: CallbackQuery) -> None: + # get all fields of the model dynamically + fields = [ + [InlineKeyboardButton(f"Edit {key.replace('_', ' ').capitalize()}", + f"edit_clt#{key}-{item.annotation}")] + for key, item in Configs.config.client.model_fields.items() + ] + + await callback_query.edit_message_text( + f"Edit Qbittorrent Client", + reply_markup=InlineKeyboardMarkup( + fields + + [ + [ + InlineKeyboardButton("🔙 Settings", "settings") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.edit_client_setting_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def edit_client_setting_callback(client: Client, callback_query: CallbackQuery) -> None: + data = callback_query.data.split("#")[1] + field_to_edit = data.split("-")[0] + data_type = convert_type_from_string(data.split("-")[1]) + + write_support(callback_query.data, callback_query.from_user.id) + + await callback_query.edit_message_text( + f"Send the new value for field \"{field_to_edit}\" for client. \n\n**Note:** the field type is \"{data_type}\"", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("🔙 Settings", "settings") + ] + ] + ) + ) diff --git a/src/bot/plugins/callbacks/settings/reload_settings_callbacks.py b/src/bot/plugins/callbacks/settings/reload_settings_callbacks.py new file mode 100644 index 0000000..292cc8d --- /dev/null +++ b/src/bot/plugins/callbacks/settings/reload_settings_callbacks.py @@ -0,0 +1,12 @@ +from pyrogram import Client +from pyrogram.types import CallbackQuery + +from .... import custom_filters +from .....configs import Configs + + +@Client.on_callback_query(custom_filters.reload_settings_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def reload_settings_callback(client: Client, callback_query: CallbackQuery) -> None: + # TO FIX reload + Configs.reload_config() + await callback_query.answer("Settings Reloaded", show_alert=True) diff --git a/src/bot/plugins/callbacks/settings/users_settings_callbacks.py b/src/bot/plugins/callbacks/settings/users_settings_callbacks.py new file mode 100644 index 0000000..168ab63 --- /dev/null +++ b/src/bot/plugins/callbacks/settings/users_settings_callbacks.py @@ -0,0 +1,133 @@ +import typing + +from pyrogram import Client +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton + +from .... import custom_filters +from .....configs import Configs +from .....db_management import write_support +from .....utils import get_user_from_config + + +@Client.on_callback_query(custom_filters.get_users_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def get_users_callback(client: Client, callback_query: CallbackQuery) -> None: + users = [ + [InlineKeyboardButton(f"User #{i.user_id}", f"user_info#{i.user_id}")] + for i in Configs.config.users + ] + + await callback_query.edit_message_text( + "Authorized users", + reply_markup=InlineKeyboardMarkup( + users + + [ + [ + InlineKeyboardButton("🔙 Settings", "settings") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.user_info_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def get_user_info_callback(client: Client, callback_query: CallbackQuery) -> None: + user_id = int(callback_query.data.split("#")[1]) + + user_info = get_user_from_config(user_id) + + write_support("None", callback_query.from_user.id) + + # get all fields of the model dynamically + fields = [ + [InlineKeyboardButton(f"Edit {key.replace('_', ' ').capitalize()}", + f"edit_user#{user_id}-{key}-{item.annotation}")] + for key, item in user_info.model_fields.items() + ] + + confs = '\n- '.join(iter([f"**{key.capitalize()}:** {item}" for key, item in user_info.model_dump().items()])) + + await callback_query.edit_message_text( + f"Edit User #{user_id}\n\n**Current Settings:**\n- {confs}", + reply_markup=InlineKeyboardMarkup( + fields + + [ + [ + InlineKeyboardButton(f"🔙 Users", f"get_users") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.edit_user_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def edit_user_callback(client: Client, callback_query: CallbackQuery) -> None: + data = callback_query.data.split("#")[1] + user_id = int(data.split("-")[0]) + field_to_edit = data.split("-")[1] + data_type = eval(data.split("-")[2].replace("", "")) + + user_info = get_user_from_config(user_id) + + if data_type == bool or data_type == typing.Optional[bool]: + await callback_query.edit_message_text( + f"Edit User #{user_id} {field_to_edit} Field", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + f"{'✅' if user_info.notify else '❌'} Toggle", + f"toggle_user_var#{user_id}-{field_to_edit}") + ], + [ + InlineKeyboardButton(f"🔙 User#{user_id} info", f"user_info#{user_id}") + ] + ] + ) + ) + + return + + write_support(callback_query.data, callback_query.from_user.id) + + await callback_query.edit_message_text( + f"Send the new value for field \"{field_to_edit}\" for user #{user_id}. \n\n**Note:** the field type is \"{data_type}\"", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(f"🔙 User#{user_id} info", f"user_info#{user_id}") + ] + ] + ) + ) + + +@Client.on_callback_query(custom_filters.toggle_user_var_filter & custom_filters.check_user_filter & custom_filters.user_is_administrator) +async def toggle_user_var(client: Client, callback_query: CallbackQuery) -> None: + data = callback_query.data.split("#")[1] + user_id = int(data.split("-")[0]) + field_to_edit = data.split("-")[1] + + user_info = get_user_from_config(user_id) + user_from_configs = Configs.config.users.index(user_info) + + if user_from_configs == -1: + return + + Configs.config.users[user_from_configs].notify = not Configs.config.users[user_from_configs].notify + Configs.update_config(Configs.config) + + await callback_query.edit_message_text( + f"Edit User #{user_id} {field_to_edit} Field", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + f"{'✅' if Configs.config.users[user_from_configs].notify else '❌'} Toggle", + f"toggle_user_var#{user_id}-{field_to_edit}") + ], + [ + InlineKeyboardButton(f"🔙 User#{user_id} info", f"user_info#{user_id}") + ] + ] + ) + ) diff --git a/src/bot/plugins/callbacks/torrent_info.py b/src/bot/plugins/callbacks/torrent_info.py new file mode 100644 index 0000000..79a7821 --- /dev/null +++ b/src/bot/plugins/callbacks/torrent_info.py @@ -0,0 +1,67 @@ +from tqdm import tqdm + +from pyrogram import Client +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery + +from ... import custom_filters +from ....client_manager import ClientRepo +from ....configs import Configs +from ....utils import convert_size, convert_eta + + +@Client.on_callback_query(custom_filters.torrentInfo_filter & custom_filters.check_user_filter) +async def torrent_info_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + torrent = repository.get_torrent_info(callback_query.data.split("#")[1]) + + text = f"{torrent.name}\n" + + if torrent.progress == 1: + text += "**COMPLETED**\n" + + else: + text += f"{tqdm.format_meter(torrent.progress, 1, 0, bar_format='{l_bar}{bar}|')}\n" + + if "stalled" not in torrent.state: + text += (f"**State:** {torrent.state.capitalize()} \n" + f"**Download Speed:** {convert_size(torrent.dlspeed)}/s\n") + + text += f"**Size:** {convert_size(torrent.size)}\n" + + if "stalled" not in torrent.state: + text += f"**ETA:** {convert_eta(int(torrent.eta))}\n" + + if torrent.category: + text += f"**Category:** {torrent.category}\n" + + buttons = [ + [ + InlineKeyboardButton("💾 Export torrent", f"export#{callback_query.data.split('#')[1]}") + ], + [ + InlineKeyboardButton("⏸ Pause", f"pause#{callback_query.data.split('#')[1]}") + ], + [ + InlineKeyboardButton("▶️ Resume", f"resume#{callback_query.data.split('#')[1]}") + ], + [ + InlineKeyboardButton("🗑 Delete", f"delete_one#{callback_query.data.split('#')[1]}") + ], + [ + InlineKeyboardButton("🔙 Menu", "menu") + ] + ] + + await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, text=text, + reply_markup=InlineKeyboardMarkup(buttons)) + + +@Client.on_callback_query(custom_filters.export_filter & custom_filters.check_user_filter) +async def export_callback(client: Client, callback_query: CallbackQuery) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + file_bytes = repository.export_torrent(torrent_hash=callback_query.data.split("#")[1]) + + await client.send_document( + callback_query.from_user.id, + file_bytes + ) diff --git a/src/bot/plugins/commands.py b/src/bot/plugins/commands.py new file mode 100644 index 0000000..13ace3c --- /dev/null +++ b/src/bot/plugins/commands.py @@ -0,0 +1,36 @@ +from pyrogram import Client, filters +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message +import psutil + +from .. import custom_filters +from ...db_management import write_support +from ...utils import convert_size +from ...configs import Configs +from .common import send_menu + + +@Client.on_message(~custom_filters.check_user_filter) +async def access_denied_message(client: Client, message: Message) -> None: + button = InlineKeyboardMarkup([[InlineKeyboardButton("Github", + url="https://github.com/ch3p4ll3/QBittorrentBot/")]]) + await client.send_message(message.chat.id, "You are not authorized to use this bot", reply_markup=button) + + +@Client.on_message(filters.command("start") & custom_filters.check_user_filter) +async def start_command(client: Client, message: Message) -> None: + """Start the bot.""" + write_support("None", message.chat.id) + await send_menu(client, message.id, message.chat.id) + + +@Client.on_message(filters.command("stats") & custom_filters.check_user_filter) +async def stats_command(client: Client, message: Message) -> None: + stats_text = f"**============SYSTEM============**\n" \ + f"**CPU Usage:** {psutil.cpu_percent(interval=None)}%\n" \ + f"**CPU Temp:** {psutil.sensors_temperatures()['coretemp'][0].current}°C\n" \ + f"**Free Memory:** {convert_size(psutil.virtual_memory().available)} of " \ + f"{convert_size(psutil.virtual_memory().total)} ({psutil.virtual_memory().percent}%)\n" \ + f"**Disks usage:** {convert_size(psutil.disk_usage('/mnt').used)} of " \ + f"{convert_size(psutil.disk_usage('/mnt').total)} ({psutil.disk_usage('/mnt').percent}%)" + + await client.send_message(message.chat.id, stats_text) diff --git a/src/bot/plugins/common.py b/src/bot/plugins/common.py new file mode 100644 index 0000000..80ea3b8 --- /dev/null +++ b/src/bot/plugins/common.py @@ -0,0 +1,89 @@ +from pyrogram import Client +from pyrogram.errors.exceptions import MessageIdInvalid +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup + +from typing import Optional + +from ... import db_management +from ...configs import Configs +from ...client_manager import ClientRepo +from ...utils import get_user_from_config +from ...configs.enums import UserRolesEnum + + +async def send_menu(client: Client, message_id: int, chat_id: int) -> None: + user = get_user_from_config(chat_id) + buttons = [ + [InlineKeyboardButton("📝 List", "list")] + ] + + if user.role in [UserRolesEnum.Manager, UserRolesEnum.Administrator]: + buttons += [ + [InlineKeyboardButton("➕ Add Magnet", "category#add_magnet"), + InlineKeyboardButton("➕ Add Torrent", "category#add_torrent")], + [InlineKeyboardButton("⏯ Pause/Resume", "menu_pause_resume")] + ] + + if user.role == UserRolesEnum.Administrator: + buttons += [ + [InlineKeyboardButton("🗑 Delete", "menu_delete")], + [InlineKeyboardButton("📂 Categories", "menu_categories")], + [InlineKeyboardButton("⚙️ Settings", "settings")] + ] + + db_management.write_support("None", chat_id) + + try: + await client.edit_message_text(chat_id, message_id, text="Qbittorrent Control", + reply_markup=InlineKeyboardMarkup(buttons)) + + except MessageIdInvalid: + await client.send_message(chat_id, text="Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) + + +async def list_active_torrents(client: Client, chat_id, message_id, callback: Optional[str] = None, status_filter: str = None) -> None: + repository = ClientRepo.get_client_manager(Configs.config.client.type) + torrents = repository.get_torrent_info(status_filter=status_filter) + + def render_categories_buttons(): + return [ + InlineKeyboardButton(f"⏳ {'*' if status_filter == 'downloading' else ''} Downloading", + "by_status_list#downloading"), + InlineKeyboardButton(f"✔️ {'*' if status_filter == 'completed' else ''} Completed", + "by_status_list#completed"), + InlineKeyboardButton(f"⏸️ {'*' if status_filter == 'paused' else ''} Paused", "by_status_list#paused"), + ] + + categories_buttons = render_categories_buttons() + if not torrents: + buttons = [categories_buttons, [InlineKeyboardButton("🔙 Menu", "menu")]] + try: + await client.edit_message_text(chat_id, message_id, "There are no torrents", + reply_markup=InlineKeyboardMarkup(buttons)) + except MessageIdInvalid: + await client.send_message(chat_id, "There are no torrents", reply_markup=InlineKeyboardMarkup(buttons)) + return + + buttons = [categories_buttons] + + if callback is not None: + for key, i in enumerate(torrents): + buttons.append([InlineKeyboardButton(i.name, f"{callback}#{i.info.hash}")]) + + buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) + + try: + await client.edit_message_reply_markup(chat_id, message_id, reply_markup=InlineKeyboardMarkup(buttons)) + except MessageIdInvalid: + await client.send_message(chat_id, "Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) + + else: + for key, i in enumerate(torrents): + buttons.append([InlineKeyboardButton(i.name, f"torrentInfo#{i.info.hash}")]) + + buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) + + try: + await client.edit_message_reply_markup(chat_id, message_id, reply_markup=InlineKeyboardMarkup(buttons)) + except MessageIdInvalid: + await client.send_message(chat_id, "Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) diff --git a/src/bot/plugins/on_message.py b/src/bot/plugins/on_message.py new file mode 100644 index 0000000..37e045f --- /dev/null +++ b/src/bot/plugins/on_message.py @@ -0,0 +1,134 @@ +import logging +import os +import tempfile +from pyrogram import Client, filters +from pyrogram.types import Message +from ...client_manager import ClientRepo +from ... import db_management +from .common import send_menu +from ...configs import Configs +from ...utils import get_user_from_config, convert_type_from_string +from .. import custom_filters + + +logger = logging.getLogger(__name__) + + +@Client.on_message(~filters.me & custom_filters.check_user_filter) +async def on_text(client: Client, message: Message) -> None: + action = db_management.read_support(message.from_user.id) + + if "magnet" in action: + if message.text.startswith("magnet:?xt"): + magnet_link = message.text.split("\n") + category = db_management.read_support(message.from_user.id).split("#")[1] + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + response = repository.add_magnet( + magnet_link=magnet_link, + category=category + ) + + if not response: + await message.reply_text("Unable to add magnet link") + return + + await send_menu(client, message.id, message.from_user.id) + db_management.write_support("None", message.from_user.id) + + else: + await client.send_message(message.from_user.id, "This magnet link is invalid! Retry") + + elif "torrent" in action and message.document: + if ".torrent" in message.document.file_name: + with tempfile.TemporaryDirectory() as tempdir: + name = f"{tempdir}/{message.document.file_name}" + category = db_management.read_support(message.from_user.id).split("#")[1] + await message.download(name) + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + response = repository.add_torrent(file_name=name, category=category) + + if not response: + await message.reply_text("Unable to add magnet link") + return + + await send_menu(client, message.id, message.from_user.id) + db_management.write_support("None", message.from_user.id) + + else: + await client.send_message(message.from_user.id, "This is not a torrent file! Retry") + + elif action == "category_name": + db_management.write_support(f"category_dir#{message.text}", message.from_user.id) + await client.send_message(message.from_user.id, f"now send me the path for the category {message.text}") + + elif "category_dir" in action: + if os.path.exists(message.text): + name = db_management.read_support(message.from_user.id).split("#")[1] + + repository = ClientRepo.get_client_manager(Configs.config.client.type) + + if "modify" in action: + repository.edit_category(name=name, save_path=message.text) + + await send_menu(client, message.id, message.from_user.id) + return + + repository.create_category(name=name, save_path=message.text) + + await send_menu(client, message.id, message.from_user.id) + + else: + await client.send_message(message.from_user.id, "The path entered does not exist! Retry") + + elif "edit_user" in action: + data = action.split("#")[1] + user_id = int(data.split("-")[0]) + field_to_edit = data.split("-")[1] + data_type = convert_type_from_string(data.split("-")[2].replace("", "")) + + try: + new_value = data_type(message.text) + + user_info = get_user_from_config(user_id) + user_from_configs = Configs.config.users.index(user_info) + + if user_from_configs == -1: + return + + setattr(Configs.config.users[user_from_configs], field_to_edit, new_value) + Configs.update_config(Configs.config) + Configs.reload_config() + logger.debug(f"Updating User #{user_id} {field_to_edit} settings to {new_value}") + db_management.write_support("None", message.from_user.id) + + await send_menu(client, message.id, message.from_user.id) + except Exception as e: + await message.reply_text( + f"Error: {e}" + ) + logger.exception(f"Error converting value \"{message.text}\" to type \"{data_type}\"", exc_info=True) + + elif "edit_clt" in action: + data = action.split("#")[1] + field_to_edit = data.split("-")[0] + data_type = convert_type_from_string(data.split("-")[1]) + + try: + new_value = data_type(message.text) + + setattr(Configs.config.client, field_to_edit, new_value) + Configs.update_config(Configs.config) + Configs.reload_config() + logger.debug(f"Updating Client field \"{field_to_edit}\" to \"{new_value}\"") + db_management.write_support("None", message.from_user.id) + + await send_menu(client, message.id, message.from_user.id) + except Exception as e: + await message.reply_text( + f"Error: {e}" + ) + logger.exception(f"Error converting value \"{message.text}\" to type \"{data_type}\"", exc_info=True) + else: + await client.send_message(message.from_user.id, "The command does not exist") diff --git a/src/client_manager/__init__.py b/src/client_manager/__init__.py new file mode 100644 index 0000000..ed8a16e --- /dev/null +++ b/src/client_manager/__init__.py @@ -0,0 +1 @@ +from .client_repo import ClientRepo diff --git a/src/client_manager/client_manager.py b/src/client_manager/client_manager.py new file mode 100644 index 0000000..be5633d --- /dev/null +++ b/src/client_manager/client_manager.py @@ -0,0 +1,100 @@ +from io import BytesIO +from typing import Union, List +from abc import ABC + + +class ClientManager(ABC): + @classmethod + def add_magnet(cls, magnet_link: Union[str, List[str]], category: str = None) -> bool: + """Add one or multiple magnet links with or without a category, return true if successful""" + raise NotImplementedError + + @classmethod + def add_torrent(cls, file_name: str, category: str = None) -> bool: + """Add one torrent file with or without a category, return true if successful""" + raise NotImplementedError + + @classmethod + def resume_all(cls) -> None: + """Resume all torrents""" + raise NotImplementedError + + @classmethod + def pause_all(cls) -> None: + """Pause all torrents""" + raise NotImplementedError + + @classmethod + def resume(cls, torrent_hash: str) -> None: + """Resume a specific torrent""" + raise NotImplementedError + + @classmethod + def pause(cls, torrent_hash: str) -> None: + """Pause a specific torrent""" + raise NotImplementedError + + @classmethod + def delete_one_no_data(cls, torrent_hash: str) -> None: + """Delete a specific torrent without deleting the data""" + raise NotImplementedError + + @classmethod + def delete_one_data(cls, torrent_hash: str) -> None: + """Delete a specific torrent deleting the data""" + raise NotImplementedError + + @classmethod + def delete_all_no_data(cls) -> None: + """Delete all torrents without deleting the data""" + raise NotImplementedError + + @classmethod + def delete_all_data(cls) -> None: + """Delete all torrents deleting the data""" + raise NotImplementedError + + @classmethod + def get_categories(cls): + """Get categories""" + raise NotImplementedError + + @classmethod + def get_torrent_info(cls, torrent_hash: str = None, status_filter: str = None): + """Get a torrent info with or without a status filter""" + raise NotImplementedError + + @classmethod + def edit_category(cls, name: str, save_path: str) -> None: + """Edit a category save path""" + raise NotImplementedError + + @classmethod + def create_category(cls, name: str, save_path: str) -> None: + """Create a new category""" + raise NotImplementedError + + @classmethod + def remove_category(cls, name: str) -> None: + """Delete a category""" + raise NotImplementedError + + @classmethod + def check_connection(cls) -> str: + """Check connection with Client""" + raise NotImplementedError + + @classmethod + def export_torrent(cls, torrent_hash: str) -> BytesIO: + """Export a .torrent file for the torrent.""" + raise NotImplementedError + + @classmethod + def get_speed_limit_mode(cls) -> bool: + """Get speed limit of the client, returns True if speed limit is active""" + raise NotImplementedError + + @classmethod + def toggle_speed_limit(cls) -> bool: + """Toggle speed limit of the client, returns True if speed limit is active""" + raise NotImplementedError diff --git a/src/client_manager/client_repo.py b/src/client_manager/client_repo.py new file mode 100644 index 0000000..e0d8596 --- /dev/null +++ b/src/client_manager/client_repo.py @@ -0,0 +1,12 @@ +from ..configs.enums import ClientTypeEnum +from .qbittorrent_manager import QbittorrentManager, ClientManager + + +class ClientRepo: + repositories = { + ClientTypeEnum.QBittorrent: QbittorrentManager + } + + @classmethod + def get_client_manager(cls, client_type: ClientTypeEnum): + return cls.repositories.get(client_type, ClientManager) diff --git a/src/client_manager/qbittorrent_manager.py b/src/client_manager/qbittorrent_manager.py new file mode 100644 index 0000000..fe26d45 --- /dev/null +++ b/src/client_manager/qbittorrent_manager.py @@ -0,0 +1,168 @@ +from io import BytesIO + +import qbittorrentapi +import logging +from src.configs import Configs +from typing import Union, List +from .client_manager import ClientManager + +logger = logging.getLogger(__name__) + + +class QbittorrentManager(ClientManager): + @classmethod + def add_magnet(cls, magnet_link: Union[str, List[str]], category: str = None) -> bool: + if category == "None": + category = None + + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + logger.debug(f"Adding magnet with category {category}") + result = qbt_client.torrents_add(urls=magnet_link, category=category) + + return result == "Ok." + + @classmethod + def add_torrent(cls, file_name: str, category: str = None) -> bool: + if category == "None": + category = None + + try: + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + logger.debug(f"Adding torrent with category {category}") + result = qbt_client.torrents_add(torrent_files=file_name, category=category) + return result == "Ok." + + except qbittorrentapi.exceptions.UnsupportedMediaType415Error: + pass + + @classmethod + def resume_all(cls) -> None: + logger.debug("Resuming all torrents") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents.resume.all() + + @classmethod + def pause_all(cls) -> None: + logger.debug("Pausing all torrents") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents.pause.all() + + @classmethod + def resume(cls, torrent_hash: str) -> None: + logger.debug(f"Resuming torrent with has {torrent_hash}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_resume(torrent_hashes=torrent_hash) + + @classmethod + def pause(cls, torrent_hash: str) -> None: + logger.debug(f"Pausing torrent with hash {torrent_hash}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_pause(torrent_hashes=torrent_hash) + + @classmethod + def delete_one_no_data(cls, torrent_hash: str) -> None: + logger.debug(f"Deleting torrent with hash {torrent_hash} without removing files") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_delete( + delete_files=False, + torrent_hashes=torrent_hash + ) + + @classmethod + def delete_one_data(cls, torrent_hash: str) -> None: + logger.debug(f"Deleting torrent with hash {torrent_hash} + removing files") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_delete( + delete_files=True, + torrent_hashes=torrent_hash + ) + + @classmethod + def delete_all_no_data(cls) -> None: + logger.debug(f"Deleting all torrents") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + for i in qbt_client.torrents_info(): + qbt_client.torrents_delete(delete_files=False, hashes=i.hash) + + @classmethod + def delete_all_data(cls) -> None: + logger.debug(f"Deleting all torrent + files") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + for i in qbt_client.torrents_info(): + qbt_client.torrents_delete(delete_files=True, hashes=i.hash) + + @classmethod + def get_categories(cls): + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + categories = qbt_client.torrent_categories.categories + if len(categories) > 0: + return categories + + else: + return + + @classmethod + def get_torrent_info(cls, torrent_hash: str = None, status_filter: str = None): + if torrent_hash is None: + logger.debug("Getting torrents infos") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + return qbt_client.torrents_info(status_filter=status_filter) + logger.debug(f"Getting infos for torrent with hash {torrent_hash}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + return next( + iter( + qbt_client.torrents_info(status_filter=status_filter, torrent_hashes=torrent_hash) + ), None + ) + + @classmethod + def edit_category(cls, name: str, save_path: str) -> None: + logger.debug(f"Editing category {name}, new save path: {save_path}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_edit_category( + name=name, + save_path=save_path + ) + + @classmethod + def create_category(cls, name: str, save_path: str) -> None: + logger.debug(f"Creating new category {name} with save path: {save_path}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_create_category( + name=name, + save_path=save_path + ) + + @classmethod + def remove_category(cls, name: str) -> None: + logger.debug(f"Removing category {name}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.torrents_remove_categories(categories=name) + + @classmethod + def check_connection(cls) -> str: + logger.debug("Checking Qbt Connection") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + return qbt_client.app.version + + @classmethod + def export_torrent(cls, torrent_hash: str) -> BytesIO: + logger.debug(f"Exporting torrent with hash {torrent_hash}") + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + torrent_bytes = qbt_client.torrents_export(torrent_hash=torrent_hash) + torrent_name = qbt_client.torrents_info(torrent_hashes=torrent_hash)[0].name + + file_to_return = BytesIO(torrent_bytes) + file_to_return.name = f"{torrent_name}.torrent" + return file_to_return + + @classmethod + def get_speed_limit_mode(cls) -> bool: + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + return qbt_client.transfer.speedLimitsMode == "1" + + @classmethod + def toggle_speed_limit(cls) -> bool: + with qbittorrentapi.Client(**Configs.config.client.connection_string) as qbt_client: + qbt_client.transfer.setSpeedLimitsMode() + return qbt_client.transfer.speedLimitsMode == "1" diff --git a/src/config.py b/src/config.py deleted file mode 100644 index cfa4b06..0000000 --- a/src/config.py +++ /dev/null @@ -1,63 +0,0 @@ -import ipaddress -from pydantic import BaseModel, field_validator -from typing import Optional -import json -from os import getenv - - -class Qbittorrent(BaseModel): - ip: ipaddress.IPv4Network - port: int - user: str - password: str - - @field_validator('port') - def port_validator(cls, v): - if v <= 0: - raise ValueError('Port must be >= 0') - return v - - @field_validator('user') - def user_validator(cls, v): - if not v or not v.strip(): - raise ValueError('User cannot be empty') - return v - - @field_validator('password') - def password_validator(cls, v): - if not v or not v.strip(): - raise ValueError('Password cannot be empty') - return v - - -class Telegram(BaseModel): - bot_token: str - api_id: int - api_hash: str - - @field_validator('bot_token') - def bot_token_validator(cls, v): - if not v or not v.strip(): - raise ValueError('Bot token cannot be empty') - return v - - @field_validator('api_hash') - def api_hash_validator(cls, v): - if not v or not v.strip(): - raise ValueError('API HASH cannot be empty') - return v - - -class Users(BaseModel): - user_id: int - notify: Optional[bool] = True - - -class Main(BaseModel): - qbittorrent: Qbittorrent - telegram: Telegram - users: list[Users] - - -with open(f'{ "/app/config/" if getenv("IS_DOCKER", False) else "./"}config.json', 'r') as config_json: - BOT_CONFIGS = Main(**(json.load(config_json))) diff --git a/src/configs/__init__.py b/src/configs/__init__.py new file mode 100644 index 0000000..a24d648 --- /dev/null +++ b/src/configs/__init__.py @@ -0,0 +1,36 @@ +from .config import MainConfig +from os import getenv +from json import load, dumps +from typing import Union + + +config_path = f'{ "/app/config/" if getenv("IS_DOCKER", False) else "./"}config.json' + + +def load_config() -> Union[MainConfig, None, int]: + with open(config_path, 'r') as config_json: + configs = MainConfig(**(load(config_json))) + + return configs + + +class Configs: + config_path = config_path + log_folder = "/app/config/logs" if getenv("IS_DOCKER", False) else "./logs" + config = load_config() + + @classmethod + def reload_config(cls) -> Union[MainConfig, None, int]: + with open(cls.config_path, 'r') as config_json: + cls.config = MainConfig(**(load(config_json))) + + return cls.config + + @classmethod + def update_config(cls, edited_config: MainConfig) -> Union[MainConfig, None]: + # TODO: update config from bot + with open(cls.config_path, "w") as json_file: + json_file.write( + edited_config.model_dump_json(indent=4) + ) + return edited_config diff --git a/src/configs/client.py b/src/configs/client.py new file mode 100644 index 0000000..2d07ecd --- /dev/null +++ b/src/configs/client.py @@ -0,0 +1,45 @@ +from pydantic import BaseModel, field_validator, IPvAnyAddress +from .enums import ClientTypeEnum + + +class Client(BaseModel): + type: ClientTypeEnum = ClientTypeEnum.QBittorrent + host: IPvAnyAddress + port: int + user: str + password: str + + @field_validator('port') + def port_validator(cls, v): + if v <= 0: + raise ValueError('Port must be >= 0') + return v + + @field_validator('user') + def user_validator(cls, v): + if not v or not v.strip(): + raise ValueError('User cannot be empty') + return v + + @field_validator('password') + def password_validator(cls, v): + if not v or not v.strip(): + raise ValueError('Password cannot be empty') + return v + + @property + def parsed_host(self) -> str: + return f"http://{self.host}" + + @property + def full_host_string(self) -> str: + return f"{self.parsed_host}:{self.port}" + + @property + def connection_string(self) -> dict: + if self.type is ClientTypeEnum.QBittorrent: + return dict( + host=self.full_host_string, + username=self.user, + password=self.password + ) diff --git a/src/configs/config.py b/src/configs/config.py new file mode 100644 index 0000000..9e28a47 --- /dev/null +++ b/src/configs/config.py @@ -0,0 +1,11 @@ +from pydantic import BaseModel + +from .client import Client +from .user import User +from .telegram import Telegram + + +class MainConfig(BaseModel): + client: Client + telegram: Telegram + users: list[User] diff --git a/src/configs/enums.py b/src/configs/enums.py new file mode 100644 index 0000000..3c58caf --- /dev/null +++ b/src/configs/enums.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class ClientTypeEnum(str, Enum): + QBittorrent = 'qbittorrent' + + +class UserRolesEnum(str, Enum): + Reader = "reader" + Manager = "manager" + Administrator = "administrator" diff --git a/src/configs/telegram.py b/src/configs/telegram.py new file mode 100644 index 0000000..64ff2de --- /dev/null +++ b/src/configs/telegram.py @@ -0,0 +1,19 @@ +from pydantic import BaseModel, field_validator + + +class Telegram(BaseModel): + bot_token: str + api_id: int + api_hash: str + + @field_validator('bot_token') + def bot_token_validator(cls, v): + if not v or not v.strip(): + raise ValueError('Bot token cannot be empty') + return v + + @field_validator('api_hash') + def api_hash_validator(cls, v): + if not v or not v.strip(): + raise ValueError('API HASH cannot be empty') + return v diff --git a/src/configs/user.py b/src/configs/user.py new file mode 100644 index 0000000..a7d45d3 --- /dev/null +++ b/src/configs/user.py @@ -0,0 +1,10 @@ +from pydantic import BaseModel +from typing import Optional + +from src.configs.enums import UserRolesEnum + + +class User(BaseModel): + user_id: int + role: UserRolesEnum = UserRolesEnum.Reader + notify: Optional[bool] = True diff --git a/src/custom_filters.py b/src/custom_filters.py deleted file mode 100644 index 93db12e..0000000 --- a/src/custom_filters.py +++ /dev/null @@ -1,23 +0,0 @@ -from pyrogram import filters - -add_category_filter = filters.create(lambda _, __, query: query.data == "add_category") -remove_category_filter = filters.create(lambda _, __, query: query.data.startswith("remove_category")) -modify_category_filter = filters.create(lambda _, __, query: query.data.startswith("modify_category")) -category_filter = filters.create(lambda _, __, query: query.data.startswith("category")) -menu_filter = filters.create(lambda _, __, query: query.data.startswith("menu")) -list_filter = filters.create(lambda _, __, query: query.data.startswith("list")) -list_by_status_filter = filters.create(lambda _, __, query: query.data.split("#")[0] == "by_status_list") -add_magnet_filter = filters.create(lambda _, __, query: query.data.startswith("add_magnet")) -add_torrent_filter = filters.create(lambda _, __, query: query.data.startswith("add_torrent")) -pause_all_filter = filters.create(lambda _, __, query: query.data.startswith("pause_all")) -resume_all_filter = filters.create(lambda _, __, query: query.data.startswith("resume_all")) -pause_filter = filters.create(lambda _, __, query: query.data.startswith("pause")) -resume_filter = filters.create(lambda _, __, query: query.data.startswith("resume")) -delete_one_filter = filters.create(lambda _, __, query: query.data.split("#")[0] == "delete_one") -delete_one_no_data_filter = filters.create(lambda _, __, query: query.data.startswith("delete_one_no_data")) -delete_one_data_filter = filters.create(lambda _, __, query: query.data.startswith("delete_one_data")) -delete_all_filter = filters.create(lambda _, __, query: query.data.split("#")[0] == "delete_all") -delete_all_no_data_filter = filters.create(lambda _, __, query: query.data.startswith("delete_all_no_data")) -delete_all_data_filter = filters.create(lambda _, __, query: query.data.startswith("delete_all_data")) -torrentInfo_filter = filters.create(lambda _, __, query: query.data.startswith("torrentInfo")) -select_category_filter = filters.create(lambda _, __, query: query.data.startswith("select_category")) diff --git a/src/db_management.py b/src/db_management.py index fae80c3..1f56dc7 100644 --- a/src/db_management.py +++ b/src/db_management.py @@ -3,7 +3,7 @@ from os import getenv db = Database() -db.bind(provider='sqlite', filename=f'{"/app/config/" if getenv("IS_DOCKER", False) else "./"}/database.sqlite', +db.bind(provider='sqlite', filename=f'{"/app/config/" if getenv("IS_DOCKER", False) else "../"}/database.sqlite', create_db=True) diff --git a/src/qbittorrent_bot.py b/src/qbittorrent_bot.py deleted file mode 100644 index 6e319d0..0000000 --- a/src/qbittorrent_bot.py +++ /dev/null @@ -1,451 +0,0 @@ -import os -import tempfile - -from pyrogram import Client, filters -from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery -from pyrogram.errors.exceptions import MessageIdInvalid -from pyrogram.enums.parse_mode import ParseMode -import psutil - -from src import custom_filters -from src.qbittorrent_manager import QbittorrentManagement -from apscheduler.schedulers.asyncio import AsyncIOScheduler -from src.utils import torrent_finished, convert_size, convert_eta -from src.config import BOT_CONFIGS -from src import db_management - -app = Client( - "qbittorrent_bot", - api_id=BOT_CONFIGS.telegram.api_id, - api_hash=BOT_CONFIGS.telegram.api_hash, - bot_token=BOT_CONFIGS.telegram.bot_token, - parse_mode=ParseMode.MARKDOWN -) - -scheduler = AsyncIOScheduler() -scheduler.add_job(torrent_finished, "interval", args=[app], seconds=60) - - -async def send_menu(client: Client, message, chat) -> None: - db_management.write_support("None", chat) - buttons = [[InlineKeyboardButton("📝 List", "list")], - [InlineKeyboardButton("➕ Add Magnet", "category#add_magnet"), - InlineKeyboardButton("➕ Add Torrent", "category#add_torrent")], - [InlineKeyboardButton("⏸ Pause", "pause"), - InlineKeyboardButton("▶️ Resume", "resume")], - [InlineKeyboardButton("⏸ Pause All", "pause_all"), - InlineKeyboardButton("▶️ Resume All", "resume_all")], - [InlineKeyboardButton("🗑 Delete", "delete_one"), - InlineKeyboardButton("🗑 Delete All", "delete_all")], - [InlineKeyboardButton("➕ Add Category", "add_category"), - InlineKeyboardButton("🗑 Remove Category", "select_category#remove_category")], - [InlineKeyboardButton("📝 Modify Category", "select_category#modify_category")]] - - try: - await client.edit_message_text(chat, message, text="Qbittorrent Control", - reply_markup=InlineKeyboardMarkup(buttons)) - - except MessageIdInvalid: - await client.send_message(chat, text="Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) - - -async def list_active_torrents(client: Client, n, chat, message, callback, status_filter: str = None) -> None: - with QbittorrentManagement() as qb: - torrents = qb.get_torrent_info(status_filter=status_filter) - - def render_categories_buttons(): - return [ - InlineKeyboardButton(f"⏳ {'*' if status_filter == 'downloading' else ''} Downloading", - "by_status_list#downloading"), - InlineKeyboardButton(f"✔️ {'*' if status_filter == 'completed' else ''} Completed", - "by_status_list#completed"), - InlineKeyboardButton(f"⏸️ {'*' if status_filter == 'paused' else ''} Paused", "by_status_list#paused"), - ] - - categories_buttons = render_categories_buttons() - if not torrents: - buttons = [categories_buttons, [InlineKeyboardButton("🔙 Menu", "menu")]] - try: - await client.edit_message_text(chat, message, "There are no torrents", - reply_markup=InlineKeyboardMarkup(buttons)) - except MessageIdInvalid: - await client.send_message(chat, "There are no torrents", reply_markup=InlineKeyboardMarkup(buttons)) - return - - buttons = [categories_buttons] - - if n == 1: - for key, i in enumerate(torrents): - buttons.append([InlineKeyboardButton(i.name, f"{callback}#{i.info.hash}")]) - - buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) - - try: - await client.edit_message_reply_markup(chat, message, reply_markup=InlineKeyboardMarkup(buttons)) - except MessageIdInvalid: - await client.send_message(chat, "Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) - - else: - for key, i in enumerate(torrents): - buttons.append([InlineKeyboardButton(i.name, f"torrentInfo#{i.info.hash}")]) - - buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) - - try: - await client.edit_message_reply_markup(chat, message, reply_markup=InlineKeyboardMarkup(buttons)) - except MessageIdInvalid: - await client.send_message(chat, "Qbittorrent Control", reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_message(filters=filters.command("start")) -async def start_command(client: Client, message: Message) -> None: - """Start the bot.""" - if message.from_user.id in [i.user_id for i in BOT_CONFIGS.users]: - await send_menu(client, message.id, message.chat.id) - - else: - button = InlineKeyboardMarkup([[InlineKeyboardButton("Github", - url="https://github.com/ch3p4ll3/QBittorrentBot/")]]) - await client.send_message(message.chat.id, "You are not authorized to use this bot", reply_markup=button) - - -@app.on_message(filters=filters.command("stats")) -async def stats_command(client: Client, message: Message) -> None: - if message.from_user.id in [i.user_id for i in BOT_CONFIGS.users]: - - stats_text = f"**============SYSTEM============**\n" \ - f"**CPU Usage:** {psutil.cpu_percent(interval=None)}%\n" \ - f"**CPU Temp:** {psutil.sensors_temperatures()['coretemp'][0].current}°C\n" \ - f"**Free Memory:** {convert_size(psutil.virtual_memory().available)} of " \ - f"{convert_size(psutil.virtual_memory().total)} ({psutil.virtual_memory().percent}%)\n" \ - f"**Disks usage:** {convert_size(psutil.disk_usage('/mnt').used)} of " \ - f"{convert_size(psutil.disk_usage('/mnt').total)} ({psutil.disk_usage('/mnt').percent}%)" - - await client.send_message(message.chat.id, stats_text) - - else: - button = InlineKeyboardMarkup([[InlineKeyboardButton("Github", - url="https://github.com/ch3p4ll3/QBittorrentBot/")]]) - await client.send_message(message.chat.id, "You are not authorized to use this bot", reply_markup=button) - - -@app.on_callback_query(filters=custom_filters.add_category_filter) -async def add_category_callback(client: Client, callback_query: CallbackQuery) -> None: - db_management.write_support("category_name", callback_query.from_user.id) - button = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Menu", "menu")]]) - try: - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - "Send the category name", reply_markup=button) - except MessageIdInvalid: - await client.send_message(callback_query.from_user.id, "Send the category name", reply_markup=button) - - -@app.on_callback_query(filters=custom_filters.select_category_filter) -async def list_categories(client: Client, callback_query: CallbackQuery): - buttons = [] - - with QbittorrentManagement() as qb: - categories = qb.get_categories() - - if categories is None: - buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - "There are no categories", reply_markup=InlineKeyboardMarkup(buttons)) - return - - for key, i in enumerate(categories): - buttons.append([InlineKeyboardButton(i, f"{callback_query.data.split('#')[1]}#{i}")]) - - buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) - - try: - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - "Choose a category:", reply_markup=InlineKeyboardMarkup(buttons)) - except MessageIdInvalid: - await client.send_message(callback_query.from_user.id, "Choose a category:", - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.remove_category_filter) -async def remove_category_callback(client: Client, callback_query: CallbackQuery) -> None: - buttons = [[InlineKeyboardButton("🔙 Menu", "menu")]] - - with QbittorrentManagement() as qb: - qb.remove_category(data=callback_query.data.split("#")[1]) - - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - f"The category {callback_query.data.split('#')[1]} has been removed", - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.modify_category_filter) -async def modify_category_callback(client: Client, callback_query: CallbackQuery) -> None: - buttons = [[InlineKeyboardButton("🔙 Menu", "menu")]] - - db_management.write_support(f"category_dir_modify#{callback_query.data.split('#')[1]}", callback_query.from_user.id) - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - f"Send new path for category {callback_query.data.split('#')[1]}", - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.category_filter) -async def category(client: Client, callback_query: CallbackQuery) -> None: - buttons = [] - - with QbittorrentManagement() as qb: - categories = qb.get_categories() - - if categories is None: - if "magnet" in callback_query.data: - await add_magnet_callback(client, callback_query) - - else: - await add_torrent_callback(client, callback_query) - - return - - for key, i in enumerate(categories): - buttons.append([InlineKeyboardButton(i, f"{callback_query.data.split('#')[1]}#{i}")]) - - buttons.append([InlineKeyboardButton("None", f"{callback_query.data.split('#')[1]}#None")]) - buttons.append([InlineKeyboardButton("🔙 Menu", "menu")]) - - try: - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, - "Choose a category:", reply_markup=InlineKeyboardMarkup(buttons)) - except MessageIdInvalid: - await client.send_message(callback_query.from_user.id, "Choose a category:", - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.menu_filter) -async def menu_callback(client: Client, callback_query: CallbackQuery) -> None: - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.list_filter) -async def list_callback(client: Client, callback_query: CallbackQuery) -> None: - await list_active_torrents(client, 0, callback_query.from_user.id, callback_query.message.id, - db_management.read_support(callback_query.from_user.id)) - - -@app.on_callback_query(filters=custom_filters.list_by_status_filter) -async def list_by_status_callback(client: Client, callback_query: CallbackQuery) -> None: - status_filter = callback_query.data.split("#")[1] - await list_active_torrents(client,0, callback_query.from_user.id, callback_query.message.id, - db_management.read_support(callback_query.from_user.id), status_filter=status_filter) - - -@app.on_callback_query(filters=custom_filters.add_magnet_filter) -async def add_magnet_callback(client: Client, callback_query: CallbackQuery) -> None: - db_management.write_support(f"magnet#{callback_query.data.split('#')[1]}", callback_query.from_user.id) - await client.answer_callback_query(callback_query.id, "Send a magnet link") - - -@app.on_callback_query(filters=custom_filters.add_torrent_filter) -async def add_torrent_callback(client: Client, callback_query: CallbackQuery) -> None: - db_management.write_support(f"torrent#{callback_query.data.split('#')[1]}", callback_query.from_user.id) - await client.answer_callback_query(callback_query.id, "Send a torrent file") - - -@app.on_callback_query(filters=custom_filters.pause_all_filter) -async def pause_all_callback(client: Client, callback_query: CallbackQuery) -> None: - with QbittorrentManagement() as qb: - qb.pause_all() - await client.answer_callback_query(callback_query.id, "Paused all torrents") - - -@app.on_callback_query(filters=custom_filters.resume_all_filter) -async def resume_all_callback(client: Client, callback_query: CallbackQuery) -> None: - with QbittorrentManagement() as qb: - qb.resume_all() - await client.answer_callback_query(callback_query.id, "Resumed all torrents") - - -@app.on_callback_query(filters=custom_filters.pause_filter) -async def pause_callback(client: Client, callback_query: CallbackQuery) -> None: - if callback_query.data.find("#") == -1: - await list_active_torrents(client, 1, callback_query.from_user.id, callback_query.message.id, "pause") - - else: - with QbittorrentManagement() as qb: - qb.pause(torrent_hash=callback_query.data.split("#")[1]) - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.resume_filter) -async def resume_callback(client: Client, callback_query: CallbackQuery) -> None: - if callback_query.data.find("#") == -1: - await list_active_torrents(client, 1, callback_query.from_user.id, callback_query.message.id, "resume") - - else: - with QbittorrentManagement() as qb: - qb.resume(torrent_hash=callback_query.data.split("#")[1]) - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.delete_one_filter) -async def delete_callback(client: Client, callback_query: CallbackQuery) -> None: - if callback_query.data.find("#") == -1: - await list_active_torrents(client, 1, callback_query.from_user.id, callback_query.message.id, "delete_one") - - else: - - buttons = [ - [InlineKeyboardButton("🗑 Delete torrent", f"delete_one_no_data#{callback_query.data.split('#')[1]}")], - [InlineKeyboardButton("🗑 Delete torrent and data", f"delete_one_data#{callback_query.data.split('#')[1]}")], - [InlineKeyboardButton("🔙 Menu", "menu")]] - - await client.edit_message_reply_markup(callback_query.from_user.id, callback_query.message.id, - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.delete_one_no_data_filter) -async def delete_no_data_callback(client: Client, callback_query: CallbackQuery) -> None: - if callback_query.data.find("#") == -1: - await list_active_torrents(client, 1, callback_query.from_user.id, callback_query.message.id, "delete_one_no_data") - - else: - with QbittorrentManagement() as qb: - qb.delete_one_no_data(torrent_hash=callback_query.data.split("#")[1]) - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.delete_one_data_filter) -async def delete_with_data_callback(client: Client, callback_query: CallbackQuery) -> None: - if callback_query.data.find("#") == -1: - await list_active_torrents(client, 1, callback_query.from_user.id, callback_query.message.id, "delete_one_data") - - else: - with QbittorrentManagement() as qb: - qb.delete_one_data(torrent_hash=callback_query.data.split("#")[1]) - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.delete_all_filter) -async def delete_all_callback(client: Client, callback_query: CallbackQuery) -> None: - buttons = [[InlineKeyboardButton("🗑 Delete all torrents", "delete_all_no_data")], - [InlineKeyboardButton("🗑 Delete all torrents and data", "delete_all_data")], - [InlineKeyboardButton("🔙 Menu", "menu")]] - await client.edit_message_reply_markup(callback_query.from_user.id, callback_query.message.id, - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_callback_query(filters=custom_filters.delete_all_no_data_filter) -async def delete_all_with_no_data_callback(client: Client, callback_query: CallbackQuery) -> None: - with QbittorrentManagement() as qb: - qb.delete_all_no_data() - await client.answer_callback_query(callback_query.id, "Deleted only torrents") - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.delete_all_data_filter) -async def delete_all_with_data_callback(client: Client, callback_query: CallbackQuery) -> None: - with QbittorrentManagement() as qb: - qb.delete_all_data() - await client.answer_callback_query(callback_query.id, "Deleted All+Torrents") - await send_menu(client, callback_query.message.id, callback_query.from_user.id) - - -@app.on_callback_query(filters=custom_filters.torrentInfo_filter) -async def torrent_info_callback(client: Client, callback_query: CallbackQuery) -> None: - with QbittorrentManagement() as qb: - torrent = qb.get_torrent_info(data=callback_query.data.split("#")[1]) - progress = torrent.progress * 100 - text = "" - - if progress == 0: - text += f"{torrent.name}\n[ ] " \ - f"{round(progress, 2)}% completed\n" \ - f"State: {torrent.state.capitalize()}\n" \ - f"Download Speed: {convert_size(torrent.dlspeed)}/s\n" \ - f"Size: {convert_size(torrent.size)}\nETA: " \ - f"{convert_eta(int(torrent.eta))}\n" \ - f"Category: {torrent.category}\n" - - elif progress == 100: - text += f"{torrent.name}\n[completed] " \ - f"{round(progress, 2)}% completed\n" \ - f"State: {torrent.state.capitalize()}\n" \ - f"Upload Speed: {convert_size(torrent.upspeed)}/s\n" \ - f"Category: {torrent.category}\n" - - else: - text += f"{torrent.name}\n[{'=' * int(progress / 10)}" \ - f"{' ' * int(12 - (progress / 10))}]" \ - f" {round(progress, 2)}% completed\n" \ - f"State: {torrent.state.capitalize()} \n" \ - f"Download Speed: {convert_size(torrent.dlspeed)}/s\n" \ - f"Size: {convert_size(torrent.size)}\nETA: " \ - f"{convert_eta(int(torrent.eta))}\n" \ - f"Category: {torrent.category}\n" - - buttons = [[InlineKeyboardButton("⏸ Pause", f"pause#{callback_query.data.split('#')[1]}")], - [InlineKeyboardButton("▶️ Resume", f"resume#{callback_query.data.split('#')[1]}")], - [InlineKeyboardButton("🗑 Delete", f"delete_one#{callback_query.data.split('#')[1]}")], - [InlineKeyboardButton("🔙 Menu", "menu")]] - - await client.edit_message_text(callback_query.from_user.id, callback_query.message.id, text=text, - reply_markup=InlineKeyboardMarkup(buttons)) - - -@app.on_message(filters=~filters.me) -async def on_text(client: Client, message: Message) -> None: - action = db_management.read_support(message.from_user.id) - - if "magnet" in action: - if message.text.startswith("magnet:?xt"): - magnet_link = message.text.split("\n") - category = db_management.read_support(message.from_user.id).split("#")[1] - - with QbittorrentManagement() as qb: - qb.add_magnet(magnet_link=magnet_link, - category=category) - - await send_menu(client, message.id, message.from_user.id) - db_management.write_support("None", message.from_user.id) - - else: - await client.send_message(message.from_user.id, "This magnet link is invalid! Retry") - - elif "torrent" in action and message.document: - if ".torrent" in message.document.file_name: - with tempfile.TemporaryDirectory() as tempdir: - name = f"{tempdir}/{message.document.file_name}" - category = db_management.read_support(message.from_user.id).split("#")[1] - await message.download(name) - - with QbittorrentManagement() as qb: - qb.add_torrent(file_name=name, - category=category) - await send_menu(client, message.id, message.from_user.id) - db_management.write_support("None", message.from_user.id) - - else: - await client.send_message(message.from_user.id, "This is not a torrent file! Retry") - - elif action == "category_name": - db_management.write_support(f"category_dir#{message.text}", message.from_user.id) - await client.send_message(message.from_user.id, f"now send me the path for the category {message.text}") - - elif "category_dir" in action: - if os.path.exists(message.text): - name = db_management.read_support(message.from_user.id).split("#")[1] - - if "modify" in action: - with QbittorrentManagement() as qb: - qb.edit_category(name=name, - save_path=message.text) - await send_menu(client, message.id, message.from_user.id) - return - - with QbittorrentManagement() as qb: - qb.create_category(name=name, - save_path=message.text) - await send_menu(client, message.id, message.from_user.id) - - else: - await client.send_message(message.from_user.id, "The path entered does not exist! Retry") - - else: - await client.send_message(message.from_user.id, "The command does not exist") diff --git a/src/qbittorrent_manager.py b/src/qbittorrent_manager.py deleted file mode 100644 index b066e22..0000000 --- a/src/qbittorrent_manager.py +++ /dev/null @@ -1,98 +0,0 @@ -import qbittorrentapi -from src.config import BOT_CONFIGS - -from typing import Union, List - - -class QbittorrentManagement: - def __init__(self): - self.qbt_client = qbittorrentapi.Client( - host=f'http://{BOT_CONFIGS.qbittorrent.ip.network_address}:' - f'{BOT_CONFIGS.qbittorrent.port}', - username=BOT_CONFIGS.qbittorrent.user, - password=BOT_CONFIGS.qbittorrent.password) - - def __enter__(self): - try: - self.qbt_client.auth_log_in() - except qbittorrentapi.LoginFailed as e: - print(e) - - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.qbt_client.auth_log_out() - - def add_magnet(self, magnet_link: Union[str, List[str]], category: str = None) -> None: - if category == "None": - category = None - - if category is not None: - self.qbt_client.torrents_add(urls=magnet_link, category=category) - else: - self.qbt_client.torrents_add(urls=magnet_link) - - def add_torrent(self, file_name: str, category: str = None) -> None: - if category == "None": - category = None - - try: - if category is not None: - self.qbt_client.torrents_add(torrent_files=file_name, category=category) - else: - self.qbt_client.torrents_add(torrent_files=file_name) - - except qbittorrentapi.exceptions.UnsupportedMediaType415Error: - pass - - def resume_all(self) -> None: - self.qbt_client.torrents.resume.all() - - def pause_all(self) -> None: - self.qbt_client.torrents.pause.all() - - def resume(self, torrent_hash: str) -> None: - self.qbt_client.torrents_resume(torrent_hashes=torrent_hash) - - def pause(self, torrent_hash: str) -> None: - self.qbt_client.torrents_pause(torrent_hashes=torrent_hash) - - def delete_one_no_data(self, torrent_hash: str) -> None: - self.qbt_client.torrents_delete(delete_files=False, - torrent_hashes=torrent_hash) - - def delete_one_data(self, torrent_hash: str) -> None: - self.qbt_client.torrents_delete(delete_files=True, - torrent_hashes=torrent_hash) - - def delete_all_no_data(self) -> None: - for i in self.qbt_client.torrents_info(): - self.qbt_client.torrents_delete(delete_files=False, hashes=i.hash) - - def delete_all_data(self) -> None: - for i in self.qbt_client.torrents_info(): - self.qbt_client.torrents_delete(delete_files=True, hashes=i.hash) - - def get_categories(self): - categories = self.qbt_client.torrent_categories.categories - if len(categories) > 0: - return categories - - else: - return - - def get_torrent_info(self, data: str = None, status_filter: str = None, ): - if data is None: - return self.qbt_client.torrents_info(status_filter=status_filter) - return next(iter(self.qbt_client.torrents_info(status_filter=status_filter, torrent_hashes=data)), None) - - def edit_category(self, name: str, save_path: str) -> None: - self.qbt_client.torrents_edit_category(name=name, - save_path=save_path) - - def create_category(self, name: str, save_path: str) -> None: - self.qbt_client.torrents_create_category(name=name, - save_path=save_path) - - def remove_category(self, data: str) -> None: - self.qbt_client.torrents_remove_categories(categories=data) diff --git a/src/utils.py b/src/utils.py index 2e83eef..b01fcee 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,18 +1,22 @@ from math import log, floor import datetime + +from pydantic import IPvAnyAddress from pyrogram.errors.exceptions import UserIsBlocked from src import db_management -from src.qbittorrent_manager import QbittorrentManagement -from src.config import BOT_CONFIGS +from src.client_manager.qbittorrent_manager import QbittorrentManager +from .configs import Configs +from .configs.enums import ClientTypeEnum, UserRolesEnum +from .configs.user import User async def torrent_finished(app): - with QbittorrentManagement() as qb: + with QbittorrentManager() as qb: for i in qb.get_torrent_info(status_filter="completed"): if db_management.read_completed_torrents(i.hash) is None: - for user in BOT_CONFIGS.users: + for user in Configs.config.users: if user.notify: try: await app.send_message(user.user_id, f"torrent {i.name} has finished downloading!") @@ -21,6 +25,14 @@ async def torrent_finished(app): db_management.write_completed_torrents(i.hash) +def get_user_from_config(user_id: int) -> User: + return next( + iter( + [i for i in Configs.config.users if i.user_id == user_id] + ) + ) + + def convert_size(size_bytes) -> str: if size_bytes == 0: return "0B" @@ -33,3 +45,16 @@ def convert_size(size_bytes) -> str: def convert_eta(n) -> str: return str(datetime.timedelta(seconds=n)) + + +def convert_type_from_string(input_type: str): + if "int" in input_type: + return int + elif "IPvAnyAddress" in input_type: + return IPvAnyAddress + elif "ClientTypeEnum" in input_type: + return ClientTypeEnum + elif "UserRolesEnum" in input_type: + return UserRolesEnum + elif "str" in input_type: + return str