# import tomllib import argparse import json import logging import requests import tomli from models import Instance def load_local_blocklist(filename: str) -> [Instance]: with open(filename, "rb") as f: data = tomli.load(f) instances = [] for instance_dict in data["instances"]: instance = Instance(instance_dict) instances.append(instance) for instance in instances: print(instance) return instances def blocklist_json_to_instances(blocklist_json: str): instances = [] for i in blocklist_json: instances.append(Instance(i)) return instances def load_remote_blocklist(server: str, token: str): headers = { f'Authorization': f'Bearer {token}', } response = requests.get(f'https://{server}/api/v1/admin/domain_blocks', headers=headers) if response.status_code == 200: blocklist_json = json.loads(response.content) return blocklist_json_to_instances(blocklist_json) else: raise ConnectionError(f"Could not connect to the server ({response.status_code}: {response.reason})") def cli(): parser = argparse.ArgumentParser(description='Deploy blocklist updates to a mastodon server') parser.add_argument('action', choices=['diff', 'deploy'], help="Either use 'diff' to check the difference between current blocks and future blocks or 'deploy'.") parser.add_argument('-s', '--server', help="The address of the server where you want to deploy (e.g. " "mastodon.social)") parser.add_argument('-t', '--token', help="Authorization token") parser.add_argument('-i', '--input-file', help="The blocklist to use") parser.add_argument('-r', '--remote-blocklist', help="The remote blocklist as json for debugging reasons") args = parser.parse_args() logging.basicConfig(level=logging.WARN) if args.input_file: blocklist_filename = args.input_file else: blocklist_filename = "blocklist.toml" local_blocklist = load_local_blocklist(blocklist_filename) if args.remote_blocklist: with open(args.remote_blocklist) as f: remote_blocklist = blocklist_json_to_instances(json.load(f)) else: remote_blocklist = load_remote_blocklist(server=args.server, token=args.token) if args.action == "diff": Instance.show_diffs(local_blocklist, remote_blocklist) elif args.action == "deploy": diffs = Instance.list_diffs(local_blocklist, remote_blocklist) Instance.apply_blocks_from_diff(diffs, args.server, args.token) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) cli()