53 lines
2.3 KiB
Python
53 lines
2.3 KiB
Python
from uuid import UUID, uuid4
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from app.dependencies import current_user
|
|
from app.models.chats import Chat, ChatPage, CreateChat
|
|
from app.storage import db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def get_chat_row(conn, chat_id, user_id):
|
|
return conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
|
JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s""",
|
|
(chat_id,user_id)).fetchone()
|
|
|
|
|
|
def chat_output(conn,row):
|
|
members=conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id',(row['id'],)).fetchall()
|
|
return {**row, 'member_ids':[m['user_id'] for m in members]}
|
|
|
|
|
|
@router.post('/api/v1/chats', response_model=Chat, status_code=201)
|
|
def create_chat(payload:CreateChat,user=Depends(current_user)):
|
|
if user['id'] not in payload.member_ids:
|
|
raise HTTPException(status_code=400,detail='Creator must be a chat member')
|
|
with db() as conn:
|
|
rows=conn.execute('SELECT id FROM users WHERE id = ANY(%s)',(payload.member_ids,)).fetchall()
|
|
if len(rows)!=len(payload.member_ids):
|
|
raise HTTPException(status_code=400,detail='Unknown member')
|
|
chat=conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
|
|
(uuid4(),payload.title)).fetchone()
|
|
for member in payload.member_ids:
|
|
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',(chat['id'],member))
|
|
return chat_output(conn,chat)
|
|
|
|
|
|
@router.get('/api/v1/chats',response_model=ChatPage)
|
|
def list_chats(limit:int=Query(default=50,ge=1,le=100),user=Depends(current_user)):
|
|
with db() as conn:
|
|
rows=conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
|
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
|
|
ORDER BY c.created_at,c.id LIMIT %s""",(user['id'],limit+1)).fetchall()
|
|
items=[chat_output(conn,row) for row in rows[:limit]]
|
|
return {'items':items,'next_cursor':None}
|
|
|
|
|
|
@router.get('/api/v1/chats/{chat_id}',response_model=Chat)
|
|
def get_chat(chat_id:UUID,user=Depends(current_user)):
|
|
with db() as conn:
|
|
row=get_chat_row(conn,chat_id,user['id'])
|
|
if row is None:
|
|
raise HTTPException(status_code=404,detail='Chat not found')
|
|
return chat_output(conn,row)
|