uncia/uncia/database/__init__.py

125 lines
2.9 KiB
Python

from datetime import datetime
from functools import partial
from izzylib import DotDict, boolean, logging
from izzylib.http_requests_client.signature import generate_rsa_key
from izzylib.sql import SqlDatabase, SqlSession
from izzylib.sql import SqlColumn as Column
from izzylib.sql.generic import OperationalError
from urllib.parse import urlparse
from . import get, put, delete
from ..config import config, dbconfig
tables = {
'config': [
Column('id'),
Column('key', 'text', nullable=False),
Column('value', 'text')
],
'inbox': [
Column('id'),
Column('domain', 'text', nullable=False),
Column('inbox', 'text', nullable=False, unique=True),
Column('actor', 'text', nullable=False, unique=True),
Column('followid', 'text'),
Column('timestamp')
],
'retry': [
Column('id'),
Column('msgid', 'text', nullable=False),
Column('inboxid', 'integer', nullable=False, fkey='inbox.id'),
Column('data', 'json', nullable=False),
Column('headers', 'json')
],
'user': [
Column('id'),
Column('handle', 'text', nullable=False, unique=True),
Column('username', 'text'),
Column('hash', 'text'),
Column('level', 'integer', nullable=False, default=0),
Column('timestamp')
],
'token': [
Column('id'),
Column('userid', 'integer', fkey='user.id'),
Column('code', 'text', nullable=False, unique=True),
Column('timestamp')
],
'whitelist': [
Column('id'),
Column('actor', 'text', nullable=False, unique=True)
],
'ban': [
Column('id'),
Column('handle', 'text'),
Column('domain', 'text'),
Column('reason', 'text')
]
}
class Session(SqlSession):
#get = get
#put = put
#delete = delete
config_defaults = dict(
version = (0, int),
pubkey = (None, str),
privkey = (None, str),
name = ('Uncia Relay', str),
description = ('Small and fast ActivityPub relay', str),
require_approval = (True, boolean),
email = (None, str),
show_domain_bans = (False, boolean),
show_user_bans = (False, boolean)
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.get = DotDict()
self.put = DotDict()
self.delete = DotDict()
self._set_commands('get', get)
self._set_commands('put', put)
self._set_commands('delete', delete)
def _set_commands(self, name, mod):
for method in dir(mod):
if method.startswith('cmd_'):
getattr(self, name)[method[4:]] = partial(getattr(mod, method), self)
db = SqlDatabase(
config.dbtype,
tables = tables,
session_class = Session,
**dbconfig
)
with db.session as s:
try:
version = s.get.config('version')
except OperationalError:
version = 0
if version == 0:
keys = generate_rsa_key()
db.create_database()
s.put.config('version', config.version)
s.put.config('pubkey', keys.pubkey)
s.put.config('privkey', keys.privkey)
elif version < config.version:
pass
#for domain in ['barkshark.xyz', 'chomp.life']:
#s.put.instance(f'https://{domain}/inbox', f'https://{domain}/actor')