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

%s

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

%s

%s" % ( 405 | status["spoiler_text"], 406 | status["content"]) 407 | 408 | info = status_template % ( 409 | file_url(media_dir, user["avatar"]), 410 | user["url"], 411 | displayname, 412 | user["acct"], 413 | status["url"], 414 | dateutil.parser.parse( 415 | status["created_at"]).strftime( 416 | "%Y-%m-%d %H:%M"), 417 | text_with_emoji(media_dir, content, status["emojis"])) 418 | 419 | media = '' 420 | attachments = status["media_attachments"] 421 | card = '' 422 | card_content = status["card"] 423 | 424 | if len(attachments) > 0: 425 | previews = [] 426 | for attachment in attachments: 427 | # video src must never be the unknown image 428 | src = file_url(media_dir, attachment["url"], None, False); 429 | if (attachment["type"] == "video" or attachment["type"] == "gifv") and src: 430 | # Pleroma and maybe others don't offer a separate 431 | # preview. The preview_url is the same as the video 432 | # source. 433 | preview = file_url(media_dir, attachment["preview_url"], None, False) 434 | if src and preview and src == preview or not preview: 435 | previews.append(video_template % ( 436 | src, # video 437 | file_url(media_dir, attachment["remote_url"]), # remote link 438 | preview)) # image for remote link 439 | else: 440 | previews.append(video_with_poster_template % ( 441 | src, # video 442 | preview, # poster 443 | file_url(media_dir, attachment["remote_url"]), # remote link 444 | preview)) # image for remote link 445 | elif attachment["type"] == "audio": 446 | previews.append(audeo_template % ( 447 | attachment["description"], # alt text 448 | src, # audio 449 | src)) # audio for download link 450 | elif attachment["type"] == "image": 451 | size = "" 452 | if len(attachments) == 1: 453 | size = "one" 454 | elif len(attachments) == 2 or (len(attachments) == 3 and len(previews) == 0): 455 | size = "tall" 456 | 457 | description = escape(attachment["description"]) if attachment["description"] is not None else "" 458 | 459 | previews.append(image_template % ( 460 | file_url(media_dir, attachment["url"]), # link to image 461 | size, # class for how it should be rendered 462 | file_url(media_dir, attachment["preview_url"], attachment["url"]), # image 463 | description, # title (hover text) 464 | description)) # alt text 465 | else: 466 | # other, likely "unknown" 467 | description = escape(attachment["description"]) if attachment["description"] is not None else attachment["type"] + " attachment" 468 | previews.append(generic_content_template % ( 469 | src, 470 | description)) 471 | 472 | media = media_template % ( 473 | ''.join(previews)) 474 | elif card_content is not None: 475 | card = card_template % ( 476 | card_content["url"], 477 | file_url(media_dir, card_content["image"]), 478 | card_content["title"], 479 | escape(card_content["title"]), 480 | urlparse(card_content["url"]).netloc) 481 | 482 | html = wrapper_template % (boost, info, media, card) 483 | fp.write(html) 484 | 485 | def html_file(domain, username, collection, page): 486 | return (domain + '.user.' + username + '.' 487 | + collection + '.' + str(page) + '.html') 488 | 489 | def html(args): 490 | """ 491 | Convert toots and media files to static HTML 492 | """ 493 | 494 | toots_per_page = args.toots 495 | collection = args.collection 496 | combine = args.combine 497 | 498 | (username, domain) = args.user.split('@') 499 | 500 | status_file = domain + '.user.' + username + '.json' 501 | media_dir = domain + '.user.' + username 502 | base_url = 'https://' + domain 503 | data = core.load(status_file, required=True, combine=combine, 504 | quiet=args.quiet) 505 | user = data["account"] 506 | statuses = data[collection] 507 | 508 | if len(statuses) > 0: 509 | 510 | (pages, offset) = divmod(len(statuses), toots_per_page) 511 | page = 0 512 | 513 | while (page <= pages): 514 | 515 | if pages == 0: 516 | nav_html = "" 517 | else: 518 | if (page == 0): 519 | previous_html = "" 520 | else: 521 | previous_html = previous_template % ( 522 | html_file(domain, username, collection, page - 1)) 523 | 524 | if (page < pages): 525 | next_html = next_template % ( 526 | html_file(domain, username, collection, page + 1)) 527 | else: 528 | next_html = "" 529 | 530 | nav_html = nav_template % (previous_html, next_html) 531 | 532 | file_name = html_file(domain, username, collection, page) 533 | 534 | with open(file_name, mode = 'w', encoding = 'utf-8') as fp: 535 | 536 | if not args.quiet: 537 | print("Writing %s" % file_name) 538 | 539 | html = header_template % ( 540 | user["display_name"], 541 | user["display_name"], 542 | user["username"], 543 | user["note"], 544 | nav_html) 545 | 546 | # This forces UTF-8 independent of terminal capabilities, thus 547 | # avoiding problems with LC_CTYPE=C and other such issues. 548 | # This works well when redirecting output to a file, which 549 | # will then be an UTF-8 encoded file. 550 | fp.write(html) 551 | 552 | # Assume 184 toots, 100 toots per page: 553 | # page 0 is 0:84, page 1 is 84:184 554 | for status in statuses[ 555 | max(0, toots_per_page * (page - 1) + offset) 556 | : toots_per_page * page + offset]: 557 | write_status(fp, media_dir, status) 558 | 559 | fp.write(footer_template % nav_html) 560 | page += 1 561 | toots = toots_per_page 562 | -------------------------------------------------------------------------------- /mastodon_archive/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (C) 2017-2019 Alex Schroeder 3 | 4 | # This program is free software: you can redistribute it and/or modify it under 5 | # the terms of the GNU General Public License as published by the Free Software 6 | # Foundation, either version 3 of the License, or (at your option) any later 7 | # version. 8 | # 9 | # This program is distributed in the hope that it will be useful, but WITHOUT 10 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License along with 14 | # this program. If not, see . 15 | 16 | import argparse 17 | from . import core 18 | from . import archive 19 | from . import replies 20 | from . import text 21 | from . import context 22 | from . import html 23 | from . import media 24 | from . import split 25 | from . import expire 26 | from . import report 27 | from . import followers 28 | from . import following 29 | from . import allowlist 30 | from . import mutuals 31 | from . import login 32 | from . import fix 33 | from . import meow 34 | 35 | def main(): 36 | parser = argparse.ArgumentParser( 37 | description="""Archive your toots, favourites and bookmarks, 38 | and work with them.""", 39 | epilog="""Once you have created archives in the current directory, you can 40 | use 'all' instead of your account and the commands will be run 41 | once for every archive in the directory.""") 42 | 43 | parser.add_argument("--quiet", "-q", action='store_true', default=False, 44 | help='do not output normal status messages') 45 | 46 | subparsers = parser.add_subparsers() 47 | 48 | 49 | parser_content = subparsers.add_parser( 50 | name='archive', 51 | help='archive your toots, favourites and bookmarks') 52 | parser_content.add_argument("--no-favourites", dest='skip_favourites', 53 | action='store_const', 54 | const=True, default=False, 55 | help='skip download of favourites') 56 | parser_content.add_argument("--no-bookmarks", dest='skip_bookmarks', 57 | action='store_const', 58 | const=True, default=False, 59 | help='skip download of bookmarks') 60 | parser_content.add_argument("--with-mentions", dest='with_mentions', 61 | action='store_const', 62 | const=True, default=False, 63 | help='download mentions (notifications where you are mentioned)') 64 | parser_content.add_argument("--with-followers", dest='with_followers', 65 | action='store_const', 66 | const=True, default=False, 67 | help='download followers (people following you)') 68 | parser_content.add_argument("--with-following", dest='with_following', 69 | action='store_const', 70 | const=True, default=False, 71 | help='download following (the people you follow)') 72 | parser_content.add_argument("--with-mutes", action='store_true', 73 | default=False, help='download people you muted') 74 | parser_content.add_argument("--with-blocks", action='store_true', 75 | default=False, help='download people you blocked') 76 | parser_content.add_argument("--with-notes", action='store_true', 77 | default=False, help='download private notes ' 78 | 'for any followers, follows, mutes, and/or ' 79 | 'blocks that have been downloaded') 80 | parser_content.add_argument("--no-stopping", dest='stopping', 81 | action='store_const', 82 | const=False, default=True, 83 | help='do not stop after seeing 10 duplicates') 84 | parser_content.add_argument("--update", dest='update', 85 | action='store_const', 86 | const=True, default=False, 87 | help='save updated versions of statuses') 88 | parser_content.add_argument("--pace", dest='pace', action='store_const', 89 | const=True, default=False, 90 | help='avoid timeouts and pace requests') 91 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 92 | const="none", default="created", 93 | help='ignore "Version check failed" error') 94 | parser_content.add_argument("user", 95 | help='your account, e.g. kensanata@octogon.social') 96 | parser_content.set_defaults(command=archive.archive) 97 | 98 | 99 | parser_content = subparsers.add_parser( 100 | name='replies', 101 | help='archive missing toots you replied to') 102 | parser_content.add_argument("--pace", dest='pace', action='store_const', 103 | const=True, default=False, 104 | help='avoid timeouts and pace requests') 105 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 106 | const="none", default="created", 107 | help='ignore "Version check failed" error') 108 | parser_content.add_argument("user", 109 | help='your account, e.g. kensanata@octogon.social') 110 | parser_content.set_defaults(command=replies.replies) 111 | 112 | 113 | parser_content = subparsers.add_parser( 114 | name='media', 115 | help='download media referred to by toots in your archive') 116 | parser_content.add_argument("user", 117 | help='your account, e.g. kensanata@octogon.social') 118 | parser_content.add_argument("--combine", 119 | action="store_true", 120 | help="combine archives in case they are split") 121 | parser_content.add_argument("--collection", dest='collection', 122 | choices=['statuses', 'favourites', 'bookmarks'], 123 | default='statuses', 124 | help='export statuses, favourites or bookmarks') 125 | parser_content.add_argument("--pace", dest='pace', action='store_const', 126 | const=True, default=False, 127 | help='avoid timeouts and pace requests') 128 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 129 | const="none", default="created", 130 | help='ignore "Version check failed" error') 131 | parser_content.add_argument("--suppress-errors", action='store_true', 132 | default=False, help="don't print messages " 133 | "about media that can't be downloaded") 134 | parser_content.set_defaults(command=media.media) 135 | 136 | 137 | parser_content = subparsers.add_parser( 138 | name='text', 139 | help='search and export toots in the archive as plain text') 140 | parser_content.add_argument("--reverse", dest='reverse', action='store_const', 141 | const=True, default=False, 142 | help='reverse output, oldest first') 143 | parser_content.add_argument("--combine", 144 | action="store_true", 145 | help="combine archives in case they are split") 146 | parser_content.add_argument("--collection", dest='collection', 147 | choices=['statuses', 'favourites', 'bookmarks', 'mentions', 'all'], 148 | default='statuses', 149 | help='export statuses, favourites, bookmarks or mentions') 150 | parser_content.add_argument("user", 151 | help='your account, e.g. kensanata@octogon.social') 152 | parser_content.add_argument("pattern", nargs='*', 153 | help='regular expressions used to filter output') 154 | parser_content.set_defaults(command=text.text) 155 | 156 | 157 | parser_content = subparsers.add_parser( 158 | name='context', 159 | help='show a toot in context (i.e. with its ancestors and its descendants') 160 | parser_content.add_argument("user", 161 | help='your account, e.g. kensanata@octogon.social') 162 | parser_content.add_argument("url", 163 | help='URL of the toot to be included') 164 | parser_content.set_defaults(command=context.context) 165 | 166 | 167 | parser_content = subparsers.add_parser( 168 | name='html', 169 | help='export toots and media in the archive as static HTML') 170 | parser_content.add_argument("--combine", 171 | action="store_true", 172 | help="combine archives in case they are split") 173 | parser_content.add_argument("--collection", dest='collection', 174 | choices=['statuses', 'favourites', 'bookmarks'], 175 | default='statuses', 176 | help='export statuses favourites or bookmarks') 177 | parser_content.add_argument("--toots-per-page", dest='toots', 178 | metavar='N', type=int, default=2000, 179 | help='how many toots per HTML page') 180 | parser_content.add_argument("user", 181 | help='your account, e.g. kensanata@octogon.social') 182 | parser_content.set_defaults(command=html.html) 183 | 184 | parser_content = subparsers.add_parser( 185 | name='split', 186 | help='split an archive into two') 187 | parser_content.add_argument("--older-than", dest='weeks', 188 | metavar='N', type=float, default=4, 189 | help='split anything older than this many weeks') 190 | parser_content.add_argument("--confirmed", dest='confirmed', 191 | action='store_const', const=True, default=False, 192 | help='save the data after splitting') 193 | parser_content.add_argument("user", 194 | help='your account, e.g. kensanata@octogon.social') 195 | parser_content.set_defaults(command=split.split) 196 | 197 | 198 | parser_content = subparsers.add_parser( 199 | name='expire', 200 | help='''delete older toots from the server and unfavour favourites 201 | if and only if they are in your archive''', 202 | epilog='''There is one problem you need to be aware of: if you expiring 203 | mentions, then the tool goes through all your notifications 204 | and looks at those of the type mention, and expires them if 205 | they are old enough. There are other types of notifications, 206 | however: follow, favourite, and reblog (at the time of this 207 | writing). As these are not archived, we also don't expire 208 | them. Thus, the list of notifications to look through keeps 209 | growing unless you use the "Clear notifications" menu in the 210 | Mastodon web client. Alternatively, you can use the 211 | --delete-other-notifications option together with 212 | --collection mentions.''') 213 | 214 | parser_content.add_argument("--collection", dest='collection', 215 | choices=['statuses', 'favourites', 'mentions'], 216 | default='statuses', 217 | help='delete statuses, unfavour favourites, or clear mention notifications') 218 | parser_content.add_argument("--older-than", dest='weeks', 219 | metavar='N', type=float, default=4, 220 | help='expire anything older than this many weeks') 221 | parser_content.add_argument("--delete-other-notifications", dest='delete_others', 222 | action='store_const', const=True, default=False, 223 | help='clear follow, favourite, and reblog notifications') 224 | parser_content.add_argument("--confirmed", dest='confirmed', 225 | action='store_const', const=True, default=False, 226 | help='perform the expiration on the server') 227 | parser_content.add_argument("--pace", dest='pace', action='store_const', 228 | const=True, default=False, 229 | help='avoid timeouts and pace requests') 230 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 231 | const="none", default="created", 232 | help='ignore "Version check failed" error') 233 | parser_content.add_argument("user", 234 | help='your account, e.g. kensanata@octogon.social') 235 | parser_content.set_defaults(command=expire.expire) 236 | 237 | 238 | 239 | parser_content = subparsers.add_parser( 240 | name='report', 241 | help='''report some numbers about your toots, favourites and bookmarks''') 242 | parser_content.add_argument("--combine", 243 | action="store_true", 244 | help="combine archives in case they are split") 245 | parser_content.add_argument("--all", dest='all', action='store_const', 246 | const=True, default=False, 247 | help='consider all toots (ignore --newer-than)') 248 | parser_content.add_argument("--newer-than", dest='weeks', 249 | metavar='N', type=int, default=12, 250 | help='only consider toots newer than this many weeks') 251 | parser_content.add_argument("--top", dest='top', 252 | metavar='N', type=int, default=10, 253 | help='only print the top N tags') 254 | parser_content.add_argument("--include-boosts", dest='include_boosts', action='store_const', 255 | const=True, default=False, 256 | help='include boosts') 257 | parser_content.add_argument("--with-emoji", dest='with_emoji', action='store_const', 258 | const=True, default=False, 259 | help='include emoji count') 260 | parser_content.add_argument("user", 261 | help='your account, e.g. kensanata@octogon.social') 262 | parser_content.set_defaults(command=report.report) 263 | 264 | 265 | parser_content = subparsers.add_parser( 266 | name='followers', 267 | help='''show followers''') 268 | parser_content.add_argument("--no-mentions", dest='mentions', action='store_const', 269 | const=False, default=True, 270 | help='Limit to followers that do not mention you') 271 | parser_content.add_argument("--block", dest='block', action='store_const', 272 | const=True, default=False, 273 | help='...and block them') 274 | parser_content.add_argument("--all", dest='all', action='store_const', 275 | const=True, default=False, 276 | help='consider all toots (ignore --newer-than) when looking for interactions') 277 | parser_content.add_argument("--newer-than", dest='weeks', 278 | metavar='N', type=int, default=12, 279 | help='require interaction within this many weeks (default is 12)') 280 | parser_content.add_argument("user", 281 | help='your account, e.g. kensanata@octogon.social') 282 | parser_content.set_defaults(command=followers.followers) 283 | 284 | 285 | parser_content = subparsers.add_parser( 286 | name='following', 287 | help='''find people you are following but who never mention you''') 288 | parser_content.add_argument("--unfollow", dest='unfollow', action='store_const', 289 | const=True, default=False, 290 | help='...and unfollow them') 291 | parser_content.add_argument("--all", dest='all', action='store_const', 292 | const=True, default=False, 293 | help='consider all toots (ignore --newer-than)') 294 | parser_content.add_argument("--newer-than", dest='weeks', 295 | metavar='N', type=int, default=12, 296 | help='require mention within this many weeks (default is 12)') 297 | parser_content.add_argument("--pace", dest='pace', action='store_const', 298 | const=True, default=False, 299 | help='avoid timeouts and pace requests') 300 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 301 | const="none", default="created", 302 | help='ignore "Version check failed" error') 303 | parser_content.add_argument("user", 304 | help='your account, e.g. kensanata@octogon.social') 305 | parser_content.set_defaults(command=following.following) 306 | 307 | 308 | parser_content = subparsers.add_parser( 309 | name='mutuals', 310 | help='''find people you are following and who follow you back''') 311 | parser_content.add_argument("--pace", dest='pace', action='store_const', 312 | const=True, default=False, 313 | help='avoid timeouts and pace requests') 314 | parser_content.add_argument("--no-version-check", dest='version_check', action='store_const', 315 | const="none", default="created", 316 | help='ignore "Version check failed" error') 317 | parser_content.add_argument("user", 318 | help='your account, e.g. kensanata@octogon.social') 319 | parser_content.set_defaults(command=mutuals.mutuals) 320 | 321 | 322 | parser_content = subparsers.add_parser( 323 | name='allowlist', 324 | help='''print the allowlist to help you debug problems''') 325 | parser_content.add_argument("user", 326 | help='your account, e.g. kensanata@octogon.social') 327 | parser_content.set_defaults(command=allowlist.print_allowlist) 328 | 329 | parser_content = subparsers.add_parser( 330 | name='fix-boosts', 331 | help='''mark all the boosts as not deleted (triggering their deletion)''') 332 | parser_content.add_argument("--combine", 333 | action="store_true", 334 | help="combine archives in case they are split") 335 | parser_content.add_argument("user", 336 | help='your account, e.g. kensanata@octogon.social') 337 | parser_content.add_argument("--confirmed", dest='confirmed', 338 | action='store_const', const=True, default=False, 339 | help='perform the change on the archive') 340 | parser_content.set_defaults(command=fix.fix_boosts) 341 | 342 | parser_content = subparsers.add_parser( 343 | name='login', 344 | help='login to the instance for testing purposes') 345 | parser_content.add_argument("user", 346 | help='your account, e.g. kensanata@octogon.social') 347 | parser_content.set_defaults(command=login.login) 348 | 349 | parser_content = subparsers.add_parser( 350 | name='meow', 351 | help='import your backup into Meow, a browser-based export viewer (see https://purr.neocities.org/about/)') 352 | parser_content.add_argument("user", 353 | help='your account, e.g. kensanata@octogon.social') 354 | parser_content.add_argument("--combine", 355 | action="store_true", 356 | help="combine archives in case they are split") 357 | parser_content.set_defaults(command=meow.meow) 358 | 359 | 360 | args = parser.parse_args() 361 | 362 | try: 363 | if hasattr(args, "command"): 364 | if hasattr(args, "user") and args.user == 'all': 365 | for user in core.all_accounts(): 366 | print(user) 367 | args.user = user 368 | args.command(args) 369 | else: 370 | args.command(args) 371 | else: 372 | parser.print_help() 373 | except KeyboardInterrupt: 374 | pass 375 | 376 | if __name__ == "__main__": 377 | main() 378 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------