Files
mtusi2026lab2/app/routers/messages.py
T

61 lines
2.7 KiB
Python

import base64
import binascii
import json
from datetime import datetime
from uuid import UUID,uuid4
from fastapi import APIRouter,Depends,HTTPException,Query
from app.dependencies import current_user
from app.models.messages import CreateMessage,Message,MessagePage
from app.routers.chats import get_chat_row
from app.storage import db
router=APIRouter()
def encode_cursor(chat_id,row):
raw=json.dumps({'chat_id':str(chat_id),'created_at':row['created_at'].isoformat(),'id':str(row['id'])}).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip('=')
def decode_cursor(chat_id,cursor):
try:
raw=base64.b64decode(cursor+'='*(-len(cursor)%4),altchars=b'-_',validate=True)
data=json.loads(raw)
ts=datetime.fromisoformat(data['created_at'])
ident=UUID(data['id'])
if data['chat_id']!=str(chat_id) or ts.tzinfo is None:
raise ValueError('Wrong cursor')
return ts,ident
except (ValueError,KeyError,TypeError,UnicodeDecodeError,binascii.Error):
raise HTTPException(status_code=400,detail='Invalid cursor')
@router.post('/api/v1/chats/{chat_id}/messages',response_model=Message,status_code=201)
def create_message(chat_id:UUID,payload:CreateMessage,user=Depends(current_user)):
with db() as conn:
if get_chat_row(conn,chat_id,user['id']) is None:
raise HTTPException(status_code=404,detail='Chat not found')
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""",
(uuid4(),chat_id,user['id'],payload.text)).fetchone()
return row
@router.get('/api/v1/chats/{chat_id}/messages',response_model=MessagePage)
def list_messages(chat_id:UUID,limit:int=Query(default=50,ge=1,le=100),
cursor:str|None=Query(default=None,min_length=1),user=Depends(current_user)):
with db() as conn:
if get_chat_row(conn,chat_id,user['id']) is None:
raise HTTPException(status_code=404,detail='Chat not found')
if cursor is not None:
ts,ident=decode_cursor(chat_id,cursor)
rows=conn.execute("""SELECT id,chat_id,sender_id,text,created_at FROM messages
WHERE chat_id=%s AND (created_at,id)>(%s,%s)
ORDER BY created_at,id LIMIT %s""",(chat_id,ts,ident,limit+1)).fetchall()
else:
rows=conn.execute("""SELECT id,chat_id,sender_id,text,created_at FROM messages
WHERE chat_id=%s ORDER BY created_at,id LIMIT %s""",(chat_id,limit+1)).fetchall()
items=rows[:limit]
next_cursor=encode_cursor(chat_id,items[-1]) if len(rows)>limit else None
return {'items':items,'next_cursor':next_cursor}