├── .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?
354 | '''
355 |
356 | emoji_template = '''\
357 |
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 |
--------------------------------------------------------------------------------