54 lines
2.3 KiB
Python
54 lines
2.3 KiB
Python
"""Use cases; independent of Flask and the concrete storage adapter."""
|
|
import re
|
|
from .domain import fields, string, uuid_value, invalid, ApiError
|
|
from .repository import Repository
|
|
from .pagination import Pagination
|
|
from .security import Authentication
|
|
|
|
|
|
class Messenger:
|
|
def __init__(self, repository: Repository, session_ttl=3600):
|
|
self.repository = repository
|
|
self.pagination = Pagination(repository.cursor_key())
|
|
self.auth = Authentication(repository, session_ttl)
|
|
|
|
def register(self, body):
|
|
fields(body, ('username', 'display_name', 'password'))
|
|
username = string(body['username'], 32)
|
|
if not re.fullmatch(r'[a-z0-9_]{3,32}', username):
|
|
invalid('Invalid username')
|
|
display_name = string(body['display_name'], 100)
|
|
password = self.auth.password(body['password'])
|
|
return self.repository.create_user(username, display_name, self.auth.hasher.hash(password))
|
|
|
|
def create_chat(self, actor, body):
|
|
fields(body, ('title', 'member_ids'))
|
|
title = string(body['title'], 100)
|
|
members = body['member_ids']
|
|
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
|
invalid('Invalid member list')
|
|
members = [uuid_value(m) for m in members]
|
|
if len(set(members)) != len(members):
|
|
invalid('Duplicate members')
|
|
return self.repository.create_chat(actor, title, members)
|
|
|
|
def chat(self, actor, chat_id):
|
|
return self.repository.chat(actor, uuid_value(chat_id))
|
|
|
|
def send(self, actor, chat_id, body):
|
|
self.chat(actor, chat_id)
|
|
fields(body, ('text',))
|
|
return self.repository.create_message(actor, uuid_value(chat_id), string(body['text'], 4000))
|
|
|
|
def chats(self, actor, limit, cursor):
|
|
scope = 'chats:' + actor
|
|
limit, after = self.pagination.decode(scope, limit, cursor)
|
|
return self.pagination.page(self.repository.chats(actor, limit + 1, after), scope, limit)
|
|
|
|
def history(self, actor, chat_id, limit, cursor):
|
|
chat_id = uuid_value(chat_id)
|
|
self.repository.chat(actor, chat_id)
|
|
scope = 'messages:' + chat_id
|
|
limit, after = self.pagination.decode(scope, limit, cursor)
|
|
return self.pagination.page(self.repository.messages(actor, chat_id, limit + 1, after), scope, limit)
|