from getpass import getpass from time import sleep import json import nacl.secret import nacl.utils from arango import ArangoClient from config import * # Starta koppling till arangodb # Avkryptera lösen till arango try: # Om scriptet körs på Macbook finns löseordet i en fil with open('password_arango.txt') as f: pwd = f.readline() except FileNotFoundError: for i in range(0, 6, 1): if i == 5: exit() try: key = "sssladnnklja" + getpass() pwd = ( nacl.secret.SecretBox(key.encode()) .decrypt(pwd_arango, encoder=nacl.encoding.HexEncoder) .decode("utf-8") ) break except: print("Fel lösenord.") sleep(1) db = ArangoClient(hosts=host_arango).db(db_arango, username=user_arango, password=pwd) from helpers import now def checked_members(): cursor = db.aql.execute( """ FOR doc IN members FILTER doc.checked == true RETURN doc._key """ ) members_checked = set([doc for doc in cursor]) return members_checked def count_docs(col): cursor = db.aql.execute( """ FOR doc IN @@col COLLECT WITH COUNT INTO length RETURN length """, bind_vars={"@col": col} ) return cursor.next() def report_blocked(profile, users): db.insert_document({ '_id':f'reports/{now()}', 'profile': profile.name, 'users': [user.username for user in users], }) def write_report(users, pictures): db.insert_document({ '_id':f'reports/{now()}', 'users': [user.username for user in users], 'members': count_docs('members'), 'total_picture_reactions':count_docs('picture_reactions'), 'pictures':count_docs('pictures'), 'new_pictures': pictures }) def get_profile(created=True): """ Hämtar profil från profiles """ cursor = db.aql.execute( """ FOR doc IN profiles FILTER doc.in_use == false FILTER doc.created == @created RETURN doc """, bind_vars={'created': created} ) return cursor.next() def friends_of_user(user): """Returnernar användare som reagerat på user:s bilder""" cursor = db.aql.execute( """ FOR doc IN picture_reactions FILTER doc._to == @user RETURN DISTINCT doc._from """, bind_vars={"user": "members/" + user}, ) return [doc[8:] for doc in cursor] def remove_profile(profile): db.collection("profiles").delete(profile['_key'], silent=True, ignore_missing=True) _print(profile.name, f'{profile.name} blockerad och borttagen {now()}.' ) # TODO #2 Bättre funktion för backup av databasen def backup(db): """Skapar en json-backup för specificerade collections. Args: db: databaskoppling till aktuell databas """ d = {} for col in ['members', 'pictures', 'picture_reactions', 'profiles']: l = [] for doc in db.collection(col).all(): l.append(doc) d[col] = l with open('data/backup.json', 'w') as f: json.dump(d, f) print(f'Senaste backup: {now()}') db = ArangoClient(hosts=host_arango).db(db_arango, username=user_arango, password=pwd)