diff --git a/masto-mutuals.py b/masto-mutuals.py index dafbeca..4e77a1e 100644 --- a/masto-mutuals.py +++ b/masto-mutuals.py @@ -4,50 +4,73 @@ from mastodon import Mastodon import configparser import xdg.BaseDirectory +def fetch_user_ids(func, idval=user_id): + user_ids = [] + # This reads like it discards the first page of results, but fetch_remaining includes the + # original results as well as the titular "remaining" ones. + fetched_users = mastodon.fetch_remaining(func(idval)) + for user in fetched_users: + user_ids.append(user['id']) + return user_ids + config_file_path = '%s/masto-mutuals/config.txt' % xdg.BaseDirectory.xdg_config_home config = configparser.ConfigParser() config.read(config_file_path) -# TODO: if config file is empty, this should write defaults into a file. +# TODO: if config file is empty, this should write defaults into the file and throw an errorS +# correctly. + +if not config['ACCOUNT_DATA']['access_token']: + print('Error: An access token is required.') + exit() + +if not config['ACCOUNT_DATA']['instance_url']: + print('Error: An instance url is required.') + exit() + +if config['ACCOUNT_DATA']['list_name']: + list_name = config['ACCOUNT_DATA']['list_name'] +else: + list_name = 'mutuals' mastodon = Mastodon( - access_token = config['ACCOUNT_DATA']['access_token'] + access_token = config['ACCOUNT_DATA']['access_token'], api_base_url = config['ACCOUNT_DATA']['instance_url'] ) user_id = mastodon.me()['id'] -def fetch_user_ids(func, idval=user_id): - user_ids = [] - initial = True - while True: - users = func(idval) if initial else mastodon.fetch_next(users) - initial = False - if users is None or len(users)==0: - break - for user in users: - user_ids.append(user['id']) - return user_ids - +print("Getting following list.") followed_ids = fetch_user_ids(mastodon.account_following) +print('You follow %s accounts.' % str(len(followed_ids))) +print("Getting followed list.") follower_ids = fetch_user_ids(mastodon.account_followers) +print('You are followed by %s accounts.' % str(len(follower_ids))) mutual_ids = [i for i in followed_ids if i in followed_ids and i in follower_ids] list_id = None for l in mastodon.lists(): - if l['title'] == 'mutuals': + if l['title'] == list_name: list_id = l['id'] if list_id is not None: break if list_id is None: - l = mastodon.list_create('mutuals') + l = mastodon.list_create(list_name) list_id = l['id'] list_ids = fetch_user_ids(mastodon.list_accounts, idval=list_id) toadd_ids = [i for i in mutual_ids if i not in list_ids] torm_ids = [i for i in list_ids if i not in mutual_ids] +list_changed = False if len(toadd_ids) > 0: + list_changed = True mastodon.list_accounts_add(list_id, toadd_ids) if len(torm_ids) > 0: + list_changed = True mastodon.list_accounts_delete(list_id, torm_ids) + +if list_changed: + print('%s list updated.' % list_name) +else: + print('%s list unchanged.' % list_name)