├── LICENSE ├── README.md └── parser.py /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.md: -------------------------------------------------------------------------------- 1 | ## How do I use it? 2 | 1. [Download your Twitter archive](https://twitter.com/settings/download_your_data) (Settings > Your account > Download an archive of your data). 3 | 2. Unzip to a folder. 4 | 3. Right-click this link --> [parser.py](https://raw.githubusercontent.com/timhutton/twitter-archive-parser/main/parser.py) <-- and select "Save Link as", and save into the folder where you extracted the archive. (Or use wget or curl on that link. Or clone the git repo.) 5 | 4. Open a command prompt and change directory into the unzipped folder where you just saved parser.py. 6 | (**Here's how to do that on Windows:** Hold shift while right-clicking in the folder. Click on `Open PowerShell`.) 7 | 5. Run parser.py with [Python 3](https://realpython.com/installing-python/). e.g. `python parser.py`. 8 | (**On Windows:** When the command window opens, paste or enter `python parser.py` at the command prompt.) 9 | 10 | 11 | 12 | If you are having problems please check the [issues list](https://github.com/timhutton/twitter-archive-parser/issues?q=is%3Aissue) to see if it has happened before, and open a new issue otherwise. 13 | 14 | ## What does it do? 15 | The Twitter archive gives you a bunch of data and an HTML file (`Your archive.html`). Open that file to take a look! It lets you view your tweets in a nice interface. It has some flaws but maybe that's all you need. If so then stop here, you don't need our script. 16 | 17 | Flaws of the Twitter archive: 18 | - It shows you tweets you posted with images, but if you click on one of the images to expand it then it takes you to the Twitter website. If you are offline or have deleted your account or twitter.com is down then that won't work. 19 | - The tweets are stored in a complex JSON structure so you can't just copy them into your blog for example. 20 | - The images they give you are smaller than the ones you uploaded. I don't know why they would do this to us. 21 | - DMs are included but don't show you who they are from - many of the user handles aren't included in the archive. 22 | - The links are all obfuscated in a short form using t.co, which hides their origin and redirects traffic to Twitter, giving them analytics. Also they will stop working if t.co goes down. 23 | 24 | Our script does the following: 25 | - Converts the tweets to [markdown](https://en.wikipedia.org/wiki/Markdown) and also HTML, with embedded images, videos and links. 26 | - Replaces t.co URLs with their original versions (the ones that can be found in the archive). 27 | - Copies used images to an output folder, to allow them to be moved to a new home. 28 | - Will query Twitter for the missing user handles (checks with you first). 29 | - Converts DMs (including group DMs) to markdown with embedded media and links, including the handles that we retrieved. 30 | - Outputs lists of followers and following. 31 | - Downloads the original size images (checks with you first). 32 | 33 | ### For advanced users: 34 | 35 | Some of the functionality requires the `requests` and `imagesize` modules. `parser.py` will offer to install these for you using pip. To avoid that you can install them before running the script. 36 | 37 | ## Articles about handling your Twitter archive: 38 | - https://techcrunch.com/2022/11/21/quit-twitter-better-with-these-free-tools-that-make-archiving-a-breeze/ 39 | - https://www.bitsgalore.org/2022/11/20/how-to-preserve-your-personal-twitter-archive 40 | - https://matthiasott.com/notes/converting-your-twitter-archive-to-markdown 41 | 42 | ## Related tools: 43 | If our script doesn't do what you want then maybe a different tool will help: 44 | - https://github.com/Webklex/tbm download Twitter bookmarks incl. download of all media, GUI/search interface via local server 45 | - https://github.com/selfawaresoup/twitter-tools 46 | - https://github.com/roobottom/twitter-archive-to-markdown-files 47 | - https://gist.github.com/divyajyotiuk/9fb29c046e1dfcc8d5683684d7068efe#file-get_twitter_bookmarks_v3-py 48 | - https://archive.alt-text.org/ 49 | - https://observablehq.com/@enjalot/twitter-archive-tweets 50 | - https://github.com/woluxwolu/twint 51 | - https://github.com/jarulsamy/Twitter-Archive 52 | - https://sk22.github.io/twitter-archive-browser/ 53 | - https://pypi.org/project/pleroma-bot/ 54 | - https://github.com/mshea/Parse-Twitter-Archive 55 | - https://github.com/dangoldin/twitter-archive-analysis 56 | - https://fedi.doom.solutions/tumelune/ 57 | - https://github.com/mhucka/taupe 58 | -------------------------------------------------------------------------------- /parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | twitter-archive-parser - Python code to parse a Twitter archive and output in various ways 4 | Copyright (C) 2022 Tim Hutton - https://github.com/timhutton/twitter-archive-parser 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | from collections import defaultdict 21 | from typing import Optional 22 | from urllib.parse import urlparse 23 | import datetime 24 | import glob 25 | import importlib 26 | import json 27 | import logging 28 | import os 29 | import re 30 | import shutil 31 | import subprocess 32 | import sys 33 | import time 34 | # hot-loaded if needed, see import_module(): 35 | # imagesize 36 | # requests 37 | 38 | 39 | # Print a compile-time error in Python < 3.6. This line does nothing in Python 3.6+ but is reported to the user 40 | # as an error (because it is the first line that fails to compile) in older versions. 41 | f' Error: This script requires Python 3.6 or later. Use `python --version` to check your version.' 42 | 43 | 44 | class UserData: 45 | def __init__(self, user_id: str, handle: str): 46 | if user_id is None: 47 | raise ValueError('ID "None" is not allowed in UserData.') 48 | self.user_id = user_id 49 | if handle is None: 50 | raise ValueError('handle "None" is not allowed in UserData.') 51 | self.handle = handle 52 | 53 | 54 | class PathConfig: 55 | """ 56 | Helper class containing constants for various directories and files. 57 | 58 | The script will only add / change / delete content in its own directories, which start with `parser-`. 59 | Files within `parser-output` are the end result that the user is probably interested in. 60 | Files within `parser-cache` are temporary working files, which improve the efficiency if you run 61 | this script multiple times. They can safely be removed without harming the consistency of the 62 | files within `parser-output`. 63 | """ 64 | def __init__(self, dir_archive): 65 | self.dir_archive = dir_archive 66 | self.dir_input_data = os.path.join(dir_archive, 'data') 67 | self.file_account_js = os.path.join(self.dir_input_data, 'account.js') 68 | 69 | # check if user is in correct folder 70 | if not os.path.isfile(self.file_account_js): 71 | print(f'Error: Failed to load {self.file_account_js}. ') 72 | exit() 73 | 74 | self.dir_input_media = find_dir_input_media(self.dir_input_data) 75 | self.dir_output = os.path.join(self.dir_archive, 'parser-output') 76 | self.dir_output_media = os.path.join(self.dir_output, 'media') 77 | self.dir_output_cache = os.path.join(self.dir_archive, 'parser-cache') 78 | self.file_output_following = os.path.join(self.dir_output, 'following.txt') 79 | self.file_output_followers = os.path.join(self.dir_output, 'followers.txt') 80 | self.file_download_log = os.path.join(self.dir_output_media, 'download_log.txt') 81 | self.file_tweet_icon = os.path.join(self.dir_output_media, 'tweet.ico') 82 | self.files_input_tweets = find_files_input_tweets(self.dir_input_data) 83 | 84 | # structured like an actual tweet output file, can be used to compute relative urls to a media file 85 | self.example_file_output_tweets = self.create_path_for_file_output_tweets(year=2020, month=12) 86 | 87 | def create_path_for_file_output_tweets(self, year, month, format="html", kind="tweets") -> str: 88 | """Builds the path for a tweet-archive file based on some properties.""" 89 | # Previously the filename was f'{dt.year}-{dt.month:02}-01-Tweet-Archive-{dt.year}-{dt.month:02}' 90 | return os.path.join(self.dir_output, f"{kind}-{format}", f"{year:04}", f"{year:04}-{month:02}-01-{kind}.{format}") 91 | 92 | def create_path_for_file_output_dms(self, name: str, index: Optional[int]=None, format: str="html", kind: str="DMs") -> str: 93 | """Builds the path for a dm-archive file based on some properties.""" 94 | index_suffix = "" 95 | if (index): 96 | index_suffix = f"-part{index:03}" 97 | return os.path.join(self.dir_output, kind, f"{kind}-{name}{index_suffix}.{format}") 98 | 99 | def create_path_for_file_output_single(self, format: str, kind: str)->str: 100 | """Builds the path for a single output file which, i.e. one that is not part of a larger group or sequence.""" 101 | return os.path.join(self.dir_output, f"{kind}.{format}") 102 | 103 | 104 | def get_consent(prompt: str, default_to_yes: bool = False): 105 | """Asks the user for consent, using the given prompt. Accepts various versions of yes/no, or 106 | an empty answer to accept the default. The default is 'no' unless default_to_yes is passed as 107 | True. The default will be indicated automatically. For unacceptable answers, the user will 108 | be asked again.""" 109 | if default_to_yes: 110 | suffix = " [Y/n]" 111 | default_answer = "yes" 112 | else: 113 | suffix = " [y/N]" 114 | default_answer = "no" 115 | while True: 116 | user_input = input(prompt + suffix) 117 | if user_input == "": 118 | print (f"Your empty response was assumed to mean '{default_answer}' (the default for this question).") 119 | return default_to_yes 120 | if user_input.lower() in ('y', 'yes'): 121 | return True 122 | if user_input.lower() in ('n', 'no'): 123 | return False 124 | print (f"Sorry, did not understand. Please answer with y, n, yes, no, or press enter to accept " 125 | f"the default (which is '{default_answer}' in this case, as indicated by the uppercase " 126 | f"'{default_answer.upper()[0]}'.)") 127 | 128 | 129 | def import_module(module): 130 | """Imports a module specified by a string. Example: requests = import_module('requests')""" 131 | try: 132 | return importlib.import_module(module) 133 | except ImportError: 134 | print(f'\nError: This script uses the "{module}" module which is not installed.\n') 135 | if not get_consent('OK to install using pip?'): 136 | exit() 137 | subprocess.run([sys.executable, '-m', 'pip', 'install', module], check=True) 138 | return importlib.import_module(module) 139 | 140 | 141 | def open_and_mkdirs(path_file): 142 | """Opens a file for writing. If the parent directory does not exist yet, it is created first.""" 143 | mkdirs_for_file(path_file) 144 | return open(path_file, 'w', encoding='utf-8') 145 | 146 | 147 | def mkdirs_for_file(path_file): 148 | """Creates the parent directory of the given file, if it does not exist yet.""" 149 | path_dir = os.path.split(path_file)[0] 150 | os.makedirs(path_dir, exist_ok=True) 151 | 152 | 153 | def rel_url(media_path, document_path): 154 | """Computes the relative URL needed to link from `document_path` to `media_path`. 155 | Assumes that `document_path` points to a file (e.g. `.md` or `.html`), not a directory.""" 156 | return os.path.relpath(media_path, os.path.split(document_path)[0]).replace("\\", "/") 157 | 158 | 159 | def get_twitter_api_guest_token(session, bearer_token): 160 | """Returns a Twitter API guest token for the current session.""" 161 | guest_token_response = session.post("https://api.twitter.com/1.1/guest/activate.json", 162 | headers={'authorization': f'Bearer {bearer_token}'}, 163 | timeout=2, 164 | ) 165 | guest_token = json.loads(guest_token_response.content)['guest_token'] 166 | if not guest_token: 167 | raise Exception(f"Failed to retrieve guest token") 168 | return guest_token 169 | 170 | 171 | def get_twitter_users(session, bearer_token, guest_token, user_ids): 172 | """Asks Twitter for all metadata associated with user_ids.""" 173 | users = {} 174 | while user_ids: 175 | max_batch = 100 176 | user_id_batch = user_ids[:max_batch] 177 | user_ids = user_ids[max_batch:] 178 | user_id_list = ",".join(user_id_batch) 179 | query_url = f"https://api.twitter.com/1.1/users/lookup.json?user_id={user_id_list}" 180 | response = session.get(query_url, 181 | headers={'authorization': f'Bearer {bearer_token}', 'x-guest-token': guest_token}, 182 | timeout=2, 183 | ) 184 | if not response.status_code == 200: 185 | raise Exception(f'Failed to get user handle: {response}') 186 | response_json = json.loads(response.content) 187 | for user in response_json: 188 | users[user["id_str"]] = user 189 | return users 190 | 191 | 192 | def lookup_users(user_ids, users): 193 | """Fill the users dictionary with data from Twitter""" 194 | # Filter out any users already known 195 | filtered_user_ids = [id for id in user_ids if id not in users] 196 | if not filtered_user_ids: 197 | # Don't bother opening a session if there's nothing to get 198 | return 199 | # Account metadata observed at ~2.1KB on average. 200 | estimated_size = int(2.1 * len(filtered_user_ids)) 201 | print(f'{len(filtered_user_ids)} users are unknown.') 202 | if not get_consent(f'Download user data from Twitter (approx {estimated_size:,} KB)?'): 203 | return 204 | 205 | requests = import_module('requests') 206 | try: 207 | with requests.Session() as session: 208 | bearer_token = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA' 209 | guest_token = get_twitter_api_guest_token(session, bearer_token) 210 | retrieved_users = get_twitter_users(session, bearer_token, guest_token, filtered_user_ids) 211 | for user_id, user in retrieved_users.items(): 212 | if user["screen_name"] is not None: 213 | users[user_id] = UserData(user_id=user_id, handle=user["screen_name"]) 214 | print() # empty line for better readability of output 215 | except Exception as err: 216 | print(f'Failed to download user data: {err}') 217 | 218 | 219 | def read_json_from_js_file(filename): 220 | """Reads the contents of a Twitter-produced .js file into a dictionary.""" 221 | print(f'Parsing {filename}...') 222 | with open(filename, 'r', encoding='utf8') as f: 223 | data = f.readlines() 224 | # if the JSON has no real content, it can happen that the file is only one line long. 225 | # in this case, return an empty dict to avoid errors while trying to read non-existing lines. 226 | if len(data) <= 1: 227 | return {} 228 | # convert js file to JSON: replace first line with just '[', squash lines into a single string 229 | prefix = '[' 230 | if '{' in data[0]: 231 | prefix += ' {' 232 | data = prefix + ''.join(data[1:]) 233 | # parse the resulting JSON and return as a dict 234 | return json.loads(data) 235 | 236 | 237 | def extract_username(paths: PathConfig): 238 | """Returns the user's Twitter username from account.js.""" 239 | account = read_json_from_js_file(paths.file_account_js) 240 | return account[0]['account']['username'] 241 | 242 | 243 | def escape_markdown(input_text: str) -> str: 244 | """ 245 | Escape markdown control characters from input text so that the text will not break in rendered markdown. 246 | (Only use on unformatted text parts that do not yet have any markdown control characters added on purpose!) 247 | """ 248 | characters_to_escape: str = r"\_*[]()~`>#+-=|{}.!" 249 | output_text: str = '' 250 | for char in input_text: 251 | if char in characters_to_escape: 252 | # add backslash before control char 253 | output_text = output_text + "\\" + char 254 | elif char == '\n': 255 | # add double space before line break 256 | output_text = output_text + " " + char 257 | else: 258 | output_text = output_text + char 259 | return output_text 260 | 261 | 262 | def convert_tweet(tweet, username, media_sources, users: dict, paths: PathConfig): 263 | """Converts a JSON-format tweet. Returns tuple of timestamp, markdown and HTML.""" 264 | if 'tweet' in tweet.keys(): 265 | tweet = tweet['tweet'] 266 | timestamp_str = tweet['created_at'] 267 | timestamp = int(round(datetime.datetime.strptime(timestamp_str, '%a %b %d %X %z %Y').timestamp())) 268 | # Example: Tue Mar 19 14:05:17 +0000 2019 269 | body_markdown = tweet['full_text'] 270 | body_html = tweet['full_text'] 271 | tweet_id_str = tweet['id_str'] 272 | # for old tweets before embedded t.co redirects were added, ensure the links are 273 | # added to the urls entities list so that we can build correct links later on. 274 | if 'entities' in tweet and 'media' not in tweet['entities'] and len(tweet['entities'].get("urls", [])) == 0: 275 | for word in tweet['full_text'].split(): 276 | try: 277 | url = urlparse(word) 278 | except ValueError: 279 | pass # don't crash when trying to parse something that looks like a URL but actually isn't 280 | else: 281 | if url.scheme != '' and url.netloc != '' and not word.endswith('\u2026'): 282 | # Shorten links similar to twitter 283 | netloc_short = url.netloc[4:] if url.netloc.startswith("www.") else url.netloc 284 | path_short = url.path if len(url.path + '?' + url.query) < 15 \ 285 | else (url.path + '?' + url.query)[:15] + '\u2026' 286 | tweet['entities']['urls'].append({ 287 | 'url': word, 288 | 'expanded_url': word, 289 | 'display_url': netloc_short + path_short, 290 | 'indices': [tweet['full_text'].index(word), tweet['full_text'].index(word) + len(word)], 291 | }) 292 | # replace t.co URLs with their original versions 293 | if 'entities' in tweet and 'urls' in tweet['entities']: 294 | for url in tweet['entities']['urls']: 295 | if 'url' in url and 'expanded_url' in url: 296 | expanded_url = url['expanded_url'] 297 | body_markdown = body_markdown.replace(url['url'], expanded_url) 298 | expanded_url_html = f'{expanded_url}' 299 | body_html = body_html.replace(url['url'], expanded_url_html) 300 | # if the tweet is a reply, construct a header that links the names 301 | # of the accounts being replied to the tweet being replied to 302 | header_markdown = '' 303 | header_html = '' 304 | if 'in_reply_to_status_id' in tweet: 305 | # match and remove all occurrences of '@username ' at the start of the body 306 | replying_to = re.match(r'^(@[0-9A-Za-z_]* )*', body_markdown)[0] 307 | if replying_to: 308 | body_markdown = body_markdown[len(replying_to):] 309 | body_html = body_html[len(replying_to):] 310 | else: 311 | # no '@username ' in the body: we're replying to self 312 | replying_to = f'@{username}' 313 | names = replying_to.split() 314 | # some old tweets lack 'in_reply_to_screen_name': use it if present, otherwise fall back to names[0] 315 | in_reply_to_screen_name = tweet['in_reply_to_screen_name'] if 'in_reply_to_screen_name' in tweet else names[0] 316 | # create a list of names of the form '@name1, @name2 and @name3' - or just '@name1' if there is only one name 317 | name_list = ', '.join(names[:-1]) + (f' and {names[-1]}' if len(names) > 1 else names[0]) 318 | in_reply_to_status_id = tweet['in_reply_to_status_id'] 319 | replying_to_url = f'https://twitter.com/{in_reply_to_screen_name}/status/{in_reply_to_status_id}' 320 | header_markdown += f'Replying to [{escape_markdown(name_list)}]({replying_to_url})\n\n' 321 | header_html += f'Replying to {name_list}
' 322 | # escape tweet body for markdown rendering: 323 | body_markdown = escape_markdown(body_markdown) 324 | # replace image URLs with image links to local files 325 | if 'entities' in tweet and 'media' in tweet['entities'] and 'extended_entities' in tweet \ 326 | and 'media' in tweet['extended_entities']: 327 | original_url = tweet['entities']['media'][0]['url'] 328 | markdown = '' 329 | html = '' 330 | for media in tweet['extended_entities']['media']: 331 | if 'url' in media and 'media_url' in media: 332 | original_expanded_url = media['media_url'] 333 | original_filename = os.path.split(original_expanded_url)[1] 334 | archive_media_filename = tweet_id_str + '-' + original_filename 335 | archive_media_path = os.path.join(paths.dir_input_media, archive_media_filename) 336 | file_output_media = os.path.join(paths.dir_output_media, archive_media_filename) 337 | media_url = rel_url(file_output_media, paths.example_file_output_tweets) 338 | markdown += '' if not markdown and body_markdown == escape_markdown(original_url) else '\n\n' 339 | html += '' if not html and body_html == original_url else '
' 340 | if os.path.isfile(archive_media_path): 341 | # Found a matching image, use this one 342 | if not os.path.isfile(file_output_media): 343 | shutil.copy(archive_media_path, file_output_media) 344 | markdown += f'![]({media_url})' 345 | html += f'' 346 | # Save the online location of the best-quality version of this file, for later upgrading if wanted 347 | best_quality_url = f'https://pbs.twimg.com/media/{original_filename}:orig' 348 | media_sources.append( 349 | (os.path.join(paths.dir_output_media, archive_media_filename), best_quality_url) 350 | ) 351 | else: 352 | # Is there any other file that includes the tweet_id in its filename? 353 | archive_media_paths = glob.glob(os.path.join(paths.dir_input_media, tweet_id_str + '*')) 354 | if len(archive_media_paths) > 0: 355 | for archive_media_path in archive_media_paths: 356 | archive_media_filename = os.path.split(archive_media_path)[-1] 357 | file_output_media = os.path.join(paths.dir_output_media, archive_media_filename) 358 | media_url = rel_url(file_output_media, paths.example_file_output_tweets) 359 | if not os.path.isfile(file_output_media): 360 | shutil.copy(archive_media_path, file_output_media) 361 | markdown += f'\n' 363 | html += f'\n' 365 | # Save the online location of the best-quality version of this file, 366 | # for later upgrading if wanted 367 | if 'video_info' in media and 'variants' in media['video_info']: 368 | best_quality_url = '' 369 | best_bitrate = -1 # some valid videos are marked with bitrate=0 in the JSON 370 | for variant in media['video_info']['variants']: 371 | if 'bitrate' in variant: 372 | bitrate = int(variant['bitrate']) 373 | if bitrate > best_bitrate: 374 | best_quality_url = variant['url'] 375 | best_bitrate = bitrate 376 | if best_bitrate == -1: 377 | print(f"Warning No URL found for {original_url} {original_expanded_url} " 378 | f"{archive_media_path} {media_url}") 379 | print(f"JSON: {tweet}") 380 | else: 381 | media_sources.append( 382 | (os.path.join(paths.dir_output_media, archive_media_filename), 383 | best_quality_url) 384 | ) 385 | else: 386 | print(f'Warning: missing local file: {archive_media_path}. Using original link instead: ' 387 | f'{original_url} (expands to {original_expanded_url})') 388 | markdown += f'![]({original_url})' 389 | html += f'{original_url}' 390 | body_markdown = body_markdown.replace(escape_markdown(original_url), markdown) 391 | body_html = body_html.replace(original_url, html) 392 | # make the body a quote 393 | body_markdown = '> ' + '\n> '.join(body_markdown.splitlines()) 394 | body_html = '

