forked from mtusi2026/mtusi2026lab6
205 lines
8.6 KiB
Python
205 lines
8.6 KiB
Python
"""Доступ к данным. Добавлены queued-статусы, variants, json с variants."""
|
||
import uuid
|
||
|
||
from . import cursor
|
||
from .errors import bad_request, not_found
|
||
from .sessions import fmt_ts
|
||
|
||
|
||
# ---------- пользователи / чаты (без изменений) ----------
|
||
|
||
def username_exists(conn, username):
|
||
return conn.execute("SELECT 1 FROM users WHERE username = %s", (username,)).fetchone() is not None
|
||
|
||
|
||
def insert_user(conn, username, display_name, password_hash):
|
||
return conn.execute(
|
||
"""INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)
|
||
RETURNING id, username, display_name, created_at""",
|
||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||
|
||
|
||
def user_for_login(conn, username):
|
||
return conn.execute(
|
||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
|
||
(username,)).fetchone()
|
||
|
||
|
||
def update_password_hash(conn, user_id, new_hash):
|
||
conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (new_hash, user_id))
|
||
|
||
|
||
def chat_json(row):
|
||
return {"id": str(row["id"]), "title": row["title"],
|
||
"member_ids": [str(x) for x in row["member_ids"]],
|
||
"created_at": fmt_ts(row["created_at"])}
|
||
|
||
|
||
def create_chat(conn, creator_id, title, member_ids, check_members=True):
|
||
if check_members:
|
||
found = conn.execute("SELECT count(*) AS n FROM users WHERE id = ANY(%s)",
|
||
(member_ids,)).fetchone()["n"]
|
||
if found != len(member_ids):
|
||
raise bad_request("Неизвестный участник чата")
|
||
chat = conn.execute(
|
||
"INSERT INTO chats (id, title, created_by) VALUES (%s, %s, %s) RETURNING id, title, created_at",
|
||
(uuid.uuid4(), title, creator_id)).fetchone()
|
||
conn.execute("INSERT INTO chat_members (chat_id, user_id) SELECT %s, unnest(%s::uuid[])",
|
||
(chat["id"], member_ids))
|
||
chat["member_ids"] = sorted(member_ids)
|
||
return chat
|
||
|
||
|
||
def get_chat(conn, chat_id, user_id):
|
||
return conn.execute(
|
||
"""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.user_id) AS member_ids
|
||
FROM chats c
|
||
WHERE c.id = %s AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = %s)""",
|
||
(chat_id, user_id)).fetchone()
|
||
|
||
|
||
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 list_chats(conn, user_id, after, limit):
|
||
base = """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.user_id) AS member_ids
|
||
FROM chat_members me JOIN chats c ON c.id = me.chat_id
|
||
WHERE me.user_id = %s"""
|
||
params = [user_id]
|
||
if after:
|
||
base += " AND (c.created_at, c.id) > (%s, %s)"
|
||
params += list(after)
|
||
rows = conn.execute(base + " ORDER BY c.created_at, c.id LIMIT %s", params + [limit + 1]).fetchall()
|
||
page, more = rows[:limit], len(rows) > limit
|
||
nxt = cursor.encode("chats", user_id, page[-1]["created_at"], page[-1]["id"]) if more else None
|
||
return [chat_json(r) for r in page], nxt
|
||
|
||
|
||
# ---------- сообщения (без изменений логики) ----------
|
||
|
||
def _message_json(row):
|
||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]),
|
||
"text": row["text"], "created_at": fmt_ts(row["created_at"]),
|
||
"attachment_ids": [str(x) for x in (row.get("attachment_ids") or [])]}
|
||
|
||
|
||
def message_json(row):
|
||
return _message_json(row)
|
||
|
||
|
||
def insert_message(conn, chat_id, sender_id, text, attachment_ids=None):
|
||
attachment_ids = attachment_ids or []
|
||
if attachment_ids:
|
||
rows = conn.execute(
|
||
"""SELECT id, status FROM attachments WHERE id = ANY(%s) AND chat_id = %s""",
|
||
(attachment_ids, chat_id)).fetchall()
|
||
by_id = {r["id"]: r for r in rows}
|
||
if len(by_id) != len(attachment_ids):
|
||
raise not_found()
|
||
for att_id in attachment_ids:
|
||
if by_id[att_id]["status"] == "failed":
|
||
raise bad_request("Нельзя прикрепить failed-вложение")
|
||
# queued/processing разрешены с lab5 — можно ссылаться до готовности.
|
||
row = conn.execute(
|
||
"""INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)
|
||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||
(uuid.uuid4(), chat_id, sender_id, text)).fetchone()
|
||
if attachment_ids:
|
||
conn.execute(
|
||
"""INSERT INTO message_attachments (message_id, attachment_id, position)
|
||
SELECT %s, unnest(%s::uuid[]), generate_subscripts(%s::uuid[], 1) - 1""",
|
||
(row["id"], attachment_ids, attachment_ids))
|
||
row["attachment_ids"] = attachment_ids
|
||
return row
|
||
|
||
|
||
def list_messages(conn, chat_id, after, limit):
|
||
sql = """SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma
|
||
WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids
|
||
FROM messages m WHERE m.chat_id = %s"""
|
||
params = [chat_id]
|
||
if after:
|
||
sql += " AND (m.created_at, m.id) > (%s, %s)"
|
||
params += list(after)
|
||
rows = conn.execute(sql + " ORDER BY m.created_at, m.id LIMIT %s", params + [limit + 1]).fetchall()
|
||
page, more = rows[:limit], len(rows) > limit
|
||
nxt = cursor.encode("messages", chat_id, page[-1]["created_at"], page[-1]["id"]) if more else None
|
||
return [_message_json(r) for r in page], nxt
|
||
|
||
|
||
# ---------- вложения lab5 ----------
|
||
|
||
def insert_attachment_queued(conn, chat_id, owner_id, filename, content_type,
|
||
size_bytes, sha256, staging_key):
|
||
return conn.execute(
|
||
"""INSERT INTO attachments
|
||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||
staging_key, status)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'queued')
|
||
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||
status, error_code, created_at, updated_at""",
|
||
(uuid.uuid4(), chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key)
|
||
).fetchone()
|
||
|
||
|
||
def mark_attachment_failed(conn, attachment_id, error_code):
|
||
conn.execute(
|
||
"""UPDATE attachments
|
||
SET status='failed', error_code=%s, updated_at=clock_timestamp()
|
||
WHERE id=%s AND status IN ('queued','processing')""",
|
||
(error_code, attachment_id))
|
||
|
||
|
||
def get_attachment_for_member(conn, attachment_id, user_id):
|
||
return conn.execute(
|
||
"""SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||
a.object_key, a.staging_key, a.status, a.error_code, a.created_at, a.updated_at
|
||
FROM attachments a
|
||
WHERE a.id = %s
|
||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""",
|
||
(attachment_id, user_id)).fetchone()
|
||
|
||
|
||
def get_variant(conn, attachment_id, variant_name):
|
||
return conn.execute(
|
||
"""SELECT attachment_id, name, object_key, content_type, size_bytes, width, height, sha256
|
||
FROM attachment_variants WHERE attachment_id = %s AND name = %s""",
|
||
(attachment_id, variant_name)).fetchone()
|
||
|
||
|
||
def list_variants(conn, attachment_id):
|
||
return conn.execute(
|
||
"""SELECT name, content_type, size_bytes, width, height, sha256
|
||
FROM attachment_variants WHERE attachment_id = %s ORDER BY name""",
|
||
(attachment_id,)).fetchall()
|
||
|
||
|
||
def attachment_json(row, variants=None):
|
||
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": row["sha256"],
|
||
"status": row["status"],
|
||
"variants": [
|
||
{
|
||
"name": v["name"],
|
||
"content_type": v["content_type"],
|
||
"size_bytes": v["size_bytes"],
|
||
"width": v["width"],
|
||
"height": v["height"],
|
||
"sha256": v["sha256"],
|
||
} for v in (variants or [])
|
||
],
|
||
"error_code": row["error_code"],
|
||
"created_at": fmt_ts(row["created_at"]),
|
||
"updated_at": fmt_ts(row["updated_at"]),
|
||
} |