├── .gitignore ├── LC_TYPE.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── RELEASE.md ├── contrib ├── README.md ├── config.sample ├── mastoarch ├── mastodon-archive ├── mastodon-archive.py ├── mastosearch └── upgrade_python-mastodon.sh ├── mastodon_archive ├── __init__.py ├── allowlist.py ├── archive.py ├── context.py ├── core.py ├── expire.py ├── fix.py ├── followers.py ├── following.py ├── html.py ├── login.py ├── media.py ├── meow.py ├── mutuals.py ├── replies.py ├── report.py ├── split.py └── text.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | /*.json 2 | /*.secret 3 | /*.html 4 | /*.egg-info 5 | /mastodon_archive/__pycache__ 6 | /*.user.* 7 | /build 8 | /setup.cfg 9 | /MANIFEST 10 | /dist 11 | -------------------------------------------------------------------------------- /LC_TYPE.md: -------------------------------------------------------------------------------- 1 | # Locale 2 | 3 | Sometimes you'll get an error relating to your locale. 4 | 5 | You can fix your setup by adding a statement to your shell's init 6 | file. The following is supposed to set a bunch of similar settings at 7 | the same time for future terminal settings. 8 | 9 | ``` 10 | echo export LANG=en_US.UTF-8 >> ~/.bashrc 11 | ``` 12 | 13 | Why does it work? Starting at the end: 14 | 15 | 1. `>> ~/.bashrc` appends a line to your shell's init file, and 16 | usually the default shell in terminals is `bash` which uses 17 | `~/.bashrc` as its init file 18 | 2. `en_US.UTF-8` means that you want English/US settings and UTF-8 19 | encoded output 20 | 3. `LANG` is the environment variable that controls all of this, more 21 | on that below 22 | 4. `export` means that it work in the current shell, and all other 23 | programs it calls (such as `mastodon-archive`) 24 | 5. `echo` simply prints the line `export LANG=en_US.UTF-8` such that 25 | `>> ~/.bashrc` will append it to the `~/.bashrc` file 26 | 27 | I promised some more information about your settings. Use the `locale` 28 | command to determine your current settings: 29 | 30 | ``` 31 | $ locale 32 | LANG= 33 | LC_COLLATE="C" 34 | LC_CTYPE="UTF-8" 35 | LC_MESSAGES="C" 36 | LC_MONETARY="C" 37 | LC_NUMERIC="C" 38 | LC_TIME="C" 39 | LC_ALL= 40 | ``` 41 | 42 | See how it changes when you set `LANG`: 43 | 44 | ``` 45 | $ export LANG=en_US.UTF-8 46 | $ locale 47 | LANG="en_US.UTF-8" 48 | LC_COLLATE="en_US.UTF-8" 49 | LC_CTYPE="UTF-8" 50 | LC_MESSAGES="en_US.UTF-8" 51 | LC_MONETARY="en_US.UTF-8" 52 | LC_NUMERIC="en_US.UTF-8" 53 | LC_TIME="en_US.UTF-8" 54 | LC_ALL= 55 | ``` 56 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | @echo "Have you edited setup.py?" 3 | @echo "Have you verified the User-Agent header in media.py?" 4 | @echo "Have you tagged the release?" 5 | 6 | .PHONY: dist upload 7 | 8 | dist: 9 | python3 setup.py sdist 10 | @echo make upload is next 11 | 12 | upload: 13 | twine upload --repository mastodon-archive dist/* 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mastodon Archive 2 | 3 | This tool enables you to make an archive of your statuses, your 4 | favourites, bookmarks and the media in both your statuses, your 5 | favourites and your bookmarks. From this archive, you can generate a 6 | simple text file, or a HTML file with or without media. Take a look at 7 | an 8 | [example](https://alexschroeder.ch/mastodon.weaponvsac.space.user.kensanata.html) 9 | if you're curious. 10 | 11 | Note that Mastodon 12 | [v2.3.0](https://github.com/tootsuite/mastodon/releases/tag/v2.3.0) 13 | added an account archive download feature: "Every 7 days you are able 14 | to request a full archive of your toots. The toots are exported in 15 | ActivityPub JSON format alongside the media files attached to them, 16 | your avatar and header images as well as the private key of your 17 | account used for signing content." If all you want to do is have a 18 | backup of your data, perhaps that is enough and you don't need this 19 | tool. Use something like 20 | [Toot-suite](https://codeberg.org/chrmoe/toot-suite) for Emacs, 21 | [Mastodon Archive Reader Lite](https://github.com/s427/MARL) (MARL), 22 | [tumelune](https://fedi.doom.solutions/tumelune/), 23 | [mastodon-data-viewer.py](https://github.com/blackle/mastodon-data-viewer.py) 24 | or [meow](#meow) to browse the archive. 25 | 26 | This tool does not download the full archive of your toots from the 27 | server. Instead, it uses the Mastodon client API to fetch them 28 | incrementally. 29 | 30 | You can get the latest sources 31 | [from the author’s site](https://src.alexschroeder.ch/mastodon-archive.git). 32 | 33 | 34 | **Table of Contents** 35 | 36 | - [Installation](#installation) 37 | - [Global options](#global-options) 38 | - [Making an archive](#making-an-archive) 39 | - [Splitting an archive](#splitting-an-archive) 40 | - [Downloading media files](#downloading-media-files) 41 | - [Generating a text file](#generating-a-text-file) 42 | - [Searching your archive](#searching-your-archive) 43 | - [Show context for a toot](#show-context-for-a-toot) 44 | - [Generating a HTML file](#generating-a-html-file) 45 | - [Meow](#meow) 46 | - [Reporting](#reporting) 47 | - [Expiring your toots and favourites](#expiring-your-toots-and-favourites) 48 | - [Troubleshooting](#troubleshooting) 49 | - [Followers](#followers) 50 | - [Following](#following) 51 | - [Mutes and blocks](#mutes-and-blocks) 52 | - [User notes](#user-notes) 53 | - [Allowlist](#allowlist) 54 | - [Mutuals](#mutuals) 55 | - [Example Setup](#example-setup) 56 | - [Documentation](#documentation) 57 | - [Development](#development) 58 | - [Processing using jq](#processing-using-jq) 59 | - [Exploring the API](#exploring-the-api) 60 | - [Alternatives](#alternatives) 61 | 62 | 63 | 64 | # Installation 65 | There are multiple alternative ways to install `mastodon-archive` on your machine: 66 | 67 | ## Linux Packages 68 | There are now packages available for Debian (`*.deb`) and Redhat (`*.rpm`) based 69 | systems. They are not in the standard repositories, though – but for now can be 70 | installed from [IzzySoft's Repositories](https://apt.izzysoft.de/). There you 71 | also find instructions on how to include them: 72 | 73 | * [Debian-based system](https://apt.izzysoft.de/ubuntu/dists/generic/) 74 | (including derivates like Ubuntu, Linux Mint etc) 75 | * [Redhat based system](https://apt.izzysoft.de/redhat/) (including Fedora, 76 | SuSE etc.) 77 | 78 | Once you've got the repo added and your indexes refreshed, just install using 79 | 80 | * `sudo apt install mastodon-archive` on Debian & derivates 81 | * `sudo yum install mastodon-archive` on Redhat & derivates 82 | 83 | Should you get a notice on your `Mastodon.py` being outdated while running 84 | `mastodon-archive` (will e.g. happen on Ubuntu 20.04), please see the 85 | [contrib/README.md](contrib/README.md) for a fix (`upgrade_python-mastodon.sh`). 86 | 87 | ## Using PIP 88 | The following command will install `mastodon-archive` and all its 89 | dependencies: 90 | 91 | ```bash 92 | # Python 3 93 | pip3 install mastodon-archive 94 | ``` 95 | 96 | If this is the first tool you installed using `pip` then perhaps it 97 | installed `mastodon-archive` in a directory that's not on your `PATH`. 98 | I had to add the following to my `~/.bashrc` file: 99 | 100 | ```bash 101 | export PATH=$PATH:$HOME/.local/bin 102 | ``` 103 | 104 | 🔥 If you're getting an error that ends with `Command "python setup.py 105 | egg_info" failed with error code 1 ...` you might have to install the 106 | setup tools. Try the following: 107 | 108 | ```bash 109 | pip3 install --user setuptools 110 | pip3 install mastodon-archive 111 | ``` 112 | 113 | ## Manually install the latest development code 114 | You can always clone the repository and run `python setup.py` from within its 115 | root directory: 116 | 117 | ```bash 118 | git clone https://github.com/kensanata/mastodon-archive 119 | cd mastodon-archive 120 | python setup.py install 121 | ``` 122 | 123 | 124 | # Global options 125 | 126 | If you don't want the script to generate any output unless there are 127 | errors, e.g., because you are running it from a scheduled task and 128 | don't want to get email about it unless something goes wrong, you can 129 | specify `--quiet` before the command to suppress non-error output, 130 | e.g., `mastodon-archive --quiet archive`, `mastodon-archive --quiet 131 | media`, etc. This will not suppress output for commands whose main 132 | point is to generate output. 133 | 134 | 135 | # Making an archive 136 | 137 | When using the app for the first time, you have to authorize it: 138 | 139 | ```text 140 | $ mastodon-archive archive kensanata@dice.camp 141 | Registering app 142 | Log in 143 | Visit the following URL and authorize the app: 144 | [the app gives you a huge URL which you need to visit using a browser] 145 | Then paste the access token here: 146 | [this is where you paste the authorization code] 147 | Get user info 148 | Get statuses (this may take a while) 149 | Save 41 statuses 150 | ``` 151 | 152 | Note that the library we are using says: "Mastodons API rate limits 153 | per IP. By default, the limit is 300 requests per 5 minute time slot. 154 | This can differ from instance to instance and is subject to change." 155 | Thus, if every request gets 20 toots, then we can get at most 6000 156 | toots per five minutes. 157 | 158 | If this is taking too long, consider skipping your favourites and bookmarks: 159 | 160 | ```text 161 | $ mastodon-archive archive --no-favourites --no-bookmarks kensanata@dice.camp 162 | ``` 163 | 164 | If you want a better picture of conversations, you can also include 165 | mentions. Mentions are notifications of statuses in which you were 166 | mentioned as opposed to statuses of yours that were favoured or 167 | boosted by others. Note that if you used to *dismiss* notifications 168 | using the "Clear notifications" menu, then no mentions will be found 169 | as mentions are simply a particular kind of notification. 170 | 171 | ```text 172 | $ mastodon-archive archive --with-mentions kensanata@dice.camp 173 | ``` 174 | 175 | No matter what you did, You will end up with three new files: 176 | 177 | `dice.camp.client.secret` is where the client secret for this instance 178 | is stored. `dice.camp.user.kensanata.secret` is where the 179 | authorisation token for this user and instance is stored. If these two 180 | files exist, you don't have to log in the next time you run the app. 181 | If your login expired, you need to remove the file containing the 182 | authorisation token and you will be asked to authorize the app again. 183 | 184 | `dice.camp.user.kensanata.json` is the JSON file with your data (but 185 | without your media attachments). If this file exists, only the missing 186 | toots will be downloaded the next time you run the app. If you suspect 187 | a problem and want to make sure that everything is downloaded again, 188 | you need to remove this file. 189 | 190 | # Splitting an archive 191 | 192 | If you keep adding your archive, it eventually grows very large. When 193 | it reaches hundreds of megabytes, consider *splitting* it. 194 | 195 | ``` 196 | $ ls -lh *.json 197 | -rw-r--r-- 1 alex alex 120M Apr 14 21:50 octodon.social.user.kensanata.json 198 | ``` 199 | 200 | You can provide an `--older-than` option to specify the number of 201 | weeks you want to keep. The default is four weeks. 202 | 203 | If you don't provide the `--confirmed` option, this is a dry run. 204 | 205 | ``` 206 | $ mastodon-archive split --older-than=10 kensanata@octodon.social 207 | This is a dry run and nothing will be moved. 208 | Instead, we'll just list what would have happened. 209 | Use --confirmed to actually do it. 210 | Loading existing archive 211 | Older than 2019-02-03 22:11:48.253408 212 | statuses: 10623 213 | favourites: 11233 214 | mentions: 10773 215 | Would have saved this to octodon.social.user.kensanata.0.json 216 | ``` 217 | 218 | When you do the split, the files are saved. 219 | 220 | ``` 221 | $ mastodon-archive split --older-than=10 --confirmed kensanata@octodon.social 222 | Loading existing archive 223 | Older than 2019-02-03 22:11:59.668432 224 | statuses: 10623 225 | favourites: 11233 226 | mentions: 10773 227 | Saving octodon.social.user.kensanata.json 228 | Saving octodon.social.user.kensanata.0.json 229 | ``` 230 | 231 | Verify the result: 232 | 233 | ``` 234 | $ ls -lh *.json 235 | -rw-r--r-- 1 alex alex 107M Apr 14 22:12 octodon.social.user.kensanata.0.json 236 | -rw-r--r-- 1 alex alex 13M Apr 14 22:12 octodon.social.user.kensanata.json 237 | ``` 238 | 239 | # Downloading media files 240 | 241 | Assuming you already made an archive of your toots: 242 | 243 | ```text 244 | $ mastodon-archive media kensanata@dice.camp 245 | 44 urls in your archive (half of them are previews) 246 | 34 files already exist 247 | Downloading |################################| 10/10 248 | ``` 249 | By default, media you uploaded and media of statuses you added your 250 | favourites or bookmarks are not part of your archive. To download these too, 251 | specify the favourites collection: 252 | 253 | ```text 254 | $ mastodon-archive media --collection favourites kensanata@dice.camp 255 | ``` 256 | specify the bookmarks collection: 257 | 258 | ```text 259 | $ mastodon-archive media --collection bookmarks kensanata@dice.camp 260 | ``` 261 | 262 | You will end up with a new directory, `dice.camp.user.kensanata`. It 263 | contains all the media you uploaded, and their corresponding previews. 264 | 265 | If you rerun it, it will simply try to get the remaining files. Note, 266 | however, that instance administrators can *delete* media files. Thus, 267 | you might be forever missing some files—particularly the ones from 268 | *remote* instances, if you added any to your favourites. If you don't 269 | want to see errors about media that fail to download for this reason, 270 | add `--suppress-errors` to the command. 271 | 272 | There's one thing you need to remember, though: the media directory 273 | contains all the media from your statuses, and all the media from your 274 | favourites. There is no particular reason why the media files from 275 | both sources need to be in the same directory, see 276 | [issue #11](https://github.com/kensanata/mastodon-archive/issues/11). 277 | 278 | # Generating a text file 279 | 280 | Assuming you already made an archive of your toots: 281 | 282 | ```text 283 | $ mastodon-archive text kensanata@dice.camp 284 | [lots of other toots] 285 | Alex Schroeder 🐉 @kensanata 2017-11-14T22:21:50.599000+00:00 286 | https://dice.camp/@kensanata/99005111284322450 287 | [#introduction](https://dice.camp/tags/introduction) I run 288 | [#osr](https://dice.camp/tags/osr) games using my own hose rule document but 289 | it all started with Labyrinth Lord which I knew long before I knew B/X. Sadly, 290 | my Indie Game Night is no longer a thing but I still love Lady Blackbird, all 291 | the [#pbta](https://dice.camp/tags/pbta) hacks on my drive, and so much more. 292 | But in the three campaigns I run, it’s all OSR right now. 293 | ``` 294 | 295 | Generating a text file just means redirection the output to a text 296 | file: 297 | 298 | ```text 299 | $ mastodon-archive text kensanata@dice.camp > statuses.txt 300 | ``` 301 | 302 | If you're working with text, you might expect the first toot to be at 303 | the top and the last toot to be at the bottom. In this case, you need 304 | to reverse the list: 305 | 306 | ```text 307 | $ mastodon-archive text --reverse kensanata@dice.camp | head 308 | ``` 309 | 310 | # Searching your archive 311 | 312 | You can also filter using regular expressions. These will be checked 313 | against the status *content* (obviously), *display name* and 314 | *username* (both are important for boosted toots), and the *created 315 | at* date. Also note that the regular expression will be applied to the 316 | raw status content. In other words, the status contains all the HTML 317 | and problably starts with a `

`, which is then removed in the 318 | output. 319 | 320 | ```text 321 | $ mastodon-archive text kensanata@dice.camp house 322 | ``` 323 | 324 | You can provide multiple regular expressions and they will all be 325 | checked: 326 | 327 | ```text 328 | $ mastodon-archive text kensanata@dice.camp house rule 329 | ``` 330 | 331 | Remember basic 332 | [regular expression syntax](https://docs.python.org/3/library/re.html#regular-expression-syntax): 333 | `\b` is a word boundary, `(?i)` ignores case, `(a|b)` is for 334 | alternatives, just to pick some useful ones. Use single quotes to 335 | protect your backslashes and questionmarks. 336 | 337 | ```text 338 | $ mastodon-archive text kensanata@dice.camp house 'rule\b' 339 | ``` 340 | 341 | You can also search your favourites, your bookmarks or your mentions: 342 | 343 | ```text 344 | $ mastodon-archive text --collection favourites kensanata@dice.camp '(?i)blackbird' 345 | ``` 346 | 347 | Dates are in ISO format (e.g. `2017-11-19T14:00`). I usually only care 348 | about year and month, though: 349 | 350 | ```text 351 | $ mastodon-archive text --collection favourites kensanata@dice.camp bird '2017-(07|08|09|10|11)' 352 | ``` 353 | 354 | 355 | # Show context for a toot 356 | 357 | Sometimes you only remember something about a *thread*. Let's say you 358 | asked a question a while back but now you can't remember the answer 359 | you got back then. First, find the question: 360 | 361 | ```text 362 | $ mastodon-archive text kensanata@dice.camp rules 363 | Alex Schroeder 🐉 @kensanata 2018-05-28T21:19:27.483000+00:00 364 | https://dice.camp/@kensanata/100109016572069901 365 | ... 366 | ``` 367 | 368 | Using the URL, you can now search the archive for some context: 369 | 370 | ```text 371 | $ mastodon-archive context kensanata@dice.camp https://dice.camp/@kensanata/100109016572069901 372 | ``` 373 | 374 | This shows the same information clicking on the toot shows you in the 375 | web client: all its ancestors and all its descendants. Obviously, if 376 | these toots are not in your archive, we can't find them. You'll have 377 | to click on the links and hope they're still around. 378 | 379 | 380 | # Generating a HTML file 381 | 382 | Assuming you already made an archive of your toots: 383 | 384 | ```text 385 | $ mastodon-archive html kensanata@dice.camp 386 | ``` 387 | 388 | This will create numbered HTML files starting with 389 | `dice.camp.user.kensanata.statuses.0.html`, each page with 2000 toots. 390 | 391 | You can change the number of toots per page using an option: 392 | 393 | ```text 394 | $ mastodon-archive html --toots-per-page 100 kensanata@dice.camp 395 | ``` 396 | 397 | If you have downloaded your media attachments, these will be used in 398 | the HTML files. Thus, if you want to upload the HTML files, you now 399 | need to upload the media directory as well or all the media links will 400 | be broken. 401 | 402 | You can also generate a file for your favourites: 403 | 404 | ```text 405 | $ mastodon-archive html --collection favourites kensanata@dice.camp 406 | ``` 407 | 408 | This will create numbered HTML files starting with 409 | `dice.camp.user.kensanata.favourites.0.html`, each page with 2000 410 | toots. 411 | 412 | Note that both the HTML file with your statuses and the HTML file with 413 | your favourites will refer to the media files in your media directory. 414 | 415 | # Meow 416 | 417 | [Meow](https://purr.neocities.org/) is a viewer for Mastodon export 418 | files (gratis but not free software). Such files contain all of one's 419 | toots, stars and bookmarks. It can also process your archives created 420 | with this tool. Meow runs locally in your browser and needs access to 421 | your archive. This is accomplished by serving the archive via a local 422 | web server. 423 | 424 | Here’s how to serve your archive, locally, for Meow to access, 425 | including all the media in your archive, if you archived it: 426 | 427 | ```text 428 | $ mastodon-archive meow kensanata@dice.camp 429 | ``` 430 | 431 | Once this is done, open Meow with the “Mastodon Archive Import URL” and 432 | it pulls the archived data from the local web server you just 433 | started: 434 | 435 | ```text 436 | https://purr.neocities.org/mastodon-archive-import/ 437 | ``` 438 | 439 | Known limitations: 440 | 441 | * If a media file doesn't exist locally, Meow generally tries to load 442 | it from the remote server. One notable exception is profile pictures 443 | and banners — you need to download your media to see them. 444 | 445 | * Boosts and favorites use post contents and media from the backup, 446 | but not user profiles (because of how Meow works internally), those 447 | are fetched from their instances. 448 | 449 | # Reporting 450 | 451 | Some numbers, including your ten most used hashtags: 452 | 453 | ```text 454 | $ mastodon-archive report kensanata@dice.camp 455 | Considering the last 12 weeks 456 | Statuses: 296 457 | Boosts: 17 458 | Media: 9 459 | 460 | Top 10 hashtags: 461 | #caster(8) #20questions(5) #osr(3) #dungeonslayers(2) #introduction(2) 462 | #currentprojects(2) #diaspora(1) #gygax(1) #yoonsuin(1) #casters(1) 463 | 464 | Favourites: 248 465 | Boosts: 0 466 | Media: 20 467 | 468 | Top 10 hashtags: 469 | #1strpg(9) #rpg(5) #myfirstcharacter(5) #introduction(5) #osr(4) 470 | #1strpgs(4) #dnd(3) #gamesnacks(1) #vancian(1) #mastoart(1) 471 | ``` 472 | 473 | You can specify a different time number of weeks to consider using 474 | `--newer-than N` or use `--all` to consider all your statuses, 475 | favourites and bookmarks. 476 | 477 | You can list a different number of hashtags using `--top N` and you 478 | can list all of them by using `--top -1`. This might result in a very 479 | long list. 480 | 481 | By default only your toots are considered for the hashtags. Use `--include-boosts` to also include toot you have boosted. 482 | 483 | # Expiring your toots and favourites 484 | 485 | **Somewhat deprecated**: Please note that Mastodon now offers 486 | Preferences → Automated post deletion. Just make sure that you never 487 | skip your backups and you should be fine. 😅 488 | 489 | Mastodon does not expire your favourites. 490 | 491 | **Warning**: This is a destructive operation. You will delete your 492 | toots on your instance, or unfavour your favourites, or dismiss your 493 | notifications on your instance. Where as it might be possible to 494 | favour all your favourites again, there is no way to repost all those 495 | toots. You will have a copy in your archive, but there is no way to 496 | restore these to your instance. 497 | 498 | **But why?** I might want to keep a copy of my toots, but I don't 499 | think they have much value going back months and years. I never read 500 | through years of tweeting history! This only benefits your enemies, 501 | never your friends. So I want to expire my toots. We can always write 502 | a blog post about the good stuff. You can read more about this [on my 503 | blog](https://alexschroeder.ch/wiki/2017-04-27_Record_Keeping). 504 | 505 | **Alternatives**: Check out [ephemtoot](https://ephemetoot.hugh.run/) 506 | (a Python script), or 507 | [MastoPurgee](https://github.com/ThomasLeister/mastopurge/#mastopurge). 508 | These tools expire your toots without archiving them. Or use the 509 | "Automated post deletion" feature you can find with your account 510 | preferences in recent versions of Mastodon. 511 | 512 | Anyway, back to *Mastodon Archive*. 🙂 513 | 514 | Sadly, I have some bad news for you: this has been rate limited to 515 | [30 statuses per 30 minutes](https://mastodon.social/@Gargron/101588449409740014)! 516 | 😭 517 | 518 | No, really! See the [merge request](https://github.com/tootsuite/mastodon/pull/10042). 519 | This is terrible. Expiry basically only works if you run it every time 520 | you have posted 30 statuses or so, in the long run. If you don't, be 521 | prepared for a *long* wait! 😴 522 | 523 | In order to not go crazy, the code catches an interrupt (such as you 524 | pressing `Ctrl-C`) and saves the data even though it hasn't finished 525 | expiring your statuses. 526 | 527 | Anyway, enough complaining. How do you do it? 528 | 529 | You can expire your toots using the `expire` command and providing the 530 | `--older-than` option. This option specifies the number of weeks to 531 | keep on the server. Anything older than that is deleted or unfavoured. 532 | If you use `--older-than 0`, then *all* your toots will be deleted, or 533 | *all* your favourites will be unfavoured, or *all* your notifications 534 | will be dismissed. 535 | 536 | ```text 537 | ~/src/mastodon-archive $ mastodon-archive expire --older-than 0 kensanata@social.nasqueron.org 538 | This is a dry run and nothing will be expired. 539 | Instead, we'll just list what would have happened. 540 | Use --confirmed to actually do it. 541 | Delete: 2017-11-26 "

Testing äöü

" 542 | ``` 543 | 544 | Actually, the default operation just does a dry run. You need to use 545 | the `--confirmed` option to proceed. 546 | 547 | And one more thing: since this requires the permission to *write* to 548 | your account, you will have to reauthorize the app. 549 | 550 | ```text 551 | $ mastodon-archive expire --collection favourites --older-than 0 \ 552 | --confirmed kensanata@social.nasqueron.org 553 | Log in 554 | Visit the following URL and authorize the app: 555 | [long URL shown here] 556 | Then paste the access token here: 557 | [long token pasted here] 558 | Expiring |################################| 1/1 559 | ``` 560 | 561 | After a while you'll notice that archiving mentions takes more and 562 | more time. The reason is when expiring mentions, the tool goes through 563 | all your notifications and looks at those of the type "mention" and 564 | expires them if they are old enough. There are other types of 565 | notifications, however: "follow", "favourite", and "reblog" (at the 566 | time of this writing). As these are not archived, we also don't expire 567 | them. Thus, the list of notifications to look through when archiving 568 | keeps growing unless you use the "Clear notifications" menu in the 569 | Mastodon web client. Alternatively, you can use the 570 | `--delete-other-notifications` option together with `--collection 571 | mentions` and then the tool will dismiss all the older other 572 | notifications for you. 573 | 574 | # Troubleshooting 575 | 576 | 🔥 If you are archiving a ton of toots and you run into a General API 577 | problem, use the `--pace` option. This is what the problem looks like: 578 | 579 | ```text 580 | $ mastodon-archive archive kensanata@dice.camp 581 | ... 582 | Get statuses (this may take a while) 583 | Traceback (most recent call last): 584 | ... 585 | mastodon.Mastodon.MastodonAPIError: General API problem. 586 | ``` 587 | 588 | Solution: 589 | 590 | ```text 591 | $ mastodon-archive archive --pace kensanata@dice.camp 592 | ``` 593 | 594 | The problem seems to be related to how Mastodon [rate 595 | limits](https://mastodonpy.readthedocs.io/en/latest/#a-note-about-rate-limits) 596 | requests. 597 | 598 | 🔥 If you are expiring many toots, same thing. The default rate limit 599 | is 300 requests per five minutes, so when more than 300 toots are to 600 | be deleted, the app simply has to wait for five minutes before 601 | continuing. It takes time. 602 | 603 | ```text 604 | $ mastodon-archive expire --confirm kensanata@octodon.social 605 | Loading existing archive 606 | Expiring | | 1/1236 607 | We need to authorize the app to make changes to your account. 608 | Log in 609 | Visit the following URL and authorize the app: 610 | [long URL here] 611 | Then paste the access token here: 612 | [access token here] 613 | Considering the default rate limit of 300 requests per five minutes and having 1236 statuses, 614 | this will take at least 20 minutes to complete. 615 | Expiring |####### | 301/1236 616 | ``` 617 | 618 | 🔥 If you are experimenting with expiry, you'll need to give the app 619 | write permissions. If you then delete the user secret file, hoping to 620 | start with a clean slate when archiving, you'll be asked to authorize 621 | the app again, but somehow Mastodon remembers that you have already 622 | granted the app read and write permissions, and you will get this 623 | error: 624 | 625 | `mastodon.Mastodon.MastodonAPIError: Granted scopes "read write" differ from requested scopes "read".` 626 | 627 | In order to get rid of this, you need to visit the website, got to 628 | Settings → Authorized apps and revoke your authorization for 629 | mastodon-archive. Now you can try the authorization URL again and you 630 | will only get read permissions instead of both read and write 631 | permissions. 632 | 633 | 🔥 Some servers are compatible with the Mastodon client protocol and 634 | yet you'll get the error "Version check failed". In these cases, you 635 | can skip this check by using the `--no-version-check` option. 636 | 637 | ```text 638 | $ mastodon-archive archive --pace --no-version-check alex@social.alexschroeder.ch 639 | ``` 640 | 641 | The problem is that the library iplementing the Mastodon client 642 | protocol tries to determine the exact feature-set available from your 643 | instance based on the instance's version string. When using 644 | mastodon-archive for instances that don't use Mastodon, you might have 645 | to skip the version check. When you disable the version check, 646 | whatever you're trying to do might work – or it might not. 647 | Unfortunately, you're on your own. 648 | 649 | # Followers 650 | 651 | This is work in progress. I'm actually not sure where I want to go 652 | with this. Right now it either lists all your followers, or it lists 653 | all your followers that haven't interacted with you; in the later case 654 | you can block them, too. This is for very grumpy users, for sure. 655 | 656 | If a toot of theirs mentions you, then that counts as an interaction. 657 | Favouring and boosting does not count. By default, this looks at the 658 | last twelve weeks. In order for this to work, you need an archive 659 | containing both mentions and followers. 660 | 661 | ```text 662 | $ mastodon-archive archive --with-mentions --with-followers kensanata@dice.camp 663 | Loading existing archive 664 | Get user info 665 | Get new statuses 666 | Fetched a total of 0 new toots 667 | Get new favourites 668 | Fetched a total of 0 new toots 669 | Get new notifications 670 | Fetched a total of 2 new toots 671 | Get followers (this may take a while) 672 | Saving 659 statuses, 376 favourites, 478 mentions, and 107 followers 673 | ``` 674 | 675 | Now you're ready to determine the list of lurkers: 676 | 677 | ```text 678 | $ mastodon-archive followers --no-mentions kensanata@dice.camp 679 | Considering the last 12 weeks 680 | There is no allowlist 681 | ... 682 | ``` 683 | 684 | As I said, this is work in progress and I don't really know where I'm 685 | going with this. More 686 | [on my blog](https://alexschroeder.ch/wiki/2018-04-13_Social_Media_Goals). 687 | 688 | This command supports the [allowlist](#allowlist). 689 | 690 | # Following 691 | 692 | Assume you're on the fediverse just for the conversation. You're not 693 | actually interested in following anybody who never talks to you: no 694 | journalists, no famous people, no pundits. You just want to follow 695 | regular people who interact with you. You can list the people you're 696 | following who never mentioned you, and you can unfollow them all! 697 | 698 | There are two prerequisites, however: 699 | 700 | 1. you need to add the people you're following to the archive 701 | 2. you need to add the mentions to the archive (this can take a long time) 702 | 703 | ```text 704 | $ mastodon-archive archive --with-following --with-mentions kensanata@dice.camp 705 | Loading existing archive 706 | Get user info 707 | Get new statuses 708 | X 709 | Added a total of 11 new items 710 | Get new favourites 711 | X 712 | Added a total of 7 new items 713 | Get new notifications and look for mentions 714 | ..... 715 | Added a total of 7 new items 716 | Skipping followers 717 | Get following (this may take a while) 718 | Saving 932 statuses, 527 favourites, 657 mentions, 107 followers, and 192 following 719 | ``` 720 | 721 | Given this data, you can now list the people we're interested in: 722 | 723 | ```text 724 | $ mastodon-archive following kensanata@dice.camp 725 | Considering the last 12 weeks 726 | ... 727 | ``` 728 | 729 | All these people that never mentioned you: do you really want to 730 | follow them all? If you don't, here's how to unfollow them: 731 | 732 | ```text 733 | $ mastodon-archive following --unfollow kensanata@dice.camp 734 | Considering the last 12 weeks 735 | Unfollowing |################################| 1/125 736 | We need to authorize the app to make changes to your account. 737 | Registering app 738 | This app needs access to your Mastodon account. 739 | Visit the following URL and authorize the app: 740 | [long URL here] 741 | Then paste the access token here: 742 | [access token here] 743 | ``` 744 | 745 | Note that the application needs the permission to unfollow people in 746 | your name, which is why you need to authorize it again. 747 | 748 | This command supports the [allowlist](#allowlist). 749 | 750 | 751 | # Mutes and Blocks 752 | 753 | You can download lists of users you've muted and/or blocked by adding 754 | `--with-mutes` and/or `--with-blocks` to the `archive` command. 755 | 756 | 757 | # User notes 758 | 759 | There is currently a deficiency in the Mastodon API: it can't list all 760 | users for whom you have added private notes. Therefore, it is 761 | impossible for this script to definitively archive all private notes. 762 | However, if you add `--with-notes` to the `archive` command, then the 763 | script will download and archive notes for all users already 764 | downloaded for other reasons, i.e., followers, follows, mutes, and/or 765 | blocks. This is useful, e.g., if you are in the habit of adding 766 | private notes documenting for your future reference why you've 767 | followed, blocked, or muted someone. 768 | 769 | # Allowlist 770 | 771 | You can have an allowlist of people you want to be exempt from some 772 | commands. Create a text file with a name like the following: 773 | `dice.camp.user.kensanata.allowlist.txt`. 774 | 775 | That is: `.user..allowlist.txt`. 776 | 777 | There, list the accounts you want to have in your allowlist, one per 778 | line. All of these formats should work: 779 | 780 | ```text 781 | kensanata 782 | kensanata@dice.camp 783 | Alex Schroeder 784 | ``` 785 | 786 | To verify your allowlist, use the allowlist command: 787 | 788 | ```text 789 | $ mastodon-archive allowlist kensanata@dice.camp 790 | 2 accounts are on the allowlist 791 | kensanata@dice.camp 792 | kensanata 793 | ``` 794 | 795 | Using `wc -l` to count the lines in my output, here's how you can see 796 | that it works: 797 | 798 | ```text 799 | $ mastodon-archive followers kensanata@dice.camp | wc -l 800 | 58 801 | $ echo linkskywalker@soc.ialis.me >> dice.camp.user.kensanata.allowlist.txt 802 | $ mastodon-archive followers kensanata@dice.camp | wc -l 803 | 57 804 | ``` 805 | 806 | # Mutuals 807 | 808 | How do you go about creating a allowlist, though? It's hard! You could 809 | start with the list of people that are following you back, perhaps? 810 | Here's a command to do just that: 811 | 812 | ```text 813 | $ mastodon-archive mutuals kensanata@dice.camp 814 | Get user info 815 | ... 816 | ``` 817 | 818 | We don't currently store the relationship status in our archive so 819 | that's why this command requires a live connection. We do have the 820 | list of people we are *following* in our archive, so we use that. If 821 | you haven't done so, you need to create an archive using the 822 | `--with-following` option before you can use the `mutuals` command. 823 | 824 | ```text 825 | $ mastodon-archive archive --with-following kensanata@dice.camp 826 | Loading existing archive 827 | ... 828 | ``` 829 | 830 | # Example Setup 831 | 832 | I have a shell script called `backup-mastodon` which does the following: 833 | 834 | ```sh 835 | #!/bin/sh 836 | mkdir -p ~/Documents/Mastodon/ 837 | cd ~/Documents/Mastodon/ || exit 838 | 839 | accounts="kensanata@octodon.social kensanata@dice.camp kensanata@tabletop.social" 840 | 841 | echo Archive Statuses, Favourites, Mentions 842 | for acc in $accounts; do 843 | echo "$acc" 844 | mastodon-archive archive --skip-bookmarks --with-mentions "$acc" 845 | done 846 | 847 | echo Expiring Statuses 848 | for acc in $accounts; do 849 | echo "$acc" 850 | mastodon-archive expire --older-than 8 --collection statuses --confirm "$acc" 851 | done 852 | 853 | echo Expiring Favourites 854 | for acc in $accounts; do 855 | echo "$acc" 856 | mastodon-archive expire --older-than 8 --collection favourites --confirm "$acc" 857 | done 858 | 859 | echo Dismissing Notifications 860 | for acc in $accounts; do 861 | echo "$acc" 862 | mastodon-archive expire --older-than 8 --collection mentions --delete-other-notifications --confirm "$acc" 863 | done 864 | ``` 865 | 866 | # Documentation 867 | 868 | The data we have in our archive file is a hash with three keys: 869 | 870 | 1. `account` is a [User dict](https://mastodonpy.readthedocs.io/en/latest/#user-dicts) 871 | 2. `statuses` is a list of [Toot dicts](https://mastodonpy.readthedocs.io/en/latest/#toot-dicts) 872 | 3. `favourites` is a list of [Toot dicts](https://mastodonpy.readthedocs.io/en/latest/#toot-dicts) 873 | 3. `bookmarks` is a list of [Toot dicts](https://mastodonpy.readthedocs.io/en/latest/#toot-dicts) 874 | 4. `mentions` is a list of [Toot dicts](https://mastodonpy.readthedocs.io/en/latest/#toot-dicts) 875 | 876 | If you want to understand the details and the nested nature of these 877 | data structures, you need to look at the Mastodon API documentation. 878 | One way to get started is to look at what a 879 | [Status](https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#status) 880 | entity looks like. 881 | 882 | # Development 883 | 884 | The 885 | [setup.py](https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation) 886 | determines how the app is installed and what its dependencies are. 887 | 888 | If you checked out the repository and you want to run the code from 889 | the working directory on a single user system, use `sudo pip3 install 890 | --upgrade --editable .` in your working directory to make it is 891 | "editable" (i.e. the installation you have is linked to your working 892 | directory, now). 893 | 894 | If you don't want to do this for the entire system, you need your own 895 | virtual environemt: `pip3 install virtualenvwrapper`, `mkvirtualenv ma 896 | --python python3` (this installs and activates a virtual environment 897 | called `ma`), `pip install -e .` (`-e` installs an "editable" copy) 898 | and you're set. Use `workon ma` to work in that virtual environment in 899 | the future. 900 | 901 | # Processing using jq 902 | 903 | [jq](https://stedolan.github.io/jq/) is a lightweight and flexible 904 | command-line JSON processor. That means you can use it to work with 905 | your archive. 906 | 907 | The following command will take all your favourites and create a map 908 | with the keys `time` and `message` for each one of them, and put it 909 | all in an array. 910 | 911 | ```sh 912 | $ jq '[.favourites[] | {time: .account.username, message: .content}]' < dice.camp.user.kensanata.json 913 | ``` 914 | 915 | Example output, assuming I had only a single favourite: 916 | 917 | ```json 918 | [ 919 | { 920 | "time": "andrhia", 921 | "message": "

It’s nice to reinvent yourself every so often, don’t you think?

" 922 | } 923 | ] 924 | ``` 925 | 926 | # Exploring the API 927 | 928 | Now that you have token files, you can explore the Mastodon API using 929 | `curl`. Your *access token* is the long string in the file 930 | `*.user.*.secret`. Here is how to use it. 931 | 932 | Get a single status: 933 | 934 | ```sh 935 | curl --silent --show-error \ 936 | --header "Authorization: Bearer "$(cat dice.camp.user.kensanata.secret) \ 937 | https://dice.camp/api/v1/statuses/99005111284322450 938 | ``` 939 | 940 | Extract the account id from your archive using `jq` and use `echo` to 941 | [strip the surrounding double quotes](https://stackoverflow.com/a/24358387/534893). 942 | Then use the id to get some statuses from the account and use `jq` to 943 | print the status ids: 944 | 945 | ```sh 946 | ID=$(eval echo $(jq .account.id < dice.camp.user.kensanata.json)) 947 | curl --silent --show-error \ 948 | --header "Authorization: Bearer "$(cat dice.camp.user.kensanata.secret) \ 949 | "https://dice.camp/api/v1/accounts/$ID/statuses?limit=3" \ 950 | | jq '.[]|.id' 951 | ``` 952 | 953 | # Alternatives 954 | 955 | There are three kinds of alternatives: 956 | 957 | 1. Solutions that extract your public toots from your profile, e.g. 958 | [https://octodon.social/@kensanata](https://octodon.social/@kensanata). 959 | The problem there is that you'll only get "top level" toots and 960 | boosts but *no replies*. 961 | 962 | * [Mastotool](https://mdhughes.tech/mastotool/) includes media 963 | download! 964 | * [MastoUserScrape.py](https://gist.github.com/FlyMyPG/2e9d4532453182ada0da78e74980193b) 965 | 966 | 2. Solutions that extract your public toots from your Atom feed, e.g. 967 | [https://octodon.social/users/kensanata.atom](https://octodon.social/users/kensanata.atom). 968 | The problem there is that you'll only get a few pages worth of 969 | toots, not *all* of them. 970 | 971 | * [Mastotool "Atom"](https://github.com/kensanata/mastotool) 972 | 973 | 3. Solutions that make use of the official Mastodon downloads. 974 | 975 | * [Mastodon Data Viewer](https://github.com/blackle/mastodon-data-viewer.py) 976 | is a viewer for Mastodon backup data written in Python. It 977 | creates a local server that you can use to browse the data. 978 | Designed for large (>40,000) toot archives. This tool only takes 979 | official Mastodon backups. 980 | * [mav-z](https://github.com/zero-mstd/mav-z) is using HTML and Javascript. 981 | You can simply open its HTML file with your browser, pick the exported 982 | archive – and see nice stats, walk though your toots, jump to a given 983 | month, etc. 984 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | # How to make a release 2 | 3 | Increase the version number in setup.py. 4 | 5 | Tag the commit. 6 | 7 | ``` 8 | make dist 9 | ``` 10 | 11 | Possibly clean up the dist/ folder. 12 | 13 | ``` 14 | make upload 15 | ``` 16 | 17 | Note that the auth token for the upload is stored in ~/.pypirc 18 | 19 | Push new tag to origin and github remotes! 20 | 21 | Send a note to Izzy for packaging `*.deb` and `*.rpm`. 22 | Or use fedi: @IzzyOnDroid@floss.social. 23 | -------------------------------------------------------------------------------- /contrib/README.md: -------------------------------------------------------------------------------- 1 | # Contrib 2 | This directory contains user-provided contributions intended to enhance 3 | mastodon-archive. 4 | 5 | ## `upgrade_python-mastodon.sh` (by Izzy) 6 | A script intended to upgrade outdated versions of `Mastodon.py` when installed 7 | via your Linux distribution's package manager. As of this writing, 8 | mastodon-archive requires at least v1.5.1 for full functionality. It will 9 | work with v1.5.0 with reduced functionality (e.g. bookmark operations are not 10 | available). Some distributions ship even older versions. We explicitly decided 11 | against requiring a specific version in the package's dependencies as that would 12 | make the package unavailable for many LTS distributions, while the underlying 13 | issue can easily be solved – by this script. 14 | 15 | What it does: 16 | 17 | * you call it from within this directory without any parameters 18 | * it uses your package manager (`dpkg` or `yum`) to find out which version of 19 | `python3-mastodon` (DEB) or `python3-Mastodon` (RPM) is installed 20 | * if it cannot find out (no `dpkg`/`yum` found or package not installed) it 21 | will inform you. You can then decide to proceed anyhow – or to use your 22 | package manager to install (this situation should not happen if you installed 23 | mastodon-archive via `apt`/`yum`, but who knows 24 | * if a proper version (1.5.1 or later) was found, it says Good-Bye 25 | * else it checks if the target directory & module exists. If not, it will abort. 26 | * now it downloads the code from PyPi and replaces the existing old version 27 | located in `/usr/lib/python3/dist-packages/mastodon`. 28 | 29 | Before any action takes place, you'll always be asked to confirm. 30 | 31 | ## `mastoarch` (by Izzy) 32 | This is a wrapper for automation – intended to keep a close-to-complete copy 33 | of your Mastodon account on your disk. Simply call it without parameters to 34 | get details on its usage. 35 | 36 | It will work in the directory you called it from. So if you wish to use it, I'd 37 | recommend you either put it into your `$PATH` or create yourself an alias for it. 38 | 39 | Once you've set it up and have it running, you could even have a Cron job 40 | taken care for regular runs. With the config set up properly, the command 41 | for that job could look like this: 42 | 43 | ```bash 44 | source /home/johndoe/.profile && mastoarch archive 45 | ``` 46 | 47 | or, alternatively: 48 | 49 | ```bash 50 | cd /path/to/archive && mastoarch -a Me@MyInstance -b "" 2>/dev/null 51 | ``` 52 | 53 | If you've initialized a git repo with your archive, you could include `-g 2` 54 | with the call to have changes committed automatically. 55 | 56 | ## `mastosearch` (by Izzy) 57 | For your impromptu searches. Again a wrapper around the main script intended 58 | to be easy to use. With your defaults set up in the configuration, a search 59 | is as easy as `mastosearch `. Again, the full syntax is shown when 60 | called without parameters. 61 | 62 | ## `config.sample` (by Izzy) 63 | Lets you define defaults to use with `mastoarch` and `mastosearch` to make 64 | calls to them as simple as possible. On your Linux machine, copy it to 65 | `${HOME}/.config/mastodon-archive/config` and adjust it to fit your needs. 66 | Hints inside. This file is optional, defaults are defined in the scripts 67 | and can be overridden using command-line parameters. 68 | 69 | ## `mastodon-archive` (by Izzy) 70 | `mastodon-archive` and `mastodon-archive.py` are wrapper scripts. The latter is 71 | usually created automatically when installing via PyPi, the former is intended 72 | to go to `/usr/bin` (or somewhere else in your `$PATH`). Both are used with the 73 | DEB/RPM packages maintained by me. 74 | -------------------------------------------------------------------------------- /contrib/config.sample: -------------------------------------------------------------------------------- 1 | # Example config file for the contrib tools. 2 | # copy this to ${HOME}/.config/mastodon-archive/config and adjust to your needs. 3 | 4 | # base where all our backups reside (mastoarch, mastosearch) 5 | # If you define MASTOBASE, your backups are looked for in $MASTOBASE/ 6 | # Otherwise they are looked for in the current working directory. 7 | MASTOBASE= 8 | 9 | # default account (mastoarch, mastosearch) 10 | myacc=Demo@Mastodon.example.net 11 | 12 | # shall followers be archived as well? (mastoarch) 13 | # this is currently of limited use, hence disabled by default. It will not only 14 | # collect user IDs, but the entire profile info; expect about 1.5kB per profile. 15 | # 0: no, 1: yes 16 | archive_followers=0 17 | 18 | # automatically backup to git (mastoarch) 19 | # 0: never, 1: ask, 2: do it 20 | autogit=0 21 | 22 | # use a specific viewer (mastosearch). 23 | # This needs markdown being available (e.g. to use lynx on Debian: 24 | # 'apt install markdown lynx'). 25 | # The viewer should accept HTML from STDIN (standard input). 26 | # If empty, results will simply be printed on your console. 27 | #viewer="lynx -stdin" 28 | viewer= 29 | -------------------------------------------------------------------------------- /contrib/mastoarch: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to automate your Mastodon backup. Run it without any arguments to show its usage. 3 | # © 2022 Izzy ; GPL-3.0-or-later 4 | # 5 | # You can use this script e.g. via Cron for automated backups of your Mastodon account. 6 | # A command for cron could be: "cd /path/to/mastoarch && ./mastoarch archive >/dev/null" 7 | 8 | # ----------------------------------------------------------------------------- 9 | # Default options (can be overridden via command-line): 10 | myacc="Demo@server.tld" # Your (default) Mastodon handle 11 | archive_followers=0 # whether to archive followers as well 12 | autogit=0 # whether to automatically check-in new data to your local git repo 13 | 14 | # !!! ================================================================== !!! 15 | # !!! Do not change below this line unless you know what you're doing :) !!! 16 | # !!! ================================================================== !!! 17 | 18 | # ----------------------------------------------------------------------------- 19 | # Load config if exists 20 | [[ -f "${HOME}/.config/mastodon-archive/config" ]] && source "${HOME}/.config/mastodon-archive/config" 21 | 22 | # ----------------------------------------------------------------------------- 23 | # Evaluate command-line options 24 | while getopts "a:b:f:g:" OPT; do 25 | case $OPT in 26 | a) myacc=$OPTARG ;; 27 | b) MASTOBASE="$OPTARG" ;; 28 | f) case "$OPTARG" in 29 | 0|1) archive_followers=$OPTARG ;; 30 | *) echo -e "\n! invalid value '$OPTARG' for archive_followers. -f must be 0 or 1.\n" 31 | exit 1 32 | ;; 33 | esac 34 | ;; 35 | g) case "$OPTARG" in 36 | 0|1|2) autogit=$OPTARG ;; 37 | *) echo -e "\n! invalid value '$OPTARG' for autogit. -g must be 0, 1 or 2.\n" 38 | exit 1 39 | ;; 40 | esac 41 | ;; 42 | *) $0 ; exit 1 ;; 43 | esac 44 | done 45 | shift $(($OPTIND - 1)) 46 | 47 | # ----------------------------------------------------------------------------- 48 | # show help 49 | syntax() { 50 | echo 51 | echo "Mastodon Archiver" 52 | echo "=================" 53 | echo 54 | echo "Syntax:" 55 | echo " $0 [options] " 56 | echo 57 | echo "Commands:" 58 | echo " archive: get data from the instance" 59 | echo " html : generate static html from gathered data" 60 | echo " backup : archive & html" 61 | echo " report : show some stats" 62 | echo " help : show this help page and exit" 63 | echo 64 | echo "Options:" 65 | echo " -a : Mastodon handle (user) to process" 66 | echo " -b : base where all our backups reside. If specified," 67 | echo " your backups are expected in MASTOBASE/" 68 | echo " (e.g. /home/peter/mastodon/mastodon.example.net if" 69 | echo " your account is @@mastodon.example.net)," 70 | echo " otherwise they will be looked for in your current" 71 | echo " working directory (where you are when invoking this script)" 72 | echo " -g <0|1|2> : whether to automatically check in changes to your local" 73 | echo " git (0: don't, 1: ask, 2: do it)" 74 | echo 75 | echo "Note that you can define your defaults (myacc, autogit) in" 76 | echo "${HOME}/.config/mastodon-archive/config" 77 | echo 78 | } 79 | 80 | # ----------------------------------------------------------------------------- 81 | # sanity check 82 | if [[ "$myacc" = "Demo@server.tld" && -n "$1" ]]; then 83 | syntax 84 | echo "You must configure your Mastodon-handle before running this script," 85 | echo "or pass it via the '-a' option." 86 | echo 87 | exit 1 88 | fi 89 | 90 | # ----------------------------------------------------------------------------- 91 | # get data from the instance 92 | function archive() { 93 | if [[ $archive_followers -eq 1 ]]; then 94 | mastodon-archive archive --with-mentions --with-following --with-followers "$myacc" 95 | else 96 | mastodon-archive archive --with-mentions --with-following "$myacc" 97 | fi 98 | mastodon-archive replies "$myacc" 99 | mastodon-archive media --collection favourites "$myacc" 100 | mastodon-archive media --collection bookmarks "$myacc" 101 | } 102 | 103 | # ----------------------------------------------------------------------------- 104 | # generate static html from gathered data 105 | function html() { 106 | mastodon-archive html "$myacc" 107 | mastodon-archive html --collection bookmarks "$myacc" 108 | mastodon-archive html --collection favourites "$myacc" 109 | } 110 | 111 | # ----------------------------------------------------------------------------- 112 | # add changes to local git repo 113 | function save() { 114 | [[ $autogit -lt 1 ]] && return 115 | [[ ! -d .git ]] && { 116 | echo "No git repo found, skipping check-in." 117 | echo "(Use 'git init' to create a repo.)" 118 | return 119 | } 120 | case $autogit in 121 | 0) gitreply=n ;; 122 | 1) read -n 1 -t 600 -p "run 'git add' and 'git commit' (y/n)? " gitreply 123 | echo 124 | ;; 125 | 2) gitreply=y ;; 126 | esac 127 | [[ ${gitreply,,} = 'y' || ${gitreply,,} = 'j' ]] && { 128 | git add . 129 | git commit -m "commit for backup after run for '$1' at $(date +'%y-%m-%y %H:%M:%S')" 130 | } 131 | } 132 | 133 | # ----------------------------------------------------------------------------- 134 | # show some stats 135 | function report() { 136 | basename="${myacc##*@}.user.${myacc%%@*}" 137 | echo 138 | echo "Account Statistics:" 139 | echo "===================" 140 | echo 141 | echo "Account: ${myacc}" 142 | echo 143 | mastodon-archive report --all "$myacc" 144 | echo 145 | echo "Followers who follow us back:" 146 | echo "-----------------------------" 147 | mastodon-archive mutuals "$myacc" | grep -iv "Get user info" 148 | echo 149 | echo "$(mastodon-archive mutuals "$myacc" | grep -iv "Get user info" | wc -l) Followers follow us back." 150 | echo 151 | echo "Header info:" 152 | echo "------------" 153 | echo "Statuses: $(jq .account.statuses_count ${basename}.json)" 154 | echo "Followers: $(jq .account.followers_count ${basename}.json)" 155 | echo "Following: $(jq .account.following_count ${basename}.json)" 156 | echo "Last status: $(jq .account.last_status_at ${basename}.json | awk -F \" '{print $2}' | awk -F T '{print $1}')" 157 | echo "Account created: $(jq .account.created_at ${basename}.json | awk -F \" '{print $2}' | awk -F T '{print $1}')" 158 | echo 159 | } 160 | 161 | # ----------------------------------------------------------------------------- 162 | # find out where to look for / create our backup 163 | if [[ -n "$MASTOBASE" ]]; then 164 | INSTDIR="${MASTOBASE}/${myacc##*@}" 165 | else 166 | INSTDIR="${PWD}" 167 | fi 168 | 169 | #===[ MAIN ]=== 170 | cd "$INSTDIR" 171 | # What to do? 172 | case "$1" in 173 | archive) archive && save archive;; 174 | html) html && save html;; 175 | backup) archive && html && save backup;; 176 | report) report;; 177 | *) syntax;; 178 | esac 179 | cd - >/dev/null 180 | -------------------------------------------------------------------------------- /contrib/mastodon-archive: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | /usr/lib/python3/dist-packages/mastodon-archive/mastodon-archive.py $* 3 | -------------------------------------------------------------------------------- /contrib/mastodon-archive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import mastodon_archive 3 | 4 | if __name__ == "__main__": 5 | mastodon_archive.main() 6 | -------------------------------------------------------------------------------- /contrib/mastosearch: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # search our local mastodon archive 3 | # © 2022 Izzy ; GPL-3.0-or-later 4 | 5 | # ----------------------------------------------------------------------------- 6 | # Defaults 7 | MASTOBASE= 8 | myacc=Demo@Mastodon.example.net 9 | viewer= 10 | 11 | # ----------------------------------------------------------------------------- 12 | # Load config if exists 13 | [[ -f "${HOME}/.config/mastodon-archive/config" ]] && source "${HOME}/.config/mastodon-archive/config" 14 | 15 | # ----------------------------------------------------------------------------- 16 | # Evaluate command-line options 17 | colls= 18 | context= 19 | follower= 20 | following= 21 | while getopts "a:b:c:f:F:t:v:" OPT; do 22 | case $OPT in 23 | a) myacc=$OPTARG ;; 24 | b) MASTOBASE="$OPTARG" ;; 25 | c) case "$OPTARG" in 26 | favorites) colls="$colls --collection favorites" ;; 27 | mentions) colls="$colls --collection mentions" ;; 28 | bookmarks) colls="$colls --collection bookmarks" ;; 29 | statuses) colls="$colls --collection statuses" ;; 30 | all) colls="--collection all" ;; 31 | *) echo "ignoring unknown collection '$OPTARG'" 32 | esac 33 | ;; 34 | F) follower="$OPTARG" ;; 35 | f) following="$OPTARG" ;; 36 | t) context="$OPTARG" ;; 37 | v) viewer="$OPTARG" ;; 38 | *) $0 ; exit 1 ;; 39 | esac 40 | done 41 | shift $(($OPTIND - 1)) 42 | 43 | # ----------------------------------------------------------------------------- 44 | # show help 45 | syntax() { 46 | echo 47 | echo "Mastodon Searcher" 48 | echo "=================" 49 | echo 50 | echo "Syntax:" 51 | echo " $0 [options] [ ...]" 52 | echo " $0 -t [-l]" 53 | echo 54 | echo "SearchRegEx:" 55 | echo " - a single search term, e.g. 'book'" 56 | echo " - a RegEx term, e.g. 'e?book\b'" 57 | echo " - a time frame, e.g. 2017-(07|08|09|10|11)' (useful as 2nd term)" 58 | echo " - a phrase, e.g. '(?i)android book'" 59 | echo 60 | echo "Options:" 61 | echo " -a : Mastodon handle (user) to process" 62 | echo " -b : base where all our backups reside. If specified," 63 | echo " your backups are expected in MASTOBASE/" 64 | echo " (e.g. /home/peter/mastodon/mastodon.example.net if" 65 | echo " your account is @@mastodon.example.net)," 66 | echo " otherwise they will be looked for in your current" 67 | echo " working directory (where you are when invoking this script)" 68 | echo " -c : search specified collection. Valid collections:" 69 | echo " favorites, bookmarks, mentions, statuses, all" 70 | echo " -f : search your followings. Requires followers to be archived" 71 | echo " and the 'jq' tool being available. Search will always be" 72 | echo " case insensitive. Returns JSON." 73 | echo " Cannot be combined with -c or -t." 74 | echo " -F : search your followers. Requires followers to be archived" 75 | echo " and the 'jq' tool being available. Search will always be" 76 | echo " case insensitive. Returns JSON." 77 | echo " Cannot be combined with -c or -t." 78 | echo " -t : thread (conText) search. is the link to a status" 79 | echo " which shall be shown with its context." 80 | echo " -v : display results with a self-defined viewer, e.g. Lynx." 81 | echo " The viewer needs to accept HTML from standard input, and" 82 | echo " this feature also needs the 'markdown' command being" 83 | echo " available on your system." 84 | echo 85 | echo "Note that you can define your defaults (MASTOBASE, myacc) in" 86 | echo "${HOME}/.config/mastodon-archive/config" 87 | echo 88 | } 89 | 90 | # ----------------------------------------------------------------------------- 91 | # evaluate settings 92 | if [[ -n "$viewer" && -z "$(which $(echo $viewer | awk '{print $1}'))" ]]; then 93 | echo -e "\n'$(echo $viewer | awk '{print $1}')' not found, resetting viewer.\n" 94 | viewer= 95 | fi 96 | if [[ -n "$MASTOBASE" ]]; then 97 | INSTDIR="${MASTOBASE}/${myacc##*@}" 98 | else 99 | INSTDIR="${PWD}" 100 | fi 101 | [[ "$myacc" = "Demo@Mastodon.example.net" ]] && { 102 | echo "You need to configure your default account (either at the top of this script or" 103 | echo "in '${HOME}/.config/mastodon-archive/config') or pass an account using the '-a' option." 104 | echo 105 | exit 2 106 | } 107 | [[ ! -f "${INSTDIR}/${myacc##*@}.user.${myacc%%@*}.json" ]] && { 108 | echo "Could not find '${INSTDIR}/${myacc##*@}.user.${myacc%%@*}.json'." 109 | echo "Maybe you did not yet create a backup?" 110 | echo 111 | exit 5 112 | } 113 | [[ -z "$1" && -z "${context}${follower}${following}" ]] && { 114 | syntax 115 | exit; 116 | } 117 | 118 | 119 | # ----------------------------------------------------------------------------- 120 | # Do it! 121 | cd "${INSTDIR}" 122 | if [[ -n "$viewer" ]]; then 123 | if [[ -n "$context" ]]; then 124 | mastodon-archive context $myacc $context | markdown | $viewer 125 | elif [[ -n "$follower" ]]; then 126 | jq --arg search "$follower" '.followers[] | select(any(. | strings | test($search; "i")))' ${myacc##*@}.user.${myacc%%@*}.json | echo -e "\`\`\`\n$(cat)\n\`\`\`\n" | markdown | sed 's!!
!;s!!
!' | $viewer 127 | elif [[ -n "$following" ]]; then 128 | jq --arg search "$following" '.following[] | select(any(. | strings | test($search; "i")))' ${myacc##*@}.user.${myacc%%@*}.json | echo -e "\`\`\`\n$(cat)\n\`\`\`\n" | markdown | sed 's!!
!;s!!
!' | $viewer 129 | else 130 | mastodon-archive text $colls $myacc $* | markdown | $viewer 131 | fi 132 | else 133 | if [[ -n "$context" ]]; then 134 | mastodon-archive context $myacc $context 135 | elif [[ -n "$follower" ]]; then 136 | jq --arg search "$follower" '.followers[] | select(any(. | strings | test($search; "i")))' ${myacc##*@}.user.${myacc%%@*}.json 137 | elif [[ -n "$following" ]]; then 138 | jq --arg search "$following" '.following[] | select(any(. | strings | test($search; "i")))' ${myacc##*@}.user.${myacc%%@*}.json 139 | else 140 | mastodon-archive text $colls $myacc $* 141 | fi 142 | fi 143 | cd - > /dev/null 144 | -------------------------------------------------------------------------------- /contrib/upgrade_python-mastodon.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # upgrade the python-mastodon module if Debian/RPM package was outdated 3 | # ----------------------------------------------------------------------------- 4 | # this is intended for the case your distribution ships with an outdated version 5 | # of the python-mastodon package (pre-1.5.1). It will simply replace the module 6 | # scripts where your packaging placed them. 7 | # 8 | # © 2022 Izzy ; GPL-3.0-or-later 9 | 10 | # ----------------------------------------------------------------------------- 11 | # define temp dir and exit-on-error 12 | function cleanup() { 13 | msg="${1:-"Something went wrong, aborting."}" 14 | lvl=${2:-1} 15 | [[ -n "${msg}" && "${msg}" != "-" ]] && { 16 | echo 17 | echo "${msg}" 18 | } 19 | echo 20 | rm -rf $tmpdir 21 | exit $lvl 22 | } 23 | 24 | tmpdir=$(mktemp -d) 25 | trap cleanup ERR 26 | 27 | 28 | # ============== 29 | # ===[ Main ]=== 30 | # ============== 31 | # ----------------------------------------------------------------------------- 32 | # check whether we need to update python3-mastodon 33 | echo 34 | echo "Let's see if your distribution has a recent version of python3-mastodon..." 35 | if [[ -f /etc/debian_version ]]; then 36 | mver="$(dpkg -l python3-mastodon |tail -n 1 |awk '{print $3}')" 37 | elif [[ -f /etc/redhat_release || -f /etc/fedora-release ]]; then 38 | mver="$(yum info python3-Mastodon |grep -Ei '^Version' |awk '{print $3}')" 39 | else 40 | echo 41 | echo "Could not determine whether your system is DEB or RPM based." 42 | echo "To continue, this script would assume that the 'python3-mastodon' module" 43 | echo "was installed to '/usr/lib/python3/dist-packages/mastodon'." 44 | echo "Please make sure that this directory exists and contains at least a file" 45 | echo "named 'Mastodon.py'. If it does not, you better abort this attempt." 46 | echo "" 47 | read -n 1 -p "Continue this way? (y/n) " REPLY 48 | if [[ "${REPLY,,}" = 'y' || "${REPLY,,}" = 'j' ]]; then 49 | echo 50 | echo "Assuming package version 1.5.0 to continue." 51 | echo 52 | mver="1.5.0-1" 53 | else 54 | cleanup "Aborting on user request." 10 55 | fi 56 | fi 57 | 58 | if [[ -z "$mver" ]]; then # package not even installed or not found 59 | echo 60 | echo "Looks like python3-mastodon is not installed at all, so we cannot update it." 61 | echo "Please install it first and then try again:" 62 | echo 63 | if [[ -f /etc/debian_version ]]; then 64 | echo " sudo apt install python3-mastodon" 65 | else 66 | echo " yum install python3-Mastodon" 67 | fi 68 | cleanup "-" 69 | fi 70 | 71 | mver="${mver%%-*}" 72 | IFS='.'; arr=($mver); unset IFS 73 | typeset -i vercode=${arr[2]}+${arr[1]}*100+${arr[0]}*10000 74 | if [[ $vercode -gt 10500 ]]; then # we need at least v1.5.1 = 10501 75 | echo "Found version '$mver' – all is fine!" 76 | else 77 | echo "Found version '$mver' – that's too old. Let's get v1.5.1 and replace the required files." 78 | if [[ -f /usr/lib/python3/dist-packages/mastodon/Mastodon.py ]]; then 79 | read -n 1 -p "Continue? (y/n) " REPLY 80 | echo 81 | if [[ "${REPLY,,}" = 'y' || "${REPLY,,}" = 'j' ]]; then 82 | echo "Downloading, extracting and copying (via sudo) files" 83 | cd $tmpdir 84 | wget -q --show-progress https://files.pythonhosted.org/packages/7c/80/f12b205fc529fff8e3245fe8e6cafb870f1783476449d3ea2a32b40928c5/Mastodon.py-1.5.1-py2.py3-none-any.whl 85 | unzip Mastodon.py-1.5.1-py2.py3-none-any.whl 86 | sudo cp mastodon/__init__.py mastodon/Mastodon.py mastodon/streaming.py /usr/lib/python3/dist-packages/mastodon 87 | cd - >/dev/null 88 | else 89 | cleanup "Aborting on user request." 10 90 | fi 91 | else 92 | echo 93 | echo "ERROR: Target directory '/usr/lib/python3/dist-packages/mastodon' was not found" 94 | echo "(or did not contain a 'Mastodon.py')." 95 | cleanup "-" 5 96 | fi 97 | rm -rf $tmpdir 98 | fi 99 | 100 | 101 | # ----------------------------------------------------------------------------- 102 | # Finito 103 | echo 104 | echo "If you saw no errors in the last step, all should be ready now. Enjoy!" 105 | echo 106 | -------------------------------------------------------------------------------- /mastodon_archive/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2019 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import argparse 17 | from . import core 18 | from . import archive 19 | from . import replies 20 | from . import text 21 | from . import context 22 | from . import html 23 | from . import media 24 | from . import split 25 | from . import expire 26 | from . import report 27 | from . import followers 28 | from . import following 29 | from . import allowlist 30 | from . import mutuals 31 | from . import login 32 | from . import fix 33 | from . import meow 34 | 35 | def main(): 36 | parser = argparse.ArgumentParser( 37 | description="""Archive your toots, favourites and bookmarks, 38 | and work with them.""", 39 | epilog="""Once you have created archives in the current directory, you can 40 | use 'all' instead of your account and the commands will be run 41 | once for every archive in the directory.""") 42 | 43 | parser.add_argument("--quiet", "-q", action='store_true', default=False, 44 | help='do not output normal status messages') 45 | 46 | subparsers = parser.add_subparsers() 47 | 48 | 49 | parser_content = subparsers.add_parser( 50 | name='archive', 51 | help='archive your toots, favourites and bookmarks') 52 | parser_content.add_argument("--no-favourites", dest='skip_favourites', 53 | action='store_const', 54 | const=True, default=False, 55 | help='skip download of favourites') 56 | parser_content.add_argument("--no-bookmarks", dest='skip_bookmarks', 57 | action='store_const', 58 | const=True, default=False, 59 | help='skip download of bookmarks') 60 | parser_content.add_argument("--with-mentions", dest='with_mentions', 61 | action='store_const', 62 | const=True, default=False, 63 | help='download mentions (notifications where you are mentioned)') 64 | parser_content.add_argument("--with-followers", dest='with_followers', 65 | action='store_const', 66 | const=True, default=False, 67 | help='download followers (people following you)') 68 | parser_content.add_argument("--with-following", dest='with_following', 69 | action='store_const', 70 | const=True, default=False, 71 | help='download following (the people you follow)') 72 | parser_content.add_argument("--with-mutes", action='store_true', 73 | default=False, help='download people you muted') 74 | parser_content.add_argument("--with-blocks", action='store_true', 75 | default=False, help='download people you blocked') 76 | parser_content.add_argument("--with-notes", action='store_true', 77 | default=False, help='download private notes ' 78 | 'for any followers, follows, mutes, and/or ' 79 | 'blocks that have been downloaded') 80 | parser_content.add_argument("--no-stopping", dest='stopping', 81 | action='store_const', 82 | const=False, default=True, 83 | help='do not stop after seeing 10 duplicates') 84 | parser_content.add_argument("--update", dest='update', 85 | action='store_const', 86 | const=True, default=False, 87 | help='save updated versions of statuses') 88 | parser_content.add_argument("--pace", dest='pace', action='store_const', 89 | const=True, default=False, 90 | help='avoid timeouts and pace requests') 91 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 92 | const="none", default="created", 93 | help='ignore "Version check failed" error') 94 | parser_content.add_argument("user", 95 | help='your account, e.g. kensanata@octogon.social') 96 | parser_content.set_defaults(command=archive.archive) 97 | 98 | 99 | parser_content = subparsers.add_parser( 100 | name='replies', 101 | help='archive missing toots you replied to') 102 | parser_content.add_argument("--pace", dest='pace', action='store_const', 103 | const=True, default=False, 104 | help='avoid timeouts and pace requests') 105 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 106 | const="none", default="created", 107 | help='ignore "Version check failed" error') 108 | parser_content.add_argument("user", 109 | help='your account, e.g. kensanata@octogon.social') 110 | parser_content.set_defaults(command=replies.replies) 111 | 112 | 113 | parser_content = subparsers.add_parser( 114 | name='media', 115 | help='download media referred to by toots in your archive') 116 | parser_content.add_argument("user", 117 | help='your account, e.g. kensanata@octogon.social') 118 | parser_content.add_argument("--combine", 119 | action="store_true", 120 | help="combine archives in case they are split") 121 | parser_content.add_argument("--collection", dest='collection', 122 | choices=['statuses', 'favourites', 'bookmarks'], 123 | default='statuses', 124 | help='export statuses, favourites or bookmarks') 125 | parser_content.add_argument("--pace", dest='pace', action='store_const', 126 | const=True, default=False, 127 | help='avoid timeouts and pace requests') 128 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 129 | const="none", default="created", 130 | help='ignore "Version check failed" error') 131 | parser_content.add_argument("--suppress-errors", action='store_true', 132 | default=False, help="don't print messages " 133 | "about media that can't be downloaded") 134 | parser_content.set_defaults(command=media.media) 135 | 136 | 137 | parser_content = subparsers.add_parser( 138 | name='text', 139 | help='search and export toots in the archive as plain text') 140 | parser_content.add_argument("--reverse", dest='reverse', action='store_const', 141 | const=True, default=False, 142 | help='reverse output, oldest first') 143 | parser_content.add_argument("--combine", 144 | action="store_true", 145 | help="combine archives in case they are split") 146 | parser_content.add_argument("--collection", dest='collection', 147 | choices=['statuses', 'favourites', 'bookmarks', 'mentions', 'all'], 148 | default='statuses', 149 | help='export statuses, favourites, bookmarks or mentions') 150 | parser_content.add_argument("user", 151 | help='your account, e.g. kensanata@octogon.social') 152 | parser_content.add_argument("pattern", nargs='*', 153 | help='regular expressions used to filter output') 154 | parser_content.set_defaults(command=text.text) 155 | 156 | 157 | parser_content = subparsers.add_parser( 158 | name='context', 159 | help='show a toot in context (i.e. with its ancestors and its descendants') 160 | parser_content.add_argument("user", 161 | help='your account, e.g. kensanata@octogon.social') 162 | parser_content.add_argument("url", 163 | help='URL of the toot to be included') 164 | parser_content.set_defaults(command=context.context) 165 | 166 | 167 | parser_content = subparsers.add_parser( 168 | name='html', 169 | help='export toots and media in the archive as static HTML') 170 | parser_content.add_argument("--combine", 171 | action="store_true", 172 | help="combine archives in case they are split") 173 | parser_content.add_argument("--collection", dest='collection', 174 | choices=['statuses', 'favourites', 'bookmarks'], 175 | default='statuses', 176 | help='export statuses favourites or bookmarks') 177 | parser_content.add_argument("--toots-per-page", dest='toots', 178 | metavar='N', type=int, default=2000, 179 | help='how many toots per HTML page') 180 | parser_content.add_argument("user", 181 | help='your account, e.g. kensanata@octogon.social') 182 | parser_content.set_defaults(command=html.html) 183 | 184 | parser_content = subparsers.add_parser( 185 | name='split', 186 | help='split an archive into two') 187 | parser_content.add_argument("--older-than", dest='weeks', 188 | metavar='N', type=float, default=4, 189 | help='split anything older than this many weeks') 190 | parser_content.add_argument("--confirmed", dest='confirmed', 191 | action='store_const', const=True, default=False, 192 | help='save the data after splitting') 193 | parser_content.add_argument("user", 194 | help='your account, e.g. kensanata@octogon.social') 195 | parser_content.set_defaults(command=split.split) 196 | 197 | 198 | parser_content = subparsers.add_parser( 199 | name='expire', 200 | help='''delete older toots from the server and unfavour favourites 201 | if and only if they are in your archive''', 202 | epilog='''There is one problem you need to be aware of: if you expiring 203 | mentions, then the tool goes through all your notifications 204 | and looks at those of the type mention, and expires them if 205 | they are old enough. There are other types of notifications, 206 | however: follow, favourite, and reblog (at the time of this 207 | writing). As these are not archived, we also don't expire 208 | them. Thus, the list of notifications to look through keeps 209 | growing unless you use the "Clear notifications" menu in the 210 | Mastodon web client. Alternatively, you can use the 211 | --delete-other-notifications option together with 212 | --collection mentions.''') 213 | 214 | parser_content.add_argument("--collection", dest='collection', 215 | choices=['statuses', 'favourites', 'mentions'], 216 | default='statuses', 217 | help='delete statuses, unfavour favourites, or clear mention notifications') 218 | parser_content.add_argument("--older-than", dest='weeks', 219 | metavar='N', type=float, default=4, 220 | help='expire anything older than this many weeks') 221 | parser_content.add_argument("--delete-other-notifications", dest='delete_others', 222 | action='store_const', const=True, default=False, 223 | help='clear follow, favourite, and reblog notifications') 224 | parser_content.add_argument("--confirmed", dest='confirmed', 225 | action='store_const', const=True, default=False, 226 | help='perform the expiration on the server') 227 | parser_content.add_argument("--pace", dest='pace', action='store_const', 228 | const=True, default=False, 229 | help='avoid timeouts and pace requests') 230 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 231 | const="none", default="created", 232 | help='ignore "Version check failed" error') 233 | parser_content.add_argument("user", 234 | help='your account, e.g. kensanata@octogon.social') 235 | parser_content.set_defaults(command=expire.expire) 236 | 237 | 238 | 239 | parser_content = subparsers.add_parser( 240 | name='report', 241 | help='''report some numbers about your toots, favourites and bookmarks''') 242 | parser_content.add_argument("--combine", 243 | action="store_true", 244 | help="combine archives in case they are split") 245 | parser_content.add_argument("--all", dest='all', action='store_const', 246 | const=True, default=False, 247 | help='consider all toots (ignore --newer-than)') 248 | parser_content.add_argument("--newer-than", dest='weeks', 249 | metavar='N', type=int, default=12, 250 | help='only consider toots newer than this many weeks') 251 | parser_content.add_argument("--top", dest='top', 252 | metavar='N', type=int, default=10, 253 | help='only print the top N tags') 254 | parser_content.add_argument("--include-boosts", dest='include_boosts', action='store_const', 255 | const=True, default=False, 256 | help='include boosts') 257 | parser_content.add_argument("--with-emoji", dest='with_emoji', action='store_const', 258 | const=True, default=False, 259 | help='include emoji count') 260 | parser_content.add_argument("user", 261 | help='your account, e.g. kensanata@octogon.social') 262 | parser_content.set_defaults(command=report.report) 263 | 264 | 265 | parser_content = subparsers.add_parser( 266 | name='followers', 267 | help='''show followers''') 268 | parser_content.add_argument("--no-mentions", dest='mentions', action='store_const', 269 | const=False, default=True, 270 | help='Limit to followers that do not mention you') 271 | parser_content.add_argument("--block", dest='block', action='store_const', 272 | const=True, default=False, 273 | help='...and block them') 274 | parser_content.add_argument("--all", dest='all', action='store_const', 275 | const=True, default=False, 276 | help='consider all toots (ignore --newer-than) when looking for interactions') 277 | parser_content.add_argument("--newer-than", dest='weeks', 278 | metavar='N', type=int, default=12, 279 | help='require interaction within this many weeks (default is 12)') 280 | parser_content.add_argument("user", 281 | help='your account, e.g. kensanata@octogon.social') 282 | parser_content.set_defaults(command=followers.followers) 283 | 284 | 285 | parser_content = subparsers.add_parser( 286 | name='following', 287 | help='''find people you are following but who never mention you''') 288 | parser_content.add_argument("--unfollow", dest='unfollow', action='store_const', 289 | const=True, default=False, 290 | help='...and unfollow them') 291 | parser_content.add_argument("--all", dest='all', action='store_const', 292 | const=True, default=False, 293 | help='consider all toots (ignore --newer-than)') 294 | parser_content.add_argument("--newer-than", dest='weeks', 295 | metavar='N', type=int, default=12, 296 | help='require mention within this many weeks (default is 12)') 297 | parser_content.add_argument("--pace", dest='pace', action='store_const', 298 | const=True, default=False, 299 | help='avoid timeouts and pace requests') 300 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 301 | const="none", default="created", 302 | help='ignore "Version check failed" error') 303 | parser_content.add_argument("user", 304 | help='your account, e.g. kensanata@octogon.social') 305 | parser_content.set_defaults(command=following.following) 306 | 307 | 308 | parser_content = subparsers.add_parser( 309 | name='mutuals', 310 | help='''find people you are following and who follow you back''') 311 | parser_content.add_argument("--pace", dest='pace', action='store_const', 312 | const=True, default=False, 313 | help='avoid timeouts and pace requests') 314 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 315 | const="none", default="created", 316 | help='ignore "Version check failed" error') 317 | parser_content.add_argument("user", 318 | help='your account, e.g. kensanata@octogon.social') 319 | parser_content.set_defaults(command=mutuals.mutuals) 320 | 321 | 322 | parser_content = subparsers.add_parser( 323 | name='allowlist', 324 | help='''print the allowlist to help you debug problems''') 325 | parser_content.add_argument("user", 326 | help='your account, e.g. kensanata@octogon.social') 327 | parser_content.set_defaults(command=allowlist.print_allowlist) 328 | 329 | parser_content = subparsers.add_parser( 330 | name='fix-boosts', 331 | help='''mark all the boosts as not deleted (triggering their deletion)''') 332 | parser_content.add_argument("--combine", 333 | action="store_true", 334 | help="combine archives in case they are split") 335 | parser_content.add_argument("user", 336 | help='your account, e.g. kensanata@octogon.social') 337 | parser_content.add_argument("--confirmed", dest='confirmed', 338 | action='store_const', const=True, default=False, 339 | help='perform the change on the archive') 340 | parser_content.set_defaults(command=fix.fix_boosts) 341 | 342 | parser_content = subparsers.add_parser( 343 | name='login', 344 | help='login to the instance for testing purposes') 345 | parser_content.add_argument("user", 346 | help='your account, e.g. kensanata@octogon.social') 347 | parser_content.set_defaults(command=login.login) 348 | 349 | parser_content = subparsers.add_parser( 350 | name='meow', 351 | help='import your backup into Meow, a browser-based export viewer (see https://purr.neocities.org/about/)') 352 | parser_content.add_argument("user", 353 | help='your account, e.g. kensanata@octogon.social') 354 | parser_content.add_argument("--combine", 355 | action="store_true", 356 | help="combine archives in case they are split") 357 | parser_content.set_defaults(command=meow.meow) 358 | 359 | 360 | args = parser.parse_args() 361 | 362 | try: 363 | if hasattr(args, "command"): 364 | if hasattr(args, "user") and args.user == 'all': 365 | for user in core.all_accounts(): 366 | print(user) 367 | args.user = user 368 | args.command(args) 369 | else: 370 | args.command(args) 371 | else: 372 | parser.print_help() 373 | except KeyboardInterrupt: 374 | pass 375 | 376 | if __name__ == "__main__": 377 | main() 378 | -------------------------------------------------------------------------------- /mastodon_archive/allowlist.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | from . import core 18 | 19 | def print_allowlist(args): 20 | 21 | (username, domain) = core.parse(args.user) 22 | 23 | allowlist = core.allowlist(domain, username) 24 | 25 | for account in allowlist: 26 | print(account) 27 | -------------------------------------------------------------------------------- /mastodon_archive/archive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2019 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import datetime 18 | import sys 19 | import os.path 20 | from . import core 21 | from mastodon.errors import MastodonAPIError 22 | 23 | def archive(args): 24 | """ 25 | Archive your toots, favourites, and bookmarks from your Mastodon account 26 | """ 27 | 28 | skip_favourites = args.skip_favourites 29 | skip_bookmarks = args.skip_bookmarks 30 | with_mentions = args.with_mentions 31 | with_followers = args.with_followers 32 | with_following = args.with_following 33 | with_mutes = args.with_mutes 34 | with_blocks = args.with_blocks 35 | with_notes = args.with_notes 36 | stopping = args.stopping 37 | update = args.update 38 | 39 | (username, domain) = core.parse(args.user) 40 | 41 | status_file = domain + '.user.' + username + '.json' 42 | data = core.load(status_file, quiet = args.quiet) 43 | 44 | mastodon = core.login(args) 45 | 46 | if not args.quiet: 47 | print("Get user info") 48 | 49 | try: 50 | user = mastodon.account_verify_credentials() 51 | except Exception as e: 52 | if "access token was revoked" in str(e): 53 | core.deauthorize(args) 54 | # retry and exit without an error 55 | archive(args) 56 | sys.exit(0) 57 | elif "Name or service not known" in str(e): 58 | print("Error: the instance name is either misspelled or offline", 59 | file=sys.stderr) 60 | else: 61 | print(e, file=sys.stderr) 62 | # exit in either case 63 | sys.exit(1) 64 | 65 | def recursive_compare(item1, item2): 66 | """True if identical, False otherwise""" 67 | # Filter out frequently changing, transient values that shouldn't 68 | # trigger a re-archive. 69 | ignore_keys = ("following_count", "followers_count", "statuses_count", 70 | "last_status_at", "verified_at") 71 | if isinstance(item1, list): 72 | if not isinstance(item2, list): 73 | return False 74 | try: 75 | for v1, v2 in zip(item1, item2, strict=True): 76 | if not recursive_compare(v1, v2): 77 | return False 78 | except ValueError: 79 | return False 80 | return True 81 | elif isinstance(item1, dict): 82 | if not isinstance(item2, dict): 83 | return False 84 | # Treat None as equivalent to not existing 85 | item1 = {k: v for k, v in item1.items() if v is not None} 86 | item2 = {k: v for k, v in item2.items() if v is not None} 87 | if len(item1) != len(item2): 88 | return False 89 | for k1, v1 in item1.items(): 90 | if k1 in ignore_keys: 91 | continue 92 | if k1 not in item2: 93 | return False 94 | if not recursive_compare(v1, item2[k1]): 95 | return False 96 | return True 97 | elif d1 := core.date_handler(item1): 98 | return True if d1 == item2 else d1 == core.data_handler(item2) 99 | elif d2 := core.date_handler(item1): 100 | return item1 == d2 101 | 102 | # *sigh* two different string dates or datetimes in different formats 103 | # representing identical values. 104 | try: 105 | d1 = datetime.date.fromisoformat(item1) 106 | d2 = datetime.date.fromisoformat(item2) 107 | return d1 == d2 108 | except (TypeError, ValueError): 109 | pass 110 | try: 111 | d1 = datetime.datetime.fromisoformat(item1) 112 | d2 = datetime.datetime.fromisoformat(item2) 113 | return d1 == d2 114 | except (TypeError, ValueError): 115 | pass 116 | 117 | return str(item1) == str(item2) 118 | 119 | # Returns True for new items, or an existing item to update, or False if 120 | # the provided item should not be saved, i.e., we've already got it. 121 | def should_keep(item, items, update): 122 | try: 123 | prev_item = items[str(item["id"])] 124 | except KeyError: 125 | return True 126 | # Just in case it's None 127 | if not prev_item: 128 | return True 129 | if not update: 130 | return False 131 | if recursive_compare(item, prev_item): 132 | return False 133 | return prev_item 134 | 135 | def complete(statuses, page, func = None): 136 | """ 137 | Why aren't we using Mastodon.fetch_remaining(first_page)? It 138 | requires some metadata for the next request to be known. This 139 | is what the documentation says about 140 | Mastodon.fetch_next(previous_page): "Pass in the previous page 141 | in its entirety, or the pagination information dict returned 142 | as a part of that pages last status (‘_pagination_next’)." 143 | When we last updated our archive, however, there was no next 144 | page: we got all the pages there were. So the archive will 145 | have a ton of _pagination_prev keys but no _pagination_next 146 | keys. That's why we fetch it all over again. Expiry helps, 147 | obviously. 148 | """ 149 | # We use str() on the ID here and above because it could be a 150 | # MaybeSnowflakeIdType when we get it from Mastodon but it's a number 151 | # or string when it's stored in the JSON file, so we canonicalize it as 152 | # a string. 153 | seen = { str(status["id"]): status for status in statuses if status is not None } 154 | if not args.quiet: 155 | progress = core.progress_bar() 156 | 157 | # define function such that we can return from the inner and 158 | # from the outer loop 159 | def process(page): 160 | count = 0 161 | duplicates = 0 162 | updated = 0 163 | while len(page) > 0: 164 | if not args.quiet: 165 | progress() 166 | for item in page: 167 | status = item 168 | # possibly a notification containing a status 169 | if "status" in item: 170 | status = item["status"] 171 | if status and "id" in status: 172 | keep = should_keep(status, seen, update) 173 | if keep is True: 174 | if func is None or func(item): 175 | statuses.insert(count, status) 176 | count = count + 1 177 | elif keep: 178 | # It's a dict that should be replaced 179 | if func is None or func(item): 180 | keep.clear() 181 | keep.update(status) 182 | updated += 1 183 | else: 184 | duplicates = duplicates + 1 185 | if duplicates > 10 and stopping: 186 | if not args.quiet: 187 | print() # at the end of the progress bar 188 | print("Seen 10 duplicates, stopping now.") 189 | print("Use --no-stopping to prevent this.") 190 | return count 191 | page = mastodon.fetch_next(page) 192 | if page is None: 193 | if not args.quiet: 194 | print() # at the end of the progress bar 195 | return count + updated 196 | # if len(page) was 0 197 | return count + updated 198 | 199 | count = process(page) 200 | if not args.quiet: 201 | print("Added or updated a total of %d new items" % count) 202 | return statuses 203 | 204 | def keep_mentions(notifications): 205 | return [x.status for x in notifications if x.type == "mention"] 206 | 207 | if data is None or not "statuses" in data or len(data["statuses"]) == 0: 208 | if not args.quiet: 209 | print("Get all statuses (this may take a while)") 210 | statuses = mastodon.account_statuses(user["id"], limit=100) 211 | statuses = mastodon.fetch_remaining( 212 | first_page = statuses) 213 | else: 214 | if not args.quiet: 215 | print("Get new statuses") 216 | statuses = complete(data["statuses"], mastodon.account_statuses(user["id"], limit=100)) 217 | 218 | if skip_favourites: 219 | if not args.quiet: 220 | print("Skipping favourites") 221 | if data is None or not "favourites" in data: 222 | favourites = [] 223 | else: 224 | favourites = data["favourites"] 225 | elif data is None or not "favourites" in data or len(data["favourites"]) == 0: 226 | if not args.quiet: 227 | print("Get favourites (this may take a while)") 228 | favourites = mastodon.favourites() 229 | favourites = mastodon.fetch_remaining( 230 | first_page = favourites) 231 | else: 232 | if not args.quiet: 233 | print("Get new favourites") 234 | favourites = complete(data["favourites"], mastodon.favourites()) 235 | 236 | try: 237 | if skip_bookmarks: 238 | if not args.quiet: 239 | print("Skipping bookmarks") 240 | if data is None or not "bookmarks" in data: 241 | bookmarks = [] 242 | else: 243 | bookmarks = data["bookmarks"] 244 | elif data is None or not "bookmarks" in data or len(data["bookmarks"]) == 0: 245 | if not args.quiet: 246 | print("Get bookmarks (this may take a while)") 247 | bookmarks = mastodon.bookmarks() 248 | bookmarks = mastodon.fetch_remaining( 249 | first_page = bookmarks) 250 | else: 251 | if not args.quiet: 252 | print("Get new bookmarks") 253 | bookmarks = complete(data["bookmarks"], mastodon.bookmarks()) 254 | except AttributeError as e: 255 | bookmarks = [] 256 | print("Skipping bookmarks since your Mastodon.py library is too old!") 257 | print("You might have a file called upgrade_python-mastodon.sh on your system.") 258 | print("Find it for example using 'locate upgrade_python-mastodon.sh' and then run it") 259 | print("to attempt an upgrade in-place: 'bash /path/to/upgrade_python-mastodon.sh'") 260 | print("If you don't have 'locate' installed, try to use 'find' to find the script:") 261 | print("'find / -name upgrade_python-mastodon.sh'") 262 | 263 | if not with_mentions: 264 | if not args.quiet: 265 | print("Skipping mentions") 266 | if data is None or not "mentions" in data: 267 | mentions = [] 268 | else: 269 | mentions = data["mentions"] 270 | elif data is None or not "mentions" in data or len(data["mentions"]) == 0: 271 | if not args.quiet: 272 | print("Get notifications and look for mentions (this may take a while)") 273 | notifications = mastodon.notifications(limit=100) 274 | notifications = mastodon.fetch_remaining( 275 | first_page = notifications) 276 | mentions = keep_mentions(notifications) 277 | else: 278 | if not args.quiet: 279 | print("Get new notifications and look for mentions") 280 | is_mention = lambda x: "type" in x and x["type"] == "mention" 281 | mentions = complete(data["mentions"], mastodon.notifications(limit=100), is_mention) 282 | 283 | if not with_followers: 284 | if not args.quiet: 285 | print("Skipping followers") 286 | if data is None or not "followers" in data: 287 | followers = [] 288 | else: 289 | followers = data["followers"] 290 | else: 291 | if not args.quiet: 292 | print("Get followers (this may take a while)") 293 | followers = mastodon.account_followers(user.id, limit=100) 294 | followers = mastodon.fetch_remaining( 295 | first_page = followers) 296 | 297 | if not with_following: 298 | if not args.quiet: 299 | print("Skipping following") 300 | if data is None or not "following" in data: 301 | following = [] 302 | else: 303 | following = data["following"] 304 | else: 305 | if not args.quiet: 306 | print("Get following (this may take a while)") 307 | following = mastodon.account_following(user.id, limit=100) 308 | following = mastodon.fetch_remaining( 309 | first_page = following) 310 | 311 | if not with_mutes: 312 | if not args.quiet: 313 | print("Skipping mutes") 314 | if data is None or not "mutes" in data: 315 | mutes = [] 316 | else: 317 | mutes = data["mutes"] 318 | else: 319 | if not args.quiet: 320 | print("Get mutes (this may take a while)") 321 | mutes = mastodon.mutes(limit=100) 322 | mutes = mastodon.fetch_remaining(first_page = mutes) 323 | 324 | if not with_blocks: 325 | if not args.quiet: 326 | print("Skipping blocks") 327 | if data is None or not "blocks" in data: 328 | blocks = [] 329 | else: 330 | blocks = data["blocks"] 331 | else: 332 | if not args.quiet: 333 | print("Get blocks (this may take a while)") 334 | blocks = mastodon.blocks(limit=100) 335 | blocks = mastodon.fetch_remaining(first_page = blocks) 336 | 337 | if not with_notes: 338 | if not args.quiet: 339 | print("Skipping notes") 340 | if data is None or not "notes" in data: 341 | notes = [] 342 | else: 343 | notes = data["notes"] 344 | else: 345 | if not args.quiet: 346 | print("Get notes (this may take a while)") 347 | all_ids = set() 348 | for coll in (followers, following, mutes, blocks): 349 | for user in coll: 350 | all_ids.add(user['id']) 351 | all_ids = list(all_ids) 352 | # If there are too many IDs the call may fail because the URI is too 353 | # long, so we use binary back-off to find a request size that works. 354 | requested = 0 355 | notes = [] 356 | request_size = len(all_ids) 357 | while requested < len(all_ids): 358 | try: 359 | relationships = mastodon.account_relationships( 360 | all_ids[requested:requested + request_size]) 361 | except MastodonAPIError as e: 362 | if 414 in e.args: # URI too large 363 | request_size = int(request_size / 2) 364 | continue 365 | raise 366 | requested += request_size 367 | notes.extend(({'id': u.id, 'note': u.note} 368 | for u in relationships if u.note)) 369 | 370 | data = { 371 | 'account': user, 372 | 'statuses': statuses, 373 | 'favourites': favourites, 374 | 'bookmarks': bookmarks, 375 | 'mentions': mentions, 376 | 'followers': followers, 377 | 'following': following, 378 | 'mutes': mutes, 379 | 'blocks': blocks, 380 | 'notes': notes, 381 | } 382 | 383 | if not args.quiet: 384 | print("Saving %d statuses, %d favourites, %d bookmarks, %d mentions, %d followers, %d following, %d mutes, %d blocks, %d notes" % ( 385 | len(statuses), 386 | len(favourites), 387 | len(bookmarks), 388 | len(mentions), 389 | len(followers), 390 | len(following), 391 | len(mutes), 392 | len(blocks), 393 | len(notes))) 394 | 395 | core.save(status_file, data, quiet=args.quiet) 396 | -------------------------------------------------------------------------------- /mastodon_archive/context.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | import html2text 19 | import re 20 | from . import core 21 | 22 | class Found(Exception): pass 23 | 24 | def context(args): 25 | """ 26 | Show the context of a toot: ancestors, the toot itself, and descendants 27 | """ 28 | 29 | url = args.url 30 | 31 | (username, domain) = core.parse(args.user) 32 | 33 | status_file = domain + '.user.' + username + '.json' 34 | data = core.load(status_file, required = True, quiet = True) 35 | 36 | found = None; 37 | index = {} # mapping ids to statuses 38 | children = {} # mapping ids to list of children ids 39 | 40 | for collection in ["statuses", 41 | "favourites", 42 | "bookmarks", 43 | "mentions"]: 44 | statuses = data[collection]; 45 | if not args.quiet: 46 | print("Indexing %d %s..." % (len(statuses), collection)) 47 | for status in statuses: 48 | 49 | if status["reblog"] is not None: 50 | status = status["reblog"] 51 | 52 | # only accept one status per id 53 | if status["id"] in index: 54 | pass 55 | # print("Warning: duplicate id %s" % status["id"], file=sys.stderr) 56 | else: 57 | index[status["id"]] = status 58 | if "in_reply_to_id" in status: 59 | if status["in_reply_to_id"] not in children: 60 | children[status["in_reply_to_id"]] = [status["id"]] 61 | else: 62 | children[status["in_reply_to_id"]].append(status["id"]) 63 | 64 | for u in [status["uri"], 65 | status["url"]]: 66 | if u == url: 67 | found = status 68 | # don't break, we want to index them all 69 | 70 | if not found: 71 | print("The URL/URI was not found", file=sys.stderr) 72 | sys.exit(5) 73 | 74 | result = [found] 75 | 76 | # add ancestors 77 | id = found["in_reply_to_id"] 78 | 79 | while id in index: 80 | status = index[id]; 81 | result.insert(0, status) 82 | id = status["in_reply_to_id"] 83 | 84 | # add descendants 85 | try: 86 | ids = children[found["id"]] 87 | print(ids) 88 | while ids: 89 | id = ids.pop(0) 90 | result.append(index[id]) 91 | if id in children: 92 | ids.extend(children[id]) 93 | except: 94 | if not result: 95 | print("The status at the provided URL/URI had no context in your archive", file=sys.stderr) 96 | sys.exit(5) 97 | 98 | for status in result: 99 | str = ''; 100 | if status["reblog"] is not None: 101 | str += (status["account"]["display_name"] + "boosted\n") 102 | status = status["reblog"] 103 | str += ("%s @%s %s\n" % ( 104 | status["account"]["display_name"], 105 | status["account"]["username"], 106 | status["created_at"])) 107 | str += status["url"] + "\n" 108 | str += html2text.html2text(status["content"]) 109 | # This forces UTF-8 independent of terminal capabilities, thus 110 | # avoiding problems with LC_CTYPE=C and other such issues. 111 | # This works well when redirecting output to a file, which 112 | # will then be an UTF-8 encoded file. 113 | sys.stdout.buffer.write(str.encode('utf-8')) 114 | -------------------------------------------------------------------------------- /mastodon_archive/core.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | from mastodon import Mastodon 17 | import sys 18 | import os.path 19 | import datetime 20 | import json 21 | import glob 22 | import re 23 | import shutil 24 | 25 | def progress_bar(chars="▏▎▍▌▋▊▉█"): 26 | """ 27 | Return a progress bar updater which you can then call. 28 | """ 29 | n = 0 30 | def progress(): 31 | nonlocal n 32 | if n != 0: 33 | sys.stdout.write("\b") 34 | sys.stdout.write(chars[n]) 35 | sys.stdout.flush() 36 | n = (n + 1) % len(chars) 37 | 38 | return progress 39 | 40 | def parse(account): 41 | """ 42 | Parse account into username and domain. 43 | """ 44 | try: 45 | (username, domain) = account.split('@') 46 | return username, domain; 47 | except ValueError: 48 | print("The account has to have the form username@domain", file=sys.stderr) 49 | sys.exit(3) 50 | 51 | def read(args): 52 | """ 53 | Login to your Mastodon account with read-only permissions. 54 | """ 55 | return login(args) 56 | 57 | def readwrite(args): 58 | """ 59 | Login to your Mastodon account with read and write permissions. 60 | Note that you will get an error when your authorization token is a 61 | read-only token. If this happens, you need to deauthorize and try 62 | again. 63 | """ 64 | try: 65 | # this is what we expect 66 | return login(args, scopes = ['read', 'write']) 67 | except Exception as e: 68 | # on some instances, there's this problem with getting a 69 | # bigger scope than requested, so just do it again and hope 70 | # for the best... (dealing with MastodonAPIError: Granted 71 | # scopes "follow read write" differ from requested scopes 72 | # "read write".) 73 | return login(args, scopes = ['follow', 'read', 'write']) 74 | 75 | def readwritefollow(args): 76 | """ 77 | Login to your Mastodon account with read, write and follow permissions. 78 | Note that you will get an error when your authorization token is a 79 | read-only token. If this happens, you need to deauthorize and try 80 | again. 81 | """ 82 | return login(args, scopes = ['follow', 'read', 'write']) 83 | 84 | def deauthorize(args): 85 | """ 86 | Deauthorize the account. 87 | """ 88 | app = App(args.user) 89 | app.deauthorize() 90 | 91 | def login(args, scopes=('read',)): 92 | """ 93 | Login to your Mastodon account. 94 | """ 95 | pace = hasattr(args, 'pace') and args.pace 96 | version_check = hasattr(args, 'version_check') and args.version_check 97 | app = App(args.user, scopes=scopes, pace=pace, version_check=version_check) 98 | return app.login() 99 | 100 | class App: 101 | """ 102 | Client application to register, authorize and login with your Mastodon 103 | account. 104 | """ 105 | 106 | def __init__(self, user, scopes=('read',), name="mastodon-archive", pace=False, version_check="created"): 107 | 108 | self.username, self.domain = user.split("@") 109 | self.url = "https://" + self.domain 110 | self.name = name 111 | self.scopes = scopes 112 | self.client_secret = self.domain + ".client.secret" 113 | self.user_secret = self.domain + ".user." + self.username + ".secret" 114 | self.pace = pace 115 | self.version_check = version_check 116 | 117 | def register(self): 118 | """ 119 | Register application and saves client secret. 120 | """ 121 | print("Registering app") 122 | Mastodon.create_app( 123 | self.name, 124 | api_base_url=self.url, 125 | scopes=self.scopes, 126 | to_file=self.client_secret 127 | ) 128 | 129 | def authorize(self): 130 | """ 131 | Tries to authorize via OAuth API, and save access token. If it fails 132 | fallsback to username and password. 133 | """ 134 | url = self.url 135 | client_secret = self.client_secret 136 | user_secret = self.user_secret 137 | scopes = self.scopes 138 | version_check = self.version_check 139 | print("This app needs access to your Mastodon account.") 140 | 141 | mastodon = Mastodon( 142 | client_id=client_secret, 143 | version_check_mode=version_check, 144 | api_base_url=url) 145 | 146 | url = mastodon.auth_request_url(client_id=client_secret, scopes=scopes) 147 | 148 | print("Visit the following URL and authorize the app:") 149 | print(url) 150 | 151 | print("Then paste the access token here:") 152 | token = sys.stdin.readline().rstrip() 153 | 154 | try: 155 | # on the very first login, --pace has no effect 156 | mastodon.log_in(code=token, to_file=user_secret, scopes=scopes) 157 | 158 | except Exception: 159 | 160 | print("Sadly, that did not work. On some sites, this login mechanism") 161 | print("(namely OAuth) seems to be broken. There is an alternative") 162 | print("if you are willing to trust us with your password just this") 163 | print("once. We need it just this once in order to get an access") 164 | print("token. We won't save it. If you don't want to try this, use") 165 | print("Ctrl+C to quit. If you want to try it, please provide your") 166 | print("login details.") 167 | 168 | sys.stdout.write("Email: ") 169 | sys.stdout.flush() 170 | email = sys.stdin.readline().rstrip() 171 | sys.stdout.write("Password: ") 172 | sys.stdout.flush() 173 | password = sys.stdin.readline().rstrip() 174 | 175 | # on the very first login, --pace has no effect 176 | mastodon.log_in( 177 | username=email, 178 | password=password, 179 | to_file=user_secret, 180 | scopes=scopes 181 | ) 182 | 183 | return mastodon 184 | 185 | def deauthorize(self): 186 | """ 187 | Deauthorize by deleting the file containing the authorization token. 188 | """ 189 | user_secret = self.user_secret 190 | client_secret = self.client_secret 191 | if os.path.isfile(user_secret): 192 | os.remove(user_secret) 193 | if os.path.isfile(client_secret): 194 | os.remove(client_secret) 195 | 196 | def login(self): 197 | """ 198 | Register app, authorize and return an instance of ``Mastodon`` 199 | """ 200 | url = self.url 201 | client_secret = self.client_secret 202 | user_secret = self.user_secret 203 | pace = self.pace 204 | version_check = self.version_check 205 | 206 | if not os.path.isfile(client_secret): 207 | self.register() 208 | 209 | if not os.path.isfile(user_secret): 210 | mastodon = self.authorize() 211 | 212 | else: 213 | 214 | if pace: 215 | 216 | # in case the user kept running into a General API problem 217 | mastodon = Mastodon( 218 | client_id=client_secret, 219 | access_token=user_secret, 220 | version_check_mode=version_check, 221 | api_base_url=url, 222 | ratelimit_method="pace", 223 | ratelimit_pacefactor=0.9, 224 | request_timeout=300 225 | ) 226 | 227 | else: 228 | 229 | # the defaults are ratelimit_method='wait', 230 | # ratelimit_pacefactor=1.1, request_timeout=300 231 | mastodon = Mastodon( 232 | client_id=client_secret, 233 | access_token=user_secret, 234 | version_check_mode=version_check, 235 | api_base_url=url, 236 | ) 237 | 238 | return mastodon 239 | 240 | def load(file_name, required=False, quiet=False, combine=False): 241 | """ 242 | Load the JSON data from a file. 243 | """ 244 | 245 | if required and not os.path.isfile(file_name): 246 | print("You need to create an archive, first", file=sys.stderr) 247 | sys.exit(2) 248 | 249 | if os.path.isfile(file_name) and os.path.getsize(file_name) > 0: 250 | 251 | def _json_load(fname): 252 | if not quiet: 253 | print("Loading existing archive:", fname) 254 | 255 | with open(fname, mode='r', encoding='utf-8') as fp: 256 | return json.load(fp) 257 | 258 | data = _json_load(file_name) 259 | if combine: 260 | # Load latest archive first to keep chronological order 261 | archives = list( 262 | reversed(glob.glob(file_name.replace(".json", ".*.json"))) 263 | ) 264 | 265 | if required and not quiet and not archives: 266 | print("Warning: No split archives to combine", file=sys.stderr) 267 | 268 | # Merge dictionaries loaded from JSON archives 269 | for archive in archives: 270 | archived_data = _json_load(archive) 271 | 272 | for collection in ["statuses", "favourites", "bookmarks", "mentions"]: 273 | if collection in archived_data: 274 | data[collection].extend(archived_data[collection]) 275 | 276 | # Bookmarks are a recent addition so older archives don't have any 277 | if "bookmarks" not in data: 278 | data["bookmarks"] = [] 279 | 280 | # Sort statuses 281 | data["statuses"].sort(key=lambda x: x["created_at"], reverse=True) 282 | 283 | return data 284 | 285 | return None 286 | 287 | def date_handler(obj): 288 | return(obj.isoformat() 289 | if isinstance(obj, (datetime.datetime, datetime.date)) 290 | else None) 291 | 292 | def save(file_name, data, quiet=False, backup=True): 293 | """ 294 | Save the JSON data in a file. If the file exists, rename it, 295 | in case backup is True (the default). 296 | """ 297 | if backup and os.path.isfile(file_name): 298 | backup_file = file_name + '~' 299 | if not quiet: 300 | print("Backing up", file_name, "to", backup_file) 301 | if os.path.isfile(backup_file): 302 | ans = "" 303 | while ans.lower() not in ("y", "n", "yes", "no"): 304 | ans = input( 305 | "Backup: {} exists! Overwrite (yes/no)? ".format(backup_file) 306 | ) 307 | 308 | if ans.lower()[0] == "y": 309 | shutil.copy2(file_name, backup_file) 310 | else: 311 | print("Exiting to avoid overwriting backup.", file=sys.stderr) 312 | sys.exit(0) 313 | 314 | with open(file_name, mode = 'w', encoding = 'utf-8') as fp: 315 | data = json.dump(data, fp, indent = 2, default = date_handler) 316 | 317 | def all_accounts(): 318 | """ 319 | Return all the known user accounts in the current directory. 320 | """ 321 | archives = glob.glob('*.user.*.json'); 322 | if not archives: 323 | print("You need to create an archive, first", file=sys.stderr) 324 | sys.exit(2) 325 | else: 326 | users = [] 327 | for archive in archives: 328 | m = re.match(r"(.*)\.user\.(.*?)(?:\.\d+)?\.json", archive) 329 | if m: 330 | user = "%s@%s" % m.group(2, 1) 331 | if user not in users: 332 | users.append("%s@%s" % m.group(2, 1)) 333 | return users 334 | 335 | def keep(statuses, weeks): 336 | """ 337 | Return all statuses newer than some weeks 338 | """ 339 | 340 | delta = datetime.timedelta(weeks = weeks) 341 | cutoff = datetime.datetime.today() - delta 342 | 343 | def matches(status): 344 | created = datetime.datetime.strptime(status["created_at"][0:10], "%Y-%m-%d") 345 | return created >= cutoff 346 | 347 | return list(filter(matches, statuses)) 348 | 349 | def allowlist(domain, username): 350 | file_name = domain + '.user.' + username + '.allowlist.txt' 351 | allowlist = set() 352 | if os.path.isfile(file_name): 353 | with open(file_name, mode = 'r', encoding = 'utf-8') as fp: 354 | for line in fp: 355 | # kensanata 356 | # kensanata@dice.camp 357 | # Alex Schroeder 358 | m = re.search(r"([a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+)", line) 359 | if not m: 360 | m = re.search(r"([a-zA-Z0-9.-]+)", line) 361 | if m: 362 | allowlist.add(m.group(1)) 363 | print("%d accounts are on the allowlist" % len(allowlist)) 364 | else: 365 | print("There is no allowlist") 366 | return allowlist 367 | -------------------------------------------------------------------------------- /mastodon_archive/expire.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import sys 18 | import os.path 19 | import math 20 | from progress.bar import Bar 21 | from datetime import timedelta, datetime 22 | from random import shuffle 23 | import signal 24 | import html2text 25 | import textwrap 26 | from . import core 27 | 28 | h = html2text.HTML2Text() 29 | h.ignore_links = True 30 | 31 | def text(status): 32 | text = textwrap.fill(h.handle(status["content"])).lstrip(); 33 | text = text.replace("\n", " ") 34 | if len(text) > 50: 35 | text = text[0:50] + '...' 36 | return "%s \"%s\"" % (status["created_at"][0:10], text) 37 | 38 | def delete(mastodon, collection, status): 39 | """ 40 | Delete toot or unfavour favourite and mark it as deleted. The 41 | "record not found" error is handled elsewhere. Mentions cannot be 42 | dismissed because mastodon.notifications_dismiss requires a 43 | notification id, not a status id. 44 | """ 45 | if collection == 'statuses': 46 | if status["reblog"]: 47 | mastodon.status_unreblog(status["reblog"]["id"]) 48 | status["deleted"] = True 49 | else: 50 | mastodon.status_delete(status["id"]) 51 | status["deleted"] = True 52 | elif collection == 'favourites': 53 | mastodon.status_unfavourite(status["id"]) 54 | status["deleted"] = True 55 | 56 | def expire(args): 57 | """ 58 | Expire toots: delete toots, unfavour favourites, or dismiss 59 | notifications older than a few weeks 60 | """ 61 | 62 | confirmed = args.confirmed 63 | collection = args.collection 64 | delete_others = args.delete_others 65 | 66 | if (delete_others and collection != 'mentions'): 67 | print("The --delete-others option can only be used " 68 | "together with --collection mentions.", 69 | file=sys.stderr) 70 | sys.exit(4) 71 | 72 | (username, domain) = args.user.split('@') 73 | 74 | status_file = domain + '.user.' + username + '.json' 75 | data = core.load(status_file, required = True, quiet = True) 76 | 77 | if confirmed: 78 | mastodon = core.readwrite(args) 79 | else: 80 | print("This is a dry run and nothing will be expired.\n" 81 | "Instead, we'll just list what would have happened.\n" 82 | "Use --confirmed to actually do it.") 83 | 84 | delta = timedelta(weeks = args.weeks) 85 | cutoff = datetime.today() - delta 86 | 87 | def matches(status): 88 | created = datetime.strptime(status["created_at"][0:10], "%Y-%m-%d") 89 | deleted = "deleted" in status and status["deleted"] == True 90 | pinned = "pinned" in status and status["pinned"] == True 91 | return created < cutoff and not deleted and not pinned 92 | 93 | if collection != "mentions": 94 | 95 | statuses = list(filter(matches, data[collection])) 96 | n_statuses = len(statuses) 97 | shuffle(statuses) 98 | 99 | if (n_statuses == 0): 100 | print(f"No {collection} are older than {args.weeks} weeks", 101 | file=sys.stderr) 102 | 103 | if confirmed and n_statuses > 0: 104 | 105 | bar = Bar('Expiring', max = len(statuses)) 106 | error = '' 107 | 108 | def signal_handler(signal, frame): 109 | print("\nYou pressed Ctrl+C! Saving data before exiting!") 110 | core.save(status_file, data) 111 | sys.exit(0) 112 | 113 | signal.signal(signal.SIGINT, signal_handler) 114 | 115 | i = 1 116 | for status in statuses: 117 | try: 118 | delete(mastodon, collection, status) 119 | if i % 300 == 0: 120 | core.save(status_file, data, quiet=True, backup=False) 121 | i = i+1 122 | bar.next() 123 | except Exception as e: 124 | if "authorized scopes" in str(e): 125 | print("\nWe need to authorize the app to make changes to your account.") 126 | core.deauthorize(args) 127 | mastodon = core.readwrite(args) 128 | # retry 129 | delete(mastodon, collection, status) 130 | elif "not found" in str(e): 131 | status["deleted"] = True 132 | bar.next() 133 | elif "Name or service not known" in str(e): 134 | error = "Error: the instance name is either misspelled or offline" 135 | else: 136 | print(e, file=sys.stderr) 137 | 138 | bar.finish() 139 | 140 | if error: 141 | print(error, file=sys.stderr) 142 | 143 | core.save(status_file, data, quiet=args.quiet) 144 | 145 | elif n_statuses > 0: 146 | 147 | for status in statuses: 148 | if collection == 'statuses': 149 | if not args.quiet: 150 | print("Delete: " + text(status)) 151 | elif collection == 'favourites': 152 | if not args.quiet: 153 | print("Unfavour: " + text(status)) 154 | 155 | if collection == "mentions": 156 | 157 | if delete_others: 158 | if not args.quiet: 159 | print('Dismissing mentions and other notifications') 160 | else: 161 | if not args.quiet: 162 | print('Dismissing mentions') 163 | 164 | if not args.quiet: 165 | progress = core.progress_bar() 166 | 167 | # only consider statuses with an id (no idea what the others are) 168 | statuses = list(filter(lambda x: "id" in x, data[collection])) 169 | if not args.quiet: 170 | n_statuses = len(statuses) 171 | print("Mentions already archived: " + str(n_statuses)) 172 | 173 | # create a dictionary for fast lookup of archived statuses that mention us 174 | ids = { x["id"]: True for x in statuses } 175 | 176 | # The date format here is slightly different. We expire 177 | # notifications if we have the status is a mention in our 178 | # archive, or if the status is not a mention and 179 | # --delete-others was used -- and if if it is older than the 180 | # cutoff period, of course. 181 | def matches(notifications): 182 | return [x for x in notifications 183 | if (x.id in ids if x.type == "mention" else delete_others) 184 | and x["created_at"].replace(tzinfo = None) < cutoff] 185 | 186 | mastodon = core.login(args) 187 | notifications = mastodon.notifications(limit=100) 188 | error = '' 189 | total = 0 190 | dismissed = 0 191 | while (notifications): 192 | if not args.quiet: 193 | progress() 194 | total += len(notifications) 195 | for notification in matches(notifications): 196 | if confirmed: 197 | try: 198 | mastodon.notifications_dismiss(notification["id"]) 199 | dismissed += 1 200 | except Exception as e: 201 | if "authorized scopes" in str(e): 202 | print("\nWe need to authorize the app to make changes to your account.") 203 | core.deauthorize(args) 204 | mastodon = core.readwrite(args) 205 | # retry 206 | mastodon.notifications_dismiss(notification["id"]) 207 | dismissed += 1 208 | elif "not found" in str(e): 209 | pass 210 | elif "Name or service not known" in str(e): 211 | error = "Error: the instance name is either misspelled or offline" 212 | else: 213 | print(e, file=sys.stderr) 214 | else: 215 | print("Dismiss" 216 | # + str(notification["id"]) 217 | + " " + notification["created_at"].strftime("%Y-%m-%d") 218 | + " " + notification["account"]["acct"] 219 | + " " + notification["type"]) 220 | 221 | notifications = mastodon.fetch_next(notifications) 222 | 223 | if error: 224 | print(error, file=sys.stderr) 225 | 226 | if not args.quiet: 227 | print(f"Dismissed {dismissed} of {total} notifications") 228 | -------------------------------------------------------------------------------- /mastodon_archive/fix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | from . import core 18 | 19 | def fix_boosts(args): 20 | """ 21 | Go through all the boosts and mark them as undeleted. 22 | """ 23 | 24 | confirmed = args.confirmed 25 | 26 | if not confirmed: 27 | 28 | print("This is a dry run and nothing will be changed.\n" 29 | "Instead, we'll just list what would have happened.\n" 30 | "Use --confirmed to actually do it.") 31 | 32 | (username, domain) = core.parse(args.user) 33 | 34 | status_file = domain + '.user.' + username + '.json' 35 | data = core.load(status_file, required=True, combine=args.combine, 36 | quiet=args.quiet) 37 | n = 0 38 | 39 | for status in data["statuses"]: 40 | if status["reblog"] and "deleted" in status and status["deleted"]: 41 | del status["deleted"] 42 | n = n + 1 43 | if n == 1 and not confirmed: 44 | print("Some examples:") 45 | if n <= 20 and not confirmed: 46 | print(str(n) + " " + status["reblog"]["url"]) 47 | 48 | if confirmed and n > 0: 49 | 50 | if not args.quiet: 51 | print("Saving updated data to", status_file) 52 | core.save(status_file, data, quiet=args.quiet) 53 | 54 | elif confirmed: 55 | 56 | if not args.quiet: 57 | print("No boosted statuses were undeleted") 58 | 59 | else: 60 | 61 | print("Would have marked " + str(n) + " statuses as not deleted") 62 | -------------------------------------------------------------------------------- /mastodon_archive/followers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | from progress.bar import Bar 19 | from datetime import timedelta, datetime 20 | from . import core 21 | 22 | def is_lurker(account, mentions): 23 | for mention in mentions: 24 | if account["id"] == mention["account"]["id"]: 25 | return False 26 | return True 27 | 28 | def find_lurkers(followers, allowlist, mentions): 29 | return [x for x in followers 30 | if x["acct"] not in allowlist 31 | and is_lurker(x, mentions)] 32 | 33 | def followers(args): 34 | """ 35 | List followers 36 | """ 37 | 38 | (username, domain) = args.user.split('@') 39 | 40 | status_file = domain + '.user.' + username + '.json' 41 | data = core.load(status_file, required=True, quiet=True, combine=True) 42 | 43 | # Print both error messages if the data is missing 44 | error = 0 45 | if args.mentions and "mentions" not in data or len(data["mentions"]) == 0: 46 | print("You need to run 'mastodon-archive archive --with-mentions'", 47 | file=sys.stderr) 48 | error = 5 49 | if "followers" not in data or len(data["followers"]) == 0: 50 | print("You need to run 'mastodon-archive archive --with-followers'", 51 | file=sys.stderr) 52 | error = 6 53 | if error > 0: 54 | sys.exit(error) 55 | 56 | # If we're not checking for mentions, this is quickly done. 57 | if not args.mentions: 58 | for account in sorted(data["followers"], key=lambda account: 59 | account["display_name"] or account["username"]): 60 | print("%s <%s>" % (account["display_name"] or account["username"], 61 | account["acct"])) 62 | sys.exit(0) 63 | 64 | if args.all: 65 | if not args.quiet: 66 | print("Considering the entire archive") 67 | mentions = data["mentions"] 68 | else: 69 | if not args.quiet: 70 | print("Considering the last " 71 | + str(args.weeks) 72 | + " weeks") 73 | mentions = core.keep(data["mentions"], args.weeks) 74 | 75 | allowlist = core.allowlist(domain, username) 76 | 77 | if args.block: 78 | mastodon = core.readwrite(args) 79 | accounts = find_lurkers(data["followers"], allowlist, mentions) 80 | 81 | if not args.quiet: 82 | bar = Bar('Blocking', max = len(accounts)) 83 | 84 | for account in accounts: 85 | if not args.quiet: 86 | bar.next() 87 | try: 88 | mastodon.account_block(account["id"]) 89 | except Exception as e: 90 | if "authorized scopes" in str(e): 91 | print("\nWe need to authorize the app to make changes to your account.") 92 | core.deauthorize(args) 93 | mastodon = core.readwrite(args) 94 | # retry 95 | mastodon.account_block(account["id"]) 96 | else: 97 | print(e, file=sys.stderr) 98 | 99 | if not args.quiet: 100 | bar.finish() 101 | 102 | else: 103 | accounts = find_lurkers(data["followers"], allowlist, mentions) 104 | for account in sorted(accounts, key=lambda account: 105 | account["display_name"] or account["username"]): 106 | print("%s <%s>" % (account["display_name"] or account["username"], 107 | account["acct"])) 108 | -------------------------------------------------------------------------------- /mastodon_archive/following.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | from progress.bar import Bar 19 | from datetime import timedelta, datetime 20 | from . import core 21 | 22 | def is_lurker(account, mentions): 23 | for mention in mentions: 24 | if account["id"] == mention["account"]["id"]: 25 | return False 26 | return True 27 | 28 | def find_lurkers(followers, allowlist, mentions): 29 | return [x for x in followers 30 | if x["acct"] not in allowlist 31 | and is_lurker(x, mentions)] 32 | 33 | def following(args): 34 | """ 35 | List people you're following but who never mention you 36 | """ 37 | 38 | (username, domain) = args.user.split('@') 39 | 40 | status_file = domain + '.user.' + username + '.json' 41 | data = core.load(status_file, required=True, quiet=True, combine=True) 42 | 43 | # Print both error messages if the data is missing 44 | error = 0 45 | if "mentions" not in data or len(data["mentions"]) == 0: 46 | print("You need to run 'mastodon-archive archive --with-mentions'", 47 | file=sys.stderr) 48 | error = 5 49 | if "following" not in data or len(data["following"]) == 0: 50 | print("You need to run 'mastodon-archive archive --with-following'", 51 | file=sys.stderr) 52 | error = 6 53 | if error > 0: 54 | sys.exit(error) 55 | 56 | if args.all: 57 | if not args.quiet: 58 | print("Considering the entire archive") 59 | mentions = data["mentions"] 60 | else: 61 | if not args.quiet: 62 | print("Considering the last " 63 | + str(args.weeks) 64 | + " weeks") 65 | mentions = core.keep(data["mentions"], args.weeks) 66 | 67 | allowlist = core.allowlist(domain, username) 68 | 69 | if args.unfollow: 70 | mastodon = core.readwrite(args) 71 | accounts = find_lurkers(data["following"], allowlist, data["mentions"]) 72 | 73 | if not args.quiet: 74 | bar = Bar('Unfollowing', max = len(accounts)) 75 | 76 | for account in accounts: 77 | if not args.quiet: 78 | bar.next() 79 | try: 80 | mastodon.account_unfollow(account["id"]) 81 | except Exception as e: 82 | if "authorized scopes" in str(e): 83 | print("\nWe need to authorize the app to make changes to your account.") 84 | core.deauthorize(args) 85 | mastodon = core.readwritefollow(args) 86 | # retry 87 | mastodon.account_block(account["id"]) 88 | else: 89 | print(e, file=sys.stderr) 90 | 91 | if not args.quiet: 92 | bar.finish() 93 | 94 | else: 95 | accounts = find_lurkers(data["following"], allowlist, data["mentions"]) 96 | for account in sorted(accounts, key=lambda account: 97 | account["display_name"] or account["username"]): 98 | print("%s <%s>" % (account["display_name"] or account["username"], 99 | account["acct"])) 100 | -------------------------------------------------------------------------------- /mastodon_archive/html.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import sys 18 | import os.path 19 | from html import escape 20 | import html2text 21 | import datetime 22 | import dateutil.parser 23 | from urllib.parse import urlparse 24 | from . import core 25 | 26 | header_template = '''\ 27 | 28 | 29 | 30 | 31 | %s 32 | 252 | 253 | 254 |
255 |
256 |

%s

257 | 263 |
264 | %s\ 265 | ''' 266 | 267 | footer_template = '''\ 268 |
269 | %s\ 270 |
271 |
272 | 273 | 274 | ''' 275 | 276 | nav_template = '''\ 277 | 281 | ''' 282 | 283 | previous_template = '''\ 284 | 285 | ''' 286 | 287 | next_template = '''\ 288 | 289 | ''' 290 | 291 | boost_template = '''\ 292 |
293 | %s boosted 294 |
295 | ''' 296 | 297 | status_template = '''\ 298 |
299 |
300 | 301 | %s 302 | @%s 303 | %s 304 |
305 |
306 | %s 307 |
308 |
309 | ''' 310 | 311 | media_template = '''\ 312 |
313 | %s
\ 314 | ''' 315 | 316 | generic_content_template = '''\ 317 | %s 318 | ''' 319 | 320 | image_template = '''\ 321 | %s 322 | ''' 323 | 324 | video_template = '''\ 325 | 326 | ''' 327 | 328 | video_with_poster_template = '''\ 329 | 330 | ''' 331 | 332 | audeo_template = '''\ 333 |
334 |
%s
335 | 336 | Download audio 337 |
338 | ''' 339 | 340 | 341 | wrapper_template = '''\ 342 |
343 | %s%s%s%s 344 |
345 | ''' 346 | 347 | card_template = '''\ 348 | 349 | 350 |
351 | %s 352 | %s 353 |
354 | ''' 355 | 356 | emoji_template = '''\ 357 | %s 358 | ''' 359 | 360 | def file_url(media_dir, url1, url2=None, no_placeholder=None): 361 | for url in [url1, url2]: 362 | if url is not None: 363 | path = urlparse(url).path 364 | if os.path.isfile(media_dir + path): 365 | return media_dir + path 366 | if no_placeholder is None: 367 | return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QsUETQjvc7YnAAAACZpVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVAgb24gYSBNYWOV5F9bAAADfElEQVRo3u1ZTUhUURg997sPy9TnDxk4IeqkmKghCKLBLNq2MCXQTXsXomFMIdK0EIoIskWLcNVKaFEulBIzxEgQLBRFXZmiaIOkboSe2Lv3tsg3+Hr96Mx7OhNzl/PuvHfPPd/5zvfdy5719Cj8B4Pwn4wkkCSQRAGilIIQ4q9zpJSQUrr6Xc2tF0kpQURgjGF2fh4zc3P4vLyMza0t27xzubkoKy1FoLYW532+yP/iBohhGHjR349P09M/qSaCUs7M/nVzE1vb23g/Po6zOTkItrcjPS0NnPOYvs9i9RGlFJ739eHj1BSI6EghY81va2nBxZKSmJiJidPvpon+wUHMzs1FwgsAGGN/3rkDz6z5T3t7sR4O/1NbnoUWA3AqJQXm/gKsHS7Iz0egrg7lZWXI1PUI6PmFBbwcGMDW9rbjXQ8eP8aznp4T1AhjICIIIVBVWYkbzc1IPX0apmnaQkXjHJXl5ai6dAmvBgbwbmzMwdSHiQlcrqmJSi+uiD0jPR3BtjZkZ2VFwkXTNMdCrQVer6/H6toaFpeWbJqamJxEoK7u+DVCRKiqqMD9UCgSQocRrJQSTQ0NNhBKKSyvrJyM2IkIvry8QwM4yM55ny++nD2alPm3rHbihnjUKiC8seEAl52VlVhFIxFhcGjIxiZjDDXV1VF7ybEz8t008SUcxsy+iR5k6drVq78ta+KOEdM0sbe3h4dPnjieNTU2QggRtX6OjREhBKSUCN69C8ZYZOeJCBeKinAlEIh/sVs7fbOz0waCc46c7Gzcam2N/w7RAtF2546ttOecI1PX0d3VFbUujg2IlBKcc7QGg7Zql3MOPSMD90MhKKVc8RVPgRARbodC4JzbQJxJTcWDe/dcA+GpRqSUeD08jG+GYauphBB41N3tWovrOSNEhDcjI46OsbOjw1Hixy0jUkqsh8OOEkTXdRTk5yfOuZZSCqtraw4gZSUliXVAp5TCzs6Oo5bK1PWY+vIT0Yhpmo6MpGmaK54RN9Vv4gPxoKHyViMAjN1dmx6EEDAMA17dKrHkjVWcDU9LlF9dnYhcd3TPnX1xacl2AEdEKPb7Uez3ewLGUyBvR0cj58La/imjv7AwcYBYYEwhbJlLKpUUezJrudGPaAeuBzTOQR46u+YViGK/39anW78lVPq1Fu0vLExsH/F60cmslQSSBHL08QPK53LVsfanXQAAAABJRU5ErkJggg==" 368 | return None 369 | 370 | def text_with_emoji(media_dir, text, emojis): 371 | for emoji in emojis: 372 | path = file_url(media_dir, emoji["url"], None, True) 373 | if path is None: 374 | continue 375 | shortcode = ":%s:" % emoji["shortcode"] 376 | image = emoji_template % ( 377 | shortcode, 378 | shortcode, 379 | path) 380 | text = text.replace(shortcode, image) 381 | return text 382 | 383 | def write_status(fp, media_dir, status): 384 | boost = "" 385 | if status["reblog"] is not None: 386 | user = status["account"] 387 | displayname = text_with_emoji(media_dir, user["display_name"], user["emojis"]) 388 | if not displayname: 389 | displayname = user["username"] 390 | boost = boost_template % ( 391 | user["url"], 392 | displayname) 393 | # display the boosted status instead 394 | status = status["reblog"] 395 | 396 | user = status["account"] 397 | displayname = text_with_emoji(media_dir, user["display_name"], user["emojis"]) 398 | if not displayname: 399 | displayname = user["username"] 400 | 401 | content = status["content"] 402 | 403 | if status["spoiler_text"]: 404 | content = "

%s

%s" % ( 405 | status["spoiler_text"], 406 | status["content"]) 407 | 408 | info = status_template % ( 409 | file_url(media_dir, user["avatar"]), 410 | user["url"], 411 | displayname, 412 | user["acct"], 413 | status["url"], 414 | dateutil.parser.parse( 415 | status["created_at"]).strftime( 416 | "%Y-%m-%d %H:%M"), 417 | text_with_emoji(media_dir, content, status["emojis"])) 418 | 419 | media = '' 420 | attachments = status["media_attachments"] 421 | card = '' 422 | card_content = status["card"] 423 | 424 | if len(attachments) > 0: 425 | previews = [] 426 | for attachment in attachments: 427 | # video src must never be the unknown image 428 | src = file_url(media_dir, attachment["url"], None, False); 429 | if (attachment["type"] == "video" or attachment["type"] == "gifv") and src: 430 | # Pleroma and maybe others don't offer a separate 431 | # preview. The preview_url is the same as the video 432 | # source. 433 | preview = file_url(media_dir, attachment["preview_url"], None, False) 434 | if src and preview and src == preview or not preview: 435 | previews.append(video_template % ( 436 | src, # video 437 | file_url(media_dir, attachment["remote_url"]), # remote link 438 | preview)) # image for remote link 439 | else: 440 | previews.append(video_with_poster_template % ( 441 | src, # video 442 | preview, # poster 443 | file_url(media_dir, attachment["remote_url"]), # remote link 444 | preview)) # image for remote link 445 | elif attachment["type"] == "audio": 446 | previews.append(audeo_template % ( 447 | attachment["description"], # alt text 448 | src, # audio 449 | src)) # audio for download link 450 | elif attachment["type"] == "image": 451 | size = "" 452 | if len(attachments) == 1: 453 | size = "one" 454 | elif len(attachments) == 2 or (len(attachments) == 3 and len(previews) == 0): 455 | size = "tall" 456 | 457 | description = escape(attachment["description"]) if attachment["description"] is not None else "" 458 | 459 | previews.append(image_template % ( 460 | file_url(media_dir, attachment["url"]), # link to image 461 | size, # class for how it should be rendered 462 | file_url(media_dir, attachment["preview_url"], attachment["url"]), # image 463 | description, # title (hover text) 464 | description)) # alt text 465 | else: 466 | # other, likely "unknown" 467 | description = escape(attachment["description"]) if attachment["description"] is not None else attachment["type"] + " attachment" 468 | previews.append(generic_content_template % ( 469 | src, 470 | description)) 471 | 472 | media = media_template % ( 473 | ''.join(previews)) 474 | elif card_content is not None: 475 | card = card_template % ( 476 | card_content["url"], 477 | file_url(media_dir, card_content["image"]), 478 | card_content["title"], 479 | escape(card_content["title"]), 480 | urlparse(card_content["url"]).netloc) 481 | 482 | html = wrapper_template % (boost, info, media, card) 483 | fp.write(html) 484 | 485 | def html_file(domain, username, collection, page): 486 | return (domain + '.user.' + username + '.' 487 | + collection + '.' + str(page) + '.html') 488 | 489 | def html(args): 490 | """ 491 | Convert toots and media files to static HTML 492 | """ 493 | 494 | toots_per_page = args.toots 495 | collection = args.collection 496 | combine = args.combine 497 | 498 | (username, domain) = args.user.split('@') 499 | 500 | status_file = domain + '.user.' + username + '.json' 501 | media_dir = domain + '.user.' + username 502 | base_url = 'https://' + domain 503 | data = core.load(status_file, required=True, combine=combine, 504 | quiet=args.quiet) 505 | user = data["account"] 506 | statuses = data[collection] 507 | 508 | if len(statuses) > 0: 509 | 510 | (pages, offset) = divmod(len(statuses), toots_per_page) 511 | page = 0 512 | 513 | while (page <= pages): 514 | 515 | if pages == 0: 516 | nav_html = "" 517 | else: 518 | if (page == 0): 519 | previous_html = "" 520 | else: 521 | previous_html = previous_template % ( 522 | html_file(domain, username, collection, page - 1)) 523 | 524 | if (page < pages): 525 | next_html = next_template % ( 526 | html_file(domain, username, collection, page + 1)) 527 | else: 528 | next_html = "" 529 | 530 | nav_html = nav_template % (previous_html, next_html) 531 | 532 | file_name = html_file(domain, username, collection, page) 533 | 534 | with open(file_name, mode = 'w', encoding = 'utf-8') as fp: 535 | 536 | if not args.quiet: 537 | print("Writing %s" % file_name) 538 | 539 | html = header_template % ( 540 | user["display_name"], 541 | user["display_name"], 542 | user["username"], 543 | user["note"], 544 | nav_html) 545 | 546 | # This forces UTF-8 independent of terminal capabilities, thus 547 | # avoiding problems with LC_CTYPE=C and other such issues. 548 | # This works well when redirecting output to a file, which 549 | # will then be an UTF-8 encoded file. 550 | fp.write(html) 551 | 552 | # Assume 184 toots, 100 toots per page: 553 | # page 0 is 0:84, page 1 is 84:184 554 | for status in statuses[ 555 | max(0, toots_per_page * (page - 1) + offset) 556 | : toots_per_page * page + offset]: 557 | write_status(fp, media_dir, status) 558 | 559 | fp.write(footer_template % nav_html) 560 | page += 1 561 | toots = toots_per_page 562 | -------------------------------------------------------------------------------- /mastodon_archive/login.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2018 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import sys 18 | import os.path 19 | from . import core 20 | 21 | def login(args): 22 | """ 23 | Just login to your Mastodon account 24 | """ 25 | 26 | mastodon = core.login(args) 27 | 28 | if not args.quiet: 29 | print("Get user info") 30 | 31 | try: 32 | user = mastodon.account_verify_credentials() 33 | except Exception as e: 34 | print(e, file=sys.stderr) 35 | if "access token was revoked" in str(e): 36 | core.deauthorize(args) 37 | archive(args) 38 | sys.exit(0) 39 | 40 | print("Login OK") 41 | -------------------------------------------------------------------------------- /mastodon_archive/media.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017–2019 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import os 18 | import sys 19 | import json 20 | import time 21 | import urllib.request 22 | from urllib.error import HTTPError 23 | from urllib.error import URLError 24 | from progress.bar import Bar 25 | from urllib.parse import urlparse 26 | from . import core 27 | 28 | def media(args): 29 | """ 30 | Download all the media files linked to from your archive 31 | """ 32 | 33 | pace = hasattr(args, 'pace') and args.pace 34 | 35 | (username, domain) = args.user.split('@') 36 | 37 | status_file = domain + '.user.' + username + '.json' 38 | media_dir = domain + '.user.' + username 39 | data = core.load(status_file, required=True, quiet=True, combine=args.combine) 40 | 41 | urls = [] 42 | preview_urls_count=0 43 | for status in data[args.collection]: 44 | attachments = status["media_attachments"] 45 | account = status["account"] 46 | emojis = status["emojis"] 47 | reactions = status.get("reactions", []) 48 | card = status["card"] 49 | if status["reblog"] is not None: 50 | attachments = status["reblog"]["media_attachments"] 51 | account = status["reblog"]["account"] 52 | emojis = status["reblog"]["emojis"] 53 | card = status["reblog"]["card"] 54 | for attachment in attachments: 55 | if attachment["preview_url"]: 56 | urls.append((attachment["preview_url"], attachment["preview_remote_url"])) 57 | preview_urls_count += 1 58 | if attachment["url"]: 59 | urls.append((attachment["url"], attachment["remote_url"])) 60 | if account["avatar"]: 61 | urls.append((account["avatar"], None)) 62 | for emoji in emojis: 63 | if emoji["url"]: 64 | urls.append((emoji["url"], None)) 65 | if len(account["emojis"]) > 0: 66 | for emoji in account["emojis"]: 67 | if emoji["url"]: 68 | urls.append((emoji["url"], None)) 69 | for reaction in reactions: 70 | if "url" in reaction and reaction["url"] : 71 | urls.append((reaction["url"], None)) 72 | if card and card["image"]: 73 | urls.append((card["image"], None)) 74 | 75 | urls = list(dict.fromkeys(urls)) 76 | 77 | # these two are always available; if the user didn't set it, will link to a 78 | # placeholder image 79 | for picture in ["avatar", "header"]: 80 | urls.append((data["account"][picture], None)) 81 | 82 | if not args.quiet: 83 | print("%d urls in your backup (%d are previews)" % (len(urls), preview_urls_count)) 84 | 85 | urls = ((url, remoteurl, media_dir + urlparse(url).path) 86 | for url, remoteurl in urls) 87 | urls = [(url, remoteurl, file_name) 88 | for url, remoteurl, file_name in urls 89 | if not os.path.isfile(file_name) and 90 | not os.path.isfile(f"{file_name}.missing")] 91 | 92 | if not args.quiet: 93 | print(f"{len(urls)} to download") 94 | bar = Bar('Downloading', max = len(urls)) 95 | 96 | errors = 0 97 | 98 | # start downloading the missing files from the back 99 | for url, remoteurl, file_name in reversed(urls): 100 | if not args.quiet: 101 | bar.next() 102 | path = urlparse(url).path 103 | dir_name = os.path.dirname(file_name) 104 | os.makedirs(dir_name, exist_ok = True) 105 | try: 106 | download(url, remoteurl, file_name, args) 107 | except OSError as e: 108 | print("\n" + str(e) + ": " + url, file=sys.stderr) 109 | errors += 1 110 | if pace: 111 | time.sleep(1) 112 | 113 | if not args.quiet: 114 | bar.finish() 115 | 116 | if errors > 0: 117 | print("%d downloads failed" % errors) 118 | 119 | def download(url, remoteurl, file_name, args, from404=True): 120 | req = urllib.request.Request( 121 | url, data=None, 122 | headers={'User-Agent': 'Mastodon-Archive/1.3 ' 123 | '(+https://github.com/kensanata/mastodon-archive#mastodon-archive)'}) 124 | retries = 5 125 | retry_downloads = True 126 | while retries > 0 and retry_downloads: 127 | try: 128 | with urllib.request.urlopen(req) as response, open(file_name, 'wb') as fp: 129 | data = response.read() 130 | fp.write(data) 131 | retry_downloads = False 132 | except HTTPError as he: 133 | if not args.suppress_errors: 134 | print("\nFailed to open " + url + " during a media request.") 135 | # We stop trying to download both 401 and 404 because 401 136 | # almost always means the server has authorized fetch enabled 137 | # and we're never going to be able to download. 138 | if remoteurl: 139 | return download(remoteurl, None, file_name, args, 140 | from404=he.status in (401, 404)) 141 | if from404 and he.status in (401, 404): 142 | flag = f"{file_name}.missing" 143 | if not args.suppress_errors: 144 | print(f"\nSuppressing future downloads with {flag}.") 145 | open(flag, "wb").close() 146 | if he.status == 429: 147 | print("Delaying next requests...") 148 | time.sleep(3*60) 149 | retries -= 1 150 | else: 151 | retry_downloads = False 152 | if remoteurl: 153 | download(remoteurl, None, file_name, args) 154 | except URLError as ue: 155 | if not args.suppress_errors: 156 | print("\nFailed to open " + url + " during a media request.") 157 | if remoteurl: 158 | download(remoteurl, None, file_name, args) 159 | retry_downloads = False 160 | -------------------------------------------------------------------------------- /mastodon_archive/meow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | # Copyright (C) 2021 cutiful (https://github.com/cutiful) 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import os 18 | import json 19 | import http.server 20 | import socketserver 21 | from progress.bar import Bar 22 | from urllib.parse import urlparse, parse_qs 23 | from . import core 24 | 25 | server_port = 13523 26 | meow_origin = "https://purr.neocities.org" 27 | meow_open_path = meow_origin + "/mastodon-archive-import/" 28 | 29 | def meow(args): 30 | """ 31 | Find and serve all archive files for Meow. 32 | """ 33 | (username, domain) = args.user.split("@") 34 | 35 | status_file = domain + ".user." + username + ".json" 36 | data = core.load(status_file, required=True, quiet=True, combine=args.combine) 37 | 38 | media_dir = domain + ".user." + username 39 | media_files = [] 40 | 41 | def use_local_file_if_exists(url): 42 | """ 43 | Checks if we have the file, in which case returns the relative path, so 44 | that Meow knows to look it up in the local storage. Otherwise, returns 45 | the URL, so Meow will try to load it remotely. Adds relative paths to 46 | media_files to serve them to Meow. 47 | """ 48 | 49 | nonlocal media_files 50 | 51 | path = urlparse(url).path 52 | if path in media_files: 53 | return path 54 | 55 | file_name = media_dir + path 56 | if os.path.isfile(file_name): 57 | media_files.append(path) 58 | return path 59 | else: 60 | return url 61 | 62 | transform_media_urls(data, use_local_file_if_exists) 63 | data["files"] = media_files 64 | 65 | print("Please, open Meow at", meow_open_path, "to continue!") 66 | 67 | file_cb = lambda *args: None 68 | 69 | bar = None 70 | if len(media_files) > 0: 71 | if not args.quiet: 72 | bar = Bar("Exporting files", max = len(media_files) + 1) 73 | file_cb = lambda *args: bar.next() 74 | 75 | serve(server_port, meow_origin, data, media_dir, media_files, file_cb) 76 | 77 | if bar: 78 | bar.finish() 79 | print("Export finished!") 80 | 81 | def transform_media_urls(data, func): 82 | """ 83 | Calls func on each media file URL and sets the latter to the result. 84 | """ 85 | for collection in ["statuses", "favourites", "bookmarks"]: 86 | for status in data[collection]: 87 | attachments = status["media_attachments"] 88 | if status["reblog"] is not None: 89 | attachments = status["reblog"]["media_attachments"] 90 | for attachment in attachments: 91 | if attachment["url"]: 92 | attachment["url"] = func(attachment["url"]) 93 | 94 | for picture in ["avatar", "header"]: 95 | data["account"][picture] = func(data["account"][picture]) 96 | 97 | def serve(port, origin, data, media_dir, media_files, file_cb): 98 | complete = False 99 | def not_completed(): 100 | nonlocal complete 101 | return not complete 102 | 103 | class Handler(http.server.BaseHTTPRequestHandler): 104 | def do_GET(self): 105 | nonlocal complete 106 | query = parse_qs(urlparse(self.path).query) 107 | 108 | if self.path == "/": 109 | self.send_response(200) 110 | self.send_header("Access-Control-Allow-Origin", origin) 111 | self.send_header("Content-type", "application/json") 112 | self.end_headers() 113 | 114 | self.wfile.write(bytes(json.dumps(data), "utf-8")) 115 | 116 | file_cb() 117 | elif "file" in query and query["file"][0] in media_files: 118 | self.send_response(200) 119 | self.send_header("Access-Control-Allow-Origin", origin) 120 | self.end_headers() 121 | 122 | file_name = media_dir + query["file"][0] 123 | with open(file_name, "rb") as file: 124 | self.wfile.write(file.read()) 125 | 126 | file_cb() 127 | elif "complete" in query: 128 | self.send_response(200) 129 | self.end_headers() 130 | 131 | complete = True 132 | else: 133 | self.send_error(404) 134 | 135 | def log_message(self, format, *args): 136 | return 137 | 138 | socketserver.TCPServer.allow_reuse_address = True 139 | with socketserver.TCPServer(("127.0.0.1", port), Handler) as httpd: 140 | while not_completed(): 141 | httpd.handle_request() 142 | -------------------------------------------------------------------------------- /mastodon_archive/mutuals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2018 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | from progress.bar import Bar 19 | from datetime import timedelta, datetime 20 | from . import core 21 | 22 | def mutuals(args): 23 | """ 24 | List people you're following and who are following you, too. 25 | """ 26 | 27 | (username, domain) = args.user.split('@') 28 | 29 | status_file = domain + '.user.' + username + '.json' 30 | data = core.load(status_file, required=True, quiet=True, combine=True) 31 | 32 | # Print both error messages if the data is missing 33 | if "following" not in data or len(data["following"]) == 0: 34 | print("You need to run 'mastodon-archive archive --with-following'", 35 | file=sys.stderr) 36 | sys.exit(7) 37 | 38 | mastodon = core.login(args) 39 | 40 | if not args.quiet: 41 | print("Get user info") 42 | 43 | try: 44 | user = mastodon.account_verify_credentials() 45 | except Exception as e: 46 | if "access token was revoked" in str(e): 47 | core.deauthorize(args) 48 | # retry and exit without an error 49 | archive(args) 50 | sys.exit(0) 51 | elif "Name or service not known" in str(e): 52 | print("Error: the instance name is either misspelled or offline", 53 | file=sys.stderr) 54 | else: 55 | print(e, file=sys.stderr) 56 | # exit in either case 57 | sys.exit(1) 58 | 59 | ids = [x["id"] for x in data["following"]] 60 | lookup = {x["id"]: "%s <%s>" % (x["display_name"] or x["username"], 61 | x["acct"]) 62 | for x in data["following"]} 63 | relations = mastodon.account_relationships(ids) 64 | for relation in relations: 65 | if relation["followed_by"]: 66 | print(lookup[relation["id"]]) 67 | -------------------------------------------------------------------------------- /mastodon_archive/replies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2019 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | from progress.bar import Bar 19 | from . import core 20 | 21 | def replies(args): 22 | """ 23 | Archive the statuses you replied to 24 | """ 25 | 26 | (username, domain) = core.parse(args.user) 27 | 28 | status_file = domain + '.user.' + username + '.json' 29 | data = core.load(status_file, required = True, quiet = args.quiet) 30 | 31 | mastodon = core.login(args) 32 | 33 | if not args.quiet: 34 | print("Get user info") 35 | 36 | try: 37 | user = mastodon.account_verify_credentials() 38 | except Exception as e: 39 | if "access token was revoked" in str(e): 40 | core.deauthorize(args) 41 | # retry and exit without an error 42 | archive(args) 43 | sys.exit(0) 44 | elif "Name or service not known" in str(e): 45 | print("Error: the instance name is either misspelled or offline", 46 | file=sys.stderr) 47 | else: 48 | print(e, file=sys.stderr) 49 | # exit in either case 50 | sys.exit(1) 51 | 52 | index = {} # mapping ids to statuses 53 | missing = [] # ids we need to fetch 54 | 55 | for collection in ["statuses", 56 | "favourites", 57 | "bookmarks", 58 | "mentions", 59 | "replies"]: 60 | if collection not in data: 61 | if not args.quiet: 62 | print("No %s in this archive..." % collection) 63 | else: 64 | statuses = data[collection]; 65 | if not args.quiet: 66 | print("Indexing %d %s..." % (len(statuses), collection)) 67 | for status in statuses: 68 | 69 | if status["reblog"] is not None: 70 | status = status["reblog"] 71 | 72 | # only accept one status per id 73 | if status["id"] in index: 74 | pass 75 | else: 76 | index[status["id"]] = 1 77 | if not args.quiet: 78 | print("Indexed %d statuses..." % (len(index))) 79 | 80 | if not args.quiet: 81 | print("Counting missing replies...") 82 | for status in data["statuses"]: 83 | # skip boosts 84 | if status["reblog"] is None and status["in_reply_to_id"] is not None: 85 | if status["in_reply_to_id"] not in index: 86 | missing.append(status["in_reply_to_id"]) 87 | if not args.quiet: 88 | print("Missing %d originals..." % (len(missing))) 89 | 90 | if len(missing) > 300: 91 | if not args.quiet: 92 | print("Given the typical rate limit of 300 requests per 5 minutes, " 93 | "this will take about %d minutes" % (len(missing) // 300 * 5)) 94 | 95 | if len(missing) > 0: 96 | if not "replies" in data: 97 | replies = [] 98 | else: 99 | replies = data["replies"] 100 | 101 | if not args.quiet: 102 | bar = Bar('Fetching', max = len(missing)) 103 | 104 | for id in missing: 105 | try: 106 | status = mastodon.status(id) 107 | replies.append(status) 108 | except Exception as e: 109 | if "not found" in str(e) or "Not Found" in str(e): 110 | pass 111 | else: 112 | print(e, file=sys.stderr) 113 | 114 | if not args.quiet: 115 | bar.next() 116 | 117 | if not args.quiet: 118 | bar.finish() 119 | 120 | data["replies"] = replies 121 | core.save(status_file, data, quiet=args.quiet) 122 | -------------------------------------------------------------------------------- /mastodon_archive/report.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | import textwrap 19 | import unicodedata 20 | from . import core 21 | 22 | def boosts(statuses): 23 | """ 24 | Count boosts in statuses 25 | """ 26 | i = 0 27 | for item in statuses: 28 | if item["reblog"] is not None: 29 | i += 1 30 | return i 31 | 32 | def media(statuses): 33 | """ 34 | Count media attachments in statuses 35 | """ 36 | i = 0 37 | for item in statuses: 38 | i += len(item["media_attachments"]) 39 | return i 40 | 41 | 42 | def tags(statuses, include_boosts): 43 | """ 44 | Count all the hashtags in statuses 45 | """ 46 | count = {} 47 | for item in statuses: 48 | if include_boosts and item["reblog"] is not None: 49 | item = item["reblog"] 50 | for name in [tag["name"] for tag in item["tags"]]: 51 | if name in count: 52 | count[name] += 1 53 | else: 54 | count[name] = 1 55 | return count 56 | 57 | def print_tags(statuses, max, include_boosts): 58 | """ 59 | Print hashtags used in statuses 60 | """ 61 | if max == -1: 62 | print("All the hashtags:") 63 | else: 64 | print("Top " + str(max) + " hashtags:") 65 | count = tags(statuses, include_boosts) 66 | most = sorted(count.keys(), key = lambda tag: -count[tag]) 67 | print(textwrap.fill(" ".join( 68 | ["#"+tag+"("+str(count[tag])+")" for tag in most[0:max]]))) 69 | 70 | def emoji(statuses): 71 | """ 72 | Count all the emoji in statuses 73 | """ 74 | count = {} 75 | for item in statuses: 76 | for char in item["content"]: 77 | if unicodedata.category(char) == 'So': 78 | if char in count: 79 | count[char] += 1 80 | else: 81 | count[char] = 1 82 | return count 83 | 84 | def print_emoji(statuses, min = 10, max_num = 30): 85 | """ 86 | Print emoji used in statuses, sorted by frequency 87 | """ 88 | print("Most frequeny Emoji:") 89 | count = emoji(statuses) 90 | count = {k: v for k, v in count.items() if v >= min } 91 | most = sorted(count.keys(), key = lambda emoji: -count[emoji]) 92 | print(textwrap.fill(" ".join([emoji for emoji in most[0:max_num]]))) 93 | 94 | def report(args): 95 | """ 96 | Report on your toots, favourites and bookmarks 97 | """ 98 | 99 | (username, domain) = args.user.split('@') 100 | 101 | status_file = domain + '.user.' + username + '.json' 102 | data = core.load(status_file, required=True, quiet=True, combine=args.combine) 103 | 104 | if args.all: 105 | print("Considering the entire archive") 106 | if "statuses" in data: 107 | statuses = data["statuses"] 108 | if "favourites" in data: 109 | favourites = data["favourites"] 110 | if "bookmarks" in data: 111 | bookmarks = data["bookmarks"] 112 | else: 113 | print("Considering the last " 114 | + str(args.weeks) 115 | + " weeks") 116 | if "statuses" in data: 117 | statuses = core.keep(data["statuses"], args.weeks) 118 | if "favourites" in data: 119 | favourites = core.keep(data["favourites"], args.weeks) 120 | if "bookmarks" in data: 121 | bookmarks = core.keep(data["bookmarks"], args.weeks) 122 | 123 | if "statuses" in data: 124 | print("Statuses:".ljust(20), str(len(statuses)).rjust(6)) 125 | print("Boosts:".ljust(20), str(boosts(statuses)).rjust(6)) 126 | print("Media:".ljust(20), str(media(statuses)).rjust(6)) 127 | 128 | print() 129 | print_tags(statuses, args.top, args.include_boosts) 130 | 131 | if args.with_emoji: 132 | print() 133 | print_emoji(statuses) 134 | 135 | if "statuses" in data and "favourites" in data: 136 | print() 137 | 138 | if "favourites" in data: 139 | print("Favourites:".ljust(20), str(len(favourites)).rjust(6)) 140 | print("Boosts:".ljust(20), str(boosts(favourites)).rjust(6)) 141 | print("Media:".ljust(20), str(media(favourites)).rjust(6)) 142 | 143 | print() 144 | print_tags(favourites, args.top, args.include_boosts) 145 | 146 | if "favourites" in data and "bookmarks" in data: 147 | print() 148 | 149 | if "bookmarks" in data: 150 | print("Bookmarks:".ljust(20), str(len(bookmarks)).rjust(6)) 151 | print("Boosts:".ljust(20), str(boosts(bookmarks)).rjust(6)) 152 | print("Media:".ljust(20), str(media(bookmarks)).rjust(6)) 153 | 154 | print() 155 | print_tags(bookmarks, args.top, args.include_boosts) 156 | -------------------------------------------------------------------------------- /mastodon_archive/split.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2019 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import sys 17 | import os.path 18 | import math 19 | from datetime import timedelta, datetime 20 | from . import core 21 | 22 | def split(args): 23 | """ 24 | Split older toots into a new file 25 | """ 26 | 27 | confirmed = args.confirmed 28 | 29 | if not confirmed: 30 | 31 | print("This is a dry run and nothing will be moved.\n" 32 | "Instead, we'll just list what would have happened.\n" 33 | "Use --confirmed to actually do it.") 34 | 35 | (username, domain) = args.user.split('@') 36 | 37 | status_file = domain + '.user.' + username + '.json' 38 | data = core.load(status_file, required = True, quiet = args.quiet) 39 | older_data = {} 40 | 41 | n = 0 42 | older_status_file = '' 43 | while True: 44 | older_status_file = domain + '.user.' + username + '.' + str(n) + '.json' 45 | if os.path.exists(older_status_file): 46 | n = n + 1 47 | else: 48 | break 49 | 50 | delta = timedelta(weeks = args.weeks) 51 | cutoff = datetime.today() - delta 52 | 53 | if not args.quiet: 54 | print("Older than " + str(cutoff)) 55 | 56 | n_statuses = 0 57 | 58 | for collection in ["statuses", 59 | "favourites", 60 | "bookmarks", 61 | "mentions"]: 62 | statuses = list(filter( 63 | lambda status: datetime.strptime(status["created_at"][0:10], "%Y-%m-%d") >= cutoff, 64 | data[collection])) 65 | older_statuses = list(filter( 66 | lambda status: datetime.strptime(status["created_at"][0:10], "%Y-%m-%d") < cutoff, 67 | data[collection])) 68 | 69 | data[collection] = statuses 70 | older_data[collection] = older_statuses 71 | 72 | moved = len(older_statuses) 73 | if not args.quiet: 74 | print(collection + ": " + str(moved)) 75 | n_statuses += moved 76 | 77 | if confirmed and n_statuses > 0: 78 | 79 | if not args.quiet: 80 | print("Saving " + status_file) 81 | core.save(status_file, data, quiet=args.quiet) 82 | if not args.quiet: 83 | print("Saving " + older_status_file) 84 | core.save(older_status_file, older_data, quiet=args.quiet) 85 | 86 | elif confirmed: 87 | 88 | if not args.quiet: 89 | print("No older statuses to move") 90 | 91 | else: 92 | 93 | print("Would have saved this to " + older_status_file) 94 | -------------------------------------------------------------------------------- /mastodon_archive/text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2018 Alex Schroeder 3 | # Copyright (C) 2017 Steve Ivy 4 | 5 | # This program is free software: you can redistribute it and/or modify it under 6 | # the terms of the GNU General Public License as published by the Free Software 7 | # Foundation, either version 3 of the License, or (at your option) any later 8 | # version. 9 | # 10 | # This program is distributed in the hope that it will be useful, but WITHOUT 11 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 12 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License along with 15 | # this program. If not, see . 16 | 17 | import itertools 18 | import sys 19 | import os.path 20 | import html2text 21 | import re 22 | from . import core 23 | from urllib.parse import urlparse 24 | 25 | def text(args): 26 | """ 27 | Convert toots to plain text, optionally filtering them 28 | """ 29 | 30 | collection = args.collection 31 | reverse = args.reverse 32 | patterns = args.pattern 33 | combine = args.combine 34 | 35 | (username, domain) = core.parse(args.user) 36 | 37 | media_dir = domain + '.user.' + username 38 | status_file = domain + '.user.' + username + '.json' 39 | data = core.load(status_file, required=True, quiet=True, combine=combine) 40 | 41 | def matches(status): 42 | if status["reblog"] is not None: 43 | status = status["reblog"] 44 | for pattern in patterns: 45 | found = False 46 | for s in [status["content"], 47 | status["account"]["display_name"], 48 | status["account"]["username"], 49 | status["created_at"]]: 50 | if re.search(pattern, s, flags=re.IGNORECASE) is not None: 51 | found = True 52 | continue 53 | if not found: 54 | return False 55 | return True 56 | 57 | if collection == "all": 58 | statuses = [] 59 | # a lenient collection of all the status types we might have 60 | for collection in ["statuses", "favourites", "bookmarks", "mentions"]: 61 | if collection in data: 62 | statuses += data[collection] 63 | else: 64 | # if a specific collection is requested, not having it in the archive is fatal 65 | if collection not in data or len(data[collection]) == 0: 66 | print("Sadly, {} are missing in your archive".format(collection), 67 | file=sys.stderr) 68 | sys.exit(5) 69 | statuses = data[collection] 70 | 71 | if len(patterns) > 0: 72 | statuses = list(filter(matches, statuses)) 73 | 74 | statuses = sorted(statuses, reverse=reverse, key=lambda status: status["created_at"]) 75 | 76 | for status in statuses: 77 | str = ''; 78 | if status["reblog"] is not None: 79 | str += (status["account"]["display_name"] + " boosted\n") 80 | status = status["reblog"] 81 | str += ("%s @%s %s\n" % ( 82 | status["account"]["display_name"], 83 | status["account"]["username"], 84 | status["created_at"])) 85 | str += "🔗 " + status["url"] + "\n" 86 | str += html2text.html2text(status["content"]).strip() + "\n" 87 | for attachment in status["media_attachments"]: 88 | # should we check attachment["preview_url"] as well? 89 | for url in [attachment["url"]]: 90 | path = urlparse(url).path 91 | file_name = media_dir + path 92 | if os.path.isfile(file_name): 93 | str += "🖻 " + file_name + "\n" 94 | elif url not in str: 95 | str += "🔗 " + url + "\n" 96 | str += "\n" 97 | # This forces UTF-8 independent of terminal capabilities, thus 98 | # avoiding problems with LC_CTYPE=C and other such issues. 99 | # This works well when redirecting output to a file, which 100 | # will then be an UTF-8 encoded file. 101 | sys.stdout.buffer.write(str.encode('utf-8')) 102 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setup( 7 | name='mastodon_archive', 8 | version='1.4.8', 9 | description="Utility for backing up your Mastodon content", 10 | long_description=long_description, 11 | long_description_content_type="text/markdown", 12 | author="Alex Schroeder", 13 | author_email="alex@gnu.org", 14 | url='https://github.com/kensanata/mastodon-archive#mastodon-archive', 15 | classifiers=[ 16 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 17 | 'Programming Language :: Python :: 3 :: Only', 18 | 'Topic :: Communications', 19 | 'Intended Audience :: End Users/Desktop', 20 | 'Environment :: Console', 21 | 'Development Status :: 5 - Production/Stable', 22 | ], 23 | packages=["mastodon_archive"], 24 | entry_points={ 25 | "console_scripts": ["mastodon-archive=mastodon_archive:main"] 26 | }, 27 | install_requires=[ 28 | "mastodon.py", 29 | "progress", 30 | "html2text", 31 | ], 32 | ) 33 | --------------------------------------------------------------------------------