1- from fastapi import APIRouter , Request , Response , Depends
2- from app .logic .data import check_new_data
1+ from fastapi import APIRouter , Request , Response , Depends , Form , UploadFile , File
2+ from app .logic .data import check_new_data , data_processor
33from app .utils .jwt import verify_jwt_token
44import asyncio
5+ import json
56
67router = APIRouter ()
78
@@ -12,13 +13,46 @@ async def get_data_longpoll(request: Request, response: Response, user=Depends(v
1213 if await request .is_disconnected ():
1314 # Don't attempt to check for new data if client disconnects before 30 seconds
1415 # This is crucial to perserve data as they get deleted after being read
15- return
16+ return Response (content = b'' , media_type = "application/octet-stream" )
17+
1618
17- messages = await asyncio .to_thread (check_new_data , user ["id" ])
18-
19- if messages :
20- return {"messages" : messages }
19+ data = await asyncio .to_thread (check_new_data , user ["id" ])
2120
21+ if data :
22+ return Response (content = data , media_type = "application/octet-stream" )
2223 await asyncio .sleep (1 )
2324
24- return {"messages" : []}
25+ return Response (content = b'' , media_type = "application/octet-stream" )
26+
27+
28+ @router .post ("/data/send" )
29+ async def send (metadata : str = Form (...), blob : UploadFile = File (...), user = Depends (verify_jwt_token )):
30+ user_id = user ["id" ]
31+
32+ metadata = json .loads (metadata )
33+
34+ if "metadata" not in metadata :
35+ raise HTTPException (status_code = 400 , detail = "Missing metadata" )
36+
37+ if "recipient" not in metadata ["metadata" ]:
38+ raise HTTPException (status_code = 400 , detail = "Missing recipient" )
39+
40+ recipient = metadata ["metadata" ]["recipient" ]
41+
42+ if (not recipient .isdigit ()) or len (recipient ) != 16 :
43+ raise HTTPException (status_code = 400 , detail = "Invalid recipient" )
44+
45+
46+ blob_data = await blob .read ()
47+ if not blob_data :
48+ raise HTTPException (status_code = 400 , detail = "Empty blob is not allowed" )
49+
50+ try :
51+ await asyncio .to_thread (data_processor , user_id , recipient , blob_data )
52+ except ValueError as e :
53+ raise HTTPException (status_code = 400 , detail = e )
54+
55+
56+
57+ return {"status" : "success" }
58+
0 commit comments