' + '
\n'.join(body_html.splitlines()) + '
' 395 | # append the original Twitter URL as a link 396 | original_tweet_url = f'https://twitter.com/{username}/status/{tweet_id_str}' 397 | icon_url = rel_url(paths.file_tweet_icon, paths.example_file_output_tweets) 398 | body_markdown = header_markdown + body_markdown + f'\n\n ' \ 399 | f'[{timestamp_str}]({original_tweet_url})' 400 | body_html = header_html + body_html + f' {timestamp_str}

' 402 | # extract user_id:handle connections 403 | if 'in_reply_to_user_id' in tweet and 'in_reply_to_screen_name' in tweet and \ 404 | tweet['in_reply_to_screen_name'] is not None: 405 | reply_to_id = tweet['in_reply_to_user_id'] 406 | if int(reply_to_id) >= 0: # some ids are -1, not sure why 407 | handle = tweet['in_reply_to_screen_name'] 408 | users[reply_to_id] = UserData(user_id=reply_to_id, handle=handle) 409 | if 'entities' in tweet and 'user_mentions' in tweet['entities'] and tweet['entities']['user_mentions'] is not None: 410 | for mention in tweet['entities']['user_mentions']: 411 | if mention is not None and 'id' in mention and 'screen_name' in mention: 412 | mentioned_id = mention['id'] 413 | if int(mentioned_id) >= 0: # some ids are -1, not sure why 414 | handle = mention['screen_name'] 415 | if handle is not None: 416 | users[mentioned_id] = UserData(user_id=mentioned_id, handle=handle) 417 | 418 | return timestamp, body_markdown, body_html 419 | 420 | 421 | def find_files_input_tweets(dir_path_input_data): 422 | """Identify the tweet archive's file and folder names - 423 | they change slightly depending on the archive size it seems.""" 424 | input_tweets_file_templates = ['tweet.js', 'tweets.js', 'tweets-part*.js'] 425 | files_paths_input_tweets = [] 426 | for input_tweets_file_template in input_tweets_file_templates: 427 | files_paths_input_tweets += glob.glob(os.path.join(dir_path_input_data, input_tweets_file_template)) 428 | if len(files_paths_input_tweets)==0: 429 | print(f'Error: no files matching {input_tweets_file_templates} in {dir_path_input_data}') 430 | exit() 431 | return files_paths_input_tweets 432 | 433 | 434 | def find_dir_input_media(dir_path_input_data): 435 | input_media_dir_templates = ['tweet_media', 'tweets_media'] 436 | input_media_dirs = [] 437 | for input_media_dir_template in input_media_dir_templates: 438 | input_media_dirs += glob.glob(os.path.join(dir_path_input_data, input_media_dir_template)) 439 | if len(input_media_dirs) == 0: 440 | print(f'Error: no folders matching {input_media_dir_templates} in {dir_path_input_data}') 441 | exit() 442 | if len(input_media_dirs) > 1: 443 | print(f'Error: multiple folders matching {input_media_dir_templates} in {dir_path_input_data}') 444 | exit() 445 | return input_media_dirs[0] 446 | 447 | 448 | def download_file_if_larger(url, filename, index, count, sleep_time): 449 | """Attempts to download from the specified URL. Overwrites file if larger. 450 | Returns whether the file is now known to be the largest available, and the number of bytes downloaded. 451 | """ 452 | requests = import_module('requests') 453 | imagesize = import_module('imagesize') 454 | 455 | pref = f'{index:3d}/{count:3d} {filename}: ' 456 | # Sleep briefly, in an attempt to minimize the possibility of trigging some auto-cutoff mechanism 457 | if index > 1: 458 | print(f'{pref}Sleeping...', end='\r') 459 | time.sleep(sleep_time) 460 | # Request the URL (in stream mode so that we can conditionally abort depending on the headers) 461 | print(f'{pref}Requesting headers for {url}...', end='\r') 462 | byte_size_before = os.path.getsize(filename) 463 | try: 464 | with requests.get(url, stream=True, timeout=2) as res: 465 | if not res.status_code == 200: 466 | # Try to get content of response as `res.text`. 467 | # For twitter.com, this will be empty in most (all?) cases. 468 | # It is successfully tested with error responses from other domains. 469 | raise Exception(f'Download failed with status "{res.status_code} {res.reason}". ' 470 | f'Response content: "{res.text}"') 471 | byte_size_after = int(res.headers['content-length']) 472 | if byte_size_after != byte_size_before: 473 | # Proceed with the full download 474 | tmp_filename = filename+'.tmp' 475 | print(f'{pref}Downloading {url}... ', end='\r') 476 | with open(tmp_filename,'wb') as f: 477 | shutil.copyfileobj(res.raw, f) 478 | post = f'{byte_size_after/2**20:.1f}MB downloaded' 479 | width_before, height_before = imagesize.get(filename) 480 | width_after, height_after = imagesize.get(tmp_filename) 481 | pixels_before, pixels_after = width_before * height_before, width_after * height_after 482 | pixels_percentage_increase = 100.0 * (pixels_after - pixels_before) / pixels_before 483 | 484 | if width_before == -1 and height_before == -1 and width_after == -1 and height_after == -1: 485 | # could not check size of both versions, probably a video or unsupported image format 486 | os.replace(tmp_filename, filename) 487 | bytes_percentage_increase = 100.0 * (byte_size_after - byte_size_before) / byte_size_before 488 | logging.info(f'{pref}SUCCESS. New version is {bytes_percentage_increase:3.0f}% ' 489 | f'larger in bytes (pixel comparison not possible). {post}') 490 | return True, byte_size_after 491 | elif width_before == -1 or height_before == -1 or width_after == -1 or height_after == -1: 492 | # could not check size of one version, this should not happen (corrupted download?) 493 | logging.info(f'{pref}SKIPPED. Pixel size comparison inconclusive: ' 494 | f'{width_before}*{height_before}px vs. {width_after}*{height_after}px. {post}') 495 | return False, byte_size_after 496 | elif pixels_after >= pixels_before: 497 | os.replace(tmp_filename, filename) 498 | bytes_percentage_increase = 100.0 * (byte_size_after - byte_size_before) / byte_size_before 499 | if bytes_percentage_increase >= 0: 500 | logging.info(f'{pref}SUCCESS. New version is {bytes_percentage_increase:3.0f}% larger in bytes ' 501 | f'and {pixels_percentage_increase:3.0f}% larger in pixels. {post}') 502 | else: 503 | logging.info(f'{pref}SUCCESS. New version is actually {-bytes_percentage_increase:3.0f}% ' 504 | f'smaller in bytes but {pixels_percentage_increase:3.0f}% ' 505 | f'larger in pixels. {post}') 506 | return True, byte_size_after 507 | else: 508 | logging.info(f'{pref}SKIPPED. Online version has {-pixels_percentage_increase:3.0f}% ' 509 | f'smaller pixel size. {post}') 510 | return True, byte_size_after 511 | else: 512 | logging.info(f'{pref}SKIPPED. Online version is same byte size, assuming same content. Not downloaded.') 513 | return True, 0 514 | except Exception as err: 515 | logging.error(f"{pref}FAIL. Media couldn't be retrieved from {url} because of exception: {err}") 516 | return False, 0 517 | 518 | 519 | def download_larger_media(media_sources, paths: PathConfig): 520 | """Uses (filename, URL) tuples in media_sources to download files from remote storage. 521 | Aborts downloads if the remote file is the same size or smaller than the existing local version. 522 | Retries the failed downloads several times, with increasing pauses between each to avoid being blocked. 523 | """ 524 | # Log to file as well as the console 525 | logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s') 526 | mkdirs_for_file(paths.file_download_log) 527 | logfile_handler = logging.FileHandler(filename=paths.file_download_log, mode='w') 528 | logfile_handler.setLevel(logging.INFO) 529 | logging.getLogger().addHandler(logfile_handler) 530 | # Download new versions 531 | start_time = time.time() 532 | total_bytes_downloaded = 0 533 | sleep_time = 0.25 534 | remaining_tries = 5 535 | while remaining_tries > 0: 536 | number_of_files = len(media_sources) 537 | success_count = 0 538 | retries = [] 539 | for index, (local_media_path, media_url) in enumerate(media_sources): 540 | success, bytes_downloaded = download_file_if_larger( 541 | media_url, local_media_path, index + 1, number_of_files, sleep_time 542 | ) 543 | if success: 544 | success_count += 1 545 | else: 546 | retries.append((local_media_path, media_url)) 547 | total_bytes_downloaded += bytes_downloaded 548 | 549 | # show % done and estimated remaining time: 550 | time_elapsed: float = time.time() - start_time 551 | estimated_time_per_file: float = time_elapsed / (index + 1) 552 | estimated_time_remaining: datetime.datetime = \ 553 | datetime.datetime.fromtimestamp( 554 | (number_of_files - (index + 1)) * estimated_time_per_file, 555 | tz=datetime.timezone.utc 556 | ) 557 | if estimated_time_remaining.hour >= 1: 558 | time_remaining_string: str = \ 559 | f"{estimated_time_remaining.hour} hour{'' if estimated_time_remaining.hour == 1 else 's'} " \ 560 | f"{estimated_time_remaining.minute} minute{'' if estimated_time_remaining.minute == 1 else 's'}" 561 | elif estimated_time_remaining.minute >= 1: 562 | time_remaining_string: str = \ 563 | f"{estimated_time_remaining.minute} minute{'' if estimated_time_remaining.minute == 1 else 's'} " \ 564 | f"{estimated_time_remaining.second} second{'' if estimated_time_remaining.second == 1 else 's'}" 565 | else: 566 | time_remaining_string: str = \ 567 | f"{estimated_time_remaining.second} second{'' if estimated_time_remaining.second == 1 else 's'}" 568 | 569 | if index + 1 == number_of_files: 570 | print(' 100 % done.') 571 | else: 572 | print(f' {(100*(index+1)/number_of_files):.1f} % done, about {time_remaining_string} remaining...') 573 | 574 | media_sources = retries 575 | remaining_tries -= 1 576 | sleep_time += 2 577 | logging.info(f'\n{success_count} of {number_of_files} tested media files ' 578 | f'are known to be the best-quality available.\n') 579 | if len(retries) == 0: 580 | break 581 | if remaining_tries > 0: 582 | print(f'----------------------\n\nRetrying the ones that failed, with a longer sleep. ' 583 | f'{remaining_tries} tries remaining.\n') 584 | end_time = time.time() 585 | 586 | logging.info(f'Total downloaded: {total_bytes_downloaded/2**20:.1f}MB = {total_bytes_downloaded/2**30:.2f}GB') 587 | logging.info(f'Time taken: {end_time-start_time:.0f}s') 588 | print(f'Wrote log to {paths.file_download_log}') 589 | 590 | 591 | def parse_tweets(username, users, html_template, paths: PathConfig): 592 | """Read tweets from paths.files_input_tweets, write to *.md and *.html. 593 | Copy the media used to paths.dir_output_media. 594 | Collect user_id:user_handle mappings for later use, in 'users'. 595 | Returns the mapping from media filename to best-quality URL. 596 | """ 597 | tweets = [] 598 | media_sources = [] 599 | for tweets_js_filename in paths.files_input_tweets: 600 | json = read_json_from_js_file(tweets_js_filename) 601 | for tweet in json: 602 | tweets.append(convert_tweet(tweet, username, media_sources, users, paths)) 603 | tweets.sort(key=lambda tup: tup[0]) # oldest first 604 | 605 | # Group tweets by month 606 | grouped_tweets = defaultdict(list) 607 | for timestamp, md, html in tweets: 608 | # Use a (markdown) filename that can be imported into Jekyll: YYYY-MM-DD-your-title-here.md 609 | dt = datetime.datetime.fromtimestamp(timestamp) 610 | grouped_tweets[(dt.year, dt.month)].append((md, html)) 611 | 612 | for (year, month), content in grouped_tweets.items(): 613 | # Write into *.md files 614 | md_string = '\n\n----\n\n'.join(md for md, _ in content) 615 | md_path = paths.create_path_for_file_output_tweets(year, month, format="md") 616 | with open_and_mkdirs(md_path) as f: 617 | f.write(md_string) 618 | 619 | # Write into *.html files 620 | html_string = '
\n'.join(html for _, html in content) 621 | html_path = paths.create_path_for_file_output_tweets(year, month, format="html") 622 | with open_and_mkdirs(html_path) as f: 623 | f.write(html_template.format(html_string)) 624 | 625 | print(f'Wrote {len(tweets)} tweets to *.md and *.html, ' 626 | f'with images and video embedded from {paths.dir_output_media}') 627 | 628 | return media_sources 629 | 630 | 631 | def collect_user_ids_from_followings(paths) -> list: 632 | """ 633 | Collect all user ids that appear in the followings archive data. 634 | (For use in bulk online lookup from Twitter.) 635 | """ 636 | # read JSON file from archive 637 | following_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'following.js')) 638 | # collect all user ids in a list 639 | following_ids = [] 640 | for follow in following_json: 641 | if 'following' in follow and 'accountId' in follow['following']: 642 | following_ids.append(follow['following']['accountId']) 643 | return following_ids 644 | 645 | 646 | def parse_followings(users, user_id_url_template, paths: PathConfig): 647 | """Parse paths.dir_input_data/following.js, write to paths.file_output_following. 648 | """ 649 | following = [] 650 | following_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'following.js')) 651 | following_ids = [] 652 | for follow in following_json: 653 | if 'following' in follow and 'accountId' in follow['following']: 654 | following_ids.append(follow['following']['accountId']) 655 | for following_id in following_ids: 656 | handle = users[following_id].handle if following_id in users else '~unknown~handle~' 657 | following.append(handle + ' ' + user_id_url_template.format(following_id)) 658 | following.sort() 659 | following_output_path = paths.create_path_for_file_output_single(format="txt", kind="following") 660 | with open_and_mkdirs(following_output_path) as f: 661 | f.write('\n'.join(following)) 662 | print(f"Wrote {len(following)} accounts to {following_output_path}") 663 | 664 | 665 | def collect_user_ids_from_followers(paths) -> list: 666 | """ 667 | Collect all user ids that appear in the followers archive data. 668 | (For use in bulk online lookup from Twitter.) 669 | """ 670 | # read JSON file from archive 671 | follower_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'follower.js')) 672 | # collect all user ids in a list 673 | follower_ids = [] 674 | for follower in follower_json: 675 | if 'follower' in follower and 'accountId' in follower['follower']: 676 | follower_ids.append(follower['follower']['accountId']) 677 | return follower_ids 678 | 679 | 680 | def parse_followers(users, user_id_url_template, paths: PathConfig): 681 | """Parse paths.dir_input_data/followers.js, write to paths.file_output_followers. 682 | """ 683 | followers = [] 684 | follower_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'follower.js')) 685 | follower_ids = [] 686 | for follower in follower_json: 687 | if 'follower' in follower and 'accountId' in follower['follower']: 688 | follower_ids.append(follower['follower']['accountId']) 689 | for follower_id in follower_ids: 690 | handle = users[follower_id].handle if follower_id in users else '~unknown~handle~' 691 | followers.append(handle + ' ' + user_id_url_template.format(follower_id)) 692 | followers.sort() 693 | followers_output_path = paths.create_path_for_file_output_single(format="txt", kind="followers") 694 | with open_and_mkdirs(followers_output_path) as f: 695 | f.write('\n'.join(followers)) 696 | print(f"Wrote {len(followers)} accounts to {followers_output_path}") 697 | 698 | 699 | def chunks(lst: list, n: int): 700 | """Yield successive n-sized chunks from lst.""" 701 | for i in range(0, len(lst), n): 702 | yield lst[i:i + n] 703 | 704 | 705 | def collect_user_ids_from_direct_messages(paths) -> list: 706 | """ 707 | Collect all user ids that appear in the direct messages archive data. 708 | (For use in bulk online lookup from Twitter.) 709 | """ 710 | # read JSON file from archive 711 | dms_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'direct-messages.js')) 712 | # collect all user ids in a set 713 | dms_user_ids = set() 714 | for conversation in dms_json: 715 | if 'dmConversation' in conversation and 'conversationId' in conversation['dmConversation']: 716 | dm_conversation = conversation['dmConversation'] 717 | conversation_id = dm_conversation['conversationId'] 718 | user1_id, user2_id = conversation_id.split('-') 719 | dms_user_ids.add(user1_id) 720 | dms_user_ids.add(user2_id) 721 | return list(dms_user_ids) 722 | 723 | 724 | def parse_direct_messages(username, users, user_id_url_template, paths: PathConfig): 725 | """Parse paths.dir_input_data/direct-messages.js, write to one markdown file per conversation. 726 | """ 727 | # read JSON file 728 | dms_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'direct-messages.js')) 729 | 730 | # Parse the DMs and store the messages in a dict 731 | conversations_messages = defaultdict(list) 732 | for conversation in dms_json: 733 | if 'dmConversation' in conversation and 'conversationId' in conversation['dmConversation']: 734 | dm_conversation = conversation['dmConversation'] 735 | conversation_id = dm_conversation['conversationId'] 736 | user1_id, user2_id = conversation_id.split('-') 737 | messages = [] 738 | if 'messages' in dm_conversation: 739 | for message in dm_conversation['messages']: 740 | if 'messageCreate' in message: 741 | message_create = message['messageCreate'] 742 | if all(tag in message_create for tag in ['senderId', 'recipientId', 'text', 'createdAt']): 743 | from_id = message_create['senderId'] 744 | to_id = message_create['recipientId'] 745 | body = message_create['text'] 746 | # replace t.co URLs with their original versions 747 | if 'urls' in message_create and len(message_create['urls']) > 0: 748 | for url in message_create['urls']: 749 | if 'url' in url and 'expanded' in url: 750 | expanded_url = url['expanded'] 751 | body = body.replace(url['url'], expanded_url) 752 | # escape message body for markdown rendering: 753 | body_markdown = escape_markdown(body) 754 | # replace image URLs with image links to local files 755 | if 'mediaUrls' in message_create \ 756 | and len(message_create['mediaUrls']) == 1 \ 757 | and 'urls' in message_create: 758 | original_expanded_url = message_create['urls'][0]['expanded'] 759 | message_id = message_create['id'] 760 | media_hash_and_type = message_create['mediaUrls'][0].split('/')[-1] 761 | media_id = message_create['mediaUrls'][0].split('/')[-2] 762 | archive_media_filename = f'{message_id}-{media_hash_and_type}' 763 | new_url = os.path.join(paths.dir_output_media, archive_media_filename) 764 | archive_media_path = \ 765 | os.path.join(paths.dir_input_data, 'direct_messages_media', archive_media_filename) 766 | if os.path.isfile(archive_media_path): 767 | # found a matching image, use this one 768 | if not os.path.isfile(new_url): 769 | shutil.copy(archive_media_path, new_url) 770 | image_markdown = f'\n![]({new_url})\n' 771 | body_markdown = body_markdown.replace( 772 | escape_markdown(original_expanded_url), image_markdown 773 | ) 774 | 775 | # Save the online location of the best-quality version of this file, 776 | # for later upgrading if wanted 777 | best_quality_url = \ 778 | f'https://ton.twitter.com/i//ton/data/dm/' \ 779 | f'{message_id}/{media_id}/{media_hash_and_type}' 780 | # there is no ':orig' here, the url without any suffix has the original size 781 | 782 | # TODO: a cookie (and a 'Referer: https://twitter.com' header) 783 | # is needed to retrieve it, so the url might be useless anyway... 784 | 785 | # WARNING: Do not uncomment the statement below until the cookie problem is solved! 786 | # media_sources.append( 787 | # ( 788 | # os.path.join(output_media_folder_name, archive_media_filename), 789 | # best_quality_url 790 | # ) 791 | # ) 792 | 793 | else: 794 | archive_media_paths = glob.glob( 795 | os.path.join(paths.dir_input_data, 'direct_messages_media', message_id + '*')) 796 | if len(archive_media_paths) > 0: 797 | for archive_media_path in archive_media_paths: 798 | archive_media_filename = os.path.split(archive_media_path)[-1] 799 | media_url = os.path.join(paths.dir_output_media, archive_media_filename) 800 | if not os.path.isfile(media_url): 801 | shutil.copy(archive_media_path, media_url) 802 | video_markdown = f'\n\n' 804 | body_markdown = body_markdown.replace( 805 | escape_markdown(original_expanded_url), video_markdown 806 | ) 807 | 808 | # TODO: maybe also save the online location of the best-quality version for videos? 809 | # (see above) 810 | 811 | else: 812 | print(f'Warning: missing local file: {archive_media_path}. ' 813 | f'Using original link instead: {original_expanded_url})') 814 | 815 | created_at = message_create['createdAt'] # example: 2022-01-27T15:58:52.744Z 816 | timestamp = \ 817 | int(round(datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp())) 818 | 819 | from_handle = escape_markdown(users[from_id].handle) if from_id in users \ 820 | else user_id_url_template.format(from_id) 821 | to_handle = escape_markdown(users[to_id].handle) if to_id in users \ 822 | else user_id_url_template.format(to_id) 823 | 824 | # make the body a quote 825 | body_markdown = '> ' + '\n> '.join(body_markdown.splitlines()) 826 | message_markdown = f'{from_handle} -> {to_handle}: ({created_at}) \n\n' \ 827 | f'{body_markdown}' 828 | messages.append((timestamp, message_markdown)) 829 | 830 | # find identifier for the conversation 831 | other_user_id = user2_id if (user1_id in users and users[user1_id].handle == username) else user1_id 832 | 833 | # collect messages per identifying user in conversations_messages dict 834 | conversations_messages[other_user_id].extend(messages) 835 | 836 | # output as one file per conversation (or part of long conversation) 837 | num_written_messages = 0 838 | num_written_files = 0 839 | for other_user_id, messages in conversations_messages.items(): 840 | # sort messages by timestamp 841 | messages.sort(key=lambda tup: tup[0]) 842 | 843 | other_user_name = escape_markdown(users[other_user_id].handle) if other_user_id in users \ 844 | else user_id_url_template.format(other_user_id) 845 | 846 | other_user_short_name: str = users[other_user_id].handle if other_user_id in users else other_user_id 847 | 848 | escaped_username = escape_markdown(username) 849 | 850 | # if there are more than 1000 messages, the conversation was split up in the twitter archive. 851 | # following this standard, also split up longer conversations in the output files: 852 | 853 | if len(messages) > 1000: 854 | for chunk_index, chunk in enumerate(chunks(messages, 1000)): 855 | markdown = '' 856 | markdown += f'### Conversation between {escaped_username} and {other_user_name}, ' \ 857 | f'part {chunk_index+1}: ###\n\n----\n\n' 858 | markdown += '\n\n----\n\n'.join(md for _, md in chunk) 859 | conversation_output_path = paths.create_path_for_file_output_dms(name=other_user_short_name, index=(chunk_index + 1), format="md") 860 | 861 | # write part to a markdown file 862 | with open_and_mkdirs(conversation_output_path) as f: 863 | f.write(markdown) 864 | print(f'Wrote {len(chunk)} messages to {conversation_output_path}') 865 | num_written_files += 1 866 | 867 | else: 868 | markdown = '' 869 | markdown += f'### Conversation between {escaped_username} and {other_user_name}: ###\n\n----\n\n' 870 | markdown += '\n\n----\n\n'.join(md for _, md in messages) 871 | conversation_output_path = paths.create_path_for_file_output_dms(name=other_user_short_name, format="md") 872 | 873 | with open_and_mkdirs(conversation_output_path) as f: 874 | f.write(markdown) 875 | print(f'Wrote {len(messages)} messages to {conversation_output_path}') 876 | num_written_files += 1 877 | 878 | num_written_messages += len(messages) 879 | 880 | print(f"\nWrote {len(conversations_messages)} direct message conversations " 881 | f"({num_written_messages} total messages) to {num_written_files} markdown files\n") 882 | 883 | 884 | def make_conversation_name_safe_for_filename(conversation_name: str) -> str: 885 | """ 886 | Remove/replace characters that could be unsafe in filenames 887 | """ 888 | forbidden_chars = \ 889 | ['"', "'", '*', '/', '\\', ':', '<', '>', '?', '|', '!', '@', ';', ',', '=', '.', '\n', '\r', '\t'] 890 | new_conversation_name = '' 891 | for char in conversation_name: 892 | if char in forbidden_chars: 893 | new_conversation_name = new_conversation_name + '_' 894 | elif char.isspace(): 895 | # replace spaces with underscores 896 | new_conversation_name = new_conversation_name + '_' 897 | elif char == 0x7F or (0x1F >= ord(char) >= 0x00): 898 | # 0x00 - 0x1F and 0x7F are also forbidden, just discard them 899 | continue 900 | else: 901 | new_conversation_name = new_conversation_name + char 902 | 903 | return new_conversation_name 904 | 905 | 906 | def find_group_dm_conversation_participant_ids(conversation: dict) -> set: 907 | """ 908 | Find IDs of all participating Users in a group direct message conversation 909 | """ 910 | group_user_ids = set() 911 | if 'dmConversation' in conversation and 'conversationId' in conversation['dmConversation']: 912 | dm_conversation = conversation['dmConversation'] 913 | if 'messages' in dm_conversation: 914 | for message in dm_conversation['messages']: 915 | if 'messageCreate' in message: 916 | group_user_ids.add(message['messageCreate']['senderId']) 917 | elif 'joinConversation' in message: 918 | group_user_ids.add(message['joinConversation']['initiatingUserId']) 919 | for participant_id in message['joinConversation']['participantsSnapshot']: 920 | group_user_ids.add(participant_id) 921 | elif "participantsJoin" in message: 922 | group_user_ids.add(message['participantsJoin']['initiatingUserId']) 923 | for participant_id in message['participantsJoin']['userIds']: 924 | group_user_ids.add(participant_id) 925 | return group_user_ids 926 | 927 | 928 | def collect_user_ids_from_group_direct_messages(paths) -> list: 929 | """ 930 | Collect all user ids that appear in the group direct messages archive data. 931 | (For use in bulk online lookup from Twitter.) 932 | """ 933 | # read JSON file from archive 934 | group_dms_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'direct-messages-group.js')) 935 | # collect all user ids in a set 936 | group_dms_user_ids = set() 937 | for conversation in group_dms_json: 938 | participants = find_group_dm_conversation_participant_ids(conversation) 939 | for participant_id in participants: 940 | group_dms_user_ids.add(participant_id) 941 | return list(group_dms_user_ids) 942 | 943 | 944 | def parse_group_direct_messages(username, users, user_id_url_template, paths): 945 | """Parse data_folder/direct-messages-group.js, write to one markdown file per conversation. 946 | """ 947 | # read JSON file from archive 948 | group_dms_json = read_json_from_js_file(os.path.join(paths.dir_input_data, 'direct-messages-group.js')) 949 | 950 | # Parse the group DMs, store messages and metadata in a dict 951 | group_conversations_messages = defaultdict(list) 952 | group_conversations_metadata = defaultdict(dict) 953 | for conversation in group_dms_json: 954 | if 'dmConversation' in conversation and 'conversationId' in conversation['dmConversation']: 955 | dm_conversation = conversation['dmConversation'] 956 | conversation_id = dm_conversation['conversationId'] 957 | participants = find_group_dm_conversation_participant_ids(conversation) 958 | participant_names = [] 959 | for participant_id in participants: 960 | if participant_id in users: 961 | participant_names.append(users[participant_id].handle) 962 | else: 963 | participant_names.append(user_id_url_template.format(participant_id)) 964 | 965 | # save names in metadata 966 | group_conversations_metadata[conversation_id]['participants'] = participants 967 | group_conversations_metadata[conversation_id]['participant_names'] = participant_names 968 | group_conversations_metadata[conversation_id]['conversation_names'] = [(0, conversation_id)] 969 | group_conversations_metadata[conversation_id]['participant_message_count'] = defaultdict(int) 970 | for participant_id in participants: 971 | # init every participant's message count with 0, so that users with no activity are not ignored 972 | group_conversations_metadata[conversation_id]['participant_message_count'][participant_id] = 0 973 | messages = [] 974 | if 'messages' in dm_conversation: 975 | for message in dm_conversation['messages']: 976 | if 'messageCreate' in message: 977 | message_create = message['messageCreate'] 978 | if all(tag in message_create for tag in ['senderId', 'text', 'createdAt']): 979 | from_id = message_create['senderId'] 980 | # count how many messages this user has sent to the group 981 | group_conversations_metadata[conversation_id]['participant_message_count'][from_id] += 1 982 | body = message_create['text'] 983 | # replace t.co URLs with their original versions 984 | if 'urls' in message_create: 985 | for url in message_create['urls']: 986 | if 'url' in url and 'expanded' in url: 987 | expanded_url = url['expanded'] 988 | body = body.replace(url['url'], expanded_url) 989 | # escape message body for markdown rendering: 990 | body_markdown = escape_markdown(body) 991 | # replace image URLs with image links to local files 992 | if 'mediaUrls' in message_create \ 993 | and len(message_create['mediaUrls']) == 1 \ 994 | and 'urls' in message_create: 995 | original_expanded_url = message_create['urls'][0]['expanded'] 996 | message_id = message_create['id'] 997 | media_hash_and_type = message_create['mediaUrls'][0].split('/')[-1] 998 | media_id = message_create['mediaUrls'][0].split('/')[-2] 999 | archive_media_filename = f'{message_id}-{media_hash_and_type}' 1000 | new_url = os.path.join(paths.dir_output_media, archive_media_filename) 1001 | archive_media_path = \ 1002 | os.path.join(paths.dir_input_data, 'direct_messages_group_media', 1003 | archive_media_filename) 1004 | if os.path.isfile(archive_media_path): 1005 | # found a matching image, use this one 1006 | if not os.path.isfile(new_url): 1007 | shutil.copy(archive_media_path, new_url) 1008 | image_markdown = f'\n![]({new_url})\n' 1009 | body_markdown = body_markdown.replace( 1010 | escape_markdown(original_expanded_url), image_markdown 1011 | ) 1012 | 1013 | # Save the online location of the best-quality version of this file, 1014 | # for later upgrading if wanted 1015 | best_quality_url = \ 1016 | f'https://ton.twitter.com/i//ton/data/dm/' \ 1017 | f'{message_id}/{media_id}/{media_hash_and_type}' 1018 | # there is no ':orig' here, the url without any suffix has the original size 1019 | 1020 | # TODO: a cookie (and a 'Referer: https://twitter.com' header) 1021 | # is needed to retrieve it, so the url might be useless anyway... 1022 | 1023 | # WARNING: Do not uncomment the statement below until the cookie problem is solved! 1024 | # media_sources.append( 1025 | # ( 1026 | # os.path.join(output_media_folder_name, archive_media_filename), 1027 | # best_quality_url 1028 | # ) 1029 | # ) 1030 | 1031 | else: 1032 | archive_media_paths = glob.glob( 1033 | os.path.join(paths.dir_input_data, 'direct_messages_group_media', 1034 | message_id + '*')) 1035 | if len(archive_media_paths) > 0: 1036 | for archive_media_path in archive_media_paths: 1037 | archive_media_filename = os.path.split(archive_media_path)[-1] 1038 | media_url = os.path.join(paths.dir_output_media, 1039 | archive_media_filename) 1040 | if not os.path.isfile(media_url): 1041 | shutil.copy(archive_media_path, media_url) 1042 | video_markdown = f'\n\n' 1044 | body_markdown = body_markdown.replace( 1045 | escape_markdown(original_expanded_url), video_markdown 1046 | ) 1047 | 1048 | # TODO: maybe also save the online location of the best-quality version for videos? 1049 | # (see above) 1050 | 1051 | else: 1052 | print(f'Warning: missing local file: {archive_media_path}. ' 1053 | f'Using original link instead: {original_expanded_url})') 1054 | created_at = message_create['createdAt'] # example: 2022-01-27T15:58:52.744Z 1055 | timestamp = int(round( 1056 | datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp() 1057 | )) 1058 | from_handle = escape_markdown(users[from_id].handle) if from_id in users \ 1059 | else user_id_url_template.format(from_id) 1060 | # make the body a quote 1061 | body_markdown = '> ' + '\n> '.join(body_markdown.splitlines()) 1062 | message_markdown = f'{from_handle}: ({created_at})\n\n' \ 1063 | f'{body_markdown}' 1064 | messages.append((timestamp, message_markdown)) 1065 | elif "conversationNameUpdate" in message: 1066 | conversation_name_update = message['conversationNameUpdate'] 1067 | if all(tag in conversation_name_update for tag in ['initiatingUserId', 'name', 'createdAt']): 1068 | from_id = conversation_name_update['initiatingUserId'] 1069 | body_markdown = f"_changed group name to: {escape_markdown(conversation_name_update['name'])}_" 1070 | created_at = conversation_name_update['createdAt'] # example: 2022-01-27T15:58:52.744Z 1071 | timestamp = int(round( 1072 | datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp() 1073 | )) 1074 | from_handle = escape_markdown(users[from_id].handle) if from_id in users \ 1075 | else user_id_url_template.format(from_id) 1076 | message_markdown = f'{from_handle}: ({created_at})\n\n{body_markdown}' 1077 | messages.append((timestamp, message_markdown)) 1078 | # save metadata about name change: 1079 | group_conversations_metadata[conversation_id]['conversation_names'].append( 1080 | (timestamp, conversation_name_update['name']) 1081 | ) 1082 | elif "joinConversation" in message: 1083 | join_conversation = message['joinConversation'] 1084 | if all(tag in join_conversation for tag in ['initiatingUserId', 'createdAt']): 1085 | from_id = join_conversation['initiatingUserId'] 1086 | created_at = join_conversation['createdAt'] # example: 2022-01-27T15:58:52.744Z 1087 | timestamp = int(round( 1088 | datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp() 1089 | )) 1090 | from_handle = escape_markdown(users[from_id].handle) if from_id in users \ 1091 | else user_id_url_template.format(from_id) 1092 | escaped_username = escape_markdown(username) 1093 | body_markdown = f'_{from_handle} added {escaped_username} to the group_' 1094 | message_markdown = f'{from_handle}: ({created_at})\n\n{body_markdown}' 1095 | messages.append((timestamp, message_markdown)) 1096 | elif "participantsJoin" in message: 1097 | participants_join = message['participantsJoin'] 1098 | if all(tag in participants_join for tag in ['initiatingUserId', 'userIds', 'createdAt']): 1099 | from_id = participants_join['initiatingUserId'] 1100 | created_at = participants_join['createdAt'] # example: 2022-01-27T15:58:52.744Z 1101 | timestamp = int(round( 1102 | datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp() 1103 | )) 1104 | from_handle = escape_markdown(users[from_id].handle) if from_id in users \ 1105 | else user_id_url_template.format(from_id) 1106 | joined_ids = participants_join['userIds'] 1107 | joined_handles = [escape_markdown(users[joined_id].handle) if joined_id in users 1108 | else user_id_url_template.format(joined_id) for joined_id in joined_ids] 1109 | name_list = ', '.join(joined_handles[:-1]) + \ 1110 | (f' and {joined_handles[-1]}' if len(joined_handles) > 1 else 1111 | joined_handles[0]) 1112 | body_markdown = f'_{from_handle} added {name_list} to the group_' 1113 | message_markdown = f'{from_handle}: ({created_at})\n\n{body_markdown}' 1114 | messages.append((timestamp, message_markdown)) 1115 | elif "participantsLeave" in message: 1116 | participants_leave = message['participantsLeave'] 1117 | if all(tag in participants_leave for tag in ['userIds', 'createdAt']): 1118 | created_at = participants_leave['createdAt'] # example: 2022-01-27T15:58:52.744Z 1119 | timestamp = int(round( 1120 | datetime.datetime.strptime(created_at, '%Y-%m-%dT%X.%fZ').timestamp() 1121 | )) 1122 | left_ids = participants_leave['userIds'] 1123 | left_handles = [escape_markdown(users[left_id].handle) if left_id in users 1124 | else user_id_url_template.format(left_id) for left_id in left_ids] 1125 | name_list = ', '.join(left_handles[:-1]) + \ 1126 | (f' and {left_handles[-1]}' if len(left_handles) > 1 else 1127 | left_handles[0]) 1128 | body_markdown = f'_{name_list} left the group_' 1129 | message_markdown = f'{name_list}: ({created_at})\n\n{body_markdown}' 1130 | messages.append((timestamp, message_markdown)) 1131 | 1132 | # collect messages per conversation in group_conversations_messages dict 1133 | group_conversations_messages[conversation_id].extend(messages) 1134 | 1135 | # output as one file per conversation (or part of long conversation) 1136 | num_written_messages = 0 1137 | num_written_files = 0 1138 | for conversation_id, messages in group_conversations_messages.items(): 1139 | # sort messages by timestamp 1140 | messages.sort(key=lambda tup: tup[0]) 1141 | # create conversation name for use in filename: 1142 | # first, try to find an official name in the parsed conversation data 1143 | 1144 | # Not-so-fun fact: 1145 | # If the name was set before the archive's owner joined the group, the name is not included 1146 | # in the archive data and can't be found anywhere (except by looking it up from twitter, 1147 | # and that would probably need a cookie). So there are many groups that do actually have a name, 1148 | # but it can't be used here because we don't know it. 1149 | 1150 | group_conversations_metadata[conversation_id]['conversation_names'].sort(key=lambda tup: tup[0], reverse=True) 1151 | official_name = group_conversations_metadata[conversation_id]['conversation_names'][0][1] 1152 | safe_group_name = make_conversation_name_safe_for_filename(official_name) 1153 | if len(safe_group_name) < 2: 1154 | # discard name if it's too short (because of collision risk) 1155 | group_name = conversation_id 1156 | else: 1157 | group_name = safe_group_name 1158 | 1159 | if group_name == conversation_id: 1160 | # try to make a nice list of participant handles for the conversation name 1161 | handles = [] 1162 | for participant_id, message_count in \ 1163 | group_conversations_metadata[conversation_id]['participant_message_count'].items(): 1164 | if participant_id in users: 1165 | participant_handle = users[participant_id].handle 1166 | if participant_handle != username: 1167 | handles.append((participant_handle, message_count)) 1168 | # sort alphabetically by handle first, for a more deterministic order 1169 | handles.sort(key=lambda tup: tup[0]) 1170 | # sort so that the most active users are at the start of the list 1171 | handles.sort(key=lambda tup: tup[1], reverse=True) 1172 | if len(handles) == 1: 1173 | group_name = \ 1174 | f'{handles[0][0]}_and_{len(group_conversations_metadata[conversation_id]["participants"]) - 1}_more' 1175 | elif len(handles) == 2 and len(group_conversations_metadata[conversation_id]["participants"]) == 3: 1176 | group_name = f'{handles[0][0]}_and_{handles[1][0]}_and_{username}' 1177 | elif len(handles) >= 2: 1178 | group_name = \ 1179 | f'{handles[0][0]}_and_{handles[1][0]}_and' \ 1180 | f'_{len(group_conversations_metadata[conversation_id]["participants"]) - 2}_more' 1181 | else: 1182 | # just use the conversation id 1183 | group_name = conversation_id 1184 | 1185 | # create a list of names of the form '@name1, @name2 and @name3' 1186 | # to use as a headline in the output file 1187 | escaped_participant_names = [ 1188 | escape_markdown(participant_name) 1189 | for participant_name in group_conversations_metadata[conversation_id]['participant_names'] 1190 | ] 1191 | name_list = ', '.join(escaped_participant_names[:-1]) + \ 1192 | (f' and {escaped_participant_names[-1]}' 1193 | if len(escaped_participant_names) > 1 1194 | else escaped_participant_names[0]) 1195 | 1196 | if len(messages) > 1000: 1197 | for chunk_index, chunk in enumerate(chunks(messages, 1000)): 1198 | markdown = '' 1199 | markdown += f'## {official_name} ##\n\n' 1200 | markdown += f'### Group conversation between {name_list}, part {chunk_index + 1}: ###\n\n----\n\n' 1201 | markdown += '\n\n----\n\n'.join(md for _, md in chunk) 1202 | conversation_output_filename = paths.create_path_for_file_output_dms( 1203 | name=group_name, format="md", kind="DMs-Group", index=chunk_index + 1 1204 | ) 1205 | 1206 | # write part to a markdown file 1207 | with open_and_mkdirs(conversation_output_filename) as f: 1208 | f.write(markdown) 1209 | print(f'Wrote {len(chunk)} messages to {conversation_output_filename}') 1210 | num_written_files += 1 1211 | else: 1212 | markdown = '' 1213 | markdown += f'## {official_name} ##\n\n' 1214 | markdown += f'### Group conversation between {name_list}: ###\n\n----\n\n' 1215 | markdown += '\n\n----\n\n'.join(md for _, md in messages) 1216 | conversation_output_filename = \ 1217 | paths.create_path_for_file_output_dms(name=group_name, format="md", kind="DMs-Group") 1218 | 1219 | with open_and_mkdirs(conversation_output_filename) as f: 1220 | f.write(markdown) 1221 | print(f'Wrote {len(messages)} messages to {conversation_output_filename}') 1222 | num_written_files += 1 1223 | 1224 | num_written_messages += len(messages) 1225 | 1226 | print(f"\nWrote {len(group_conversations_messages)} direct message group conversations " 1227 | f"({num_written_messages} total messages) to {num_written_files} markdown files") 1228 | 1229 | 1230 | def migrate_old_output(paths: PathConfig): 1231 | """If present, moves media and cache files from the archive root to the new locations in 1232 | `paths.dir_output_media` and `paths.dir_output_cache`. Then deletes old output files 1233 | (md, html, txt) from the archive root, if the user consents.""" 1234 | 1235 | # Create new folders, so we can potentially use them to move files there 1236 | os.makedirs(paths.dir_output_media, exist_ok=True) 1237 | os.makedirs(paths.dir_output_cache, exist_ok=True) 1238 | 1239 | # Move files that we can re-use: 1240 | if os.path.exists(os.path.join(paths.dir_archive, "media")): 1241 | files_to_move = glob.glob(os.path.join(paths.dir_archive, "media", "*")) 1242 | if len(files_to_move) > 0: 1243 | print(f"Moving {len(files_to_move)} files from 'media' to '{paths.dir_output_media}'") 1244 | for file_path_to_move in files_to_move: 1245 | file_name_to_move = os.path.split(file_path_to_move)[1] 1246 | os.rename(file_path_to_move, os.path.join(paths.dir_output_media, file_name_to_move)) 1247 | os.rmdir(os.path.join(paths.dir_archive, "media")) 1248 | 1249 | known_tweets_old_path = os.path.join(paths.dir_archive, "known_tweets.json") 1250 | known_tweets_new_path = os.path.join(paths.dir_output_cache, "known_tweets.json") 1251 | if os.path.exists(known_tweets_old_path): 1252 | os.rename(known_tweets_old_path, known_tweets_new_path) 1253 | 1254 | # Delete files that would be overwritten anyway (if user consents): 1255 | output_globs = [ 1256 | "TweetArchive.html", 1257 | "*Tweet-Archive*.html", 1258 | "*Tweet-Archive*.md", 1259 | "DMs-Archive-*.html", 1260 | "DMs-Archive-*.md", 1261 | "DMs-Group-Archive-*.html", 1262 | "DMs-Group-Archive-*.md", 1263 | "followers.txt", 1264 | "following.txt", 1265 | ] 1266 | files_to_delete = [] 1267 | 1268 | for output_glob in output_globs: 1269 | files_to_delete += glob.glob(os.path.join(paths.dir_archive, output_glob)) 1270 | 1271 | # TODO maybe remove those files only after the new ones have been generated? This way, the user would never 1272 | # end up with less output than before. On the other hand, they might end up with old *and* new versions 1273 | # of the output, if the script crashes before it reaches the code to delete the old version. 1274 | if len(files_to_delete) > 0: 1275 | print(f"\nThere are {len(files_to_delete)} files in the root of the archive,") 1276 | print("which were probably generated from an older version of this script.") 1277 | print("Since then, the directory layout of twitter-archive-parser has changed") 1278 | print("and these files are generated into the sub-directory 'parser-output' or") 1279 | print("various sub-sub-directories therein. These are the affected files:") 1280 | 1281 | for file_to_delete in files_to_delete: 1282 | print(file_to_delete) 1283 | 1284 | user_input = input('\nOK delete these files? (If the the directory layout would not have changed, they would be overwritten anyway) [y/N]') 1285 | if user_input.lower() in ('y', 'yes'): 1286 | for file_to_delete in files_to_delete: 1287 | os.remove(file_to_delete) 1288 | print(f"Files have been deleted. New versions of these files will be generated into 'parser-output' soon.") 1289 | 1290 | 1291 | def is_archive(path): 1292 | """Return true if there is a Twitter archive at the given path""" 1293 | return os.path.isfile(os.path.join(path, 'data', 'account.js')) 1294 | 1295 | 1296 | def find_archive(): 1297 | """ 1298 | Search for the archive 1299 | 1. First try the working directory. 1300 | 2. Then try the script directory. 1301 | 3. Finally prompt the user. 1302 | """ 1303 | if is_archive('.'): 1304 | return '.' 1305 | script_dir = os.path.dirname(__file__) 1306 | if script_dir != os.getcwd(): 1307 | if is_archive(script_dir): 1308 | return script_dir 1309 | print('Archive not found in working directory or script directory.\n' 1310 | 'Please enter the path of your Twitter archive, or just press Enter to exit.\n' 1311 | 'On most operating systems, you can also try to drag and drop your archive folder ' 1312 | 'into the terminal window, and it will paste its path automatically.\n') 1313 | # Give the user as many attempts as they need. 1314 | while True: 1315 | input_path = input('Archive path: ') 1316 | if not input_path: 1317 | exit() 1318 | if is_archive(input_path): 1319 | return input_path 1320 | print(f'Archive not found at {input_path}') 1321 | 1322 | 1323 | def main(): 1324 | archive_path = find_archive() 1325 | paths = PathConfig(dir_archive=archive_path) 1326 | 1327 | # Extract the archive owner's username from data/account.js 1328 | username = extract_username(paths) 1329 | 1330 | user_id_url_template = 'https://twitter.com/i/user/{}' 1331 | 1332 | html_template = """\ 1333 | 1334 | 1335 | 1336 | 1337 | 1338 | 1340 | Your Twitter archive! 1341 | 1342 | 1343 |

