import uuid from psycopg import errors from db import connection, iso from errors import ApiError from pagination import decode_cursor, page USER_COLUMNS = 'u.id, u.username, u.display_name, u.created_at' ATTACHMENT_IDS = ('ARRAY(SELECT ma.attachment_id FROM message_attachments ma ' 'WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids') MESSAGE_COLUMNS = 'm.id, m.chat_id, m.sender_id, m.text, m.created_at, ' + ATTACHMENT_IDS ATTACHMENT_COLUMNS = 'a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, a.status, a.created_at, a.updated_at' CHAT_SELECT = ('SELECT c.id, c.title, c.created_at, ' 'ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids ' 'FROM chats c ') def utf8(value): return value.encode('utf-8') def unicode(value): return bytes(value).decode('utf-8') def user_out(row): return {'id': str(row['id']), 'username': row['username'], 'display_name': unicode(row['display_name']), 'created_at': iso(row['created_at'])} def chat_out(row): return {'id': str(row['id']), 'title': unicode(row['title']), 'member_ids': [str(m) for m in row['member_ids']], 'created_at': iso(row['created_at'])} def message_out(row): return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']), 'text': unicode(row['text']), 'created_at': iso(row['created_at']), 'attachment_ids': [str(a) for a in row['attachment_ids']]} def attachment_out(row): return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'owner_id': str(row['owner_id']), 'filename': row['filename'], 'content_type': row['content_type'], 'size_bytes': row['size_bytes'], 'sha256': bytes(row['sha256']).hex(), 'status': row['status'], 'variants': [], 'error_code': None, 'created_at': iso(row['created_at']), 'updated_at': iso(row['updated_at'])} def create_user(username, display_name, password_hash): try: with connection() as conn: row = conn.execute( 'INSERT INTO users AS u (username, display_name, password_hash) VALUES (%s, %s, %s) ' 'RETURNING ' + USER_COLUMNS, (username, utf8(display_name), password_hash)).fetchone() except errors.UniqueViolation: raise ApiError(409, 'Имя пользователя уже занято') from None return user_out(row) def find_credentials(username): with connection() as conn: return conn.execute('SELECT ' + USER_COLUMNS + ', u.password_hash FROM users u WHERE u.username = %s', (username,)).fetchone() def create_session(user_id, token_hash, ttl_seconds): with connection() as conn: conn.execute('DELETE FROM sessions WHERE user_id = %s AND expires_at <= now()', (user_id,)) return conn.execute( 'INSERT INTO sessions (token_hash, user_id, expires_at) ' 'VALUES (%s, %s, now() + make_interval(secs => %s)) RETURNING expires_at', (token_hash, user_id, ttl_seconds)).fetchone()['expires_at'] def session_user(token_hash): with connection() as conn: return conn.execute( 'SELECT ' + USER_COLUMNS + ', s.expires_at FROM sessions s JOIN users u ON u.id = s.user_id ' 'WHERE s.token_hash = %s AND s.expires_at > now()', (token_hash,)).fetchone() def revoke_session(token_hash, keep_seconds): with connection() as conn: conn.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,)) conn.execute('INSERT INTO session_revocations (token_hash, expires_at) ' 'VALUES (%s, now() + make_interval(secs => %s)) ' 'ON CONFLICT (token_hash) DO UPDATE SET expires_at = EXCLUDED.expires_at', (token_hash, keep_seconds)) def pending_revocations(): with connection() as conn: conn.execute('DELETE FROM session_revocations WHERE expires_at <= now()') return [bytes(r['token_hash']) for r in conn.execute('SELECT token_hash FROM session_revocations').fetchall()] def clear_revocations(token_hashes): with connection() as conn: conn.execute('DELETE FROM session_revocations WHERE token_hash = ANY(%s)', (list(token_hashes),)) def create_chat(creator_id, title, member_ids): try: members = [str(uuid.UUID(m)) for m in member_ids] except ValueError: raise ApiError(400, 'Неизвестный участник чата') from None if len(set(members)) != len(members): raise ApiError(400, 'Участники не должны повторяться') if creator_id not in members: raise ApiError(400, 'Создатель должен быть участником чата') try: with connection() as conn, conn.transaction(): chat = conn.execute('INSERT INTO chats (title, created_by) VALUES (%s, %s) RETURNING id, title, created_at', (utf8(title), creator_id)).fetchone() conn.execute('INSERT INTO chat_members (chat_id, user_id, position) ' 'SELECT %s, member, position FROM unnest(%s::uuid[]) WITH ORDINALITY AS t(member, position)', (chat['id'], members)) except errors.ForeignKeyViolation: raise ApiError(400, 'Неизвестный участник чата') from None return chat_out({**chat, 'member_ids': members}) def get_chat(chat_id, user_id): with connection() as conn: row = conn.execute(CHAT_SELECT + 'JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s ' 'WHERE c.id = %s', (user_id, chat_id)).fetchone() if row is None: raise ApiError(404, 'Чат не найден') return chat_out(row) def list_chats(user_id, cursor, limit): scope = 'user:' + user_id sql = CHAT_SELECT + 'JOIN chat_members me ON me.chat_id = c.id WHERE me.user_id = %s ' params = [user_id] if cursor: sql += 'AND (c.created_at, c.id) > (%s, %s) ' params += decode_cursor(scope, cursor) sql += 'ORDER BY c.created_at, c.id LIMIT %s' with connection() as conn: rows = conn.execute(sql, params + [limit + 1]).fetchall() return page([chat_out(r) for r in rows], scope, limit) def is_member(conn, chat_id, user_id): return conn.execute('SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s', (chat_id, user_id)).fetchone() is not None def create_message(chat_id, sender_id, text, attachment_ids, key, request_hash, key_ttl_seconds): scope = 'POST /api/v1/chats/%s/messages' % chat_id with connection() as conn, conn.transaction(): conn.execute('DELETE FROM idempotency_keys WHERE user_id = %s AND created_at < now() - make_interval(secs => %s)', (sender_id, key_ttl_seconds)) claimed = conn.execute( 'INSERT INTO idempotency_keys (user_id, scope, key, request_hash) VALUES (%s, %s, %s, %s) ' 'ON CONFLICT DO NOTHING RETURNING 1', (sender_id, scope, key, request_hash)).fetchone() if claimed is None: if not is_member(conn, chat_id, sender_id): raise ApiError(404, 'Чат не найден') stored = conn.execute( 'SELECT k.request_hash, ' + MESSAGE_COLUMNS + ' ' 'FROM idempotency_keys k JOIN messages m ON m.id = k.message_id ' 'WHERE k.user_id = %s AND k.scope = %s AND k.key = %s', (sender_id, scope, key)).fetchone() if bytes(stored['request_hash']) != request_hash: raise ApiError(409, 'Idempotency-Key уже использован с другим запросом') return message_out(stored) row = conn.execute( 'INSERT INTO messages AS m (chat_id, sender_id, text) SELECT %s, %s, %s ' 'WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s) ' 'RETURNING m.id, m.chat_id, m.sender_id, m.text, m.created_at', (chat_id, sender_id, utf8(text), chat_id, sender_id)).fetchone() if row is None: raise ApiError(404, 'Чат не найден') if attachment_ids: found = conn.execute("SELECT count(*) AS n FROM attachments WHERE id = ANY(%s::uuid[]) " "AND chat_id = %s AND status = 'ready'", (attachment_ids, chat_id)).fetchone()['n'] if found != len(attachment_ids): raise ApiError(404, 'Вложение не найдено в этом чате') conn.execute('INSERT INTO message_attachments (message_id, attachment_id, position) ' 'SELECT %s, attachment, position FROM unnest(%s::uuid[]) WITH ORDINALITY AS t(attachment, position)', (row['id'], attachment_ids)) row = dict(row, attachment_ids=attachment_ids) conn.execute('UPDATE idempotency_keys SET message_id = %s WHERE user_id = %s AND scope = %s AND key = %s', (row['id'], sender_id, scope, key)) return message_out(row) def list_messages(chat_id, user_id, cursor, limit): scope = 'chat:' + chat_id sql = 'SELECT ' + MESSAGE_COLUMNS + ' FROM messages m WHERE m.chat_id = %s ' params = [chat_id] if cursor: sql += 'AND (m.created_at, m.id) > (%s, %s) ' params += decode_cursor(scope, cursor) sql += 'ORDER BY m.created_at, m.id LIMIT %s' with connection() as conn: if not is_member(conn, chat_id, user_id): raise ApiError(404, 'Чат не найден') rows = conn.execute(sql, params + [limit + 1]).fetchall() return page([message_out(r) for r in rows], scope, limit) def start_attachment(attachment_id, chat_id, owner_id, filename, content_type, size, sha256, object_key): with connection() as conn: if not is_member(conn, chat_id, owner_id): raise ApiError(404, 'Чат не найден') conn.execute("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, " "object_key, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'uploading')", (attachment_id, chat_id, owner_id, filename, content_type, size, sha256, object_key)) def finish_attachment(attachment_id): with connection() as conn: row = conn.execute("UPDATE attachments AS a SET status = 'ready', updated_at = clock_timestamp() " "WHERE a.id = %s AND a.status = 'uploading' RETURNING " + ATTACHMENT_COLUMNS, (attachment_id,)).fetchone() if row is None: raise ApiError(503, 'Загрузка не завершена, повторите') return attachment_out(row) def forget_attachment(attachment_id): with connection() as conn: conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'uploading'", (attachment_id,)) def check_member(chat_id, user_id): with connection() as conn: if not is_member(conn, chat_id, user_id): raise ApiError(404, 'Чат не найден') def get_attachment(attachment_id, user_id): with connection() as conn: row = conn.execute("SELECT " + ATTACHMENT_COLUMNS + " FROM attachments a " "JOIN chat_members me ON me.chat_id = a.chat_id AND me.user_id = %s " "WHERE a.id = %s AND a.status = 'ready'", (user_id, attachment_id)).fetchone() if row is None: raise ApiError(404, 'Вложение не найдено') return row