├── LICENSE ├── README.md ├── bin └── torrent-hound ├── requirements.txt └── torrent-hound.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Torrent Hound 2 | Search torrents from multiple websites via the CLI 3 | 4 | 5 | ### Requirements 6 | - Python 3 7 | - bs4 8 | - clint 9 | - pyperclip 10 | - humanize 11 | - VeryPrettyTable 12 | 13 | ### Installation 14 | Install package and dependencies directly via pip using `pip install torrent-hound` 15 | 16 | Or run `pip install -r requirements.txt` in the shell to install all dependencies 17 | 18 | 19 | ### Update existing Intallation 20 | To upgrade `torrent-hound` via pip, run `pip install torrent-hound -U` 21 | 22 | If installed via `git`, then simply run `git pull` in the shell after navigating to the `torrent-hound` directory 23 | 24 | Otherwise download the latest binary from the `releases` section of this repository 25 | 26 | 27 | ### Usage 28 | If installed via pip, `torrent-hound` would have been added to `$PATH`. Simply run `torrent-hound` or `torrent-hound [search-query]` to begin. 29 | 30 | Download the `torrent-hound` binary from the `bin/` directory. 31 | 32 | `torrent-hound [search-query]` or simply `torrent-hound` 33 | 34 | 35 | ### Menu 36 | Available Commands : 37 | 38 | 1. `m` - Print magnet link of selected torrent 39 | 2. `c` - Copy magnet link of selected torrent to clipboard 40 | 3. `d` - Download torrent using default torrent client 41 | 4. `o` - Open the torrent page of the selected torrent in the default browser 42 | 5. `cs` - Copy magnet link and open Seedr.cc 43 | 6. `p` - Print top 10 results from each website for the given query 44 | 45 | `` : [{default : 1}, {0 : Print formatted result}, {1 : Pretty print results}] 46 | 7. `s` - Enter a new query to search for over all avilable torrent websites 47 | 8. `r` - Repeat last search (with same query) 48 | 49 | 50 | ### Help 51 | In case of an `SSL Error`, consult [these answers on Stackoverflow](https://stackoverflow.com/questions/31649390/python-requests-ssl-handshake-failure) for potential fixes. 52 | -------------------------------------------------------------------------------- /bin/torrent-hound: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # @author : Yashovardhan Sharma 3 | # @github : github.com/baddymaster 4 | 5 | # 6 | # Copyright (C) <2023> 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published 10 | # by the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | from __future__ import print_function 22 | from builtins import input 23 | from builtins import str 24 | from bs4 import BeautifulSoup 25 | from datetime import datetime, timedelta 26 | from clint.textui import colored 27 | from veryprettytable import VeryPrettyTable 28 | import requests 29 | import re 30 | import sys 31 | import pyperclip 32 | import webbrowser 33 | import json 34 | import humanize 35 | import traceback 36 | import random 37 | import time 38 | import argparse 39 | import traceback 40 | 41 | defaultQuery, query = 'jason bourne', '' 42 | results_sky = None 43 | results_tpb_condensed = None 44 | results_tpb_api, num_results_tpb_api = None, 0 45 | results_1337x = None 46 | results, results_rarbg, exit, error_detected_rarbg, error_detected_tpb = None, None, None, None, None 47 | num_results, num_results_rarbg, num_results_sky, num_results_1337x, print_version = 0, 0, 0, 0, 1 48 | auth_token = 'None' 49 | app_id = 'None' 50 | tpb_working_domain = 'tpb.tw' 51 | rarbg_url, skytorrents_url, tpb_url, url_1337x = '', '', '', '' 52 | tpb_retries, max_tpb_retries = 0, 3 53 | 54 | def enum(**enums): 55 | """ 56 | Lets define enums 57 | """ 58 | return type('Enum', (), enums) 59 | 60 | ORDER_BY = enum(NAME = 1, 61 | SIZE = 3, 62 | UPLOADER = 5, 63 | SEEDERS = 7, 64 | LEECHERS = 9, 65 | TYPE = 13, 66 | UPLOADED = 99) 67 | 68 | SORT_BY_TBP = enum(NAME = 'title_asc', 69 | NAME_DESC = 'title_desc', 70 | SEEDS = 'seeds_asc', 71 | SEEDS_DESC = 'seeds_desc', 72 | LEECHERS = 'leeches_asc', 73 | LEECHERS_DESC = 'leeches_desc', 74 | MOST_RECENT = 'time_desc', 75 | OLDEST = 'time_asc', 76 | UPLOADER = 'uploader_asc', 77 | UPLOADER_DESC = 'uploader_desc', 78 | SIZE = 'size_asc', 79 | SIZE_DESC = 'size_desc', 80 | FILE_TYPE = 'category_asc', 81 | FILE_TYPE_DESC = 'category_desc') 82 | 83 | ORDER_BY_SKY = enum(RELEVANCE = 'ss', 84 | SEEDS_DESC = 'ed', 85 | SEEDS_ASC = 'ea', 86 | PEERS_DESC = 'pd', 87 | PEERS_ASC = 'pa', 88 | SIZE_DESC = 'sd', 89 | SIZE_ASC = 'sa', 90 | NEWEST = 'ad', 91 | OLDEST = 'aa') 92 | 93 | def generateNewTorrentAPIToken(error=False, quiet_mode=False): 94 | global auth_token, error_detected_rarbg, app_id 95 | 96 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 97 | headers_safari = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15'} 98 | refresh_url = 'https://torrentapi.org/pubapi_v2.php?get_token=get_token&app_id=' + str(app_id) 99 | 100 | #print(f"App ID: {app_id}") 101 | #print(f"Token Refresh URL: {refresh_url}") 102 | try: 103 | r = requests.get(refresh_url, headers=headers_safari) 104 | if(str(r).split()[1][1:4] != '200'): 105 | if quiet_mode == False: 106 | print(colored.red("HTTP Response Error : %s" % str(r))) 107 | error_detected_rarbg = True 108 | return error_detected_rarbg 109 | 110 | auth_token = json.loads(r.text)['token'] 111 | #print(f"Auth Token: {auth_token}") 112 | 113 | if error != False: 114 | success_string = '[RARBG] Success : Generated new token! ' 115 | if quiet_mode == False: 116 | print(colored.blue(success_string)) 117 | except requests.exceptions.ConnectionError as e: 118 | err_string = str(e).split(',')[0] 119 | if 'Connection aborted' in err_string: 120 | if quiet_mode == False: 121 | print(colored.red("Server cannot be reached. Check Internet connectivity!")) 122 | #sys.exit(1) 123 | 124 | #except SysCallError, e: 125 | # print colored.red("SysCallError for RARBG search. Fix?") 126 | 127 | def searchRarbg(search_string=defaultQuery, quiet_mode=False): 128 | global auth_token, results_rarbg, error_detected_rarbg, app_id, rarbg_url 129 | # API Documentaion : https://torrentapi.org/apidocs_v2.txt 130 | # https://torrentapi.org/pubapi_v2.php?mode=search&search_string=Suits%20S06E10&format=json_extended&ranked=0&token=7dib9orxpa&app_id=0 131 | # echo 'torrent-hound' | shasum -a 512 132 | generateNewTorrentAPIToken(quiet_mode=quiet_mode) 133 | #print(f"Auth Token: {auth_token}") 134 | if error_detected_rarbg == True: 135 | #print "Error detected!\n" 136 | return results_rarbg 137 | 138 | #print(f"Auth token: {auth_token.decode('utf-8')}\n") 139 | search_string = search_string.replace(" ", "%20") 140 | base_url = 'https://torrentapi.org/pubapi_v2.php?' 141 | new_token = 'get_token=get_token&app_id=' + str(app_id) 142 | search_criteria = 'mode=search&search_string=' + search_string + "&" 143 | options = 'format=json_extended&ranked=0&token=' + str(auth_token) + '&app_id=' + str(app_id) 144 | url = base_url + search_criteria + options 145 | rarbg_url = url 146 | #print(f"RARBG Search URL: {url}") 147 | 148 | headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0'} 149 | # User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15 150 | headers_safari = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15'} 151 | 152 | try: 153 | response = requests.get(url, headers=headers_safari) 154 | #print(f"Response: {response}") 155 | rt = response.text 156 | #print(f"Response Text: {rt}\n") 157 | response_json = json.loads(rt) 158 | #print response_json 159 | except Exception as e: 160 | if quiet_mode == False: 161 | status_code = str(response).split()[1].strip('<[]>') 162 | if status_code == '429': # Too Many Requests 163 | print(colored.yellow(' : Too Many Requests. Please try again after a while!')) 164 | print(colored.red('[RARBG] Error : ' + str(e))) 165 | else: 166 | print(colored.red('[RARBG] Error : ' + str(e))) 167 | #traceback.print_exc() 168 | 169 | return [] 170 | results_rarbg = [] 171 | 172 | error_detected_rarbg = checkResponseForErrors(response_json, quiet_mode=quiet_mode) 173 | if(error_detected_rarbg == False): 174 | results_rarbg = parse_results_rarbg(response_json, quiet_mode=quiet_mode) 175 | return results_rarbg 176 | 177 | def checkResponseForErrors(response_json, quiet_mode=False): 178 | global results_rarbg, error_detected_rarbg, query, auth_token 179 | search_string = query.replace(" ", "%20") 180 | 181 | if 'error_code' in response_json: 182 | #print 'In function' 183 | error_string = '[RARBG] Error : ' + response_json['error'] 184 | if quiet_mode == False: 185 | print(colored.magenta(error_string)) 186 | 187 | if response_json['error_code'] == 4: 188 | generateNewTorrentAPIToken(error=True) 189 | results_rarbg = searchRarbg(search_string) 190 | # elif response_json['error_code'] == 20: 191 | # print "No results found. Try different keywords!\n" 192 | return True #Some error detected 193 | else: 194 | return False #No errors. Print results 195 | 196 | def parse_results_rarbg(response_json, quiet_mode=False, limit=10): 197 | global results_rarbg 198 | if error_detected_rarbg == False: 199 | #print len(response_json['torrent_results']) 200 | for post in response_json['torrent_results'][:limit]: 201 | res = {} 202 | res['name'] = post['title'] 203 | res['link'] = post['info_page'] 204 | 205 | temp_size = humanize.naturalsize(post['size'], binary=True, format='%.2f') 206 | s1 = temp_size.split('.') 207 | if(len(s1[0]) == 4): 208 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.0f') 209 | elif(len(s1[1]) == 3): 210 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.1f') 211 | else: 212 | res['size'] = temp_size 213 | #res['time'] = Implement later 214 | res['seeders'] = post['seeders'] 215 | res['leechers'] = post['leechers'] 216 | try: 217 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 218 | except ZeroDivisionError: 219 | res['ratio'] = 'inf' 220 | res['magnet'] = post['download'] 221 | results_rarbg.append(res) 222 | else: 223 | if quiet_mode == False: 224 | print("----------- " + colored.green('RARBG') + " -----------") 225 | print(" [No results found] ") 226 | return [] 227 | return results_rarbg 228 | 229 | def print_top_results_rarbg(limit=10): 230 | global results_rarbg 231 | if results_rarbg != [] and results_rarbg != None: 232 | print('\n---------------------------------------------- ' + colored.green('RARBG') + ' ----------------------------------------------') 233 | print('{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6))) 234 | index = 1 235 | for r in results_rarbg[:limit]: 236 | print('{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(10), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8))) 237 | index = index + 1 238 | print("---------------------------------------------------------------------------------------------------") 239 | return index - 1 240 | 241 | def pretty_print_top_results_rarbg(limit=10): 242 | global results_rarbg 243 | table_rarbg = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 244 | no_str = str(colored.red('No')) 245 | name_str = str(colored.red('Torrent Name')) 246 | size_str = str(colored.red('Size')) 247 | seed_str = str(colored.red('S')) 248 | leech_str = str(colored.red('L')) 249 | ratio_str = str(colored.red('S/L')) 250 | table_rarbg.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 251 | 252 | print('\n\t\t\t\t\t\t' + colored.green('RARBG')) 253 | if (results_rarbg != []) and (results_rarbg != None): 254 | #print 'Empty table' 255 | #print '{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6)) 256 | index = 1 257 | for r in results_rarbg[:limit]: 258 | table_rarbg.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 259 | #print '{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(10), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8)) 260 | index = index + 1 261 | table_rarbg.align[no_str] = 'l' 262 | table_rarbg.align[name_str] = 'l' 263 | table_rarbg.align[size_str] = 'r' 264 | table_rarbg.align[seed_str] = 'r' 265 | table_rarbg.align[leech_str] = 'r' 266 | table_rarbg.align[ratio_str] = 'r' 267 | print(table_rarbg) 268 | return index - 1 269 | else: 270 | table_rarbg.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 271 | table_rarbg.align[colored.red('Torrent Name')] = 'l' 272 | print(table_rarbg) 273 | return 0 274 | 275 | def extract_magnet_link_1337x(url): 276 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 277 | response = requests.get(url, headers=headers) 278 | soup = BeautifulSoup(response.content, 'html.parser') 279 | magnet_link = soup.find('a', href=lambda href: href and href.startswith("magnet:")) 280 | if magnet_link: 281 | return magnet_link['href'] 282 | else: 283 | return None 284 | 285 | def search1337x(search_string=defaultQuery, domain='1337x.to', quiet_mode=False, limit=10): 286 | global results_1337x, url_1337x 287 | 288 | query = removeAndReplaceSpaces(search_string) 289 | page_no = 1 290 | baseURL = f'https://{domain}' 291 | url = f'{baseURL}/search/{query}/{page_no}/' 292 | url_1337x = url 293 | 294 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 295 | response = requests.get(url, headers=headers) 296 | soup = BeautifulSoup(response.text, 'html.parser') 297 | results_1337x = [] 298 | 299 | try: 300 | table = soup.find('table', {'class': 'table-list'}) 301 | rows = table.tbody.find_all('tr') 302 | for row in rows[:limit]: 303 | row_data = {} 304 | name_col = row.find('td', {'class': 'coll-1 name'}) 305 | row_data['name'] = name_col.a.next_sibling.text 306 | row_data['link'] = baseURL + name_col.a.next_sibling['href'] 307 | row_data['seeders'] = int(row.find('td', {'class': 'coll-2 seeds'}).text.strip()) 308 | row_data['leechers'] = int(row.find('td', {'class': 'coll-3 leeches'}).text.strip()) 309 | try: 310 | row_data['ratio'] = format( (float(row_data['seeders'])/float(row_data['leechers'])), '.1f' ) 311 | except ZeroDivisionError: 312 | row_data['ratio'] = 'inf' 313 | row_data['time'] = row.find('td', {'class': 'coll-date'}).text.strip() 314 | size_col = row.find('td', {'class': 'coll-4'}) 315 | if size_col: 316 | row_data['size'] = size_col.contents[0].strip() 317 | else: 318 | row_data['size'] = '' 319 | # uploader_col = row.find('td', {'class': 'coll-5'}) 320 | # if uploader_col: 321 | # row_data['uploader'] = uploader_col.contents[0].text.strip() 322 | # else: 323 | # row_data['uploader'] = '' 324 | row_data['magnet'] = extract_magnet_link_1337x(row_data['link']) 325 | results_1337x.append(row_data) 326 | except AttributeError as e: 327 | print(colored.magenta("[1337x] Error : No results found")) 328 | return results_1337x 329 | 330 | def pretty_print_top_results_1337x(limit=10): 331 | global results_1337x, num_results_tpb_api, num_results 332 | table_1337x = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 333 | no_str = str(colored.red('No')) 334 | name_str = str(colored.red('Torrent Name')) 335 | size_str = str(colored.red('Size')) 336 | seed_str = str(colored.red('S')) 337 | leech_str = str(colored.red('L')) 338 | ratio_str = str(colored.red('S/L')) 339 | table_1337x.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 340 | 341 | #print '\n\t\t\t\t\t\t' + '+-----------+' 342 | #print '\t\t\t\t\t\t| ' + colored.green('PirateBay') + ' |' 343 | print('\n\t\t\t\t\t\t' + colored.green('1337x')) 344 | # print results 345 | if results_1337x != [{}] and results_1337x != [] and results_1337x != None: 346 | #index = num_results_tpb_api + 1 # Index after TBP API 347 | index = num_results + 1 # Index after TBP regular 348 | for r in results_1337x[:limit]: 349 | try : 350 | table_1337x.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 351 | index = index + 1 352 | except KeyError as e: 353 | # Fix error where {} is included in results and screws up numbering # 354 | if r != {}: 355 | print(r) 356 | print(e) 357 | table_1337x.align[no_str] = 'l' 358 | table_1337x.align[name_str] = 'l' 359 | table_1337x.align[size_str] = 'r' 360 | table_1337x.align[seed_str] = 'r' 361 | table_1337x.align[leech_str] = 'r' 362 | table_1337x.align[ratio_str] = 'r' 363 | print(table_1337x) 364 | return index - 1 365 | else: 366 | table_1337x.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 367 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 368 | print(table_1337x) 369 | return num_results 370 | 371 | def searchSkyTorrents(search_string=defaultQuery, domain='skytorrents.lol', order_by=ORDER_BY_SKY.RELEVANCE, quiet_mode=False, limit=10): 372 | global results_sky, skytorrents_url 373 | search_string = removeAndReplaceSpaces(search_string) 374 | baseURL = 'https://' + domain 375 | url = baseURL + '/?query=' + search_string 376 | skytorrents_url = url 377 | #url = baseURL + '/search/all/' + order_by + '/1/?l=en-us&q=' + search_string 378 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 379 | tbody = None 380 | #headers = {'User-Agent': 'Mozilla/5.0'} 381 | try: 382 | r = requests.get(url, headers=headers) 383 | soup = BeautifulSoup(r.content, "html.parser") 384 | #print soup 385 | tbody = soup.find('tbody') 386 | results_sky = [] 387 | 388 | trows = tbody.findAll("tr") 389 | #print len(trows) 390 | for trow in trows[:limit]: 391 | res = {} 392 | tds = trow.findAll("td") 393 | #tds[0] -> Name, Magnet, Link 394 | res['name'] = tds[0].findAll("a")[0].contents[0] 395 | res['link'] = baseURL + '/' + tds[0].findAll("a")[0].attrs['href'] 396 | 397 | if tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_upm.png' and tds[0].findAll("img")[1].attrs['src'] == '/files/thumb_downm.png': 398 | # Both upvotes and downvotes found 399 | res['up'] = '{:+}'.format(int(tds[0].contents[2])) 400 | res['down'] = '{:+}'.format(int(tds[0].contents[4])) 401 | elif tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_upm.png': 402 | # Only upvotes, no downvotes found 403 | res['up'] = '{:+}'.format(int(tds[0].contents[2])) 404 | res['down'] = '0' 405 | elif tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_downm.png': 406 | # Only downvotes, no upvotes found 407 | res['up'] = '0' 408 | res['down'] = '{:+}'.format(int(tds[0].contents[2])) 409 | else: 410 | # No upvotes or downvotes found 411 | res['up'] = '0' 412 | res['down'] = '0' 413 | 414 | res['magnet'] = tds[0].findAll("a")[2].attrs['href'] 415 | #tds[1] -> Size 416 | res['size'] = tds[1].contents[0].encode('utf-8') 417 | #tds[2] -> No. of files 418 | # res['num_files'] = tds[0].contents[0].encode('utf-8') 419 | #tds[3] -> Date added 420 | # res['date'] = tds[3].contents[0].encode('utf-8') 421 | #tds[4] -> Seeders 422 | res['seeders'] = tds[4].contents[0].replace(',', '') 423 | #tds[5] -> Leechers 424 | res['leechers'] = tds[5].contents[0].replace(',', '') 425 | try: 426 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 427 | except ZeroDivisionError: 428 | res['ratio'] = 'inf' 429 | results_sky.append(res) 430 | 431 | except Exception as e: 432 | if quiet_mode == False: 433 | if tbody == None: 434 | print(colored.magenta("[SkyTorrents] Error : No results found")) 435 | else: 436 | print(colored.red("[SkyTorrents] Error : Unkown problem while searching")) 437 | print(colored.yellow('ERR_MSG : ' + str(e))) 438 | #traceback.print_exc() 439 | 440 | return results_sky 441 | 442 | def removeAndReplaceSpaces(string): 443 | if string[0] == " ": 444 | string = string[1:] 445 | return string.replace(" ", "+") 446 | 447 | def pretty_print_top_results_skytorrents(limit=10): 448 | global results_sky, num_results_tpb_api, num_results 449 | table_skytorrents = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 450 | no_str = str(colored.red('No')) 451 | name_str = str(colored.red('Torrent Name')) 452 | size_str = str(colored.red('Size')) 453 | seed_str = str(colored.red('S')) 454 | leech_str = str(colored.red('L')) 455 | ratio_str = str(colored.red('S/L')) 456 | votes_str = str(colored.red('Votes')) 457 | table_skytorrents.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str, votes_str] 458 | 459 | #print '\n\t\t\t\t\t\t' + '+-----------+' 460 | #print '\t\t\t\t\t\t| ' + colored.green('PirateBay') + ' |' 461 | print('\n\t\t\t\t\t\t' + colored.green('Sky Torrents')) 462 | # print results 463 | if results_sky != [{}] and results_sky != [] and results_sky != None: 464 | #index = num_results_tpb_api + 1 465 | index = num_results + 1 466 | for r in results_sky[:limit]: 467 | try : 468 | table_skytorrents.add_row([index, r['name'][:57], r['size'].decode('utf-8'), r['seeders'], r['leechers'], r['ratio'], (r['up'] + '/' + r['down'])]) 469 | index = index + 1 470 | except KeyError as e: 471 | # Fix error where {} is included in results and screws up numbering # 472 | if r != {}: 473 | print(r) 474 | print(e) 475 | table_skytorrents.align[no_str] = 'l' 476 | table_skytorrents.align[name_str] = 'l' 477 | table_skytorrents.align[size_str] = 'r' 478 | table_skytorrents.align[seed_str] = 'r' 479 | table_skytorrents.align[leech_str] = 'r' 480 | table_skytorrents.align[ratio_str] = 'r' 481 | table_skytorrents.align[votes_str] = 'c' 482 | print(table_skytorrents) 483 | return index - 1 484 | else: 485 | table_skytorrents.add_row(["Null", "Null", "Null", "Null", "Null", "Null", "Null"]) 486 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 487 | print(table_skytorrents) 488 | return num_results 489 | 490 | def searchPirateBayCondensed(search_string=defaultQuery, page=0, order_by=ORDER_BY.SEEDERS, domain='thepiratebay.org', quiet_mode=False, limit=10): 491 | global tpb_working_domain, tpb_url, results_tpb_condensed 492 | url = f'https://{tpb_working_domain}/s/?q={removeAndReplaceSpaces(search_string)}&page=0&orderby=99' 493 | tpb_url = url 494 | #print url 495 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 496 | table = None 497 | 498 | try: 499 | r = requests.get(url, headers=headers) 500 | soup = BeautifulSoup(r.content, "html.parser") 501 | table = soup.find("table", {"id": "searchResult"}) 502 | trs = table.findAll("tr") 503 | del trs[:1] 504 | 505 | results_tpb_condensed = [] 506 | #for tr in trs: 507 | for tr in trs[:limit]: 508 | tds = tr.findAll("td") 509 | 510 | res = {} 511 | link_name = tds[1].find("a", {"class": "detLink"}) 512 | res['name'] = link_name.contents[0].strip() 513 | res['link'] = link_name["href"] 514 | res['seeders'] = int(tds[2].contents[0]) 515 | res['leechers'] = int(tds[3].contents[0]) 516 | try: 517 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 518 | except ZeroDivisionError: 519 | res['ratio'] = 'inf' 520 | res['magnet'] = tds[1].find("img", {"alt": "Magnet link"}).parent['href'] 521 | res['size'] = str(tds[1].find("font").contents[0].split(',')[1].split(' ')[2].replace('\xa0', ' ')) 522 | 523 | results_tpb_condensed.append(res) 524 | except Exception as e: 525 | if quiet_mode == False: 526 | if table == None: 527 | print(colored.magenta("[PirateBay] Error : No results found")) 528 | else: 529 | print(colored.red("[PirateBay] Error : Unkown problem while searching")) 530 | print(colored.yellow('ERR_MSG : ' + str(e))) 531 | #table = None 532 | #print(f"Search results TBP: {results_tpb_condensed}") 533 | return results_tpb_condensed 534 | 535 | def searchPirateBay(search_string = defaultQuery, page = 0, order_by = ORDER_BY.UPLOADER, domain = 'thepiratebay.org', quiet_mode=False): 536 | """ 537 | Searches for the given string in The Pirate Bay. 538 | Returns a list of dictionaries with the information of each torrent. 539 | """ 540 | global tpb_working_domain, tpb_url 541 | baseURL = 'https://' + domain + '/s/?q=' 542 | url = baseURL + removeAndReplaceSpaces(search_string) + '&page=0&orderby=99' 543 | tpb_url = url 544 | #print url 545 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 546 | try: 547 | r = requests.get(url, headers=headers) 548 | soup = BeautifulSoup(r.content, "html.parser") 549 | table = soup.find("table", {"id": "searchResult"}) 550 | # print "TBP Response : \n" 551 | # print r.content 552 | except requests.exceptions.ConnectionError as e: 553 | #print e 554 | err_string = str(e).split(',')[2] 555 | #print err_string 556 | if 'Operation timed out' in err_string: 557 | if domain == 'thepiratebay.org': 558 | tpb_working_domain = alternate_domain ='piratebay.red' 559 | error_str = colored.yellow("[PirateBay] Error : Connection to ") + colored.magenta(domain) + colored.yellow(" timed out.\n") 560 | error_str += colored.yellow("Trying to connect via ") + colored.magenta(alternate_domain) + colored.yellow("...") 561 | if quiet_mode == False: 562 | print(error_str) 563 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 564 | elif domain == 'piratebay.red': 565 | error_str = colored.yellow("[PirateBay] Error : Connection to ") + colored.magenta(domain) + colored.yellow(" timed out.\n") 566 | error_str += colored.red("Exiting. Try connecting via a proxy...") 567 | if quiet_mode == False: 568 | print(error_str) 569 | table = None 570 | #sys.exit(1) 571 | elif 'Connection refused' in err_string: 572 | if domain == 'thepiratebay.org': 573 | tpb_working_domain = alternate_domain = 'piratebay.red' 574 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 575 | error_str += colored.red("Trying to connect via ") + (alternate_domain) + colored.red("...") 576 | if quiet_mode == False: 577 | print(error_str) 578 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 579 | elif domain == 'piratebay.red': 580 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 581 | error_str += colored.red("Exiting. Try connecting via a proxy...") 582 | if quiet_mode == False: 583 | print(error_str) 584 | table = None 585 | #sys.exit(1) 586 | elif 'failed to respond' in err_string: 587 | if domain == 'thepiratebay.org': 588 | tpb_working_domain = alternate_domain = 'piratebay.red' 589 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" is probably blocked.\n") 590 | error_str += colored.red("Trying to connect via ") + (alternate_domain) + colored.red("...") 591 | if quiet_mode == False: 592 | print(error_str) 593 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 594 | elif domain == 'piratebay.red': 595 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 596 | error_str += colored.red("Exiting. Try connecting via a proxy...") 597 | if quiet_mode == False: 598 | print(error_str) 599 | table = None 600 | #sys.exit(1) 601 | else: 602 | error_str = colored.red("[PirateBay] Unhandled Error : ") + colored.red(str(e)) + colored.red("\nExiting...") 603 | if quiet_mode == False: 604 | print(error_str) 605 | table = None 606 | #sys.exit(1) 607 | except TypeError as e: 608 | #print("Something's wrong...") 609 | table = None 610 | 611 | # print table 612 | if table == None: 613 | if domain == 'piratebay.red': 614 | error_string = str(colored.yellow('[PirateBay] Error : No results found. ')) + str(colored.magenta(domain)) + str(colored.yellow(' might be unreachable!')) 615 | if quiet_mode == False: 616 | print(error_string) 617 | return _parse_search_result_table(table, quiet_mode) 618 | else: 619 | tpb_working_domain = alternate_domain = 'piratebay.red' 620 | # print "!!!!" 621 | error_string = str(colored.yellow('[PirateBay] Error : No results found. ')) + str(colored.magenta(domain)) + str(colored.yellow(' might be unreachable!')) 622 | error_string += str(colored.yellow('\nTrying ')) + str(colored.magenta(alternate_domain)) + str(colored.yellow('...')) 623 | if quiet_mode == False: 624 | print (error_string) 625 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 626 | else: 627 | return _parse_search_result_table(table, quiet_mode=quiet_mode) 628 | 629 | def _parse_search_result_table(table, quiet_mode=False, limit=10): 630 | if table == None: 631 | results = [] 632 | return results 633 | trs = table.findAll("tr") 634 | del trs[:1] 635 | # print "\n'tr' tags within table : \n" 636 | # print trs 637 | results = [] 638 | error_detected_tpb = False 639 | index = 1 640 | for tr in trs[:limit]: 641 | #print index 642 | #print tr 643 | index += 1 644 | if(error_detected_tpb == False): 645 | results.append(_parse_search_result_table_row(tr)) 646 | else: 647 | error_string = '[PirateBay] Error : No results found' 648 | if quiet_mode == False: 649 | print(colored.yellow(error_string)) 650 | break 651 | return results 652 | 653 | def _parse_search_result_table_row(tr): 654 | global error_detected_tpb, tpb_working_domain 655 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 656 | 657 | res = {} 658 | tds = tr.findAll("td") 659 | #print tds 660 | 661 | link_name = tds[1].find("a", {"class": "detLink"}) 662 | #print "Link Name : " + str(link_name.contents) 663 | if link_name.contents == []: 664 | error_detected_tpb = True 665 | #print error_detected_tpb 666 | return {} 667 | else: 668 | res['name'] = link_name.contents[0].encode('utf-8').strip() 669 | res['link'] = link_name["href"].encode('utf-8') 670 | desc_string = tds[1].find("font").contents[0].encode('utf-8').replace(" ", " ") 671 | m = re.search(r"^Uploaded (Today|Y-day|\d\d-\d\d)\xc2\xa0(\d{4}|\d\d:\d\d), " + r"Size (\d+(?:.\d*)?\xc2\xa0(?:[KMG]iB))", desc_string) 672 | try : 673 | temp_size = str(m.group(3)).replace('\xc2\xa0', ' ') 674 | s1 = temp_size.split('.') 675 | #print s1 676 | try: 677 | s2 = s1[1].split(' ') 678 | except IndexError as e: # Special case where size is an integer (eg. s1 = 2 GiB), i.e, no decimal place 679 | #print 'Reached here' 680 | s1 = s1[0].split(' ') 681 | #print s1 682 | s2 = ['0'] 683 | s2.append(s1[1]) 684 | temp_size = s1[0] + '.0 ' + s1[1] 685 | if(len(s1[0]) == 4): 686 | res['size'] = s1[0] + s2[1] 687 | elif(len(s1[0]) == 3): 688 | res['size'] = s1[0] + '.' + s2[0][0] + " " + s2[1] 689 | else: 690 | res['size'] = temp_size 691 | except AttributeError as e: 692 | #print 'Reached here next' 693 | error_detected_tpb = True 694 | #print e 695 | #print "\nRegex misbehaving. Try running the script again!\n" 696 | return {} 697 | now = datetime.today() 698 | if re.match(r"\d{4}", m.group(2)) == None: 699 | hour =" " + m.group(2) 700 | if m.group(1) == "Today": 701 | res['time'] = datetime.strptime( 702 | now.strftime("%m-%d-%Y") + hour, 703 | "%m-%d-%Y %H:%M") 704 | elif m.group(1) == "Y-day": 705 | res['time'] = datetime.strptime( 706 | (now + timedelta(-1)).strftime("%m-%d-%Y") + hour, 707 | "%m-%d-%Y %H:%M") 708 | else: 709 | res['time'] = datetime.strptime( 710 | m.group(1) + "-" + str(now.year) + hour, 711 | "%m-%d-%Y %H:%M") 712 | else: 713 | res['time'] = datetime.strptime(m.group(1) + "-" + m.group(2), 714 | "%m-%d-%Y") 715 | res['seeders'] = int(tds[2].contents[0]) 716 | res['leechers'] = int(tds[3].contents[0]) 717 | try: 718 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 719 | except ZeroDivisionError: 720 | res['ratio'] = 'inf' 721 | res['magnet'] = tds[1].find("img", {"alt": "Magnet link"}).parent['href'] 722 | 723 | # Check if magnet link was found on this page, or if need to go one level deeper 724 | if res['magnet'] == res['link']: # Magnet link not found 725 | magnet_link_page = 'https://' + tpb_working_domain + res['link'] 726 | #print magnet_link_page 727 | try: 728 | magnet_req = requests.get(magnet_link_page, headers=headers) 729 | soup2 = BeautifulSoup(magnet_req.content, "html.parser") 730 | content = soup2.find_all(class_='download') 731 | res['magnet'] = content[0].contents[1].attrs['href'].encode('utf-8') 732 | except Exception as e: 733 | print(colored.red("[PirateBay] Error : Unkown problem while searching for magnet link")) 734 | print(colored.yellow('ERR_MSG : ' + str(e))) 735 | #print res 736 | return res 737 | 738 | def searchPirateBayWithAPI(search_string = defaultQuery, sort_by = SORT_BY_TBP.SEEDS_DESC, domain = 'tpbc.herokuapp.com', quiet_mode=False): 739 | global results_tpb_api, tpb_url 740 | base_url = 'https://' + domain 741 | url = base_url + '/search/' + removeAndReplaceSpaces(search_string) + '/?sort=' + sort_by 742 | tpb_url = url 743 | 744 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 745 | 746 | try: 747 | response = requests.get(url, headers=headers) 748 | response_json = json.loads(response.text) 749 | results_tpb_api = parse_results_tpb_api(response_json, quiet_mode=quiet_mode) 750 | except Exception as e: 751 | if quiet_mode == False : 752 | print(colored.red("[PirateBay] : Error while searching")) 753 | print(colored.yellow('ERR_MSG : ' + str(e))) 754 | #traceback.print_exc() 755 | 756 | # try: 757 | # results_tpb_api = parse_results_tpb_api(response_json) 758 | # except Exception, e: 759 | # print colored.red("[PirateBay] : Error while parsing search results.") 760 | # print colored.yellow('ERR_MSG : ' + str(e)) 761 | 762 | return results_tpb_api 763 | 764 | def parse_results_tpb_api(response_json, quiet_mode=False): 765 | #global results_tpb_api 766 | results_list = [] 767 | if response_json == []: 768 | if quiet_mode == False: 769 | error_string = '[PirateBay] Error : No results found' 770 | print(colored.magenta(error_string)) 771 | return [] 772 | else: 773 | for post in response_json: 774 | res = {} 775 | res['name'] = post['title'].encode('utf-8') 776 | #res['link'] = '' 777 | 778 | temp_size = humanize.naturalsize(post['size'], binary=True, format='%.2f') 779 | s1 = temp_size.split('.') 780 | if(len(s1[0]) == 4): 781 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.0f') 782 | else: 783 | res['size'] = temp_size 784 | #res['time'] = Implement later 785 | res['seeders'] = post['seeds'] 786 | res['leechers'] = post['leeches'] 787 | try: 788 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 789 | except ZeroDivisionError: 790 | res['ratio'] = 'inf' 791 | res['magnet'] = post['magnet'].encode('utf-8') 792 | results_list.append(res) 793 | 794 | return results_list 795 | 796 | def getQuery(): 797 | global query 798 | query = input('Enter search query : ') 799 | return query 800 | 801 | def print_top_results(limit=10): 802 | global results 803 | if results != [{}]: 804 | print('-------------------------------------------- ' + colored.green('PirateBay') + ' --------------------------------------------') 805 | print('{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6))) 806 | index = num_results_rarbg + 1 807 | for r in results[:limit]: 808 | print('{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(11), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8))) 809 | index = index + 1 810 | print("---------------------------------------------------------------------------------------------------") 811 | return index - 1 812 | 813 | def pretty_print_top_results_piratebay(limit=10): 814 | global results, num_results_rarbg 815 | table_piratebay = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 816 | no_str = str(colored.red('No')) 817 | name_str = str(colored.red('Torrent Name')) 818 | size_str = str(colored.red('Size')) 819 | seed_str = str(colored.red('S')) 820 | leech_str = str(colored.red('L')) 821 | ratio_str = str(colored.red('S/L')) 822 | table_piratebay.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 823 | 824 | print('\n\t\t\t\t\t\t' + colored.green('PirateBay')) 825 | # print results 826 | if results != [{}] and results != [] and results != None: 827 | index = num_results_rarbg + 1 828 | #print index 829 | #print len(results) 830 | for r in results[:limit]: 831 | try : 832 | #print index 833 | #print r 834 | table_piratebay.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 835 | index = index + 1 836 | except KeyError as e: 837 | # Fix error where {} is included in results and screws up numbering # 838 | if r != {}: 839 | print(r) 840 | print(e) 841 | table_piratebay.align[no_str] = 'l' 842 | table_piratebay.align[name_str] = 'l' 843 | table_piratebay.align[size_str] = 'r' 844 | table_piratebay.align[seed_str] = 'r' 845 | table_piratebay.align[leech_str] = 'r' 846 | table_piratebay.align[ratio_str] = 'r' 847 | print(table_piratebay) 848 | return index - 1 849 | else: 850 | table_piratebay.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 851 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 852 | print(table_piratebay) 853 | return num_results_rarbg 854 | 855 | def pretty_print_top_results_piratebay_api(limit=10): 856 | global results_tpb_api, num_results_rarbg 857 | table_piratebay = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 858 | no_str = str(colored.red('No')) 859 | name_str = str(colored.red('Torrent Name')) 860 | size_str = str(colored.red('Size')) 861 | seed_str = str(colored.red('S')) 862 | leech_str = str(colored.red('L')) 863 | ratio_str = str(colored.red('S/L')) 864 | table_piratebay.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 865 | 866 | print('\n\t\t\t\t\t\t' + colored.green('PirateBay')) 867 | if results_tpb_api != [] and results_tpb_api != None: 868 | index = num_results_rarbg + 1 869 | for r in results_tpb_api[:limit]: 870 | try : 871 | table_piratebay.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 872 | index = index + 1 873 | except KeyError as e: 874 | # Fix error where {} is included in results and screws up numbering # 875 | if r != {}: 876 | print(r) 877 | print(e) 878 | table_piratebay.align[no_str] = 'l' 879 | table_piratebay.align[name_str] = 'l' 880 | table_piratebay.align[size_str] = 'r' 881 | table_piratebay.align[seed_str] = 'r' 882 | table_piratebay.align[leech_str] = 'r' 883 | table_piratebay.align[ratio_str] = 'r' 884 | print(table_piratebay) 885 | return index - 1 886 | else: 887 | table_piratebay.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 888 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 889 | print(table_piratebay) 890 | return num_results_rarbg 891 | 892 | def switch(arg, tpb_api=False): 893 | global results, exit, defaultQuery, num_results, query, num_results_rarbg, results_rarbg, print_version, tpb_working_domain, results_tpb_api, num_results_tpb_api, results_1337x, num_results_1337x, rarbg_url, skytorrents_url, tpb_url, url_1337x 894 | if ('c' in arg) and ('s' not in arg) and ('z' not in arg): 895 | try: 896 | resNum = int(re.search(r'\d+', arg).group()) 897 | if resNum <= 0 or resNum > num_results_1337x: 898 | print('Invalid command!\n') 899 | else: 900 | if tpb_api == True: 901 | if resNum <= num_results_rarbg : 902 | mLink = results_rarbg[resNum-1]['magnet'] 903 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 904 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 905 | else: 906 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 907 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 908 | else: 909 | if resNum <= num_results_rarbg : 910 | mLink = results_rarbg[resNum-1]['magnet'] 911 | elif resNum > num_results_rarbg and resNum <= num_results: 912 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 913 | else: 914 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 915 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 916 | pyperclip.copy(str(mLink)) 917 | print('Magnet link copied to clipboard!') 918 | except AttributeError: 919 | print('Enter a valid torrent number as well!') 920 | elif ('cs' in arg) and ('z' not in arg): 921 | try: 922 | resNum = int(re.search(r'\d+', arg).group()) 923 | if resNum <= 0 or resNum > num_results_1337x: 924 | print('Invalid command!\n') 925 | else: 926 | if tpb_api == True: 927 | if resNum <= num_results_rarbg : 928 | mLink = results_rarbg[resNum-1]['magnet'] 929 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 930 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 931 | else: 932 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 933 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 934 | else: 935 | if resNum <= num_results_rarbg : 936 | mLink = results_rarbg[resNum-1]['magnet'] 937 | elif resNum > num_results_rarbg and resNum <= num_results: 938 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 939 | else: 940 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 941 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 942 | pyperclip.copy(str(mLink)) 943 | webbrowser.open('https://www.seedr.cc', new=2) 944 | print('Seedr.cc opened and Magnet link copied to clipboard!') 945 | except AttributeError: 946 | print('Enter a valid torrent number as well!') 947 | elif 'cz' in arg: 948 | try: 949 | resNum = int(re.search(r'\d+', arg).group()) 950 | if resNum <= 0 or resNum > num_results_1337x: 951 | print('Invalid command!\n') 952 | else: 953 | if tpb_api == True: 954 | if resNum <= num_results_rarbg : 955 | mLink = results_rarbg[resNum-1]['magnet'] 956 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 957 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 958 | else: 959 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 960 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 961 | else: 962 | if resNum <= num_results_rarbg : 963 | mLink = results_rarbg[resNum-1]['magnet'] 964 | elif resNum > num_results_rarbg and resNum <= num_results: 965 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 966 | else: 967 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 968 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 969 | pyperclip.copy(str(mLink)) 970 | webbrowser.open('https://zbigz.unihax.in/', new=2) 971 | print('zbigz opened and Magnet link copied to clipboard!') 972 | except AttributeError: 973 | print('Enter a valid torrent number as well!') 974 | elif 'm' in arg: 975 | try: 976 | resNum = int(re.search(r'\d+', arg).group()) 977 | if resNum <= 0 or resNum > num_results_1337x: 978 | print('Invalid command\n') 979 | else: 980 | if tpb_api == True: 981 | if resNum <= num_results_rarbg : 982 | mLink = results_rarbg[resNum-1]['magnet'] 983 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 984 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 985 | else: 986 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 987 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 988 | else: 989 | if resNum <= num_results_rarbg : 990 | mLink = results_rarbg[resNum-1]['magnet'] 991 | elif resNum > num_results_rarbg and resNum <= num_results: 992 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 993 | else: 994 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 995 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 996 | print("\nMagnet Link : \n" + mLink) 997 | except AttributeError: 998 | print('Enter a valid torrent number as well!') 999 | elif 'd' in arg: 1000 | try: 1001 | resNum = int(re.search(r'\d+', arg).group()) 1002 | if resNum <= 0 or resNum > num_results_1337x: 1003 | print('Invalid command!\n') 1004 | else: 1005 | if tpb_api == True: 1006 | if resNum <= num_results_rarbg : 1007 | mLink = results_rarbg[resNum-1]['magnet'] 1008 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 1009 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 1010 | else: 1011 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 1012 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 1013 | else: 1014 | if resNum <= num_results_rarbg : 1015 | mLink = results_rarbg[resNum-1]['magnet'] 1016 | elif resNum > num_results_rarbg and resNum <= num_results: 1017 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 1018 | else: 1019 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 1020 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 1021 | webbrowser.open(mLink, new=2) 1022 | print('Magnet link sent to default torrent client!') 1023 | except AttributeError: 1024 | print('Enter a valid torrent number as well!') 1025 | elif 'o' in arg: 1026 | try: 1027 | resNum = int(re.search(r'\d+', arg).group()) 1028 | #print("resNum : %d" % resNum) 1029 | if resNum <= 0 or resNum > num_results_1337x: 1030 | print('Invalid command!\n') 1031 | else: 1032 | if tpb_api == True: 1033 | if resNum <= num_results_rarbg : 1034 | tLink = results_rarbg[resNum-1]['link'] 1035 | #print("resNum(%d) <= num_results_rarbg(%d)" % (resNum, results_rarbg)) 1036 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 1037 | tLink = "https://" + tpb_working_domain + results_tpb_api[(resNum-1)-num_results_rarbg]['link'] 1038 | #print("resNum(%d) > num_results_rarbg(%d) and resNum(%d) <= (num_results_rarbg(%d)+num_results(%d))" % (resNum, num_results_rarbg, resNum, num_results_rarbg, num_results)) 1039 | else: 1040 | #tLink = results_sky[(resNum-1)-num_results_tpb_api]['link'] 1041 | #print("Reached SkyTorrents. Link : %s" % tLink) 1042 | tLink = results_1337x[(resNum-1)-num_results_tpb_api]['link'] 1043 | else: 1044 | if resNum <= num_results_rarbg : 1045 | tLink = results_rarbg[resNum-1]['link'] 1046 | elif resNum > num_results_rarbg and resNum <= num_results: 1047 | #tLink = "https://" + tpb_working_domain + results[(resNum-1)-num_results_rarbg]['link'] 1048 | tLink = results[(resNum-1)-num_results_rarbg]['link'] 1049 | else: 1050 | #tLink = results_sky[(resNum-1)-num_results]['link'] 1051 | tLink = results_1337x[(resNum-1)-num_results]['link'] 1052 | #webbrowser.get('chrome').open(tLink, new=2) 1053 | webbrowser.open(tLink, new=2) 1054 | print('Torrent page opened in default browser!') 1055 | except AttributeError: 1056 | print('Enter a valid torrent number as well!') 1057 | elif arg == 'u': 1058 | print(colored.green('[RARBG] URL') + ' : ' + rarbg_url) 1059 | print(colored.green('[PirateBay] URL') + ' : ' + tpb_url) 1060 | print(colored.green('[SkyTorrents] URL') + ' : ' + url_1337x) 1061 | elif arg == 'h': 1062 | print_menu(0) 1063 | elif arg == 'q': 1064 | exit = True 1065 | elif 'p' in arg: 1066 | try: 1067 | resNum = int(re.search(r'\d+', arg).group()) 1068 | if resNum == 0: 1069 | printTopResults(resNum) 1070 | elif resNum == 1: 1071 | printTopResults(resNum) 1072 | else: 1073 | print("Not a valid option!") 1074 | except AttributeError: 1075 | if arg == 'p': 1076 | printTopResults(print_version) 1077 | else: 1078 | print("Not a valid command!") 1079 | elif arg == 's': 1080 | query = input("Enter query : ") 1081 | if query == '': 1082 | query = defaultQuery 1083 | searchAllSites(query, force_search=True) 1084 | printTopResults(print_version) 1085 | elif arg == 'r': 1086 | searchAllSites(query) 1087 | printTopResults(print_version) 1088 | else: 1089 | print('Invalid command!\n') 1090 | 1091 | def print_menu(arg=0): 1092 | if arg == 0: 1093 | print(''' 1094 | ------ Help Menu ------- 1095 | Available Commands : 1096 | 1. m - Print magnet link of selected torrent 1097 | 2. c - Copy magnet link of selected torrent to clipboard 1098 | 3. d - Download torrent using default torrent client 1099 | 4. o - Open the torrent page of the selected torrent in the default browser 1100 | 5. cs - Copy magnet link and open seedr.cc 1101 | 6. cz - Copy magnet link and open zbigz 1102 | 7. p[optional:] - Print top 10 results from each website for the given query 1103 | : [{default : 1}, {0 : Print formatted result}, {1 : Pretty print results}] 1104 | 8. s - Enter a new query to search for over all avilable torrent websites 1105 | 9. r - Repeat last search (with same query) 1106 | ------------------------''') 1107 | elif arg == 1: 1108 | print(''' 1109 | Enter 'q' to exit and 'h' to see all available commands. 1110 | ''') 1111 | 1112 | def searchAllSites(query=defaultQuery, force_search=False, quiet_mode=False): 1113 | global results, results_rarbg, results_sky, results_tpb_api, tpb_retries, max_tpb_retries, tpb_working_domain, results_tpb_condensed, results_1337x 1114 | #results = searchPirateBay(query, domain='pirateproxy.cam') 1115 | #results = searchPirateBay(query) 1116 | 1117 | if force_search == True: 1118 | results_rarbg = None 1119 | results_tpb_api = None 1120 | results_sky = None 1121 | results_1337x = None 1122 | results = None 1123 | results_tpb_condensed = None 1124 | 1125 | ## Search RARBG 1126 | # print(colored.magenta("Searching RARBG..."), end='') 1127 | # if results_rarbg == None or results_rarbg == []: 1128 | # results_rarbg = searchRarbg(query, quiet_mode=quiet_mode) 1129 | # print(colored.green("Done.")) 1130 | results_rarbg = [] 1131 | 1132 | # if results_tpb_api == None or results_tpb_api == []: 1133 | # if tpb_retries < max_tpb_retries: 1134 | # results_tpb_api = searchPirateBayWithAPI(query, quiet_mode=quiet_mode) 1135 | # results = results_tpb_api 1136 | # tpb_retries += 1 1137 | # else: 1138 | # results_tpb_api = searchPirateBay(query, quiet_mode=quiet_mode) 1139 | # results = results_tpb_api 1140 | 1141 | # print 'P searching...' 1142 | # else: 1143 | # print 'P not searching...' 1144 | # print 'Results P : ' 1145 | # print results_tpb_api 1146 | 1147 | # if results == None or results == []: 1148 | # tpb_working_domain = 'thepiratebay.zone' 1149 | # results = searchPirateBay(query, quiet_mode=quiet_mode, domain=tpb_working_domain) 1150 | # # #print results 1151 | 1152 | print(colored.magenta("Searching TBP..."), end='') 1153 | if results_tpb_condensed == None or results_tpb_condensed == []: 1154 | tpb_working_domain = 'thepiratebay.zone' 1155 | results_tpb_condensed = searchPirateBayCondensed(search_string=query, domain=tpb_working_domain, quiet_mode=quiet_mode) 1156 | results = results_tpb_condensed 1157 | print(colored.green("Done.")) 1158 | # print('P searching...') 1159 | # else: 1160 | # print('P not searching...') 1161 | # print(f'Results P: {results_tpb_condensed}') 1162 | 1163 | # if results_sky == None or results_sky == []: 1164 | # results_sky = searchSkyTorrents(query, quiet_mode=quiet_mode) 1165 | # # print 'S searching...' 1166 | # else: 1167 | # print 'S not searching...' 1168 | # print 'Results S : ' 1169 | # print results_sky 1170 | 1171 | print(colored.magenta("Searching 1337x..."), end='') 1172 | if results_1337x == None or results_1337x == []: 1173 | results_1337x = search1337x(query, quiet_mode=quiet_mode) 1174 | print(colored.green("Done.")) 1175 | 1176 | def printCombinedTopResults(): 1177 | global num_results, num_results_rarbg 1178 | num_results_rarbg = print_top_results_rarbg(10) 1179 | num_results = print_top_results(10) 1180 | 1181 | def prettyPrintCombinedTopResults(): 1182 | global num_results, num_results_rarbg, num_results_sky, num_results_tpb_api, num_results_1337x 1183 | 1184 | #num_results_rarbg = pretty_print_top_results_rarbg(10) 1185 | num_results_rarbg = 0 1186 | 1187 | num_results = pretty_print_top_results_piratebay(10) 1188 | #num_results_tpb_api = pretty_print_top_results_piratebay_api(10) 1189 | #num_results = num_results_tpb_api 1190 | 1191 | #num_results_sky = pretty_print_top_results_skytorrents(10) 1192 | num_results_1337x = pretty_print_top_results_1337x(10) 1193 | 1194 | def printTopResults(version=1): 1195 | if version == 0: 1196 | printCombinedTopResults() 1197 | elif version == 1: 1198 | prettyPrintCombinedTopResults() 1199 | 1200 | def convertListJSONToPureJSON(result_list): 1201 | # Sample JSON Structure 1202 | # { 1203 | # 'count' : x, ### Gives total number of results 1204 | # 'results' : {'0' : {...}, {'1' : {...}, ...} ### Stores actual results 1205 | # } 1206 | result_json = {'count' : '0'} 1207 | index = 0 1208 | 1209 | if result_list != [] and result_list != None: # Create a key 'results' only if there are some results 1210 | result_json['results'] = {} 1211 | rj_results = result_json['results'] 1212 | 1213 | for item in result_list: 1214 | rj_results[str(index)] = result_list[index] 1215 | index += 1 1216 | result_json['count'] = str(index) # Update total number of results 1217 | 1218 | return result_json 1219 | 1220 | def printResultsQuietly(): 1221 | global results_rarbg, results_tpb_api, results_sky, results_1337x 1222 | 1223 | results_json_rarbg = convertListJSONToPureJSON(results_rarbg) 1224 | results_json_tpb = convertListJSONToPureJSON(results_tpb_api) 1225 | #results_json_sky = convertListJSONToPureJSON(results_sky) 1226 | results_json_1337x = convertListJSONToPureJSON(results_1337x) 1227 | #print results_json_tpb 1228 | 1229 | combined_json_results = {} 1230 | combined_json_results['rarbg'] = results_json_rarbg 1231 | combined_json_results['tpb'] = results_json_tpb 1232 | #combined_json_results['sky'] = results_json_sky 1233 | combined_json_results['1337x'] = results_json_1337x 1234 | 1235 | print(combined_json_results) 1236 | 1237 | def generateAppID(version=-1): 1238 | if version == 0: # Product of 3 random numbers 1239 | x, y, z = random.randint(1, 100), random.randint(1, 100), random.randint(1, 100) 1240 | app_id = x * y * z 1241 | else : # Hash current epoch time 1242 | epoch_time = time.time() 1243 | app_id = hash(epoch_time) 1244 | return app_id 1245 | 1246 | if __name__ == '__main__': 1247 | # initiate the parser 1248 | parser = argparse.ArgumentParser() 1249 | 1250 | # add arguments 1251 | parser.add_argument("query", help="Specify the search query", nargs='+', default=defaultQuery) 1252 | parser.add_argument('-q', '--quiet', help='Print output of search without any additional options', default=False, action='store_true') 1253 | 1254 | # read arguments from the command line 1255 | args = parser.parse_args() 1256 | 1257 | if args.query: 1258 | #print("The query is : %s\n" % (' '.join(args.query))) 1259 | print_version = 1 1260 | app_id = generateAppID() 1261 | query = ' '.join(args.query) # converts args from list to string 1262 | else: 1263 | print("Please enter a valid query.") 1264 | sys.exit(0) 1265 | 1266 | if args.quiet: # Continue in non-interactive mode 1267 | #print("Result will be printed quiety...") 1268 | searchAllSites(query, quiet_mode=True) 1269 | printResultsQuietly() 1270 | else: # Continue in interactive mode 1271 | searchAllSites(query) # quiet_mode is off by default 1272 | printTopResults(print_version) 1273 | 1274 | exit = False 1275 | while(exit != True): 1276 | print_menu(1) 1277 | choice = input("Enter command : ") 1278 | switch(choice, tpb_api=False) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bs4 2 | requests 3 | clint 4 | pyperclip 5 | humanize 6 | VeryPrettyTable 7 | cfscrape -------------------------------------------------------------------------------- /torrent-hound.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # @author : Yashovardhan Sharma 3 | # @github : github.com/baddymaster 4 | 5 | # 6 | # Copyright (C) <2023> 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published 10 | # by the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see . 20 | 21 | from __future__ import print_function 22 | from builtins import input 23 | from builtins import str 24 | from bs4 import BeautifulSoup 25 | from datetime import datetime, timedelta 26 | from clint.textui import colored 27 | from veryprettytable import VeryPrettyTable 28 | import requests 29 | import re 30 | import sys 31 | import pyperclip 32 | import webbrowser 33 | import json 34 | import humanize 35 | import traceback 36 | import random 37 | import time 38 | import argparse 39 | import traceback 40 | 41 | defaultQuery, query = 'jason bourne', '' 42 | results_sky = None 43 | results_tpb_condensed = None 44 | results_tpb_api, num_results_tpb_api = None, 0 45 | results_1337x = None 46 | results, results_rarbg, exit, error_detected_rarbg, error_detected_tpb = None, None, None, None, None 47 | num_results, num_results_rarbg, num_results_sky, num_results_1337x, print_version = 0, 0, 0, 0, 1 48 | auth_token = 'None' 49 | app_id = 'None' 50 | tpb_working_domain = 'tpb.tw' 51 | rarbg_url, skytorrents_url, tpb_url, url_1337x = '', '', '', '' 52 | tpb_retries, max_tpb_retries = 0, 3 53 | 54 | def enum(**enums): 55 | """ 56 | Lets define enums 57 | """ 58 | return type('Enum', (), enums) 59 | 60 | ORDER_BY = enum(NAME = 1, 61 | SIZE = 3, 62 | UPLOADER = 5, 63 | SEEDERS = 7, 64 | LEECHERS = 9, 65 | TYPE = 13, 66 | UPLOADED = 99) 67 | 68 | SORT_BY_TBP = enum(NAME = 'title_asc', 69 | NAME_DESC = 'title_desc', 70 | SEEDS = 'seeds_asc', 71 | SEEDS_DESC = 'seeds_desc', 72 | LEECHERS = 'leeches_asc', 73 | LEECHERS_DESC = 'leeches_desc', 74 | MOST_RECENT = 'time_desc', 75 | OLDEST = 'time_asc', 76 | UPLOADER = 'uploader_asc', 77 | UPLOADER_DESC = 'uploader_desc', 78 | SIZE = 'size_asc', 79 | SIZE_DESC = 'size_desc', 80 | FILE_TYPE = 'category_asc', 81 | FILE_TYPE_DESC = 'category_desc') 82 | 83 | ORDER_BY_SKY = enum(RELEVANCE = 'ss', 84 | SEEDS_DESC = 'ed', 85 | SEEDS_ASC = 'ea', 86 | PEERS_DESC = 'pd', 87 | PEERS_ASC = 'pa', 88 | SIZE_DESC = 'sd', 89 | SIZE_ASC = 'sa', 90 | NEWEST = 'ad', 91 | OLDEST = 'aa') 92 | 93 | def generateNewTorrentAPIToken(error=False, quiet_mode=False): 94 | global auth_token, error_detected_rarbg, app_id 95 | 96 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 97 | headers_safari = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15'} 98 | refresh_url = 'https://torrentapi.org/pubapi_v2.php?get_token=get_token&app_id=' + str(app_id) 99 | 100 | #print(f"App ID: {app_id}") 101 | #print(f"Token Refresh URL: {refresh_url}") 102 | try: 103 | r = requests.get(refresh_url, headers=headers_safari) 104 | if(str(r).split()[1][1:4] != '200'): 105 | if quiet_mode == False: 106 | print(colored.red("HTTP Response Error : %s" % str(r))) 107 | error_detected_rarbg = True 108 | return error_detected_rarbg 109 | 110 | auth_token = json.loads(r.text)['token'] 111 | #print(f"Auth Token: {auth_token}") 112 | 113 | if error != False: 114 | success_string = '[RARBG] Success : Generated new token! ' 115 | if quiet_mode == False: 116 | print(colored.blue(success_string)) 117 | except requests.exceptions.ConnectionError as e: 118 | err_string = str(e).split(',')[0] 119 | if 'Connection aborted' in err_string: 120 | if quiet_mode == False: 121 | print(colored.red("Server cannot be reached. Check Internet connectivity!")) 122 | #sys.exit(1) 123 | 124 | #except SysCallError, e: 125 | # print colored.red("SysCallError for RARBG search. Fix?") 126 | 127 | def searchRarbg(search_string=defaultQuery, quiet_mode=False): 128 | global auth_token, results_rarbg, error_detected_rarbg, app_id, rarbg_url 129 | # API Documentaion : https://torrentapi.org/apidocs_v2.txt 130 | # https://torrentapi.org/pubapi_v2.php?mode=search&search_string=Suits%20S06E10&format=json_extended&ranked=0&token=7dib9orxpa&app_id=0 131 | # echo 'torrent-hound' | shasum -a 512 132 | generateNewTorrentAPIToken(quiet_mode=quiet_mode) 133 | #print(f"Auth Token: {auth_token}") 134 | if error_detected_rarbg == True: 135 | #print "Error detected!\n" 136 | return results_rarbg 137 | 138 | #print(f"Auth token: {auth_token.decode('utf-8')}\n") 139 | search_string = search_string.replace(" ", "%20") 140 | base_url = 'https://torrentapi.org/pubapi_v2.php?' 141 | new_token = 'get_token=get_token&app_id=' + str(app_id) 142 | search_criteria = 'mode=search&search_string=' + search_string + "&" 143 | options = 'format=json_extended&ranked=0&token=' + str(auth_token) + '&app_id=' + str(app_id) 144 | url = base_url + search_criteria + options 145 | rarbg_url = url 146 | #print(f"RARBG Search URL: {url}") 147 | 148 | headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0'} 149 | # User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15 150 | headers_safari = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15'} 151 | 152 | try: 153 | response = requests.get(url, headers=headers_safari) 154 | #print(f"Response: {response}") 155 | rt = response.text 156 | #print(f"Response Text: {rt}\n") 157 | response_json = json.loads(rt) 158 | #print response_json 159 | except Exception as e: 160 | if quiet_mode == False: 161 | status_code = str(response).split()[1].strip('<[]>') 162 | if status_code == '429': # Too Many Requests 163 | print(colored.yellow(' : Too Many Requests. Please try again after a while!')) 164 | print(colored.red('[RARBG] Error : ' + str(e))) 165 | else: 166 | print(colored.red('[RARBG] Error : ' + str(e))) 167 | #traceback.print_exc() 168 | 169 | return [] 170 | results_rarbg = [] 171 | 172 | error_detected_rarbg = checkResponseForErrors(response_json, quiet_mode=quiet_mode) 173 | if(error_detected_rarbg == False): 174 | results_rarbg = parse_results_rarbg(response_json, quiet_mode=quiet_mode) 175 | return results_rarbg 176 | 177 | def checkResponseForErrors(response_json, quiet_mode=False): 178 | global results_rarbg, error_detected_rarbg, query, auth_token 179 | search_string = query.replace(" ", "%20") 180 | 181 | if 'error_code' in response_json: 182 | #print 'In function' 183 | error_string = '[RARBG] Error : ' + response_json['error'] 184 | if quiet_mode == False: 185 | print(colored.magenta(error_string)) 186 | 187 | if response_json['error_code'] == 4: 188 | generateNewTorrentAPIToken(error=True) 189 | results_rarbg = searchRarbg(search_string) 190 | # elif response_json['error_code'] == 20: 191 | # print "No results found. Try different keywords!\n" 192 | return True #Some error detected 193 | else: 194 | return False #No errors. Print results 195 | 196 | def parse_results_rarbg(response_json, quiet_mode=False, limit=10): 197 | global results_rarbg 198 | if error_detected_rarbg == False: 199 | #print len(response_json['torrent_results']) 200 | for post in response_json['torrent_results'][:limit]: 201 | res = {} 202 | res['name'] = post['title'] 203 | res['link'] = post['info_page'] 204 | 205 | temp_size = humanize.naturalsize(post['size'], binary=True, format='%.2f') 206 | s1 = temp_size.split('.') 207 | if(len(s1[0]) == 4): 208 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.0f') 209 | elif(len(s1[1]) == 3): 210 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.1f') 211 | else: 212 | res['size'] = temp_size 213 | #res['time'] = Implement later 214 | res['seeders'] = post['seeders'] 215 | res['leechers'] = post['leechers'] 216 | try: 217 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 218 | except ZeroDivisionError: 219 | res['ratio'] = 'inf' 220 | res['magnet'] = post['download'] 221 | results_rarbg.append(res) 222 | else: 223 | if quiet_mode == False: 224 | print("----------- " + colored.green('RARBG') + " -----------") 225 | print(" [No results found] ") 226 | return [] 227 | return results_rarbg 228 | 229 | def print_top_results_rarbg(limit=10): 230 | global results_rarbg 231 | if results_rarbg != [] and results_rarbg != None: 232 | print('\n---------------------------------------------- ' + colored.green('RARBG') + ' ----------------------------------------------') 233 | print('{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6))) 234 | index = 1 235 | for r in results_rarbg[:limit]: 236 | print('{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(10), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8))) 237 | index = index + 1 238 | print("---------------------------------------------------------------------------------------------------") 239 | return index - 1 240 | 241 | def pretty_print_top_results_rarbg(limit=10): 242 | global results_rarbg 243 | table_rarbg = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 244 | no_str = str(colored.red('No')) 245 | name_str = str(colored.red('Torrent Name')) 246 | size_str = str(colored.red('Size')) 247 | seed_str = str(colored.red('S')) 248 | leech_str = str(colored.red('L')) 249 | ratio_str = str(colored.red('S/L')) 250 | table_rarbg.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 251 | 252 | print('\n\t\t\t\t\t\t' + colored.green('RARBG')) 253 | if (results_rarbg != []) and (results_rarbg != None): 254 | #print 'Empty table' 255 | #print '{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6)) 256 | index = 1 257 | for r in results_rarbg[:limit]: 258 | table_rarbg.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 259 | #print '{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(10), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8)) 260 | index = index + 1 261 | table_rarbg.align[no_str] = 'l' 262 | table_rarbg.align[name_str] = 'l' 263 | table_rarbg.align[size_str] = 'r' 264 | table_rarbg.align[seed_str] = 'r' 265 | table_rarbg.align[leech_str] = 'r' 266 | table_rarbg.align[ratio_str] = 'r' 267 | print(table_rarbg) 268 | return index - 1 269 | else: 270 | table_rarbg.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 271 | table_rarbg.align[colored.red('Torrent Name')] = 'l' 272 | print(table_rarbg) 273 | return 0 274 | 275 | def extract_magnet_link_1337x(url): 276 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 277 | response = requests.get(url, headers=headers) 278 | soup = BeautifulSoup(response.content, 'html.parser') 279 | magnet_link = soup.find('a', href=lambda href: href and href.startswith("magnet:")) 280 | if magnet_link: 281 | return magnet_link['href'] 282 | else: 283 | return None 284 | 285 | def search1337x(search_string=defaultQuery, domain='1337x.to', quiet_mode=False, limit=10): 286 | global results_1337x, url_1337x 287 | 288 | query = removeAndReplaceSpaces(search_string) 289 | page_no = 1 290 | baseURL = f'https://{domain}' 291 | url = f'{baseURL}/search/{query}/{page_no}/' 292 | url_1337x = url 293 | 294 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 295 | response = requests.get(url, headers=headers) 296 | soup = BeautifulSoup(response.text, 'html.parser') 297 | results_1337x = [] 298 | 299 | try: 300 | table = soup.find('table', {'class': 'table-list'}) 301 | rows = table.tbody.find_all('tr') 302 | for row in rows[:limit]: 303 | row_data = {} 304 | name_col = row.find('td', {'class': 'coll-1 name'}) 305 | row_data['name'] = name_col.a.next_sibling.text 306 | row_data['link'] = baseURL + name_col.a.next_sibling['href'] 307 | row_data['seeders'] = int(row.find('td', {'class': 'coll-2 seeds'}).text.strip()) 308 | row_data['leechers'] = int(row.find('td', {'class': 'coll-3 leeches'}).text.strip()) 309 | try: 310 | row_data['ratio'] = format( (float(row_data['seeders'])/float(row_data['leechers'])), '.1f' ) 311 | except ZeroDivisionError: 312 | row_data['ratio'] = 'inf' 313 | row_data['time'] = row.find('td', {'class': 'coll-date'}).text.strip() 314 | size_col = row.find('td', {'class': 'coll-4'}) 315 | if size_col: 316 | row_data['size'] = size_col.contents[0].strip() 317 | else: 318 | row_data['size'] = '' 319 | # uploader_col = row.find('td', {'class': 'coll-5'}) 320 | # if uploader_col: 321 | # row_data['uploader'] = uploader_col.contents[0].text.strip() 322 | # else: 323 | # row_data['uploader'] = '' 324 | row_data['magnet'] = extract_magnet_link_1337x(row_data['link']) 325 | results_1337x.append(row_data) 326 | except AttributeError as e: 327 | print(colored.magenta("[1337x] Error : No results found")) 328 | return results_1337x 329 | 330 | def pretty_print_top_results_1337x(limit=10): 331 | global results_1337x, num_results_tpb_api, num_results 332 | table_1337x = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 333 | no_str = str(colored.red('No')) 334 | name_str = str(colored.red('Torrent Name')) 335 | size_str = str(colored.red('Size')) 336 | seed_str = str(colored.red('S')) 337 | leech_str = str(colored.red('L')) 338 | ratio_str = str(colored.red('S/L')) 339 | table_1337x.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 340 | 341 | #print '\n\t\t\t\t\t\t' + '+-----------+' 342 | #print '\t\t\t\t\t\t| ' + colored.green('PirateBay') + ' |' 343 | print('\n\t\t\t\t\t\t' + colored.green('1337x')) 344 | # print results 345 | if results_1337x != [{}] and results_1337x != [] and results_1337x != None: 346 | #index = num_results_tpb_api + 1 # Index after TBP API 347 | index = num_results + 1 # Index after TBP regular 348 | for r in results_1337x[:limit]: 349 | try : 350 | table_1337x.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 351 | index = index + 1 352 | except KeyError as e: 353 | # Fix error where {} is included in results and screws up numbering # 354 | if r != {}: 355 | print(r) 356 | print(e) 357 | table_1337x.align[no_str] = 'l' 358 | table_1337x.align[name_str] = 'l' 359 | table_1337x.align[size_str] = 'r' 360 | table_1337x.align[seed_str] = 'r' 361 | table_1337x.align[leech_str] = 'r' 362 | table_1337x.align[ratio_str] = 'r' 363 | print(table_1337x) 364 | return index - 1 365 | else: 366 | table_1337x.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 367 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 368 | print(table_1337x) 369 | return num_results 370 | 371 | def searchSkyTorrents(search_string=defaultQuery, domain='skytorrents.lol', order_by=ORDER_BY_SKY.RELEVANCE, quiet_mode=False, limit=10): 372 | global results_sky, skytorrents_url 373 | search_string = removeAndReplaceSpaces(search_string) 374 | baseURL = 'https://' + domain 375 | url = baseURL + '/?query=' + search_string 376 | skytorrents_url = url 377 | #url = baseURL + '/search/all/' + order_by + '/1/?l=en-us&q=' + search_string 378 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 379 | tbody = None 380 | #headers = {'User-Agent': 'Mozilla/5.0'} 381 | try: 382 | r = requests.get(url, headers=headers) 383 | soup = BeautifulSoup(r.content, "html.parser") 384 | #print soup 385 | tbody = soup.find('tbody') 386 | results_sky = [] 387 | 388 | trows = tbody.findAll("tr") 389 | #print len(trows) 390 | for trow in trows[:limit]: 391 | res = {} 392 | tds = trow.findAll("td") 393 | #tds[0] -> Name, Magnet, Link 394 | res['name'] = tds[0].findAll("a")[0].contents[0] 395 | res['link'] = baseURL + '/' + tds[0].findAll("a")[0].attrs['href'] 396 | 397 | if tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_upm.png' and tds[0].findAll("img")[1].attrs['src'] == '/files/thumb_downm.png': 398 | # Both upvotes and downvotes found 399 | res['up'] = '{:+}'.format(int(tds[0].contents[2])) 400 | res['down'] = '{:+}'.format(int(tds[0].contents[4])) 401 | elif tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_upm.png': 402 | # Only upvotes, no downvotes found 403 | res['up'] = '{:+}'.format(int(tds[0].contents[2])) 404 | res['down'] = '0' 405 | elif tds[0].findAll("img")[0].attrs['src'] == '/files/thumb_downm.png': 406 | # Only downvotes, no upvotes found 407 | res['up'] = '0' 408 | res['down'] = '{:+}'.format(int(tds[0].contents[2])) 409 | else: 410 | # No upvotes or downvotes found 411 | res['up'] = '0' 412 | res['down'] = '0' 413 | 414 | res['magnet'] = tds[0].findAll("a")[2].attrs['href'] 415 | #tds[1] -> Size 416 | res['size'] = tds[1].contents[0].encode('utf-8') 417 | #tds[2] -> No. of files 418 | # res['num_files'] = tds[0].contents[0].encode('utf-8') 419 | #tds[3] -> Date added 420 | # res['date'] = tds[3].contents[0].encode('utf-8') 421 | #tds[4] -> Seeders 422 | res['seeders'] = tds[4].contents[0].replace(',', '') 423 | #tds[5] -> Leechers 424 | res['leechers'] = tds[5].contents[0].replace(',', '') 425 | try: 426 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 427 | except ZeroDivisionError: 428 | res['ratio'] = 'inf' 429 | results_sky.append(res) 430 | 431 | except Exception as e: 432 | if quiet_mode == False: 433 | if tbody == None: 434 | print(colored.magenta("[SkyTorrents] Error : No results found")) 435 | else: 436 | print(colored.red("[SkyTorrents] Error : Unkown problem while searching")) 437 | print(colored.yellow('ERR_MSG : ' + str(e))) 438 | #traceback.print_exc() 439 | 440 | return results_sky 441 | 442 | def removeAndReplaceSpaces(string): 443 | if string[0] == " ": 444 | string = string[1:] 445 | return string.replace(" ", "+") 446 | 447 | def pretty_print_top_results_skytorrents(limit=10): 448 | global results_sky, num_results_tpb_api, num_results 449 | table_skytorrents = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 450 | no_str = str(colored.red('No')) 451 | name_str = str(colored.red('Torrent Name')) 452 | size_str = str(colored.red('Size')) 453 | seed_str = str(colored.red('S')) 454 | leech_str = str(colored.red('L')) 455 | ratio_str = str(colored.red('S/L')) 456 | votes_str = str(colored.red('Votes')) 457 | table_skytorrents.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str, votes_str] 458 | 459 | #print '\n\t\t\t\t\t\t' + '+-----------+' 460 | #print '\t\t\t\t\t\t| ' + colored.green('PirateBay') + ' |' 461 | print('\n\t\t\t\t\t\t' + colored.green('Sky Torrents')) 462 | # print results 463 | if results_sky != [{}] and results_sky != [] and results_sky != None: 464 | #index = num_results_tpb_api + 1 465 | index = num_results + 1 466 | for r in results_sky[:limit]: 467 | try : 468 | table_skytorrents.add_row([index, r['name'][:57], r['size'].decode('utf-8'), r['seeders'], r['leechers'], r['ratio'], (r['up'] + '/' + r['down'])]) 469 | index = index + 1 470 | except KeyError as e: 471 | # Fix error where {} is included in results and screws up numbering # 472 | if r != {}: 473 | print(r) 474 | print(e) 475 | table_skytorrents.align[no_str] = 'l' 476 | table_skytorrents.align[name_str] = 'l' 477 | table_skytorrents.align[size_str] = 'r' 478 | table_skytorrents.align[seed_str] = 'r' 479 | table_skytorrents.align[leech_str] = 'r' 480 | table_skytorrents.align[ratio_str] = 'r' 481 | table_skytorrents.align[votes_str] = 'c' 482 | print(table_skytorrents) 483 | return index - 1 484 | else: 485 | table_skytorrents.add_row(["Null", "Null", "Null", "Null", "Null", "Null", "Null"]) 486 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 487 | print(table_skytorrents) 488 | return num_results 489 | 490 | def searchPirateBayCondensed(search_string=defaultQuery, page=0, order_by=ORDER_BY.SEEDERS, domain='thepiratebay.org', quiet_mode=False, limit=10): 491 | global tpb_working_domain, tpb_url, results_tpb_condensed 492 | url = f'https://{tpb_working_domain}/s/?q={removeAndReplaceSpaces(search_string)}&page=0&orderby=99' 493 | tpb_url = url 494 | #print url 495 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 496 | table = None 497 | 498 | try: 499 | r = requests.get(url, headers=headers) 500 | soup = BeautifulSoup(r.content, "html.parser") 501 | table = soup.find("table", {"id": "searchResult"}) 502 | trs = table.findAll("tr") 503 | del trs[:1] 504 | 505 | results_tpb_condensed = [] 506 | #for tr in trs: 507 | for tr in trs[:limit]: 508 | tds = tr.findAll("td") 509 | 510 | res = {} 511 | link_name = tds[1].find("a", {"class": "detLink"}) 512 | res['name'] = link_name.contents[0].strip() 513 | res['link'] = link_name["href"] 514 | res['seeders'] = int(tds[2].contents[0]) 515 | res['leechers'] = int(tds[3].contents[0]) 516 | try: 517 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 518 | except ZeroDivisionError: 519 | res['ratio'] = 'inf' 520 | res['magnet'] = tds[1].find("img", {"alt": "Magnet link"}).parent['href'] 521 | res['size'] = str(tds[1].find("font").contents[0].split(',')[1].split(' ')[2].replace('\xa0', ' ')) 522 | 523 | results_tpb_condensed.append(res) 524 | except Exception as e: 525 | if quiet_mode == False: 526 | if table == None: 527 | print(colored.magenta("[PirateBay] Error : No results found")) 528 | else: 529 | print(colored.red("[PirateBay] Error : Unkown problem while searching")) 530 | print(colored.yellow('ERR_MSG : ' + str(e))) 531 | #table = None 532 | #print(f"Search results TBP: {results_tpb_condensed}") 533 | return results_tpb_condensed 534 | 535 | def searchPirateBay(search_string = defaultQuery, page = 0, order_by = ORDER_BY.UPLOADER, domain = 'thepiratebay.org', quiet_mode=False): 536 | """ 537 | Searches for the given string in The Pirate Bay. 538 | Returns a list of dictionaries with the information of each torrent. 539 | """ 540 | global tpb_working_domain, tpb_url 541 | baseURL = 'https://' + domain + '/s/?q=' 542 | url = baseURL + removeAndReplaceSpaces(search_string) + '&page=0&orderby=99' 543 | tpb_url = url 544 | #print url 545 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 546 | try: 547 | r = requests.get(url, headers=headers) 548 | soup = BeautifulSoup(r.content, "html.parser") 549 | table = soup.find("table", {"id": "searchResult"}) 550 | # print "TBP Response : \n" 551 | # print r.content 552 | except requests.exceptions.ConnectionError as e: 553 | #print e 554 | err_string = str(e).split(',')[2] 555 | #print err_string 556 | if 'Operation timed out' in err_string: 557 | if domain == 'thepiratebay.org': 558 | tpb_working_domain = alternate_domain ='piratebay.red' 559 | error_str = colored.yellow("[PirateBay] Error : Connection to ") + colored.magenta(domain) + colored.yellow(" timed out.\n") 560 | error_str += colored.yellow("Trying to connect via ") + colored.magenta(alternate_domain) + colored.yellow("...") 561 | if quiet_mode == False: 562 | print(error_str) 563 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 564 | elif domain == 'piratebay.red': 565 | error_str = colored.yellow("[PirateBay] Error : Connection to ") + colored.magenta(domain) + colored.yellow(" timed out.\n") 566 | error_str += colored.red("Exiting. Try connecting via a proxy...") 567 | if quiet_mode == False: 568 | print(error_str) 569 | table = None 570 | #sys.exit(1) 571 | elif 'Connection refused' in err_string: 572 | if domain == 'thepiratebay.org': 573 | tpb_working_domain = alternate_domain = 'piratebay.red' 574 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 575 | error_str += colored.red("Trying to connect via ") + (alternate_domain) + colored.red("...") 576 | if quiet_mode == False: 577 | print(error_str) 578 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 579 | elif domain == 'piratebay.red': 580 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 581 | error_str += colored.red("Exiting. Try connecting via a proxy...") 582 | if quiet_mode == False: 583 | print(error_str) 584 | table = None 585 | #sys.exit(1) 586 | elif 'failed to respond' in err_string: 587 | if domain == 'thepiratebay.org': 588 | tpb_working_domain = alternate_domain = 'piratebay.red' 589 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" is probably blocked.\n") 590 | error_str += colored.red("Trying to connect via ") + (alternate_domain) + colored.red("...") 591 | if quiet_mode == False: 592 | print(error_str) 593 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 594 | elif domain == 'piratebay.red': 595 | error_str = colored.red("[PirateBay] Error : Connection to ") + (domain) + colored.red(" refused.\n") 596 | error_str += colored.red("Exiting. Try connecting via a proxy...") 597 | if quiet_mode == False: 598 | print(error_str) 599 | table = None 600 | #sys.exit(1) 601 | else: 602 | error_str = colored.red("[PirateBay] Unhandled Error : ") + colored.red(str(e)) + colored.red("\nExiting...") 603 | if quiet_mode == False: 604 | print(error_str) 605 | table = None 606 | #sys.exit(1) 607 | except TypeError as e: 608 | #print("Something's wrong...") 609 | table = None 610 | 611 | # print table 612 | if table == None: 613 | if domain == 'piratebay.red': 614 | error_string = str(colored.yellow('[PirateBay] Error : No results found. ')) + str(colored.magenta(domain)) + str(colored.yellow(' might be unreachable!')) 615 | if quiet_mode == False: 616 | print(error_string) 617 | return _parse_search_result_table(table, quiet_mode) 618 | else: 619 | tpb_working_domain = alternate_domain = 'piratebay.red' 620 | # print "!!!!" 621 | error_string = str(colored.yellow('[PirateBay] Error : No results found. ')) + str(colored.magenta(domain)) + str(colored.yellow(' might be unreachable!')) 622 | error_string += str(colored.yellow('\nTrying ')) + str(colored.magenta(alternate_domain)) + str(colored.yellow('...')) 623 | if quiet_mode == False: 624 | print (error_string) 625 | return searchPirateBay(search_string=search_string, domain='piratebay.red') 626 | else: 627 | return _parse_search_result_table(table, quiet_mode=quiet_mode) 628 | 629 | def _parse_search_result_table(table, quiet_mode=False, limit=10): 630 | if table == None: 631 | results = [] 632 | return results 633 | trs = table.findAll("tr") 634 | del trs[:1] 635 | # print "\n'tr' tags within table : \n" 636 | # print trs 637 | results = [] 638 | error_detected_tpb = False 639 | index = 1 640 | for tr in trs[:limit]: 641 | #print index 642 | #print tr 643 | index += 1 644 | if(error_detected_tpb == False): 645 | results.append(_parse_search_result_table_row(tr)) 646 | else: 647 | error_string = '[PirateBay] Error : No results found' 648 | if quiet_mode == False: 649 | print(colored.yellow(error_string)) 650 | break 651 | return results 652 | 653 | def _parse_search_result_table_row(tr): 654 | global error_detected_tpb, tpb_working_domain 655 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 656 | 657 | res = {} 658 | tds = tr.findAll("td") 659 | #print tds 660 | 661 | link_name = tds[1].find("a", {"class": "detLink"}) 662 | #print "Link Name : " + str(link_name.contents) 663 | if link_name.contents == []: 664 | error_detected_tpb = True 665 | #print error_detected_tpb 666 | return {} 667 | else: 668 | res['name'] = link_name.contents[0].encode('utf-8').strip() 669 | res['link'] = link_name["href"].encode('utf-8') 670 | desc_string = tds[1].find("font").contents[0].encode('utf-8').replace(" ", " ") 671 | m = re.search(r"^Uploaded (Today|Y-day|\d\d-\d\d)\xc2\xa0(\d{4}|\d\d:\d\d), " + r"Size (\d+(?:.\d*)?\xc2\xa0(?:[KMG]iB))", desc_string) 672 | try : 673 | temp_size = str(m.group(3)).replace('\xc2\xa0', ' ') 674 | s1 = temp_size.split('.') 675 | #print s1 676 | try: 677 | s2 = s1[1].split(' ') 678 | except IndexError as e: # Special case where size is an integer (eg. s1 = 2 GiB), i.e, no decimal place 679 | #print 'Reached here' 680 | s1 = s1[0].split(' ') 681 | #print s1 682 | s2 = ['0'] 683 | s2.append(s1[1]) 684 | temp_size = s1[0] + '.0 ' + s1[1] 685 | if(len(s1[0]) == 4): 686 | res['size'] = s1[0] + s2[1] 687 | elif(len(s1[0]) == 3): 688 | res['size'] = s1[0] + '.' + s2[0][0] + " " + s2[1] 689 | else: 690 | res['size'] = temp_size 691 | except AttributeError as e: 692 | #print 'Reached here next' 693 | error_detected_tpb = True 694 | #print e 695 | #print "\nRegex misbehaving. Try running the script again!\n" 696 | return {} 697 | now = datetime.today() 698 | if re.match(r"\d{4}", m.group(2)) == None: 699 | hour =" " + m.group(2) 700 | if m.group(1) == "Today": 701 | res['time'] = datetime.strptime( 702 | now.strftime("%m-%d-%Y") + hour, 703 | "%m-%d-%Y %H:%M") 704 | elif m.group(1) == "Y-day": 705 | res['time'] = datetime.strptime( 706 | (now + timedelta(-1)).strftime("%m-%d-%Y") + hour, 707 | "%m-%d-%Y %H:%M") 708 | else: 709 | res['time'] = datetime.strptime( 710 | m.group(1) + "-" + str(now.year) + hour, 711 | "%m-%d-%Y %H:%M") 712 | else: 713 | res['time'] = datetime.strptime(m.group(1) + "-" + m.group(2), 714 | "%m-%d-%Y") 715 | res['seeders'] = int(tds[2].contents[0]) 716 | res['leechers'] = int(tds[3].contents[0]) 717 | try: 718 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 719 | except ZeroDivisionError: 720 | res['ratio'] = 'inf' 721 | res['magnet'] = tds[1].find("img", {"alt": "Magnet link"}).parent['href'] 722 | 723 | # Check if magnet link was found on this page, or if need to go one level deeper 724 | if res['magnet'] == res['link']: # Magnet link not found 725 | magnet_link_page = 'https://' + tpb_working_domain + res['link'] 726 | #print magnet_link_page 727 | try: 728 | magnet_req = requests.get(magnet_link_page, headers=headers) 729 | soup2 = BeautifulSoup(magnet_req.content, "html.parser") 730 | content = soup2.find_all(class_='download') 731 | res['magnet'] = content[0].contents[1].attrs['href'].encode('utf-8') 732 | except Exception as e: 733 | print(colored.red("[PirateBay] Error : Unkown problem while searching for magnet link")) 734 | print(colored.yellow('ERR_MSG : ' + str(e))) 735 | #print res 736 | return res 737 | 738 | def searchPirateBayWithAPI(search_string = defaultQuery, sort_by = SORT_BY_TBP.SEEDS_DESC, domain = 'tpbc.herokuapp.com', quiet_mode=False): 739 | global results_tpb_api, tpb_url 740 | base_url = 'https://' + domain 741 | url = base_url + '/search/' + removeAndReplaceSpaces(search_string) + '/?sort=' + sort_by 742 | tpb_url = url 743 | 744 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 745 | 746 | try: 747 | response = requests.get(url, headers=headers) 748 | response_json = json.loads(response.text) 749 | results_tpb_api = parse_results_tpb_api(response_json, quiet_mode=quiet_mode) 750 | except Exception as e: 751 | if quiet_mode == False : 752 | print(colored.red("[PirateBay] : Error while searching")) 753 | print(colored.yellow('ERR_MSG : ' + str(e))) 754 | #traceback.print_exc() 755 | 756 | # try: 757 | # results_tpb_api = parse_results_tpb_api(response_json) 758 | # except Exception, e: 759 | # print colored.red("[PirateBay] : Error while parsing search results.") 760 | # print colored.yellow('ERR_MSG : ' + str(e)) 761 | 762 | return results_tpb_api 763 | 764 | def parse_results_tpb_api(response_json, quiet_mode=False): 765 | #global results_tpb_api 766 | results_list = [] 767 | if response_json == []: 768 | if quiet_mode == False: 769 | error_string = '[PirateBay] Error : No results found' 770 | print(colored.magenta(error_string)) 771 | return [] 772 | else: 773 | for post in response_json: 774 | res = {} 775 | res['name'] = post['title'].encode('utf-8') 776 | #res['link'] = '' 777 | 778 | temp_size = humanize.naturalsize(post['size'], binary=True, format='%.2f') 779 | s1 = temp_size.split('.') 780 | if(len(s1[0]) == 4): 781 | res['size'] = humanize.naturalsize(post['size'], binary=True, format='%.0f') 782 | else: 783 | res['size'] = temp_size 784 | #res['time'] = Implement later 785 | res['seeders'] = post['seeds'] 786 | res['leechers'] = post['leeches'] 787 | try: 788 | res['ratio'] = format( (float(res['seeders'])/float(res['leechers'])), '.1f' ) 789 | except ZeroDivisionError: 790 | res['ratio'] = 'inf' 791 | res['magnet'] = post['magnet'].encode('utf-8') 792 | results_list.append(res) 793 | 794 | return results_list 795 | 796 | def getQuery(): 797 | global query 798 | query = input('Enter search query : ') 799 | return query 800 | 801 | def print_top_results(limit=10): 802 | global results 803 | if results != [{}]: 804 | print('-------------------------------------------- ' + colored.green('PirateBay') + ' --------------------------------------------') 805 | print('{0} {1} {2} {3} {4} {5}'.format(colored.red('No.').ljust(3), colored.red('Torrent Name').ljust(60), colored.red('File Size').rjust(10), colored.red('Seeders').rjust(7), colored.red('Leechers').rjust(6), colored.red('Ratio').rjust(6))) 806 | index = num_results_rarbg + 1 807 | for r in results[:limit]: 808 | print('{0} {1} {2} {3} {4} {5}'.format(str(index).ljust(3), r['name'][:60].ljust(60), r['size'].rjust(11), str(r['seeders']).rjust(6), str(r['leechers']).rjust(6), str(r['ratio']).rjust(8))) 809 | index = index + 1 810 | print("---------------------------------------------------------------------------------------------------") 811 | return index - 1 812 | 813 | def pretty_print_top_results_piratebay(limit=10): 814 | global results, num_results_rarbg 815 | table_piratebay = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 816 | no_str = str(colored.red('No')) 817 | name_str = str(colored.red('Torrent Name')) 818 | size_str = str(colored.red('Size')) 819 | seed_str = str(colored.red('S')) 820 | leech_str = str(colored.red('L')) 821 | ratio_str = str(colored.red('S/L')) 822 | table_piratebay.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 823 | 824 | print('\n\t\t\t\t\t\t' + colored.green('PirateBay')) 825 | # print results 826 | if results != [{}] and results != [] and results != None: 827 | index = num_results_rarbg + 1 828 | #print index 829 | #print len(results) 830 | for r in results[:limit]: 831 | try : 832 | #print index 833 | #print r 834 | table_piratebay.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 835 | index = index + 1 836 | except KeyError as e: 837 | # Fix error where {} is included in results and screws up numbering # 838 | if r != {}: 839 | print(r) 840 | print(e) 841 | table_piratebay.align[no_str] = 'l' 842 | table_piratebay.align[name_str] = 'l' 843 | table_piratebay.align[size_str] = 'r' 844 | table_piratebay.align[seed_str] = 'r' 845 | table_piratebay.align[leech_str] = 'r' 846 | table_piratebay.align[ratio_str] = 'r' 847 | print(table_piratebay) 848 | return index - 1 849 | else: 850 | table_piratebay.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 851 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 852 | print(table_piratebay) 853 | return num_results_rarbg 854 | 855 | def pretty_print_top_results_piratebay_api(limit=10): 856 | global results_tpb_api, num_results_rarbg 857 | table_piratebay = VeryPrettyTable(left_padding_width=0, right_padding_width=0, padding_width=0) 858 | no_str = str(colored.red('No')) 859 | name_str = str(colored.red('Torrent Name')) 860 | size_str = str(colored.red('Size')) 861 | seed_str = str(colored.red('S')) 862 | leech_str = str(colored.red('L')) 863 | ratio_str = str(colored.red('S/L')) 864 | table_piratebay.field_names = [no_str, name_str, size_str, seed_str, leech_str, ratio_str] 865 | 866 | print('\n\t\t\t\t\t\t' + colored.green('PirateBay')) 867 | if results_tpb_api != [] and results_tpb_api != None: 868 | index = num_results_rarbg + 1 869 | for r in results_tpb_api[:limit]: 870 | try : 871 | table_piratebay.add_row([index, r['name'][:57], r['size'], r['seeders'], r['leechers'], r['ratio']]) 872 | index = index + 1 873 | except KeyError as e: 874 | # Fix error where {} is included in results and screws up numbering # 875 | if r != {}: 876 | print(r) 877 | print(e) 878 | table_piratebay.align[no_str] = 'l' 879 | table_piratebay.align[name_str] = 'l' 880 | table_piratebay.align[size_str] = 'r' 881 | table_piratebay.align[seed_str] = 'r' 882 | table_piratebay.align[leech_str] = 'r' 883 | table_piratebay.align[ratio_str] = 'r' 884 | print(table_piratebay) 885 | return index - 1 886 | else: 887 | table_piratebay.add_row(["Null", "Null", "Null", "Null", "Null", "Null"]) 888 | #table_piratebay.align[colored.red('Torrent Name')] = 'l' 889 | print(table_piratebay) 890 | return num_results_rarbg 891 | 892 | def switch(arg, tpb_api=False): 893 | global results, exit, defaultQuery, num_results, query, num_results_rarbg, results_rarbg, print_version, tpb_working_domain, results_tpb_api, num_results_tpb_api, results_1337x, num_results_1337x, rarbg_url, skytorrents_url, tpb_url, url_1337x 894 | if ('c' in arg) and ('s' not in arg) and ('z' not in arg): 895 | try: 896 | resNum = int(re.search(r'\d+', arg).group()) 897 | if resNum <= 0 or resNum > num_results_1337x: 898 | print('Invalid command!\n') 899 | else: 900 | if tpb_api == True: 901 | if resNum <= num_results_rarbg : 902 | mLink = results_rarbg[resNum-1]['magnet'] 903 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 904 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 905 | else: 906 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 907 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 908 | else: 909 | if resNum <= num_results_rarbg : 910 | mLink = results_rarbg[resNum-1]['magnet'] 911 | elif resNum > num_results_rarbg and resNum <= num_results: 912 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 913 | else: 914 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 915 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 916 | pyperclip.copy(str(mLink)) 917 | print('Magnet link copied to clipboard!') 918 | except AttributeError: 919 | print('Enter a valid torrent number as well!') 920 | elif ('cs' in arg) and ('z' not in arg): 921 | try: 922 | resNum = int(re.search(r'\d+', arg).group()) 923 | if resNum <= 0 or resNum > num_results_1337x: 924 | print('Invalid command!\n') 925 | else: 926 | if tpb_api == True: 927 | if resNum <= num_results_rarbg : 928 | mLink = results_rarbg[resNum-1]['magnet'] 929 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 930 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 931 | else: 932 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 933 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 934 | else: 935 | if resNum <= num_results_rarbg : 936 | mLink = results_rarbg[resNum-1]['magnet'] 937 | elif resNum > num_results_rarbg and resNum <= num_results: 938 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 939 | else: 940 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 941 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 942 | pyperclip.copy(str(mLink)) 943 | webbrowser.open('https://www.seedr.cc', new=2) 944 | print('Seedr.cc opened and Magnet link copied to clipboard!') 945 | except AttributeError: 946 | print('Enter a valid torrent number as well!') 947 | elif 'cz' in arg: 948 | try: 949 | resNum = int(re.search(r'\d+', arg).group()) 950 | if resNum <= 0 or resNum > num_results_1337x: 951 | print('Invalid command!\n') 952 | else: 953 | if tpb_api == True: 954 | if resNum <= num_results_rarbg : 955 | mLink = results_rarbg[resNum-1]['magnet'] 956 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 957 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 958 | else: 959 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 960 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 961 | else: 962 | if resNum <= num_results_rarbg : 963 | mLink = results_rarbg[resNum-1]['magnet'] 964 | elif resNum > num_results_rarbg and resNum <= num_results: 965 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 966 | else: 967 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 968 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 969 | pyperclip.copy(str(mLink)) 970 | webbrowser.open('https://zbigz.unihax.in/', new=2) 971 | print('zbigz opened and Magnet link copied to clipboard!') 972 | except AttributeError: 973 | print('Enter a valid torrent number as well!') 974 | elif 'm' in arg: 975 | try: 976 | resNum = int(re.search(r'\d+', arg).group()) 977 | if resNum <= 0 or resNum > num_results_1337x: 978 | print('Invalid command\n') 979 | else: 980 | if tpb_api == True: 981 | if resNum <= num_results_rarbg : 982 | mLink = results_rarbg[resNum-1]['magnet'] 983 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 984 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 985 | else: 986 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 987 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 988 | else: 989 | if resNum <= num_results_rarbg : 990 | mLink = results_rarbg[resNum-1]['magnet'] 991 | elif resNum > num_results_rarbg and resNum <= num_results: 992 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 993 | else: 994 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 995 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 996 | print("\nMagnet Link : \n" + mLink) 997 | except AttributeError: 998 | print('Enter a valid torrent number as well!') 999 | elif 'd' in arg: 1000 | try: 1001 | resNum = int(re.search(r'\d+', arg).group()) 1002 | if resNum <= 0 or resNum > num_results_1337x: 1003 | print('Invalid command!\n') 1004 | else: 1005 | if tpb_api == True: 1006 | if resNum <= num_results_rarbg : 1007 | mLink = results_rarbg[resNum-1]['magnet'] 1008 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 1009 | mLink = results_tpb_api[(resNum-1)-num_results_rarbg]['magnet'] 1010 | else: 1011 | #mLink = results_sky[(resNum-1)-num_results_tpb_api]['magnet'] 1012 | mLink = results_1337x[(resNum-1)-num_results_tpb_api]['magnet'] 1013 | else: 1014 | if resNum <= num_results_rarbg : 1015 | mLink = results_rarbg[resNum-1]['magnet'] 1016 | elif resNum > num_results_rarbg and resNum <= num_results: 1017 | mLink = results[(resNum-1)-num_results_rarbg]['magnet'] 1018 | else: 1019 | #mLink = results_sky[(resNum-1)-num_results]['magnet'] 1020 | mLink = results_1337x[(resNum-1)-num_results]['magnet'] 1021 | webbrowser.open(mLink, new=2) 1022 | print('Magnet link sent to default torrent client!') 1023 | except AttributeError: 1024 | print('Enter a valid torrent number as well!') 1025 | elif 'o' in arg: 1026 | try: 1027 | resNum = int(re.search(r'\d+', arg).group()) 1028 | #print("resNum : %d" % resNum) 1029 | if resNum <= 0 or resNum > num_results_1337x: 1030 | print('Invalid command!\n') 1031 | else: 1032 | if tpb_api == True: 1033 | if resNum <= num_results_rarbg : 1034 | tLink = results_rarbg[resNum-1]['link'] 1035 | #print("resNum(%d) <= num_results_rarbg(%d)" % (resNum, results_rarbg)) 1036 | elif resNum > num_results_rarbg and resNum <= num_results_tpb_api: 1037 | tLink = "https://" + tpb_working_domain + results_tpb_api[(resNum-1)-num_results_rarbg]['link'] 1038 | #print("resNum(%d) > num_results_rarbg(%d) and resNum(%d) <= (num_results_rarbg(%d)+num_results(%d))" % (resNum, num_results_rarbg, resNum, num_results_rarbg, num_results)) 1039 | else: 1040 | #tLink = results_sky[(resNum-1)-num_results_tpb_api]['link'] 1041 | #print("Reached SkyTorrents. Link : %s" % tLink) 1042 | tLink = results_1337x[(resNum-1)-num_results_tpb_api]['link'] 1043 | else: 1044 | if resNum <= num_results_rarbg : 1045 | tLink = results_rarbg[resNum-1]['link'] 1046 | elif resNum > num_results_rarbg and resNum <= num_results: 1047 | #tLink = "https://" + tpb_working_domain + results[(resNum-1)-num_results_rarbg]['link'] 1048 | tLink = results[(resNum-1)-num_results_rarbg]['link'] 1049 | else: 1050 | #tLink = results_sky[(resNum-1)-num_results]['link'] 1051 | tLink = results_1337x[(resNum-1)-num_results]['link'] 1052 | #webbrowser.get('chrome').open(tLink, new=2) 1053 | webbrowser.open(tLink, new=2) 1054 | print('Torrent page opened in default browser!') 1055 | except AttributeError: 1056 | print('Enter a valid torrent number as well!') 1057 | elif arg == 'u': 1058 | print(colored.green('[RARBG] URL') + ' : ' + rarbg_url) 1059 | print(colored.green('[PirateBay] URL') + ' : ' + tpb_url) 1060 | print(colored.green('[SkyTorrents] URL') + ' : ' + url_1337x) 1061 | elif arg == 'h': 1062 | print_menu(0) 1063 | elif arg == 'q': 1064 | exit = True 1065 | elif 'p' in arg: 1066 | try: 1067 | resNum = int(re.search(r'\d+', arg).group()) 1068 | if resNum == 0: 1069 | printTopResults(resNum) 1070 | elif resNum == 1: 1071 | printTopResults(resNum) 1072 | else: 1073 | print("Not a valid option!") 1074 | except AttributeError: 1075 | if arg == 'p': 1076 | printTopResults(print_version) 1077 | else: 1078 | print("Not a valid command!") 1079 | elif arg == 's': 1080 | query = input("Enter query : ") 1081 | if query == '': 1082 | query = defaultQuery 1083 | searchAllSites(query, force_search=True) 1084 | printTopResults(print_version) 1085 | elif arg == 'r': 1086 | searchAllSites(query) 1087 | printTopResults(print_version) 1088 | else: 1089 | print('Invalid command!\n') 1090 | 1091 | def print_menu(arg=0): 1092 | if arg == 0: 1093 | print(''' 1094 | ------ Help Menu ------- 1095 | Available Commands : 1096 | 1. m - Print magnet link of selected torrent 1097 | 2. c - Copy magnet link of selected torrent to clipboard 1098 | 3. d - Download torrent using default torrent client 1099 | 4. o - Open the torrent page of the selected torrent in the default browser 1100 | 5. cs - Copy magnet link and open seedr.cc 1101 | 6. cz - Copy magnet link and open zbigz 1102 | 7. p[optional:] - Print top 10 results from each website for the given query 1103 | : [{default : 1}, {0 : Print formatted result}, {1 : Pretty print results}] 1104 | 8. s - Enter a new query to search for over all avilable torrent websites 1105 | 9. r - Repeat last search (with same query) 1106 | ------------------------''') 1107 | elif arg == 1: 1108 | print(''' 1109 | Enter 'q' to exit and 'h' to see all available commands. 1110 | ''') 1111 | 1112 | def searchAllSites(query=defaultQuery, force_search=False, quiet_mode=False): 1113 | global results, results_rarbg, results_sky, results_tpb_api, tpb_retries, max_tpb_retries, tpb_working_domain, results_tpb_condensed, results_1337x 1114 | #results = searchPirateBay(query, domain='pirateproxy.cam') 1115 | #results = searchPirateBay(query) 1116 | 1117 | if force_search == True: 1118 | results_rarbg = None 1119 | results_tpb_api = None 1120 | results_sky = None 1121 | results_1337x = None 1122 | results = None 1123 | results_tpb_condensed = None 1124 | 1125 | ## Search RARBG 1126 | # print(colored.magenta("Searching RARBG..."), end='') 1127 | # if results_rarbg == None or results_rarbg == []: 1128 | # results_rarbg = searchRarbg(query, quiet_mode=quiet_mode) 1129 | # print(colored.green("Done.")) 1130 | results_rarbg = [] 1131 | 1132 | # if results_tpb_api == None or results_tpb_api == []: 1133 | # if tpb_retries < max_tpb_retries: 1134 | # results_tpb_api = searchPirateBayWithAPI(query, quiet_mode=quiet_mode) 1135 | # results = results_tpb_api 1136 | # tpb_retries += 1 1137 | # else: 1138 | # results_tpb_api = searchPirateBay(query, quiet_mode=quiet_mode) 1139 | # results = results_tpb_api 1140 | 1141 | # print 'P searching...' 1142 | # else: 1143 | # print 'P not searching...' 1144 | # print 'Results P : ' 1145 | # print results_tpb_api 1146 | 1147 | # if results == None or results == []: 1148 | # tpb_working_domain = 'thepiratebay.zone' 1149 | # results = searchPirateBay(query, quiet_mode=quiet_mode, domain=tpb_working_domain) 1150 | # # #print results 1151 | 1152 | print(colored.magenta("Searching TBP..."), end='') 1153 | if results_tpb_condensed == None or results_tpb_condensed == []: 1154 | tpb_working_domain = 'thepiratebay.zone' 1155 | results_tpb_condensed = searchPirateBayCondensed(search_string=query, domain=tpb_working_domain, quiet_mode=quiet_mode) 1156 | results = results_tpb_condensed 1157 | print(colored.green("Done.")) 1158 | # print('P searching...') 1159 | # else: 1160 | # print('P not searching...') 1161 | # print(f'Results P: {results_tpb_condensed}') 1162 | 1163 | # if results_sky == None or results_sky == []: 1164 | # results_sky = searchSkyTorrents(query, quiet_mode=quiet_mode) 1165 | # # print 'S searching...' 1166 | # else: 1167 | # print 'S not searching...' 1168 | # print 'Results S : ' 1169 | # print results_sky 1170 | 1171 | print(colored.magenta("Searching 1337x..."), end='') 1172 | if results_1337x == None or results_1337x == []: 1173 | results_1337x = search1337x(query, quiet_mode=quiet_mode) 1174 | print(colored.green("Done.")) 1175 | 1176 | def printCombinedTopResults(): 1177 | global num_results, num_results_rarbg 1178 | num_results_rarbg = print_top_results_rarbg(10) 1179 | num_results = print_top_results(10) 1180 | 1181 | def prettyPrintCombinedTopResults(): 1182 | global num_results, num_results_rarbg, num_results_sky, num_results_tpb_api, num_results_1337x 1183 | 1184 | #num_results_rarbg = pretty_print_top_results_rarbg(10) 1185 | num_results_rarbg = 0 1186 | 1187 | num_results = pretty_print_top_results_piratebay(10) 1188 | #num_results_tpb_api = pretty_print_top_results_piratebay_api(10) 1189 | #num_results = num_results_tpb_api 1190 | 1191 | #num_results_sky = pretty_print_top_results_skytorrents(10) 1192 | num_results_1337x = pretty_print_top_results_1337x(10) 1193 | 1194 | def printTopResults(version=1): 1195 | if version == 0: 1196 | printCombinedTopResults() 1197 | elif version == 1: 1198 | prettyPrintCombinedTopResults() 1199 | 1200 | def convertListJSONToPureJSON(result_list): 1201 | # Sample JSON Structure 1202 | # { 1203 | # 'count' : x, ### Gives total number of results 1204 | # 'results' : {'0' : {...}, {'1' : {...}, ...} ### Stores actual results 1205 | # } 1206 | result_json = {'count' : '0'} 1207 | index = 0 1208 | 1209 | if result_list != [] and result_list != None: # Create a key 'results' only if there are some results 1210 | result_json['results'] = {} 1211 | rj_results = result_json['results'] 1212 | 1213 | for item in result_list: 1214 | rj_results[str(index)] = result_list[index] 1215 | index += 1 1216 | result_json['count'] = str(index) # Update total number of results 1217 | 1218 | return result_json 1219 | 1220 | def printResultsQuietly(): 1221 | global results_rarbg, results_tpb_api, results_sky, results_1337x 1222 | 1223 | results_json_rarbg = convertListJSONToPureJSON(results_rarbg) 1224 | results_json_tpb = convertListJSONToPureJSON(results_tpb_api) 1225 | #results_json_sky = convertListJSONToPureJSON(results_sky) 1226 | results_json_1337x = convertListJSONToPureJSON(results_1337x) 1227 | #print results_json_tpb 1228 | 1229 | combined_json_results = {} 1230 | combined_json_results['rarbg'] = results_json_rarbg 1231 | combined_json_results['tpb'] = results_json_tpb 1232 | #combined_json_results['sky'] = results_json_sky 1233 | combined_json_results['1337x'] = results_json_1337x 1234 | 1235 | print(combined_json_results) 1236 | 1237 | def generateAppID(version=-1): 1238 | if version == 0: # Product of 3 random numbers 1239 | x, y, z = random.randint(1, 100), random.randint(1, 100), random.randint(1, 100) 1240 | app_id = x * y * z 1241 | else : # Hash current epoch time 1242 | epoch_time = time.time() 1243 | app_id = hash(epoch_time) 1244 | return app_id 1245 | 1246 | if __name__ == '__main__': 1247 | # initiate the parser 1248 | parser = argparse.ArgumentParser() 1249 | 1250 | # add arguments 1251 | parser.add_argument("query", help="Specify the search query", nargs='+', default=defaultQuery) 1252 | parser.add_argument('-q', '--quiet', help='Print output of search without any additional options', default=False, action='store_true') 1253 | 1254 | # read arguments from the command line 1255 | args = parser.parse_args() 1256 | 1257 | if args.query: 1258 | #print("The query is : %s\n" % (' '.join(args.query))) 1259 | print_version = 1 1260 | app_id = generateAppID() 1261 | query = ' '.join(args.query) # converts args from list to string 1262 | else: 1263 | print("Please enter a valid query.") 1264 | sys.exit(0) 1265 | 1266 | if args.quiet: # Continue in non-interactive mode 1267 | #print("Result will be printed quiety...") 1268 | searchAllSites(query, quiet_mode=True) 1269 | printResultsQuietly() 1270 | else: # Continue in interactive mode 1271 | searchAllSites(query) # quiet_mode is off by default 1272 | printTopResults(print_version) 1273 | 1274 | exit = False 1275 | while(exit != True): 1276 | print_menu(1) 1277 | choice = input("Enter command : ") 1278 | switch(choice, tpb_api=False) --------------------------------------------------------------------------------