├── .gitignore ├── LICENSE ├── README.CN.md ├── README.md ├── chTracker.py └── tu.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.CN.md: -------------------------------------------------------------------------------- 1 | # TorrentUtils = tu 2 | 3 | 所有主要功能现已能使用,欢迎试用和汇报问题,脚本参数和内部接口未来仍存在变动。 4 | 5 | **注意**:由于 2009 年 10 月 Unicode 5.2.0 改变了部分字符的编码方式,使用 Unicode 5.2+ 与 Unicode 5.2- 编码的特殊字符如 emoji 相互不兼容。本脚本由 Python 3.8+ 继承 Unicode 12+,因此如果你使用本脚本制种并计划使用在 Unicode 5.2- 的老旧客户端如 uTorrent 2.2.1,应避免文件名中使用特殊字符。 6 | 7 | --- 8 | 9 | ## 需求 10 | 11 | ```txt 12 | python>=3.8 13 | tqdm (可选, 用于显示进度条) 14 | ``` 15 | 16 | 直接使用发布的 exe 执行文件的话不需要以上这些。 17 | 18 | --- 19 | 20 | ## 命令行参数 21 | 22 | ```txt 23 | $ python3 tu.py -h 24 | usage: tu [-h] [-m {create,print,verify,modify}] [-t url [url ...]] [-s number] [-c text] [-p {0,1}] 25 | [--by text] [--time number] [--source text] [--encoding text] [--json path] 26 | [--time-suffix] [--progress] [-y] 27 | [path [path ...]] 28 | 29 | positional arguments: 30 | path 1 or 2 paths depending on mode 31 | 32 | optional arguments: 33 | -h, --help show this help message and exit 34 | -m, --mode {create,print,verify,modify} mode will be inferred from paths if not specified 35 | -t, --tracker url [url ...] trackers can be supplied multiple times 36 | -c, --comment text your message to show in various clients 37 | -s, --piece-size number piece size in KiB (default: 4096) 38 | -p, --private {0,1} private torrent if 1 (default: 0) 39 | --by text set the creator of the torrent (default: Github) 40 | --time number set the time in second since 19700101 (default: now) 41 | --encoding text set the text encoding (default&recommended: UTF-8) 42 | --source text set the special source message (will change hash) 43 | --json path load a json for metadata preset in creating torrent 44 | --no-progress disable progress bar in creating torrent 45 | --time-suffix append current time to torrent filename 46 | -y, --yes just say yes - don't ask any question 47 | ``` 48 | 49 | --- 50 | 51 | ## 自动模式推测和路径选取 52 | 53 | 如果没有以 -m 参数指出模式,那么将自动根据输入的路径进行推测,同时判断那个路径是用来做什么的。下表给出规则: 54 | 55 | 简写:\ 56 | 路径参数:`1`/`2` = 第一个输入的路径 / 第二个输入的路径 (如果有) \ 57 | 路径类型:`F`/`D`/`T` = 看起来像文件但不像种子的路径 / 看起来像目录的路径 / 看起来像种子的路径 \ 58 | 操作:`L`/`R`/`W` = 由此读取文件 / 由此读取种子 / 保存种子到 59 | 60 | | 命令行 -m 参数 | 1:F/D | 1:T | 1:D
2:F | 1:F/D
2:D | 1:T
2:F/D | 1:F/D
2:T | 1:T
2:T | 1:F
2:F | 61 | | -------------------- | ---------- | ---------- | ---------- | ------------ | ------------ | ------------ | ---------- | ---------- | 62 | | 未输入或
拖拽操作 | -m create | -m print | -m create | -m create | -m verify | -m verify | - | - | 63 | | -m create | L 1
W 1 | L 1
W 1 | L 2
W 1 | L 1
W 2 | L 2
W 1 | L 1
W 2 | R 1
W 2 | - | 64 | | -m print | - | R 1 | - | - | - | - | - | - | 65 | | -m verify | - | - | - | - | R 1
L 2 | L 1
R 2 | - | - | 66 | | -m modify | - | R 1
W 1 | - | - | - | - | R 1
W 2 | - | 67 | 68 | --- 69 | 70 | ## 感谢 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TorrentUtils = tu 2 | 3 | [中文README](README.CN.md) 4 | 5 | **All major functions should work now. You're welcome to try and post bug reports. API and CLI are still subject to change.** 6 | 7 | **Caution**: 8 | 9 | Due to the breaking change in Unicode 5.2.0 (Oct 2009), special characters like emoji encoded with Unicode 5.2+ and 5.2- are **mutually incompatible**. Since TorrentUtils uses Unicode 12+ from Python 3.8+, if you plan to make & run torrent with legacy clients (Unicode 5.2-), e.g. uTorrent 2.2.1, be careful to avoid special characters in filenames. 10 | 11 | ## Requirements 12 | 13 | ```txt 14 | python>=3.8 15 | tqdm (optional, for progress bar) 16 | ``` 17 | 18 | Nothing needed if you just use the released executables. 19 | 20 | ## CLI Usage 21 | 22 | ```txt 23 | $ python3 tu.py -h 24 | usage: tu [-h] [-m {create,print,verify,modify}] [-t url [url ...]] [-s number] [-c text] [-p {0,1}] 25 | [--by text] [--time number] [--source text] [--encoding text] [--json path] 26 | [--time-suffix] [--progress] [-y] 27 | [path [path ...]] 28 | 29 | positional arguments: 30 | path 1 or 2 paths depending on mode 31 | 32 | optional arguments: 33 | -h, --help show this help message and exit 34 | -m, --mode {create,print,verify,modify} mode will be inferred from paths if not specified 35 | -t, --tracker url [url ...] trackers can be supplied multiple times 36 | -c, --comment text your message to show in various clients 37 | -s, --piece-size number piece size in KiB (default: 4096) 38 | -p, --private {0,1} private torrent if 1 (default: 0) 39 | --by text set the creator of the torrent (default: Github) 40 | --time number set the time in second since 19700101 (default: now) 41 | --encoding text set the text encoding (default&recommended: UTF-8) 42 | --source text set the special source message (will change hash) 43 | --json path load a json for metadata preset in creating torrent 44 | --no-progress disable progress bar in creating torrent 45 | --time-suffix append current time to torrent filename 46 | -y, --yes just say yes - don't ask any question 47 | ``` 48 | 49 | --- 50 | 51 | ## Automatic Mode Inference and Path Selector 52 | 53 | If not given working mode via `-m`, the script will infer one from the input paths, and also which path to load/read/save. The rules are given below: 54 | 55 | Abbr: \ 56 | Path Args: `1`/`2` = the 1st path you input / the 2nd path you input (if) \ 57 | Path Types: `F`/`D`/`T` = a file-like path (not torrent-like) / a directory-like path / a torrent-like path \ 58 | Actions: `L`/`R`/`W` = Load files from / Read torrent from / Write torrent to 59 | 60 | | CLI -m argument | 1:F/D | 1:T | 1:D
2:F | 1:F/D
2:D | 1:T
2:F/D | 1:F/D
2:T | 1:T
2:T | 1:F
2:F | 61 | | ------------------------------ | ---------- | ---------- | ---------- | ------------ | ------------ | ------------ | ---------- | ---------- | 62 | | not given or
GUI drag-drop | -m create | -m print | -m create | -m create | -m verify | -m verify | - | - | 63 | | -m create | L 1
W 1 | L 1
W 1 | L 2
W 1 | L 1
W 2 | L 2
W 1 | L 1
W 2 | R 1
W 2 | - | 64 | | -m print | - | R 1 | - | - | - | - | - | - | 65 | | -m verify | - | - | - | - | R 1
L 2 | L 1
R 2 | - | - | 66 | | -m modify | - | R 1
W 1 | - | - | - | - | R 1
W 2 | - | 67 | 68 | --- 69 | 70 | ## TODO and Progress 71 | 72 | 1. Move progress bar implementation outside of core class. 73 | 2. Implement multi-process loader for faster torrent creating. 74 | 75 | ### Core API 76 | 77 | - [x] minimal torrent functionality 78 | - [x] set/get/clear common torrent metadata 79 | - [x] read/write torrent files 80 | - [x] load (rebuild) from source files 81 | - [x] verify source files against torrent 82 | 83 | ### CLI 84 | 85 | - [x] Argument Parser 86 | - [x] Working mode 87 | - [x] **print** torrent information incl. general info, trackers and files 88 | - [x] **create** new torrent from source files, w/ json preset loader 89 | - [x] **modify** torrent metadata 90 | - [x] **verify** source files with torrent 91 | - [x] Automatic mode inference (for GUI Drag-Drop) 92 | - [x] print torrent information by dropping a single torrent file 93 | - [x] create a torrent by dropping a non-torrent file/dir, w/ json preset auto-loading 94 | - [x] verify source files with torrent by dropping a non-torrent file/dir and a torrent 95 | 96 | --- 97 | 98 | ## Thanks to 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /chTracker.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | import string 4 | import argparse 5 | from pathlib import Path 6 | from operator import methodcaller as mc 7 | from itertools import chain 8 | from functools import partial 9 | 10 | 11 | if sys.version_info < (3, 8): 12 | print('Please use Python 3.8 or higher') 13 | sys.exit(1) 14 | 15 | 16 | 17 | 18 | def _encode(obj, encoding='utf-8'): 19 | tobj = type(obj) 20 | if tobj is bytes: 21 | ret = str(len(obj)).encode(encoding) + b":" + obj 22 | elif tobj is str: 23 | ret = _encode(obj.encode(encoding)) 24 | elif tobj is int: 25 | ret = b"i" + str(obj).encode(encoding) + b"e" 26 | elif tobj in (list, tuple): 27 | ret = b"l" + b"".join(map(partial(_encode, encoding=encoding), obj)) + b"e" 28 | elif tobj is dict: 29 | ret = b'd' 30 | for key, val in sorted(obj.items()): 31 | if type(key) in (bytes, str): 32 | ret += _encode(key, encoding) + _encode(val, encoding) 33 | else: 34 | raise ValueError("Dict key must be str or bytes") 35 | ret += b'e' 36 | else: 37 | raise ValueError('Input must be int, bytes, list or dict') 38 | return ret 39 | 40 | 41 | 42 | 43 | def _decode(s, encoding='ascii'): 44 | def decode_first(s): 45 | if s.startswith(b"i"): 46 | match = re.match(b"i(-?\\d+)e", s) 47 | return int(match.group(1)), s[match.span()[1]:] 48 | elif s.startswith(b"l") or s.startswith(b"d"): 49 | l = [] 50 | rest = s[1:] 51 | while not rest.startswith(b"e"): 52 | elem, rest = decode_first(rest) 53 | l.append(elem) 54 | rest = rest[1:] 55 | if s.startswith(b"l"): 56 | return l, rest 57 | else: 58 | return {i: j for i, j in zip(l[::2], l[1::2])}, rest 59 | elif any(s.startswith(i.encode(encoding)) for i in string.digits): 60 | m = re.match(b"(\\d+):", s) 61 | length = int(m.group(1)) 62 | rest_i = m.span()[1] 63 | start = rest_i 64 | end = rest_i + length 65 | return s[start:end], s[end:] 66 | else: 67 | raise ValueError("Invalid bencoded data") 68 | 69 | s = s.encode(encoding) if isinstance(s, str) else s 70 | ret, rest = decode_first(s) 71 | if rest: 72 | raise ValueError("Invalid bencoded data") 73 | return ret 74 | 75 | 76 | 77 | 78 | def main(args): 79 | for fpath in filter(mc('match', '*.' + args.mode), filter(mc('is_file'), args.path + list(chain(*map(list, map(mc('rglob', '*'), args.path)))))): 80 | try: 81 | 82 | data = _decode(fpath.read_bytes()) 83 | if not isinstance(data, dict): 84 | raise TypeError(f'Expect bencoded dict; not {type(data)}') 85 | 86 | encoding = data.get('encoding', 'utf-8') 87 | 88 | if args.mode == 'fastresume': 89 | if args.new_path: 90 | data[b'qBt-savePath'] = bytes(args.new_path, encoding) 91 | data[b'save_path'] = bytes(args.new_path, encoding) 92 | trackers = list(chain(*data.get(b'trackers', []))) 93 | if args.clear_tracker: 94 | trackers = [] 95 | for tracker in args.trackers_to_remove + args.trackers_to_add: 96 | trackers = list(filter(mc('__ne__', bytes(tracker, encoding)), trackers)) 97 | for i, tracker in enumerate(args.trackers_to_add): 98 | trackers.insert(i, bytes(tracker, encoding)) 99 | data[b'trackers'] = list([tracker] for tracker in trackers) 100 | 101 | if args.mode == 'torrent': 102 | trackers = ([data.get(b'announce')] if data.get(b'announce') else []) + list(chain(*data.get(b'announce-list', []))) 103 | if len(trackers) >= 2 and trackers[0] == trackers[1]: 104 | trackers.pop(0) 105 | if args.clear_tracker: 106 | trackers = [] 107 | for tracker in args.trackers_to_remove + args.trackers_to_add: 108 | trackers = list(filter(mc('__ne__', bytes(tracker, encoding)), trackers)) 109 | for i, tracker in enumerate(args.trackers_to_add): 110 | trackers.insert(i, bytes(tracker, encoding)) 111 | if len(trackers) == 0: 112 | if b'announce' in data.keys(): data.pop(b'announce') 113 | if b'announce-list' in data.keys(): data.pop(b'announce-list') 114 | elif len(trackers) == 1: 115 | data[b'announce'] = trackers[0] 116 | if b'announce-list' in data.keys(): data.pop(b'announce-list') 117 | else: 118 | data[b'announce'] = trackers[0] 119 | data[b'announce-list'] = list([tracker] for tracker in trackers) 120 | 121 | fpath.write_bytes(_encode(data, encoding)) 122 | 123 | except Exception as err: 124 | print(f'\'{fpath.absolute()}\' : Skipped as {err.__class__.__name__} ({err})') 125 | continue 126 | else: 127 | print(f'\'{fpath.absolute()}\' : OK') 128 | 129 | 130 | 131 | 132 | class _CustomHelpFormatter(argparse.HelpFormatter): 133 | 134 | def __init__(self, prog): 135 | super().__init__(prog, max_help_position=50, width=100) 136 | 137 | def _format_action_invocation(self, action): 138 | if not action.option_strings or action.nargs == 0: 139 | return super()._format_action_invocation(action) 140 | default = self._get_default_metavar_for_optional(action) 141 | args_string = self._format_args(action, default) 142 | return ', '.join(action.option_strings) + ' ' + args_string 143 | 144 | 145 | 146 | 147 | if __name__ == '__main__': 148 | parser = argparse.ArgumentParser(formatter_class=lambda prog: _CustomHelpFormatter(prog), 149 | epilog='Note: tracker operation sequence is clear > del > add; ' 150 | 'added trackers will be placed on top; ' 151 | 'existing trackers in one tier will be flattened to different tiers.') 152 | parser.add_argument('path', nargs='+', type=Path, metavar='path', 153 | help='recursively find fastresume/torrent in these files/folders') 154 | parser.add_argument('-m', '--mode', choices=('fastresume', 'torrent'), default='fastresume', 155 | help='to modify libt fastresume or torrent (default: fastresume)') 156 | parser.add_argument('-at', '--add-tracker', dest='trackers_to_add', nargs='+', action='extend', default=[], metavar='url', 157 | help='add a tracker; can be supplied multiple times') 158 | parser.add_argument('-dt', '--del-tracker', dest='trackers_to_remove', nargs='+', action='extend', default=[], metavar='url', 159 | help='del a tracker; can be supplied multiple times') 160 | parser.add_argument('-ct', '--clear-tracker', dest='clear_tracker', action='store_true', default=False, 161 | help='remove all existing trackers') 162 | parser.add_argument('-to', '--move-to', dest='new_path', type=str, default='', metavar='new_path', 163 | help='change saved path in fastresume; no effect in torrent mode') 164 | main(parser.parse_args()) 165 | -------------------------------------------------------------------------------- /tu.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sys 4 | import math 5 | import time 6 | import json 7 | import codecs 8 | import urllib 9 | import shutil 10 | import string 11 | import hashlib 12 | import pathlib 13 | import warnings 14 | import argparse 15 | 16 | from operator import methodcaller 17 | from itertools import repeat, chain 18 | from functools import partial 19 | from collections import namedtuple 20 | 21 | try: 22 | import tqdm 23 | except ImportError: 24 | pass 25 | 26 | 27 | 28 | 29 | '''===================================================================================================================== 30 | Helper Error Types 31 | =====================================================================================================================''' 32 | 33 | 34 | class TorrentNotReadyError(Exception): 35 | pass 36 | 37 | 38 | class BdecodeError(ValueError): 39 | pass 40 | 41 | 42 | class PieceSizeTooSmall(ValueError): 43 | pass 44 | 45 | 46 | class PieceSizeUncommon(ValueError): 47 | pass 48 | 49 | 50 | class EmptySourceSize(ValueError): 51 | pass 52 | 53 | 54 | 55 | 56 | '''===================================================================================================================== 57 | Public Helper Functions 58 | =====================================================================================================================''' 59 | 60 | 61 | def bencode(obj, enc:str='UTF-8') -> bytes: 62 | '''Bencode objects. Modified from .''' 63 | if isinstance(obj, bytes): 64 | ret = str(len(obj)).encode(enc) + b":" + obj 65 | elif isinstance(obj, str): 66 | ret = bencode(obj.encode(enc)) 67 | elif isinstance(obj, int): 68 | ret = b"i" + str(obj).encode(enc) + b"e" 69 | elif isinstance(obj, (list, tuple)): 70 | ret = b"l" + b"".join(map(partial(bencode, enc=enc), obj)) + b"e" 71 | elif isinstance(obj, dict): 72 | ret = b'd' 73 | for key, val in sorted(obj.items()): 74 | if isinstance(key, (bytes, str)): 75 | ret += bencode(key, enc) + bencode(val, enc) 76 | else: 77 | raise TypeError(f"Expect str or bytes, not {key}:{type(key)}.") 78 | ret += b'e' 79 | else: 80 | raise TypeError(f"Expect int, bytes, list or dict, not {obj}:{type(obj)}.") 81 | 82 | return ret 83 | 84 | 85 | def bdecode(s:bytes, encoding='ascii'): 86 | '''Bdecode bytes. Modified from .''' 87 | 88 | def decode_first(s): 89 | if s.startswith(b"i"): 90 | match = re.match(b"i(-?\\d+)e", s) 91 | return int(match.group(1)), s[match.span()[1]:] 92 | elif s.startswith(b"l") or s.startswith(b"d"): 93 | l = [] 94 | rest = s[1:] 95 | while not rest.startswith(b"e"): 96 | elem, rest = decode_first(rest) 97 | l.append(elem) 98 | rest = rest[1:] 99 | if s.startswith(b"l"): 100 | return l, rest 101 | else: 102 | return {i: j for i, j in zip(l[::2], l[1::2])}, rest 103 | elif any(s.startswith(i.encode(encoding)) for i in string.digits): 104 | m = re.match(b"(\\d+):", s) 105 | length = int(m.group(1)) 106 | rest_i = m.span()[1] 107 | start = rest_i 108 | end = rest_i + length 109 | return s[start:end], s[end:] 110 | else: 111 | raise BdecodeError("Malformed input.") 112 | 113 | s = s.encode(encoding) if isinstance(s, str) else s 114 | ret, rest = decode_first(s) 115 | if rest: 116 | raise BdecodeError("Malformed input.") 117 | 118 | return ret 119 | 120 | 121 | def hash(bchars:bytes, /) -> bytes: 122 | '''Return the sha1 hash for the given bytes.''' 123 | if isinstance(bchars, bytes): 124 | hasher = hashlib.sha1() 125 | hasher.update(bchars) 126 | return hasher.digest() 127 | else: 128 | raise TypeError(f"Expect bytes, not {type(bchars)}.") 129 | 130 | 131 | def fromTorrent(path): 132 | '''Wrapper function to read a torrent file and return it.''' 133 | torrent = Torrent() 134 | torrent.read(pathlib.Path(path)) 135 | return torrent 136 | 137 | 138 | def fromFiles(path): 139 | '''Wrapper function to load files as a torrent and return it.''' 140 | torrent = Torrent() 141 | torrent.load(pathlib.Path(path)) 142 | return torrent 143 | 144 | 145 | '''===================================================================================================================== 146 | Core Torrent Class 147 | =====================================================================================================================''' 148 | 149 | 150 | class Torrent(): 151 | 152 | 153 | def __init__(self, **kwargs): 154 | '''Create an instance of an empty torrent. Supply any arguments supported by`self.set()` to init metadata. 155 | 156 | Currently, only the most common attributes are supported, including: 157 | at the 1st level of torrent: 158 | `announce`, `announce-list`, `comment`, `created by`, `creation data`, `encoding`, `info` 159 | and in the `info` key: 160 | `files`, `name`, `piece length`, `pieces`, `private`, `source` 161 | Any other attributes will be lost. 162 | ''' 163 | 164 | # internal attributes and their default values 165 | self._tracker_lst = list() # for `announce` and `announce-list` 166 | self._comment_str = str() # for `comment` 167 | self._creator_str = str() # for `created by` 168 | self._datesec_int = 0 # for `creation date` 169 | self._enc4txt_str = 'UTF-8' # for `encoding` 170 | self._srcpath_lst = list() # for `files` 171 | self._srcsize_lst = list() # for `length` 172 | self._trtname_str = str() # for `name` 173 | self._piecesz_int = 4096 << 10 # for `piece length` 174 | self._srcsha1_byt = bytes() # for `pieces` 175 | self._private_int = 0 # for `private` 176 | self._tsource_str = str() # for `source` 177 | 178 | # metadata init 179 | self.set(**kwargs) 180 | 181 | 182 | '''----------------------------------------------------------------------------------------------------------------- 183 | Basic properties that mimic keys in an actual torrent, providing a straightforward access (except `info`). 184 | If the return value is `False`, the key does not exist. 185 | Note that `get()` method does not handle all of these properties. 186 | -----------------------------------------------------------------------------------------------------------------''' 187 | 188 | 189 | @property 190 | def announce(self) -> str: 191 | '''Return the first tracker, or empty string if none.''' 192 | return self._tracker_lst[0] if self._tracker_lst else '' 193 | 194 | @announce.setter 195 | def announce(self, url): 196 | '''Set the first tracker.''' 197 | assert isinstance(url, str), f"expect str, not {url.__class__.__name__}" 198 | self.setTracker([url] + self.announce_list) # `setTracker()` will deduplicate 199 | 200 | 201 | @property 202 | def announce_list(self) -> list: 203 | '''Return all trackers if no less than 2, otherwise empty list.''' 204 | return self._tracker_lst if len(self._tracker_lst) >= 2 else [] 205 | 206 | @announce_list.setter 207 | def announce_list(self, urls): 208 | '''Set the whole tracker list, must be no less than 2.''' 209 | if len(urls) >= 2: 210 | self.setTracker(urls) 211 | else: 212 | raise ValueError(f'Trackers supplied to announce-list must be no less than 2.') 213 | 214 | 215 | @property 216 | def comment(self) -> str: 217 | '''Return the comment message, which can be displayed in various clients.''' 218 | return self._comment_str 219 | 220 | @comment.setter 221 | def comment(self, chars): 222 | '''Set the comment message.''' 223 | self.setComment(chars) 224 | 225 | 226 | @property 227 | def created_by(self) -> str: 228 | '''Return the creator of the torrent.''' 229 | return self._creator_str 230 | 231 | @created_by.setter 232 | def created_by(self, creator): 233 | '''Set the creator of the torrent.''' 234 | self.setCreator(creator) 235 | 236 | 237 | @property 238 | def creation_date(self) -> int: 239 | '''Return torrent creation time, counted as the number of second since 1970-01-01.''' 240 | return self._datesec_int 241 | 242 | @creation_date.setter 243 | def creation_date(self, date): 244 | '''Set torrent creation time.''' 245 | self.setDate(date) 246 | 247 | 248 | @property 249 | def encoding(self) -> str: 250 | '''Return the encoding for text.''' 251 | return self._enc4txt_str 252 | 253 | @encoding.setter 254 | def encoding(self, enc): 255 | '''Set the encoding for text.''' 256 | self.setEncoding(enc) 257 | 258 | 259 | @property 260 | def files(self) -> list: 261 | '''Return the list of list of file size and path parts if no less than 2 files (repel `length`). Read-only.''' 262 | return list([fsize, fpath.parts] for fsize, fpath in zip(self._srcsize_lst, self._srcpath_lst)) \ 263 | if len(self._srcpath_lst) >= 2 else [] 264 | 265 | 266 | @property 267 | def length(self) -> int: 268 | '''Return the size of single file torrent (repel `files`). Read-only.''' 269 | return self._srcsize_lst[0] if len(self._srcsize_lst) == 1 else 0 270 | 271 | 272 | @property 273 | def name(self) -> str: 274 | '''Return the root name of the torrent.''' 275 | return self._trtname_str 276 | 277 | @name.setter 278 | def name(self, name): 279 | '''Set the root name of the torrent.''' 280 | self.setName(name) 281 | 282 | 283 | @property 284 | def piece_length(self) -> int: 285 | '''Return the piece size in bytes.''' 286 | return self._piecesz_int 287 | 288 | @piece_length.setter 289 | def piece_length(self, size): 290 | '''Set the piece size in bytes.''' 291 | self.setPieceLength(size) 292 | 293 | 294 | @property 295 | def pieces(self) -> str: 296 | '''Return the long raw bytes of pieces' sha1. Read-only.''' 297 | return self._srcsha1_byt 298 | 299 | 300 | @property 301 | def private(self) -> int: 302 | '''Return 1 if the torrent is private, otherwise 0.''' 303 | return 1 if self._private_int else 0 304 | 305 | @private.setter 306 | def private(self, private): 307 | '''Set torrent private or not.''' 308 | self.setPrivate(private) 309 | 310 | 311 | @property 312 | def source(self) -> str: 313 | '''Return the special message particularly used by private trackers.''' 314 | return self._tsource_str 315 | 316 | @source.setter 317 | def source(self, src): 318 | '''Set the special message, which is normally invisible in clients.''' 319 | self.setSource(src) 320 | 321 | 322 | '''----------------------------------------------------------------------------------------------------------------- 323 | Useful public torrent properties 324 | -----------------------------------------------------------------------------------------------------------------''' 325 | 326 | 327 | @property 328 | def tracker_list(self) -> list: 329 | '''Unlike `announce_list`, always returns the full tracker list unconditionally.''' 330 | return self._tracker_lst 331 | 332 | @tracker_list.setter 333 | def tracker_list(self, urls): 334 | '''Set the whole tracker urls.''' 335 | self.setTracker(urls) 336 | 337 | 338 | @property 339 | def file_list(self) -> list: 340 | '''Unlike `files` and `length`, always returns the full file size and paths unconditionally. Read-only.''' 341 | return list([fsize, fpath.parts] for fsize, fpath in zip(self._srcsize_lst, self._srcpath_lst)) 342 | 343 | 344 | @property 345 | def size(self) -> int: 346 | '''Return the total size of all source files in the torrent. Read-only.''' 347 | return sum(self._srcsize_lst) 348 | 349 | 350 | @property 351 | def torrent_size(self) -> int: 352 | '''Return the size of the torrent file itself (not source files). Read-only.''' 353 | return len(bencode(self.torrent_dict, self.encoding)) 354 | 355 | 356 | @property 357 | def num_pieces(self) -> int: 358 | '''Return the total number of pieces within the torrent. Read-only.''' 359 | return len(self._srcsha1_byt) // 20 360 | 361 | 362 | @property 363 | def num_files(self) -> int: 364 | '''Return the total number of files within the torrent. Read-only.''' 365 | return len(self.file_list) 366 | 367 | 368 | @property 369 | def hash(self) -> str: 370 | '''Return the torrent hash at the moment. Read-only.''' 371 | return hash(bencode(self.info_dict, self.encoding)).hex() 372 | 373 | 374 | @property 375 | def magnet(self) -> str: 376 | '''Return the magnet link of the torrent. Read-only.''' 377 | ret = f"magnet:?xt=urn:btih:{self.hash}" 378 | if self.name: 379 | ret += f"&dn={urllib.parse.quote(self.name)}" 380 | if self.size: 381 | ret += f"&xl={self.size}" 382 | for url in self.tracker_list: 383 | ret += f"&tr={urllib.parse.quote(url)}" 384 | return ret 385 | 386 | 387 | def get(self, key, ret=None): 388 | '''Get various metadata with more flexible key aliases: 389 | 390 | tracker: t, tr, tracker, trackers, tl, trackerlist, announce, announces, announcelist 391 | comment: c, comm, comment, comments 392 | creator: b, by, createdby, creator, tool, creatingtool 393 | date: d, date, time, second, seconds, creationdate, creationtime, creatingdate, creatingtime 394 | encoding: e, enc, encoding, codec 395 | name: n, name, torrentname 396 | piece size: ps, pl, piecesize, piecelength 397 | private: p, private, privatetorrent, torrentprivate, pub, public, publictorrent, torrentpublic 398 | source: s, src, source 399 | filelist: fl, filelist 400 | size: ssz, sourcesize, sourcesz, size 401 | torrentsize: tsz, torrentsize, torrentsz 402 | numpieces: np, numpiece, numpieces 403 | numfiles: nf, numfile, numfiles 404 | hash: th, torrenthash, sha1, hash 405 | magnet: magnet, magnetlink, magneturl 406 | 407 | All alias are case-insensitive. 408 | All whitespaces and underscores will be stripped (e.g. dA_te == date). 409 | Same as calls to properties, this method does not raise error on key inexistence, but return None(default). 410 | ''' 411 | key = re.sub(r'[\s_]', '', key).lower() 412 | if key in ('t', 'tr', 'tracker', 'trackers', 'trackerlist', 'announce', 'announces', 'announcelist'): 413 | ret = self.tracker_list 414 | elif key in ('c', 'comment', 'comments'): 415 | ret = self.comment 416 | elif key in ('b', 'by', 'createdby', 'creator', 'tool', 'creatingtool'): 417 | ret = self.created_by 418 | elif key in ('d', 'date', 'time', 'second', 'seconds', 'creationdate', 'creationtime', 'creatingdate', 'creatingtime'): 419 | ret = self.creation_date 420 | elif key in ('e', 'enc', 'encoding', 'codec'): 421 | ret = self.encoding 422 | elif key in ('n', 'name', 'torrentname'): 423 | ret = self.name 424 | elif key in ('ps', 'pl', 'piecesize', 'piecelength'): 425 | ret = self.piece_length 426 | elif key in ('p', 'private', 'privatetorrent', 'torrentprivate'): 427 | ret = self.private 428 | elif key in ('pub', 'public', 'publictorrent', 'torrentpublic'): 429 | ret = not self.private 430 | elif key in ('s', 'src', 'source'): 431 | ret = self.source 432 | elif key in ('fl', 'filelist'): 433 | ret = self.file_list 434 | elif key in ('ssz', 'sourcesize', 'sourcesz', 'size'): 435 | ret = self.size 436 | elif key in ('tsz', 'torrentsize', 'torrentsz'): 437 | ret = self.torrent_size 438 | elif key in ('np', 'numpiece', 'numpieces'): 439 | ret = self.num_pieces 440 | elif key in ('nf', 'numfile', 'numfiles'): 441 | ret = self.num_files 442 | elif key in ('th', 'torrenthash', 'sha1', 'hash'): 443 | ret = self.hash 444 | elif key in ('magnet', 'magnetlink', 'magneturl'): 445 | ret = self.magnet 446 | 447 | return ret 448 | 449 | '''----------------------------------------------------------------------------------------------------------------- 450 | The following properties does not support `get()` method 451 | -----------------------------------------------------------------------------------------------------------------''' 452 | 453 | 454 | @property 455 | def info_dict(self) -> dict: 456 | '''Return the `info` dict of the torrent that affects hash. Read-only.''' 457 | info_dict = {} 458 | if self.length: 459 | info_dict[b'length'] = self.length 460 | if self.files: 461 | info_dict[b'files'] = [] 462 | for fsize, fpath_parts in self.files: 463 | info_dict[b'files'].append({b'length': fsize, b'path': fpath_parts}) 464 | if self.name: 465 | info_dict[b'name'] = self.name 466 | if self.piece_length: 467 | info_dict[b'piece length'] = self.piece_length 468 | if self.pieces: 469 | info_dict[b'pieces'] = self.pieces 470 | if self.private: 471 | info_dict[b'private'] = self.private 472 | if self.source: 473 | info_dict[b'source'] = self.source 474 | return info_dict 475 | 476 | 477 | @property 478 | def torrent_dict(self) -> bytes: 479 | '''Return the complete dict of the torrent, ready to be bencoded and saved. Read-only.''' 480 | torrent_dict = {b'info':{}} 481 | 482 | # keys that not impact torrent hash 483 | if self.announce: 484 | torrent_dict[b'announce'] = self.announce 485 | if self.announce_list: 486 | torrent_dict[b'announce-list'] = list([url] for url in self.announce_list) 487 | if self.comment: 488 | torrent_dict[b'comment'] = self.comment 489 | if self.creation_date: 490 | torrent_dict[b'creation date'] = self.creation_date 491 | if self.created_by: 492 | torrent_dict[b'created by'] = self.created_by 493 | if self.encoding: 494 | torrent_dict[b'encoding'] = self.encoding 495 | 496 | # keys that impact torrent hash 497 | torrent_dict[b'info'] = self.info_dict 498 | 499 | # additional key to store the original hash 500 | torrent_dict[b'hash'] = self.hash 501 | 502 | return torrent_dict 503 | 504 | 505 | 506 | 507 | '''----------------------------------------------------------------------------------------------------------------- 508 | Property setters 509 | -----------------------------------------------------------------------------------------------------------------''' 510 | 511 | 512 | def addTracker(self, urls, /, top=True): 513 | '''Add trackers. 514 | 515 | Arguments: 516 | urls: The tracker urls, can be a single string or an iterable of strings. Auto deduplicate. 517 | top: bool=True, place added trackers to the top if True, otherwise bottom. 518 | ''' 519 | urls = [urls] if isinstance(urls, str) else list(urls) 520 | if top: 521 | for url in urls[::-1]: # we're appending left, so reverse it 522 | try: 523 | idx = self._tracker_lst.index(url) 524 | except ValueError: # not found, add it 525 | self._tracker_lst.insert(0, url) 526 | else: # found, remove the existing and push it to top 527 | self._tracker_lst.pop(idx) 528 | self._tracker_lst.insert(0, url) 529 | else: 530 | for url in urls: 531 | try: 532 | idx = self._tracker_lst.index(url) 533 | except ValueError: # not found, add it 534 | self.append(url) 535 | else: # found, no need to update its position 536 | pass 537 | 538 | 539 | def setTracker(self, urls, /): 540 | '''Set tracker list with the given urls, dropping all existing ones. 541 | 542 | Argument: 543 | urls: The tracker urls, can be a single string or an iterable of strings. Auto deduplicate. 544 | ''' 545 | urls = [urls] if isinstance(urls, str) else list(urls) 546 | self._tracker_lst.clear() 547 | self.addTracker(urls) # `addTracker() will deduplicate 548 | 549 | 550 | def rmTracker(self, urls, /): 551 | '''Remove tracker. 552 | 553 | Arguments: 554 | urls: The tracker urls, can be a single string or an iterable of strings. 555 | ''' 556 | urls = {urls} if isinstance(urls, str) else set(urls) 557 | for url in urls: 558 | try: 559 | idx = self._tracker_lst.index(url) 560 | except ValueError: 561 | continue # not found, skip 562 | else: 563 | self._tracker_lst.pop(idx) # found, remove it 564 | 565 | 566 | def setComment(self, comment, /): 567 | '''Set the comment message. 568 | 569 | Argument: 570 | comment: The comment message as str.''' 571 | self._comment_str = str(comment) 572 | 573 | 574 | def setCreator(self, creator, /): 575 | '''Set the creator of the torrent. 576 | 577 | Argument: 578 | creator: The str of the creator.''' 579 | self._creator_str = str(creator) 580 | 581 | 582 | def setDate(self, date, /): 583 | '''Set the time. 584 | 585 | Argument: 586 | date: Second since 1970-1-1 if int or float, `time.strptime()` format if str, 587 | time tuple or `time.struct_time` otherwise. 588 | ''' 589 | if isinstance(date, (int, float)): 590 | self._datesec_int = int(date) 591 | elif isinstance(date, str): 592 | self._datesec_int = int(time.mktime(time.strptime(date))) 593 | elif isinstance(date, time.struct_time): 594 | self._datesec_int = int(time.mktime(date)) 595 | elif '__len__' in dir(date) and len(date) == 9: 596 | self._datesec_int = int(time.mktime(tuple(date))) 597 | else: 598 | raise ValueError('Supplied date is not understood.') 599 | 600 | 601 | def setEncoding(self, enc, /): 602 | '''Set the encoding for text. 603 | 604 | Argument: 605 | enc: The encoding, must be a valid one in python. 606 | ''' 607 | enc = str(enc) 608 | codecs.lookup(enc) # will raise LookupError if this encoding not exists 609 | self._enc4txt_str = enc # respect the encoding str supplied by user 610 | 611 | 612 | def setName(self, name, /): 613 | '''Set the root name. Note that this will prevent the torrent from hashing on the source files. 614 | 615 | Argument: 616 | name: The new root name.''' 617 | name = str(name) 618 | if not name: 619 | raise ValueError('Torrent name cannot be empty.') 620 | if not all([False if (char in name) else True for char in r'\/:*?"<>|' ]): 621 | raise ValueError('Torrent name contains invalid character.') 622 | self._trtname_str = name 623 | 624 | 625 | def setPieceLength(self, size, /, no_check=False): 626 | '''Set torrent piece size. 627 | Note that changing piece size to a different value will clear existing torrent piece hash. 628 | Exception will be raised when the new piece size looks strange: 629 | 1. the piece size divided by 16KiB does not obtain a power of 2. 630 | 2. the piece size is beyond the range [256KiB, 32MiB]. 631 | Piece size smaller than 16KiB is never allowed. 632 | 633 | Argument: 634 | size: the piece size in bytes 635 | no_check: bool=False, whether to allow uncommon piece size and bypass exceptions 636 | ''' 637 | size = int(size) 638 | no_check = bool(no_check) 639 | if size == self._piecesz_int: # we have nothing to do 640 | return 641 | 642 | if size < 16384: # piece size must be larger than 16KiB 643 | raise PieceSizeTooSmall() 644 | if (not no_check) and ((math.log2(size / 262144) % 1) or (size < 262144) or (size > 33554432)): 645 | raise PieceSizeUncommon() 646 | if size != self._piecesz_int: # changing piece size will clear existing hash 647 | self._srcsha1_byt = bytes() 648 | self._piecesz_int = size 649 | 650 | 651 | def setPrivate(self, private, /): 652 | '''Set torrent private or not. 653 | 654 | Argument: 655 | private: Any value that can be converted to `bool`; private torrent if `True`. 656 | ''' 657 | self._private_int = int(bool(private)) 658 | 659 | 660 | def setSource(self, src, /): 661 | '''Set the source message. 662 | 663 | Argument: 664 | src: The message text that can be converted to `str`. 665 | ''' 666 | self._tsource_str = str(src) 667 | 668 | 669 | def set(self, **metadata): 670 | '''Set various metadata with more flexible key aliases: 671 | 672 | tracker: t, tr, tracker, trackers, trackerlist, announce, announces, announcelist 673 | comment: c, comm, comment, comments 674 | creator: b, by, createdby, creator, tool, creatingtool 675 | date: d, date, time, second, seconds, creationdate, creationtime, creatingdate, creatingtime 676 | encoding: e, enc, encoding, codec 677 | name: n, name, torrentname 678 | piece size: ps, pl, piecesize, piecelength 679 | private: p, private, privatetorrent, torrentprivate, pub, public, publictorrent, torrentpublic 680 | source: s, src, source 681 | 682 | All alias are case-insensitive. 683 | All whitespaces and underscores will be stripped (e.g. dA_te == date). 684 | If equivalent keys are supplied multiple times, the last one takes effect. 685 | Note that the values of keys have the same requirement as each backend function. 686 | ''' 687 | for key, value in metadata.items(): 688 | key = re.sub(r'[\s_]', '', key).lower() 689 | if key in ('t', 'tr', 'tracker', 'trackers', 'trackerlist', 'announce', 'announces', 'announcelist'): 690 | self.setTracker(value) 691 | elif key in ('c', 'comment', 'comments'): 692 | self.setComment(value) 693 | elif key in ('b', 'by', 'createdby', 'creator', 'tool', 'creatingtool'): 694 | self.setCreator(value) 695 | elif key in ('d', 'date', 'time', 'second', 'seconds', 'creationdate', 'creationtime', 'creatingdate', 'creatingtime'): 696 | self.setDate(value) 697 | elif key in ('e', 'enc', 'encoding', 'codec'): 698 | self.setEncoding(value) 699 | elif key in ('n', 'name', 'torrentname'): 700 | self.setName(value) 701 | elif key in ('ps', 'pl', 'piecesize', 'piecelength'): 702 | self.setPieceLength(value) 703 | elif key in ('p', 'private', 'privatetorrent', 'torrentprivate'): 704 | self.setPrivate(value) 705 | elif key in ('pub', 'public', 'publictorrent', 'torrentpublic'): 706 | self.setPrivate(not value) 707 | elif key in ('s', 'src', 'source'): 708 | self.setSource(value) 709 | else: 710 | raise KeyError(f"Unknown key: {key}.") 711 | 712 | 713 | '''----------------------------------------------------------------------------------------------------------------- 714 | Input/output operations 715 | -----------------------------------------------------------------------------------------------------------------''' 716 | 717 | 718 | def read(self, tpath, /): 719 | '''Load everything from the template. Note that this function will clear all existing properties. 720 | 721 | Argument: 722 | tpath: the path to the torrent.''' 723 | tpath = pathlib.Path(tpath) 724 | if not tpath.is_file(): 725 | raise FileNotFoundError(f"The supplied '{tpath}' does not exist.") 726 | torrent_dict = bdecode(tpath.read_bytes()) 727 | 728 | # we need to know encoding first 729 | encoding = torrent_dict.get(b'encoding', b'UTF-8').decode() # str 730 | 731 | # tracker list 732 | trackers = [torrent_dict[b'announce']] if torrent_dict.get(b'announce') else [] 733 | trackers += list(chain(*torrent_dict[b'announce-list'])) if torrent_dict.get(b'announce-list') else [] 734 | trackers = list(map(methodcaller('decode', encoding), trackers)) # bytes to str 735 | trackers = list(dict.fromkeys(trackers)) # ordered deduplicate 736 | 737 | # other keys 738 | comment = torrent_dict.get(b'comment', b'').decode(encoding) # str 739 | created_by = torrent_dict.get(b'created by', b'').decode(encoding) # str 740 | creation_date = torrent_dict.get(b'creation date', 0) # int 741 | files = torrent_dict.get(b'info').get(b'files', []) # list 742 | length = torrent_dict.get(b'info').get(b'length', 0) # int 743 | name = torrent_dict.get(b'info').get(b'name', b'').decode(encoding) # str 744 | piece_length = torrent_dict.get(b'info').get(b'piece length', 0) # int 745 | pieces = torrent_dict.get(b'info').get(b'pieces', b'') # str 746 | private = torrent_dict.get(b'info').get(b'private', 0) # int 747 | source = torrent_dict.get(b'info').get(b'source', b'').decode(encoding) # str 748 | 749 | # everything looks good, now let's write attributes 750 | self.setTracker(trackers) 751 | self.setComment(comment) 752 | self.setCreator(created_by) 753 | self.setDate(creation_date) 754 | self.setEncoding(encoding) 755 | self.setName(name) 756 | self.setPieceLength(piece_length, no_check=True) 757 | self.setPrivate(private) 758 | self.setSource(source) 759 | 760 | self._srcsha1_byt = pieces 761 | if length and not files: 762 | self._srcpath_lst = [pathlib.Path('.')] 763 | self._srcsize_lst = [length] 764 | elif not length and files: 765 | fsize_list = [] 766 | fpath_list = [] 767 | for file in files: 768 | fsize_list.append(file[b'length']) 769 | fpath_list.append(pathlib.Path().joinpath(*map(methodcaller('decode', encoding), file[b'path']))) 770 | self._srcsize_lst = fsize_list 771 | self._srcpath_lst = fpath_list 772 | else: 773 | raise ValueError('Unexpected error in handling source files structure.') 774 | 775 | 776 | def readMetadata(self, tpath, /, include_key={}, exclude_key={'source'}): 777 | '''Unlike `read()`, this only loads and overwrites selected properties: 778 | trackers, comment, created_by, creation_date, encoding, source 779 | 780 | Arguments: 781 | tpath: the path to the torrent 782 | `include_key`: str or set of str, only these keys will be copied 783 | keys: {trackers, comment, created_by, creation_date, encoding, source} (default=all) 784 | `exclude_key`: str or set of str, these keys will not be copied (override `include_key`) 785 | keys: {trackers, comment, created_by, creation_date, encoding, source} (default='source') 786 | ''' 787 | tpath = pathlib.Path(tpath) 788 | if not tpath.is_file(): 789 | raise FileNotFoundError(f"The supplied '{tpath}' does not exist.") 790 | 791 | key_set = {'tracker', 'comment', 'created_by', 'creation_date', 'encoding', 'source'} 792 | include_key = {include_key} if isinstance(include_key, str) else ( 793 | set(include_key) if include_key else key_set) 794 | exclude_key = {exclude_key} if isinstance(exclude_key, str) else set(exclude_key) 795 | if (not include_key.issubset(key_set)) or (not exclude_key.issubset(key_set)): 796 | raise KeyError('Invalid key supplied.') 797 | 798 | template = Torrent() 799 | template.read(tpath) 800 | for key in include_key.difference(exclude_key): 801 | if key == 'tracker': 802 | self._tracker_lst.addTracker(template.trackers) 803 | continue 804 | elif key == 'comment' and template.comment: 805 | self._comment_str = template.comment 806 | continue 807 | elif key == 'created_by' and template.created_by: 808 | self._creator_str = template.created_by 809 | continue 810 | elif key == 'creation_date' and template.creation_date: 811 | self._datesec_int = template.creation_date 812 | continue 813 | elif key == 'encoding' and template.encoding: 814 | self._enc4txt_str = template.encoding 815 | continue 816 | elif key == 'source' and template.source: 817 | self._tsource_str = template.source 818 | continue 819 | raise RuntimeError('Loop not correctly continued.') 820 | 821 | 822 | def load(self, spath, keep_name=False, show_progress=False): 823 | '''Load new file list and piece hash from the Source PATH (spath). 824 | 825 | The following torrent keys will be overwritten on success: 826 | files, name (may be preserved by `keep_name=True`), pieces 827 | 828 | Arguments: 829 | spath: path-like objects, the source path to be loaded 830 | keep_name: bool=False, whether to keep the old torrent name 831 | show_progress: bool=False, whether to show a progress bar during loading, maybe removed in the future 832 | ''' 833 | # argument handler 834 | spath = pathlib.Path(spath) 835 | if not spath.exists(): 836 | raise FileNotFoundError(f"The supplied '{spath}' does not exist.") 837 | keep_name = bool(keep_name) 838 | show_progress = bool(show_progress) 839 | 840 | fpaths = [spath] if spath.is_file() else sorted(filter(methodcaller('is_file'), spath.rglob('*'))) 841 | fpath_list = [fpath.relative_to(spath) for fpath in fpaths] 842 | fsize_list = [fpath.stat().st_size for fpath in fpaths] 843 | if sum(fsize_list): 844 | if show_progress: # TODO: stdout is dirty in core class method and should be moved out in the future 845 | sha1 = b'' 846 | piece_bytes = bytes() 847 | pbar1 = tqdm.tqdm(total=sum(fsize_list), desc='Size', unit='B', unit_scale=True, ascii=True, dynamic_ncols=True) 848 | pbar2 = tqdm.tqdm(total=len(fsize_list), desc='File', unit='', ascii=True, dynamic_ncols=True) 849 | for fpath in fpaths: 850 | with fpath.open('rb', buffering=0) as fobj: 851 | while (read_bytes := fobj.read(self.piece_length - len(piece_bytes))): 852 | piece_bytes += read_bytes 853 | if len(piece_bytes) == self.piece_length: 854 | sha1 += hash(piece_bytes) 855 | piece_bytes = bytes() 856 | pbar1.update(len(read_bytes)) 857 | pbar2.update(1) 858 | sha1 += hash(piece_bytes) if piece_bytes else b'' 859 | pbar1.close() 860 | pbar2.close() 861 | else: # not show progress bar 862 | sha1 = b'' 863 | piece_bytes = bytes() 864 | for fpath in fpaths: 865 | with fpath.open('rb', buffering=0) as fobj: 866 | while (read_bytes := fobj.read(self.piece_length - len(piece_bytes))): 867 | piece_bytes += read_bytes 868 | if len(piece_bytes) == self.piece_length: 869 | sha1 += hash(piece_bytes) 870 | piece_bytes = bytes() 871 | sha1 += hash(piece_bytes) if piece_bytes else b'' 872 | else: 873 | raise EmptySourceSize() 874 | 875 | # Everything looks good, let's update internal parameters 876 | self.name = self.name if keep_name else spath.name 877 | self._srcpath_lst = fpath_list 878 | self._srcsize_lst = fsize_list 879 | self._srcsha1_byt = sha1 880 | 881 | 882 | def write(self, tpath, overwrite=False): 883 | '''Save the torrent to file. 884 | 885 | Arguments: 886 | tpath: path-like object, the path to save the torrent. 887 | If supplied an existing dir, it will be saved under that dir. 888 | overwrite: bool=False, whether to overwrite if the target file already exists. 889 | ''' 890 | tpath = pathlib.Path(tpath) 891 | overwrite = bool(overwrite) 892 | if (error := self.check()): 893 | raise TorrentNotReadyError(f"The torrent is not ready to be saved: {error}.") 894 | 895 | fpath = tpath.joinpath(f"{self.name}.torrent") if tpath.is_dir() else tpath 896 | if fpath.is_file() and not overwrite: 897 | raise FileExistsError(f"The target '{fpath}' already exists.") 898 | else: 899 | fpath.parent.mkdir(parents=True, exist_ok=True) 900 | fpath.write_bytes(bencode(self.torrent_dict, self.encoding)) 901 | 902 | 903 | def verify(self, spath): 904 | '''Verify external source files with the internal torrent. 905 | 906 | Argument: 907 | path: the path to source files. 908 | 909 | Return: 910 | The piece index from 0 that failed to hash 911 | ''' 912 | spath = pathlib.Path(spath) 913 | if not spath.exists(): 914 | raise FileNotFoundError(f"The source path '{spath}' does not exist.") 915 | if (error := self.check()): 916 | raise TorrentNotReadyError(f"The torrent is not ready for verification.") 917 | 918 | if self.num_files == 1: 919 | if spath.is_file() and spath.name == self.name: 920 | spath = spath 921 | elif spath.is_dir(): 922 | raise IsADirectoryError(f"Expect a single file, not a directory '{spath}'.") 923 | else: 924 | raise RuntimeError('Unexpected Error.') 925 | elif self.num_files > 1: 926 | if spath.is_file(): 927 | raise NotADirectoryError(f"Expect a directory, not a single file '{spath}'.") 928 | elif spath.is_dir() and spath.name == self.name: 929 | spath = spath 930 | else: 931 | raise RuntimeError('Unexpected Error.') 932 | else: 933 | raise RuntimeError('Unexpected Error.') 934 | 935 | piece_bytes = bytes() 936 | piece_idx = 0 937 | piece_error_list = [] 938 | for fsize, fpath in self.file_list: 939 | dest_fpath = spath.joinpath(*fpath) 940 | if dest_fpath.is_file(): 941 | read_quota = min(fsize, dest_fpath.stat().st_size) # we only need to load the smaller file size 942 | with dest_fpath.open('rb', buffering=0) as dest_fobj: 943 | while (read_bytes := dest_fobj.read(min(self.piece_length - len(piece_bytes), read_quota))): 944 | piece_bytes += read_bytes 945 | if len(piece_bytes) == self.piece_length: # whole piece loaded 946 | if hash(piece_bytes) != self.pieces[20 * piece_idx : 20 * piece_idx + 20]: # sha1 mismatch 947 | piece_error_list.append(piece_idx) 948 | piece_idx += 1 # whole piece loaded, piece index increase 949 | piece_bytes = bytes() # whole piece loaded, clear existing bytes 950 | if (read_quota := read_quota - len(read_bytes)) == 0: # smaller file read 951 | # we need to fill remaining bytes 952 | piece_bytes += b'\0' * diff if (diff := fsize - dest_fpath.stat().st_size) > 0 else b'' 953 | break 954 | else: # the file does not exist 955 | size = len(piece_bytes) + fsize 956 | n_empty_piece, piece_blank_shift = divmod(size, self.piece_length) 957 | piece_bytes = b'\0' * piece_blank_shift # it should be OK to just replace existing piece_bytes by \0 958 | for _ in range(n_empty_piece): 959 | piece_error_list.append(piece_idx) 960 | piece_idx += 1 961 | if piece_bytes and hash(piece_bytes) != self.pieces[20 * piece_idx : 20 * piece_idx + 20]: # remainder 962 | piece_error_list.append(piece_idx) 963 | 964 | return piece_error_list 965 | 966 | 967 | '''----------------------------------------------------------------------------------------------------------------- 968 | Other helper properties and members 969 | -----------------------------------------------------------------------------------------------------------------''' 970 | 971 | 972 | def check(self): 973 | '''Return the problems within the torrent.''' 974 | ret = [] 975 | if not self.name: 976 | ret.append('Torrent name has not been set.') 977 | if not self.piece_length: 978 | ret.append('Piece size cannot be 0.') 979 | if not self.file_list: 980 | ret.append('There is no source file within the torrent.') 981 | if not self.pieces: 982 | ret.append('Piece hash is empty.') 983 | if not self.size: 984 | ret.append('Torrent size is 0.') 985 | if self.piece_length * (self.num_pieces - 1) > self.size: 986 | ret.append('Too many pieces for content size.') 987 | if self.piece_length * self.num_pieces < self.size: 988 | ret.append('Too less pieces for content size.') 989 | try: 990 | codecs.lookup(self.encoding) 991 | except LookupError as e: 992 | ret.append(f"Invalid encoding {self.encoding}.") 993 | try: 994 | bencode(self.torrent_dict, self.encoding) 995 | except Exception as e: 996 | ret.append(f"Torrent bencoding failed ({e}).") 997 | return ret 998 | 999 | 1000 | def index(self, path, /, num=1): 1001 | '''Given filename, return its piece index. 1002 | 1003 | Arguments: 1004 | filename: str, the filename to find. 1005 | Path parts are matched backward. e.g. 'b/c' will match 'a/b/c' instead of 'b/c/a'. 1006 | num: int=1, stop search when this number of files are found (find all when num <= 0). 1007 | 1008 | Return: 1009 | A list of 3-element tuple of (path, start-index, end-index) 1010 | Indexed in python style, from 0 to len-1, and [m, n+1] for items from m to n 1011 | ''' 1012 | fparts = pathlib.Path(path).parts 1013 | num = int(num) if int(num) > 0 else 0 1014 | if self.check(): 1015 | raise TorrentNotReadyError('Torrent is not ready for indexing.') 1016 | 1017 | ret = [] 1018 | loaded_size = 0 1019 | for fsize, fpath in self.file_list: 1020 | n_shorter = min(len(fpath), len(fparts)) 1021 | if fpath[:-n_shorter-1:-1] == fparts[:-n_shorter-1:-1]: 1022 | ret.append([os.path.join(self.name, *fpath), 1023 | math.floor(loaded_size / self.piece_length), 1024 | math.ceil((loaded_size + fsize) / self.piece_length)]) 1025 | if (num := num - 1) == 0: 1026 | break 1027 | loaded_size += fsize 1028 | 1029 | return ret 1030 | 1031 | 1032 | def __getitem__(self, key): 1033 | '''Given piece index, return files associated with it.''' 1034 | if self.check(): 1035 | raise TorrentNotReadyError('Torrent is not ready to for item getter.') 1036 | 1037 | if isinstance(key, int): 1038 | lsize = self.piece_length * (key if key >= 0 else self.num_pieces + key) 1039 | hsize = lsize + self.piece_length 1040 | elif isinstance(key, slice): 1041 | if key.step in (1, None): 1042 | lsize = self.piece_length * (key.start if key.start >= 0 else self.num_pieces + key.start) 1043 | hsize = self.piece_length * (key.stop if key.stop >= 0 else self.num_pieces + key.stop) 1044 | else: 1045 | raise ValueError(f"Piece index step must be 1, not {key.step}.") 1046 | else: 1047 | raise TypeError(f"Expect int or slice, not {key.__class__}.") 1048 | 1049 | ret = [] 1050 | 1051 | if lsize >= hsize or lsize >= self.size: 1052 | return ret 1053 | 1054 | size = 0 1055 | for fsize, fpath in self.file_list: 1056 | size += fsize 1057 | if size > lsize: 1058 | ret.append(os.path.join(self.name, *fpath)) 1059 | if size >= hsize: 1060 | break 1061 | 1062 | return ret 1063 | 1064 | 1065 | '''===================================================================================================================== 1066 | CLI Class 1067 | =====================================================================================================================''' 1068 | 1069 | class Path(type(pathlib.Path())): 1070 | 1071 | 1072 | def isF(self): 1073 | '''Is file (not torrent).''' 1074 | return self.is_file() and self.suffix.lower() != '.torrent' 1075 | 1076 | 1077 | def isVF(self, path): 1078 | '''Is virtual file (not torrent).''' 1079 | return not self.is_dir() and self.suffix.lower() != '.torrent' 1080 | 1081 | 1082 | def isT(self): 1083 | '''Is torrent.''' 1084 | return self.is_file() and self.suffix.lower() == '.torrent' 1085 | 1086 | 1087 | def isVT(self): 1088 | '''Is virtual torrent.''' 1089 | return not self.is_dir() and self.suffix.lower() == '.torrent' 1090 | 1091 | 1092 | def isD(self): 1093 | '''Is directory.''' 1094 | return self.is_dir() 1095 | 1096 | 1097 | def isVD(self): 1098 | '''Is virtual directory.''' 1099 | return self.is_dir() or not self.is_file() 1100 | 1101 | 1102 | 1103 | 1104 | class Main(): 1105 | 1106 | 1107 | def __init__(self, args): 1108 | self.torrent = Torrent() 1109 | 1110 | # extract cli config from cli arguments 1111 | self.cfg = self.__pickCliCfg(args) 1112 | # infer `mode` from the properties of supplied paths if not specified by the user 1113 | self.mode = self.__pickMode(args.mode, args.fpaths) 1114 | # pick the most appropriate paths for torrent and source path 1115 | self.tpath, self.spath = self.__pickPath(args.fpaths, self.mode) 1116 | # try loading user-defined preset for metadata 1117 | self.metadata = self.__loadPreset(args.preset, self.mode) 1118 | # extract metadata from cli arguments 1119 | self.metadata = self.__pickMetadata(args, self.mode, self.metadata) 1120 | 1121 | 1122 | @staticmethod 1123 | def __pickCliCfg(args): 1124 | if args.show_progress and 'tqdm' not in globals().keys(): 1125 | print("I: Progress bar won't be shown as not installed, consider `python3 -m pip install tqdm`.") 1126 | args.show_progress=False 1127 | cfg = namedtuple('CFG', ' show_prompt show_progress with_time_suffix')( 1128 | args.show_prompt, args.show_progress, args.with_time_suffix) 1129 | return cfg 1130 | 1131 | 1132 | @staticmethod 1133 | def __pickMode(mode, fpaths): 1134 | '''Pick mode from paths is limited: some modes cannot be inferred.''' 1135 | if mode: 1136 | 1137 | if mode not in ('create', 'print', 'modify', 'verify'): 1138 | Main.__exit('E: unexpected error in mode picker, please file a bug report.') 1139 | 1140 | else: # mode == False 1141 | 1142 | if len(fpaths) == 1: 1143 | if fpaths[0].isD() or fpaths[0].isF(): # 1:F/D -> c 1144 | mode = 'create' 1145 | elif fpaths[0].isT(): # 1:T -> p 1146 | mode = 'print' 1147 | else: 1148 | Main.__exit(f"E: You supplied '{fpaths[0]}' cannot suggest a working mode as it does not exist.") 1149 | 1150 | elif len(fpaths) == 2: 1151 | # inferred as `create` mode requires 1 existing and 1 virtual path 1152 | if fpaths[0].isVD() and fpaths[1].isF(): # 1:D(v) 2:F = c 1153 | mode = 'create' 1154 | elif (fpaths[0].isF() or fpaths[0].isD()) and fpaths[1].isVD(): # 1:F/D 2:D(v) = c 1155 | mode = 'create' 1156 | # inferred as `verify` requires both paths existing 1157 | elif fpaths[0].isT() and (fpaths[1].isF() or fpaths[1].isD()): # 1:T 2:F/D = v 1158 | mode = 'verify' 1159 | elif (fpaths[0].isF() or fpaths[0].isD()) and fpaths[1].isT(): # 1:F/D 2:T = v 1160 | mode = 'verify' 1161 | else: 1162 | Main.__exit(f"E: You supplied '{fpaths[0]}' and '{fpaths[1]}' cannot suggest a working mode.") 1163 | 1164 | else: 1165 | Main.__exit(f"E: Expect 1 or 2 positional paths, not {len(fpaths)}.") 1166 | 1167 | print(f"I: Working mode is '{mode}'.") 1168 | return mode 1169 | 1170 | 1171 | @staticmethod 1172 | def __pickPath(fpaths, mode): 1173 | '''Based on the working mode, sort out the most proper paths for torrent and content.''' 1174 | spath = None # Source PATH is the path to the files specified by a torrent 1175 | tpath = None # Torrent PATH is the path to the torrent itself 1176 | 1177 | # `create` mode requires 1 or 2 paths 1178 | # spath must exist, while tpath can be virtual 1179 | if mode == 'create': 1180 | if len(fpaths) == 1: 1181 | if fpaths[0].exists(): # 1:F/D/T 1182 | spath = fpaths[0] 1183 | tpath = spath.parent.joinpath(f"{spath.name}.torrent") 1184 | else: 1185 | Main.__exit(f"E: The source path '{fpaths[0]}' does not exist.") 1186 | elif len(fpaths) == 2: 1187 | if fpaths[0].isVD() and fpaths[1].isF(): # 1:D(v) 2:F 1188 | spath = fpaths[1] 1189 | tpath = fpaths[0].joinpath(f"{spath.name}.torrent") 1190 | elif (fpaths[0].isD() or fpaths[0].isF()) and fpaths[1].isVD(): # 1:F/D 2:D(v) 1191 | spath = fpaths[0] 1192 | tpath = fpaths[1].joinpath(f"{spath.name}.torrent") 1193 | elif fpaths[0].isVT() and (fpaths[1].isD() or fpaths[1].isF()): # 1:T(v) 2:F/D 1194 | spath = fpaths[1] 1195 | tpath = fpaths[0] 1196 | elif (fpaths[0].isD() or fpaths[0].isF()) and fpaths[1].isVT(): # 1:F/D 2:T(v) 1197 | spath = fpaths[0] 1198 | tpath = fpaths[1] 1199 | elif fpaths[0].isT() and fpaths[1].isVT(): # 1:T 2:T(v) 1200 | spath = fpaths[0] 1201 | tpath = fpaths[1] 1202 | elif fpaths[0].isVT() and fpaths[1].isT(): # 1:T(v) 2:T 1203 | spath = fpaths[1] 1204 | tpath = fpaths[0] 1205 | else: 1206 | Main.__exit('E: You supplied paths cannot work in `create` mode.') 1207 | else: 1208 | Main.__exit(f"E: `create` mode expects 1 or 2 paths, not {len(fpaths)}.") 1209 | if spath == tpath: # stop 1:T=2:T 1210 | Main.__exit('E: Source and torrent path cannot be same.') 1211 | if spath.is_file() and spath.suffix.lower() == '.torrent': # warn spath:T 1212 | print('W: You are likely to create torrent from torrent, which may be unexpected.') 1213 | 1214 | # `print` mode requires exactly 1 path 1215 | # the path must be an existing tpath 1216 | elif mode == 'print': 1217 | if len(fpaths) == 1: 1218 | if fpaths[0].isT(): 1219 | tpath = fpaths[0] 1220 | else: 1221 | Main.__exit(f"E: `print` mode expects a valid torrent path, not {fpaths[0]}.") 1222 | else: 1223 | Main.__exit(f"E: `print` mode expects exactly 1 path, not {len(fpaths)}.") 1224 | 1225 | # `verify` mode requires exactly 2 paths 1226 | # inferred as `verify` requires both paths existing 1227 | elif mode == 'verify': 1228 | if len(fpaths) == 2: 1229 | if fpaths[0].isT() and (fpaths[1].isF() or fpaths[1].isD()): 1230 | spath = fpaths[1] 1231 | tpath = fpaths[0] 1232 | elif (fpaths[0].isF() or fpaths[0].isD()) and fpaths[1].isT(): 1233 | spath = fpaths[0] 1234 | tpath = fpaths[1] 1235 | else: 1236 | Main.__exit('E: `verify` mode expects a pair of valid source and torrent paths, but not found.') 1237 | else: 1238 | Main.__exit(f"E: `verify` mode expects exactly 2 paths, not {len(fpaths)}.") 1239 | 1240 | # `modify` mode requires 1 or 2 paths 1241 | elif mode == 'modify': 1242 | if 1 <= len(fpaths) <= 2: 1243 | if fpaths[0].isT(): 1244 | spath = fpaths[0] 1245 | tpath = spath if not fpaths[1:] else ( 1246 | fpaths[1].joinpath(spath.name) if fpaths[1].is_dir() else ( 1247 | fpaths[1] if fpaths[1].suffix.lower() == '.torrent' else \ 1248 | fpaths[1].parent.joinpath(f"{fpaths[1].name}.torrent"))) 1249 | if spath == tpath: 1250 | print('W: You are likely to overwrite the source torrent, which may be unexpected.') 1251 | else: 1252 | Main.__exit(f"E: `modify` mode expects a valid torrent path, not {fpaths[0]}.") 1253 | else: 1254 | Main.__exit(f"E: `modify` mode expects 1 or 2 paths, not {len(fpaths)}.") 1255 | 1256 | else: 1257 | Main.__exit('E: Unexpected point reached in path picker, please file a bug report.') 1258 | 1259 | return tpath, spath 1260 | 1261 | 1262 | @staticmethod 1263 | def __loadPreset(path, mode): 1264 | metadata = dict() 1265 | if mode != 'create': 1266 | return metadata 1267 | 1268 | # prepare a preset candidate to read 1269 | preset_path = None 1270 | if path: 1271 | preset_path = Path(path).absolute() 1272 | if not preset_path.is_file(): 1273 | Main.__exit(f"The preset file '{path}' does not exist.") 1274 | if preset_path.suffix not in ('.json', '.torrent'): 1275 | Main.__exit(f"E: Expect json or torrent to read presets, not '{path}'.") 1276 | else: 1277 | exec_path = sys.executable if getattr(sys, 'frozen', False) else __file__ 1278 | for ext in ('.json', '.torrent'): 1279 | if (_ := Path(exec_path).absolute().with_suffix(ext)).is_file(): 1280 | preset_path = _ 1281 | break 1282 | 1283 | # try read the preset file 1284 | if preset_path: 1285 | try: 1286 | print(f"I: Loading user presets from '{preset_path}'...", end=' ', flush=True) 1287 | if preset_path.suffix == '.torrent': 1288 | (d := Torrent()).read(preset_path) 1289 | elif preset_path.suffix == '.json': 1290 | d = json.loads(preset_path.read_bytes()) 1291 | else: 1292 | Main.__exit('E: Unexpected point reached in loading preset, please file a bug report.') 1293 | 1294 | if _ := d.get('tracker_list'): 1295 | if isinstance(_, list) and all(isinstance(i, str) for i in _): 1296 | metadata['tracker_list'] = _ 1297 | else: 1298 | print('W: tracker list is not loaded as incorrect format.') 1299 | if d.get('comment'): metadata['comment'] = str(d.get('comment')) 1300 | if d.get('created_by'): metadata['created_by'] = str(d.get('created_by')) 1301 | if d.get('creation_date'): 1302 | if preset_path.suffix == '.torrent': 1303 | pass # don't copy date if preset is a torrent file 1304 | else: 1305 | metadata['creation_date'] = int(d.get('creation_date')) 1306 | if d.get('encoding'): metadata['encoding'] = str(d.get('encoding')) 1307 | if d.get('piece_size'): 1308 | metadata['piece_size'] = int(d.get('piece_size')) 1309 | if preset_path.suffix != '.torrent': 1310 | metadata['piece_size'] = int(d.get('piece_size')) << 10 1311 | if d.get('private'): metadata['private'] = int(d.get('private')) 1312 | if d.get('source'): metadata['source'] = str(d.get('source')) 1313 | except FileNotFoundError: 1314 | Main.__exit('failed (file not found)') 1315 | except UnicodeDecodeError: 1316 | Main.__exit('failed (invalid file)') 1317 | except json.decoder.JSONDecodeError: 1318 | Main.__exit('failed (invalid file)') 1319 | except BdecodeError: 1320 | Main.__exit('failed (invalid file)') 1321 | except KeyError: 1322 | Main.__exit('failed (missing key)') 1323 | else: 1324 | print('succeeded') 1325 | 1326 | return metadata 1327 | 1328 | 1329 | @staticmethod 1330 | def __pickMetadata(args, mode, metadata): 1331 | 1332 | if mode == 'create': 1333 | metadata['tracker_list'] = args.tracker_list if args.tracker_list else ( 1334 | _ if (_ := metadata.get('tracker_list')) else []) 1335 | metadata['comment'] = args.comment if args.comment else ( 1336 | _ if (_ := metadata.get('comment')) else '') 1337 | metadata['created_by'] = args.created_by if args.created_by else ( 1338 | _ if (_ := metadata.get('created_by')) else 'https://github.com/airium/TorrentUtils') 1339 | metadata['creation_date'] = args.creation_date if args.creation_date else ( 1340 | _ if (_ := metadata.get('creation_date')) else int(time.time())) 1341 | metadata['encoding'] = args.encoding if args.encoding else ( 1342 | _ if (_ := metadata.get('encoding')) else 'UTF-8') 1343 | metadata['piece_size'] = args.piece_size << 10 if args.piece_size else ( 1344 | _ if (_ := metadata.get('piece_size')) else 4096 << 10) # B -> KiB 1345 | metadata['private'] = args.private if args.private else ( 1346 | _ if (_ := metadata.get('private')) else 0) 1347 | metadata['source'] = args.source if args.source else ( 1348 | _ if (_ := metadata.get('source')) else '') 1349 | 1350 | elif mode == 'modify': 1351 | if not (args.tracker_list is None): metadata['tracker_list'] = args.tracker_list 1352 | if not (args.comment is None): metadata['comment'] = args.comment 1353 | if not (args.created_by is None): metadata['created_by'] = args.created_by 1354 | if not (args.creation_date is None): metadata['creation_date'] = args.creation_date 1355 | if not (args.encoding is None): metadata['encoding'] = args.encoding 1356 | if not (args.piece_size is None): 1357 | print('W: supplied piece size has no effect in `modify` mode.') 1358 | if 'piece_size' in metadata.keys(): # if piece_size is loaded from json, remove it 1359 | metadata.pop('piece_size') 1360 | if not (args.private is None): metadata['private'] = args.private 1361 | if not (args.source is None): metadata['source'] = args.source 1362 | 1363 | else: # `print` or `verify` 1364 | if not (args.tracker_list is None): print(f"W: supplied tracker has not effect in {mode} mode.") 1365 | if not (args.comment is None): print(f"W: supplied comment has not effect in {mode} mode.") 1366 | if not (args.created_by is None): print(f"W: supplied creator has not effect in {mode} mode.") 1367 | if not (args.creation_date is None): print(f"W: supplied time has not effect in {mode} mode.") 1368 | if not (args.encoding is None): print(f"W: supplied encoding has not effect in {mode} mode.") 1369 | if not (args.piece_size is None): print(f"W: supplied piece size has not effect in {mode} mode.") 1370 | if not (args.private is None): print(f"W: supplied private attribute has not effect in {mode} mode.") 1371 | if not (args.source is None): print(f"W: supplied source has not effect in {mode} mode.") 1372 | 1373 | return metadata 1374 | 1375 | 1376 | @staticmethod 1377 | def __exit(chars=''): 1378 | input(chars + '\nTerminated. (Press ENTER to exit)') 1379 | sys.exit() 1380 | 1381 | 1382 | def __prompt(self, chars): 1383 | if (not self.cfg.show_prompt) or input(chars).lower() in ('y', 'yes'): 1384 | return True 1385 | else: 1386 | return False 1387 | 1388 | 1389 | def __call__(self): 1390 | if self.mode == 'create': 1391 | print(f"I: Creating torrent from '{self.spath}'.") 1392 | self._set() 1393 | self._load() 1394 | self._write() 1395 | elif self.mode == 'print': 1396 | self._read() 1397 | self._print() 1398 | elif self.mode == 'verify': 1399 | print('I: Verifying Source files with Torrent.') 1400 | print(f"Source: '{self.spath}'") 1401 | print(f"Torrent: '{self.tpath}'") 1402 | self._read() 1403 | self._verify() 1404 | elif self.mode == 'modify': 1405 | print(f"I: Modifying torrent '{self.spath}'.") 1406 | self._read() 1407 | self._set() 1408 | self._write() 1409 | else: 1410 | self.__exit(f"Invalid mode: {mode}.") 1411 | 1412 | print(); 1413 | input('Press ENTER to exit...') 1414 | 1415 | 1416 | def _print(self): 1417 | tname = self.torrent.name 1418 | tsize = self.torrent.torrent_size 1419 | tencd = self.torrent.encoding 1420 | thash = self.torrent.hash 1421 | fsize = self.torrent.size 1422 | fnum = len(self.torrent.file_list) 1423 | psize = self.torrent.piece_length >> 10 1424 | pnum = self.torrent.num_pieces 1425 | tdate = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(self.torrent.creation_date)) \ 1426 | if self.torrent.creation_date else '' 1427 | tfrom = self.torrent.created_by if self.torrent.created_by else '' 1428 | tpriv = 'Private' if self.torrent.private else 'Public' 1429 | tsour = self.torrent.source 1430 | tcomm = self.torrent.comment 1431 | 1432 | width = shutil.get_terminal_size()[0] 1433 | 1434 | print(f'General Info ' + '-' * (width - 14)) 1435 | print(f"Name: {tname}") 1436 | print(f"File: {tsize:,} Bytes, Bencoded" + (f" with {tencd}" if tencd else '')) 1437 | print(f"Hash: {thash}") 1438 | print(f"Size: {fsize:,} Bytes" + f", {fnum} File" + ('s' if fnum > 1 else '') + f", {psize} KiB x {pnum} Pieces") 1439 | if tdate and tfrom: 1440 | print(f"Time: {tdate} by {tfrom}") 1441 | elif tdate: 1442 | print(f"Time: {tdate}") 1443 | elif tfrom: 1444 | print(f"From: {tdate}") 1445 | if tcomm: 1446 | print(f"Comm: {tcomm}") 1447 | print(f"Else: {tpriv} torrent" + (f" by {tsour}" if tsour else '')) 1448 | 1449 | print(f'Trackers ' + '-' * (width - 10)) 1450 | if self.torrent.tracker_list: 1451 | trnum = math.ceil(math.log10(len(self.torrent.tracker_list))) if self.torrent.tracker_list else 0 1452 | for i, url in enumerate(self.torrent.tracker_list, start=1): 1453 | print(eval("f'{i:0>" + str(trnum) + "}: {url}'")) 1454 | else: 1455 | print('No tracker') 1456 | 1457 | print(f'Files ' + '-' * (width - 7)) 1458 | if fnum == 1: 1459 | print(f'1: {tname}') 1460 | else: 1461 | fnum = math.ceil(math.log10(fnum)) if fnum else 0 1462 | for i, (fsize, fpath) in enumerate(self.torrent.file_list, start=1): 1463 | print(eval("f'{i:0>" + str(fnum) + "}: {os.path.join(fpath[0], *fpath[1:])} ({fsize:,} bytes)'")) 1464 | if i == 500 and self.cfg.show_prompt: 1465 | print('Truncated at 500 files (use -y/--yes to list all)') 1466 | break 1467 | 1468 | 1469 | def _load(self): 1470 | try: 1471 | self.torrent.load(self.spath, False, self.cfg.show_progress) 1472 | except EmptySourceSize: 1473 | self.__exit(f"The source path '{self.spath.absolute()}' has a total size of 0.") 1474 | 1475 | 1476 | def _read(self): 1477 | if self.mode in ('verify', 'print'): 1478 | self.torrent.read(self.tpath) 1479 | elif self.mode == 'modify': 1480 | self.torrent.read(self.spath) 1481 | else: 1482 | self.__exit(f"Unexpected {self.mode} mode for read operation.") 1483 | 1484 | 1485 | def _verify(self): 1486 | spath = self.spath 1487 | tname = self.torrent.name 1488 | 1489 | if self.torrent.num_files == 1: 1490 | if spath.is_file() and spath.name == tname: 1491 | spath = self.spath 1492 | elif spath.is_dir(): 1493 | if Path(tname) in spath.iterdir() and (tmp := spath.joinpath(tname)).is_file(): 1494 | spath = tmp 1495 | else: 1496 | self.__exit(f"E: The source file '{spath}' was not found.") 1497 | elif self.torrent.num_files > 1: 1498 | if spath.is_file(): 1499 | self.__exit(f"E: The source directory '{spath}' was not found.") 1500 | elif spath.is_dir(): 1501 | if spath.name == tname: 1502 | spath = spath 1503 | elif Path(tname) in spath.iterdir() and (tmp := spath.joinpath(self.name)).is_dir(): 1504 | spath = tmp 1505 | else: 1506 | self.__exit(f"E: The source directory '{spath}' was not found.") 1507 | 1508 | piece_broken_list = self.torrent.verify(spath) 1509 | ptotal = self.torrent.num_pieces 1510 | pbroken = len(piece_broken_list) 1511 | ppassed = ptotal - pbroken 1512 | 1513 | 1514 | files_broken_list = [self.torrent[i] for i in piece_broken_list] 1515 | files_broken_list = list(dict.fromkeys(chain(*files_broken_list))) 1516 | ftotal = self.torrent.num_files 1517 | fbroken = len(files_broken_list) 1518 | fpassed = ftotal - fbroken 1519 | 1520 | print('Processing...') 1521 | print(f"Piece: {ptotal:>10d} total = {ppassed:>10d} passed + {pbroken:>10d} missing or broken") 1522 | print(f"Files: {ftotal:>10d} total = {fpassed:>10d} passed + {fbroken:>10d} missing or broken") 1523 | if files_broken_list: 1524 | print('Files missing or broken:') 1525 | for i, fpath in enumerate(files_broken_list): 1526 | print(spath.parent.joinpath(fpath)) 1527 | if i == 49: 1528 | if fbroken > 50: 1529 | print('Truncated at 50 files - too many potential missing or broken files.') 1530 | break 1531 | print('\nI: Some files may be in fact OK but cannot be verified as their neighbour files failed.') 1532 | 1533 | 1534 | def _set(self): 1535 | try: 1536 | self.torrent.set(**self.metadata) 1537 | except PieceSizeTooSmall as e: 1538 | self.__exit(f"Piece size must be larger than 16KiB, not {self.metadata['piece_size']} bytes.") 1539 | except PieceSizeUncommon as e: 1540 | if self.__prompt(f"Uncommon piece size {self.metadata['piece_size'] >> 10} KiB. Confirm? (y/N): "): 1541 | self.torrent.setPieceLength(self.metadata['piece_size'], no_check=True) 1542 | self.metadata.pop('piece_size') 1543 | self.torrent.set(**self.metadata) 1544 | else: 1545 | self.__exit() 1546 | 1547 | 1548 | def _write(self): 1549 | fpath = self.tpath.with_suffix( 1550 | f"{'.' + time.strftime('%y%m%d-%H%M%S') if self.cfg.with_time_suffix else ''}.torrent") 1551 | try: 1552 | self.torrent.write(fpath, overwrite=False) 1553 | print(f"I: Torrent saved to '{fpath}'.") 1554 | except FileExistsError as e: 1555 | if self.__prompt(f"The target file '{fpath}' already exists. Overwrite? (y/N): "): 1556 | self.torrent.write(fpath, overwrite=True) 1557 | print(f"I: Torrent saved to '{fpath}' (overwritten).") 1558 | else: 1559 | self.__exit() 1560 | except IsADirectoryError as e: 1561 | self.__exit(f"E: The target '{fpath}' is a directory.") 1562 | 1563 | 1564 | 1565 | 1566 | '''===================================================================================================================== 1567 | CLI Interface 1568 | =====================================================================================================================''' 1569 | 1570 | 1571 | class _CustomHelpFormatter(argparse.HelpFormatter): 1572 | 1573 | def __init__(self, prog): 1574 | super().__init__(prog, max_help_position=50, width=100) 1575 | 1576 | def _format_action_invocation(self, action): 1577 | if not action.option_strings or action.nargs == 0: 1578 | return super()._format_action_invocation(action) 1579 | default = self._get_default_metavar_for_optional(action) 1580 | args_string = self._format_args(action, default) 1581 | return ', '.join(action.option_strings) + ' ' + args_string 1582 | 1583 | 1584 | if __name__ == '__main__': 1585 | parser = argparse.ArgumentParser(prog='tu', formatter_class=lambda prog: _CustomHelpFormatter(prog)) 1586 | 1587 | parser.add_argument('fpaths', type=Path, nargs='*', 1588 | help='1 or 2 paths depending on mode', metavar='path') 1589 | parser.add_argument('-m', '--mode', dest='mode', choices=('create', 'print', 'verify', 'modify'), 1590 | help='mode will be inferred from paths if not specified') 1591 | parser.add_argument('-t', '--tracker', dest='tracker_list', type=str, action='extend', nargs='+', 1592 | help='trackers can be supplied multiple times', metavar='url') 1593 | parser.add_argument('-c', '--comment', dest='comment', type=str, 1594 | help='your message to show in various clients', metavar='text') 1595 | parser.add_argument('-s', '--piece-size', dest='piece_size', type=int, 1596 | help='piece size in KiB (default: 4096)', metavar='number') 1597 | parser.add_argument('-p', '--private', dest='private', type=int, choices={0, 1}, 1598 | help='private torrent if 1 (default: 0)') 1599 | parser.add_argument('--by', dest='created_by', type=str, 1600 | help='set the creator of the torrent (default: Github)', metavar='text') 1601 | parser.add_argument('--time', dest='creation_date', type=int, 1602 | help='set the time in second since 19700101 (default: now)', metavar='number') 1603 | parser.add_argument('--encoding', dest='encoding', type=str, 1604 | help='set the text encoding (default&recommended: UTF-8)', metavar='text') 1605 | parser.add_argument('--source', dest='source', type=str, 1606 | help='set the special source message (will change hash)', metavar='text') 1607 | parser.add_argument('--preset', dest='preset', type=Path, 1608 | help='load a preset file for metadata in creating torrent', metavar='path') 1609 | parser.add_argument('--no-progress', dest='show_progress', action='store_false', 1610 | help='disable progress bar in creating torrent') 1611 | parser.add_argument('--time-suffix', dest='with_time_suffix', action='store_true', 1612 | help='append current time to torrent filename') 1613 | parser.add_argument('-y', '--yes', dest='show_prompt', action='store_false', 1614 | help='just say yes - don\'t ask any question') 1615 | parser.add_argument('--version', action='version', version='TorrentUtils 0.1.0.2') 1616 | 1617 | Main(parser.parse_args())() 1618 | --------------------------------------------------------------------------------