Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 4 |
-
from fastapi.staticfiles import StaticFiles
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
-
# Allow CORS for development
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
allow_origins=["*"],
|
|
@@ -16,80 +18,200 @@ app.add_middleware(
|
|
| 16 |
allow_headers=["*"],
|
| 17 |
)
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
if
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
|
|
|
|
|
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import uuid
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
|
|
|
| 13 |
app.add_middleware(
|
| 14 |
CORSMiddleware,
|
| 15 |
allow_origins=["*"],
|
|
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
+
# In-memory database (for demo purposes)
|
| 22 |
+
users_db = {}
|
| 23 |
+
chats_db = {}
|
| 24 |
+
messages_db = {}
|
| 25 |
+
|
| 26 |
+
# Helper functions
|
| 27 |
+
def save_data():
|
| 28 |
+
with open('users.json', 'w') as f:
|
| 29 |
+
json.dump(users_db, f)
|
| 30 |
+
with open('chats.json', 'w') as f:
|
| 31 |
+
json.dump(chats_db, f)
|
| 32 |
+
with open('messages.json', 'w') as f:
|
| 33 |
+
json.dump(messages_db, f)
|
| 34 |
+
|
| 35 |
+
def load_data():
|
| 36 |
+
global users_db, chats_db, messages_db
|
| 37 |
+
if os.path.exists('users.json'):
|
| 38 |
+
with open('users.json', 'r') as f:
|
| 39 |
+
users_db = json.load(f)
|
| 40 |
+
if os.path.exists('chats.json'):
|
| 41 |
+
with open('chats.json', 'r') as f:
|
| 42 |
+
chats_db = json.load(f)
|
| 43 |
+
if os.path.exists('messages.json'):
|
| 44 |
+
with open('messages.json', 'r') as f:
|
| 45 |
+
messages_db = json.load(f)
|
| 46 |
+
|
| 47 |
+
load_data()
|
| 48 |
+
|
| 49 |
+
# Request Models
|
| 50 |
+
class CreateUserRequest(BaseModel):
|
| 51 |
+
username: str
|
| 52 |
+
email: str
|
| 53 |
+
|
| 54 |
+
class SendMessageRequest(BaseModel):
|
| 55 |
+
sender_id: str
|
| 56 |
+
receiver_id: Optional[str] = None
|
| 57 |
+
chat_id: Optional[str] = None
|
| 58 |
+
content: str
|
| 59 |
+
|
| 60 |
+
class CreateGroupRequest(BaseModel):
|
| 61 |
+
creator_id: str
|
| 62 |
+
group_name: str
|
| 63 |
+
participants: List[str]
|
| 64 |
+
|
| 65 |
+
class UpdatePresenceRequest(BaseModel):
|
| 66 |
+
user_id: str
|
| 67 |
+
online: bool
|
| 68 |
+
|
| 69 |
+
# API Endpoints
|
| 70 |
+
@app.post("/api/create_user")
|
| 71 |
+
async def create_user(data: CreateUserRequest):
|
| 72 |
+
user_id = str(uuid.uuid4())
|
| 73 |
+
users_db[user_id] = {
|
| 74 |
+
'username': data.username,
|
| 75 |
+
'email': data.email,
|
| 76 |
+
'online': False,
|
| 77 |
+
'last_seen': None,
|
| 78 |
+
'created_at': datetime.now().isoformat()
|
| 79 |
+
}
|
| 80 |
+
save_data()
|
| 81 |
+
return {"user_id": user_id, "status": "success"}
|
| 82 |
+
|
| 83 |
+
@app.get("/api/get_user/{user_id}")
|
| 84 |
+
async def get_user(user_id: str):
|
| 85 |
+
if user_id in users_db:
|
| 86 |
+
return {"user": users_db[user_id], "status": "success"}
|
| 87 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 88 |
+
|
| 89 |
+
@app.post("/api/send_message")
|
| 90 |
+
async def send_message(data: SendMessageRequest):
|
| 91 |
+
message_id = str(uuid.uuid4())
|
| 92 |
+
timestamp = datetime.now().isoformat()
|
| 93 |
+
chat_id = data.chat_id
|
| 94 |
+
|
| 95 |
+
if not chat_id:
|
| 96 |
+
participants = sorted([data.sender_id, data.receiver_id])
|
| 97 |
+
chat_id = 'private_' + '_'.join(participants)
|
| 98 |
+
if chat_id not in chats_db:
|
| 99 |
+
chats_db[chat_id] = {
|
| 100 |
+
'type': 'private',
|
| 101 |
+
'participants': participants,
|
| 102 |
+
'created_at': timestamp
|
| 103 |
+
}
|
| 104 |
+
elif chat_id not in chats_db:
|
| 105 |
+
raise HTTPException(status_code=404, detail="Chat not found")
|
| 106 |
+
|
| 107 |
+
messages_db[message_id] = {
|
| 108 |
+
'chat_id': chat_id,
|
| 109 |
+
'sender_id': data.sender_id,
|
| 110 |
+
'content': data.content,
|
| 111 |
+
'timestamp': timestamp,
|
| 112 |
+
'status': 'sent'
|
| 113 |
+
}
|
| 114 |
+
save_data()
|
| 115 |
+
return {"message_id": message_id, "status": "success"}
|
| 116 |
+
|
| 117 |
+
@app.get("/api/get_messages")
|
| 118 |
+
async def get_messages(chat_id: str, user_id: str):
|
| 119 |
+
if chat_id not in chats_db:
|
| 120 |
+
raise HTTPException(status_code=404, detail="Chat not found")
|
| 121 |
+
if user_id not in chats_db[chat_id]['participants']:
|
| 122 |
+
raise HTTPException(status_code=403, detail="Unauthorized")
|
| 123 |
+
|
| 124 |
+
chat_messages = [msg for msg in messages_db.values() if msg['chat_id'] == chat_id]
|
| 125 |
+
chat_messages.sort(key=lambda x: x['timestamp'])
|
| 126 |
+
|
| 127 |
+
for msg in chat_messages:
|
| 128 |
+
if msg['sender_id'] != user_id and msg['status'] == 'sent':
|
| 129 |
+
msg['status'] = 'delivered'
|
| 130 |
+
|
| 131 |
+
save_data()
|
| 132 |
+
return {"messages": chat_messages}
|
| 133 |
+
|
| 134 |
+
@app.get("/api/get_user_chats")
|
| 135 |
+
async def get_user_chats(user_id: str):
|
| 136 |
+
if user_id not in users_db:
|
| 137 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 138 |
+
|
| 139 |
+
user_chats = []
|
| 140 |
+
for chat_id, chat in chats_db.items():
|
| 141 |
+
if user_id in chat['participants']:
|
| 142 |
+
chat_messages = [msg for msg in messages_db.values() if msg['chat_id'] == chat_id]
|
| 143 |
+
chat_messages.sort(key=lambda x: x['timestamp'])
|
| 144 |
+
last_message = chat_messages[-1] if chat_messages else None
|
| 145 |
+
|
| 146 |
+
if chat['type'] == 'private':
|
| 147 |
+
other_user_id = [uid for uid in chat['participants'] if uid != user_id][0]
|
| 148 |
+
chat_name = users_db.get(other_user_id, {}).get('username', f'User {other_user_id[:4]}')
|
| 149 |
+
else:
|
| 150 |
+
chat_name = chat.get('group_name', 'Group Chat')
|
| 151 |
+
|
| 152 |
+
user_chats.append({
|
| 153 |
+
'chat_id': chat_id,
|
| 154 |
+
'type': chat['type'],
|
| 155 |
+
'name': chat_name,
|
| 156 |
+
'participants': chat['participants'],
|
| 157 |
+
'last_message': last_message,
|
| 158 |
+
'created_at': chat['created_at']
|
| 159 |
+
})
|
| 160 |
+
|
| 161 |
+
user_chats.sort(key=lambda x: x['last_message']['timestamp'] if x['last_message'] else x['created_at'], reverse=True)
|
| 162 |
+
return {"chats": user_chats}
|
| 163 |
+
|
| 164 |
+
@app.post("/api/create_group")
|
| 165 |
+
async def create_group(data: CreateGroupRequest):
|
| 166 |
+
user_id = data.creator_id
|
| 167 |
+
group_name = data.group_name
|
| 168 |
+
participants = data.participants
|
| 169 |
+
|
| 170 |
+
if user_id not in participants:
|
| 171 |
+
participants.append(user_id)
|
| 172 |
+
|
| 173 |
+
if len(participants) < 2:
|
| 174 |
+
raise HTTPException(status_code=400, detail="Group must have at least 2 participants")
|
| 175 |
+
|
| 176 |
+
chat_id = 'group_' + str(uuid.uuid4())
|
| 177 |
+
timestamp = datetime.now().isoformat()
|
| 178 |
+
|
| 179 |
+
chats_db[chat_id] = {
|
| 180 |
+
'type': 'group',
|
| 181 |
+
'group_name': group_name,
|
| 182 |
+
'creator_id': user_id,
|
| 183 |
+
'participants': participants,
|
| 184 |
+
'created_at': timestamp
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
save_data()
|
| 188 |
+
return {"chat_id": chat_id, "status": "success"}
|
| 189 |
+
|
| 190 |
+
@app.post("/api/update_presence")
|
| 191 |
+
async def update_presence(data: UpdatePresenceRequest):
|
| 192 |
+
user_id = data.user_id
|
| 193 |
+
online = data.online
|
| 194 |
+
|
| 195 |
+
if user_id in users_db:
|
| 196 |
+
users_db[user_id]['online'] = online
|
| 197 |
+
users_db[user_id]['last_seen'] = None if online else datetime.now().isoformat()
|
| 198 |
+
save_data()
|
| 199 |
+
return {"status": "success"}
|
| 200 |
+
|
| 201 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 202 |
+
|
| 203 |
+
@app.get("/api/search_users")
|
| 204 |
+
async def search_users(query: str = ""):
|
| 205 |
+
query = query.lower()
|
| 206 |
+
matching_users = []
|
| 207 |
+
for user_id, user in users_db.items():
|
| 208 |
+
if (query in user['username'].lower() or
|
| 209 |
+
query in user['email'].lower() or
|
| 210 |
+
query in user_id.lower()):
|
| 211 |
+
matching_users.append({
|
| 212 |
+
'user_id': user_id,
|
| 213 |
+
'username': user['username'],
|
| 214 |
+
'email': user['email']
|
| 215 |
+
})
|
| 216 |
+
|
| 217 |
+
return {"users": matching_users}
|