abdullahalioo commited on
Commit
dfdb6c8
·
verified ·
1 Parent(s): 75a3076

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +205 -83
main.py CHANGED
@@ -1,13 +1,15 @@
1
- import os
2
- import uuid
3
- from fastapi import FastAPI, WebSocket, WebSocketDisconnect
4
- from fastapi.staticfiles import StaticFiles
5
  from fastapi.middleware.cors import CORSMiddleware
6
- from typing import Dict, List
 
 
 
 
 
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
- # Store active connections and messages
20
- class ConnectionManager:
21
- def __init__(self):
22
- self.active_connections: Dict[str, WebSocket] = {}
23
- self.messages: List[dict] = []
24
- self.users: Dict[str, dict] = {}
25
-
26
- async def connect(self, websocket: WebSocket, user_id: str, username: str, email: str):
27
- await websocket.accept()
28
- self.active_connections[user_id] = websocket
29
- self.users[user_id] = {"username": username, "email": email}
30
- await self.send_user_list()
31
-
32
- def disconnect(self, user_id: str):
33
- if user_id in self.active_connections:
34
- del self.active_connections[user_id]
35
- del self.users[user_id]
36
-
37
- async def send_personal_message(self, message: str, websocket: WebSocket):
38
- await websocket.send_text(message)
39
-
40
- async def broadcast(self, message: dict):
41
- for connection in self.active_connections.values():
42
- await connection.send_json(message)
43
-
44
- async def send_user_list(self):
45
- user_list = {
46
- "type": "user_list",
47
- "data": list(self.users.values())
48
- }
49
- await self.broadcast(user_list)
50
-
51
- manager = ConnectionManager()
52
-
53
- @app.websocket("/ws/{user_id}/{username}/{email}")
54
- async def websocket_endpoint(websocket: WebSocket, user_id: str, username: str, email: str):
55
- await manager.connect(websocket, user_id, username, email)
56
- try:
57
- while True:
58
- data = await websocket.receive_json()
59
- if data["type"] == "message":
60
- message = {
61
- "id": str(uuid.uuid4()),
62
- "sender": {
63
- "id": user_id,
64
- "username": username,
65
- "email": email
66
- },
67
- "content": data["content"],
68
- "timestamp": data["timestamp"],
69
- "type": data["message_type"],
70
- "fileName": data.get("fileName"),
71
- "fileSize": data.get("fileSize")
72
- }
73
- manager.messages.append(message)
74
- await manager.broadcast({
75
- "type": "new_message",
76
- "data": message
77
- })
78
- except WebSocketDisconnect:
79
- manager.disconnect(user_id)
80
- await manager.send_user_list()
81
-
82
- @app.get("/messages")
83
- async def get_messages():
84
- return manager.messages
85
-
86
- @app.get("/users")
87
- async def get_users():
88
- return list(manager.users.values())
89
-
90
- # Serve frontend files
91
- app.mount("/", StaticFiles(directory="../frontend", html=True), name="frontend")
92
-
93
- if __name__ == "__main__":
94
- import uvicorn
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}