#!/usr/bin/env python3
import json
import sys
import requests
import time
import shelve

# those stupid pigfuckers at twitter don't include your followers or
# following lists in your twitter data export by username, only by numeric
# userid, so you can't easily take your social graph with you, if you e.g.
# want to use nitter to RSS follow certain twitter feeds.

# additionally, the export includes your twitter user lists: but only the
# names and IDs of the lists - *none of the actual userids or usernames that
# comprise the lists*.  just that you have a list of id x and name y, not
# who's actually on it.

# twitter are fucking assholes.
# i deleted my account right after this export.
# https://sneak.berlin/20201031/goodbye-twitter/

EXPORT_DATE = "2020-11-08T01:07:55Z"

# thanks random php person
CONVERTER_URL = "https://tweeterid.com/ajax.php"

def main():
    followers = json.load(open('followers.json'))
    followings = json.load(open('followings.json'))

    with shelve.open('usernamedb') as db:
        def save_username(id,username):
            if username != "error":
                db[str(id)] = username
                print("saved db[%s]='%s'" % (id, username))
            else:
                raise ValueError("api error");

        for following in followings:
            id = following['following']['accountId']
            if db.get(str(id),None) is None:
                time.sleep(1)
                username = requests.post(CONVERTER_URL, { "input": id }).text.strip()
                save_username(id,username)
            else:
                username = db.get(str(id))
                print("already had db[%s]=%s" % (id, username))


        for follower in followers:
            id = follower['follower']['accountId']
            if db.get(str(id),None) is None:
                time.sleep(1)
                username = requests.post(CONVERTER_URL, { "input": id }).text.strip()
                save_username(id,username)
            else:
                username = db.get(str(id))
                print("already had db[%s]=%s" % (id, username))

if __name__ == "__main__":
    main()