Your twitter archive

1344 |
1345 | {} 1346 |
1347 | 1348 | """ 1349 | 1350 | users = {} 1351 | 1352 | migrate_old_output(paths) 1353 | 1354 | # Make a folder to copy the images and videos into. 1355 | os.makedirs(paths.dir_output_media, exist_ok=True) 1356 | if not os.path.isfile(paths.file_tweet_icon): 1357 | shutil.copy('assets/images/favicon.ico', paths.file_tweet_icon) 1358 | 1359 | media_sources = parse_tweets(username, users, html_template, paths) 1360 | 1361 | following_ids = collect_user_ids_from_followings(paths) 1362 | print(f'found {len(following_ids)} user IDs in followings.') 1363 | follower_ids = collect_user_ids_from_followers(paths) 1364 | print(f'found {len(follower_ids)} user IDs in followers.') 1365 | dms_user_ids = collect_user_ids_from_direct_messages(paths) 1366 | print(f'found {len(dms_user_ids)} user IDs in direct messages.') 1367 | group_dms_user_ids = collect_user_ids_from_group_direct_messages(paths) 1368 | print(f'found {len(group_dms_user_ids)} user IDs in group direct messages.') 1369 | 1370 | # bulk lookup for user handles from followers, followings, direct messages and group direct messages 1371 | collected_user_ids_without_followers = list( 1372 | set(following_ids).union(set(dms_user_ids)).union(set(group_dms_user_ids)) 1373 | ) 1374 | collected_user_ids_only_in_followers: set = set(follower_ids).difference(set(collected_user_ids_without_followers)) 1375 | collected_user_ids: list = list(set(collected_user_ids_without_followers) 1376 | .union(collected_user_ids_only_in_followers)) 1377 | 1378 | print(f'\nfound {len(collected_user_ids)} user IDs overall.') 1379 | 1380 | # give the user a choice if followers should be included in the lookup 1381 | # (but only in case they make up a large amount): 1382 | unknown_collected_user_ids: set = set(collected_user_ids).difference(users.keys()) 1383 | unknown_follower_user_ids: set = unknown_collected_user_ids.intersection(collected_user_ids_only_in_followers) 1384 | if len(unknown_follower_user_ids) > 5000: 1385 | # Account metadata observed at ~2.1KB on average. 1386 | estimated_follower_lookup_size = int(2.1 * len(unknown_follower_user_ids)) 1387 | # we can look up at least 3000 users per minute. 1388 | estimated_max_follower_lookup_time_in_minutes = len(unknown_follower_user_ids) / 3000 1389 | print( 1390 | f'For some user IDs, the @handle is not included in the archive data. ' 1391 | f'Unknown user handles can be looked up online.' 1392 | f'{len(unknown_follower_user_ids)} of {len(unknown_collected_user_ids)} total ' 1393 | f'user IDs with unknown handles are from your followers. Online lookup would be ' 1394 | f'about {estimated_follower_lookup_size:,} KB smaller and up to ' 1395 | f'{estimated_max_follower_lookup_time_in_minutes:.1f} minutes faster without them.\n' 1396 | ) 1397 | 1398 | if not get_consent(f'Do you want to include handles of your followers ' 1399 | f'in the online lookup of user handles anyway?', default_to_yes=True): 1400 | collected_user_ids = collected_user_ids_without_followers 1401 | 1402 | lookup_users(collected_user_ids, users) 1403 | 1404 | parse_followings(users, user_id_url_template, paths) 1405 | parse_followers(users, user_id_url_template, paths) 1406 | parse_direct_messages(username, users, user_id_url_template, paths) 1407 | parse_group_direct_messages(username, users, user_id_url_template, paths) 1408 | 1409 | # Download larger images, if the user agrees 1410 | print(f"\nThe archive doesn't contain the original-size images. We can attempt to download them from twimg.com.") 1411 | print(f'Please be aware that this script may download a lot of data, which will cost you money if you are') 1412 | print(f'paying for bandwidth. Please be aware that the servers might block these requests if they are too') 1413 | print(f'frequent. This script may not work if your account is protected. You may want to set it to public') 1414 | print(f'before starting the download.\n') 1415 | 1416 | if get_consent('OK to start downloading?'): 1417 | download_larger_media(media_sources, paths) 1418 | print('In case you set your account to public before initiating the download, ' 1419 | 'do not forget to protect it again.') 1420 | 1421 | 1422 | if __name__ == "__main__": 1423 | main() 1424 | --------------------------------------------------------------------------------