#!/usr/bin/env python3 import logging from json import loads from os import environ from subprocess import check_output from sys import exit import psycopg2 PSQL_HOST = environ['DB_HOSTNAME'] PSQL_USER = environ['DB_USERNAME'] PSQL_PASS = environ['DB_PASSWORD'] PSQL_DB = environ['DB_DATABASE_NAME'] logging.basicConfig(level=logging.INFO) docker_networks = loads(check_output(['docker', 'network', 'inspect', 'aaarghhh'])) container_ip = None # why the fuck is this a list of networks, even though we have to provide # a network name to inspect ... for network in docker_networks: if network['Name'] != 'aaarghhh': continue for _, container in network['Containers'].items(): if container['Name'] == PSQL_HOST: container_ip = container['IPv4Address'].split('/')[0] if not container_ip: logging.error(f'could not find ip address for container {PSQL_HOST=} in json') logging.debug(f'{docker_networks=}') exit(0) logging.debug(f'{PSQL_HOST=} {container_ip=}') conn = psycopg2.connect( dbname=PSQL_DB, host=container_ip, password=PSQL_PASS, user=PSQL_USER, ) with conn: with conn.cursor() as cur: cur.execute('SELECT "id","ownerId","albumName" FROM albums;') albums = { i[0]: { 'owner': i[1], 'name': i[2], } for i in cur.fetchall() } logging.debug(f'{albums=}') with conn.cursor() as cur: cur.execute('SELECT "id","name" FROM users;') users = { i[0]: i[1] for i in cur.fetchall() } logging.debug(f'{users=}') for album_id, album in albums.items(): log = logging.getLogger(album["name"]) with conn: with conn.cursor() as cur: cur.execute('SELECT "usersId" FROM albums_shared_users_users WHERE "albumsId" = %s;', (album_id,)) album_shares = [i[0] for i in cur.fetchall()] log.info(f'album is shared with {len(album_shares)} users') log.debug(f'{album_shares=}') for user_id, user_name in users.items(): if user_id == album['owner'] or user_id in album_shares: continue log.info(f'sharing album with user {user_name}') try: with conn.cursor() as cur: cur.execute( 'INSERT INTO albums_shared_users_users ("albumsId","usersId","role") VALUES (%s, %s, %s);', (album_id, user_id, 'viewer'), ) except Exception: log.exception('failure while creating share') conn.close()