-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
310 lines (260 loc) · 9.32 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
from fastapi import FastAPI, HTTPException, Depends, status, UploadFile, File
from fastapi.responses import HTMLResponse
from fastapi import WebSocket, WebSocketDisconnect
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, text
from sqlalchemy.orm import relationship
from pydantic import BaseModel
from sqlalchemy.orm import Session
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.sql import or_, and_
from schemas import (
MessageCreate,
UserBase,
RoomNumber,
Login,
ImageDisplay,
ChatImage,
DocumentDisplay,
ChatDocuments,
VideoDisplay,
ChatVideo,
)
from database.database import get_db
from database.models import User, Message, Rooms, Images, Documents, Videos
from database import models
from database.database import engine
from typing import List
import json
import uuid
import shutil
from fastapi.staticfiles import StaticFiles
import os
app = FastAPI()
ALLOWED_IMAGES_EXT = ["jpg", "png", "gif", "jpeg"]
ALLOWED_DOCUMENTS_EXT = ["doc", "docx", "pdf", "txt"]
ALLOWED_VIDEOS_EXT = ["mp4", "divx"]
origins = ["http://localhost:3000"] # we use this for our web application
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class WebsocketManager:
def __init__(self):
self.active_connections = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_json(message)
manager = WebsocketManager()
client = []
@app.websocket("/ws/{room_id}")
async def websocket_endpoint(
websocket: WebSocket, room_id: int, db: Session = Depends(get_db)
):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_json()
print(data["sender_id"])
message = {"message": data["message"], "sender_id": data["sender_id"]}
new_room_message = Message(
sender_id=data["sender_id"],
receiver_id=data["receiver_id"],
content=data["message"],
type_of_message=data["type_of_message"],
)
db.add(new_room_message)
db.commit()
db.refresh(new_room_message)
await manager.broadcast(json.dumps(message))
except WebSocketDisconnect:
manager.disconnect(websocket)
models.Base.metadata.create_all(engine)
@app.post("/register")
def register_user(request: UserBase, db: Session = Depends(get_db)):
new_user = User(username=request.username)
db.add(new_user)
db.commit()
db.refresh(new_user)
new_user = db.query(User).filter(User.username == request.username).first()
users = db.query(User).all()
for user in users:
if new_user.id != user.id:
new_room = Rooms(sender_id=new_user.id, receiver_id=user.id)
db.add(new_room)
db.commit()
db.refresh(new_room)
return {"message": "New user registered!"}
@app.post("/messages", response_model=MessageCreate)
def create_message(message: MessageCreate, db: Session = Depends(get_db)):
db_message = Message(
sender_id=message.sender_id,
receiver_id=message.receiver_id,
content=message.content,
type_of_message=message.type_of_message,
)
db.add(db_message)
db.commit()
db.refresh(db_message)
return db_message
@app.get("/messages/{sender_id}/{receiver_id}", response_model=List[MessageCreate])
async def get_messages(sender_id: int, receiver_id: int, db: Session = Depends(get_db)):
sender = db.query(User).filter(User.id == sender_id).first()
receiver = db.query(User).filter(User.id == receiver_id).first()
if not sender:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with id: {sender_id} not found.",
)
if not receiver:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with id: {receiver_id} not found.",
)
messages = (
db.query(Message)
.filter(
or_(
and_(
Message.sender_id == sender_id, Message.receiver_id == receiver_id
),
and_(
Message.sender_id == receiver_id, Message.receiver_id == sender_id
),
)
)
.all()
)
return messages
@app.get("/users/{id}", response_model=List[UserBase])
def get_users(id: int, db: Session = Depends(get_db)):
users_ = []
users = db.query(User).all()
for user in users:
if user.id != id:
users_.append(user)
return users_
@app.get("/room_number/{sender_id}/{receiver_id}", response_model=RoomNumber)
def get_room_number(sender_id: int, receiver_id: int, db: Session = Depends(get_db)):
room = (
db.query(Rooms)
.filter(
or_(
and_(Rooms.sender_id == sender_id, Rooms.receiver_id == receiver_id),
and_(Rooms.sender_id == receiver_id, Rooms.receiver_id == sender_id),
)
)
.first()
)
if room:
return room
else:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"Room not found"
)
@app.post("/login", response_model=UserBase)
def login(request: Login, db: Session = Depends(get_db)):
user = db.query(User).filter(User.username == request.username).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"User not found!"
)
return user
@app.get("/message/{message_uuid}")
def get_message_uuid(message_uuid: str, db: Session = Depends(get_db)):
message = db.query(Message).filter(Message.message_uuid == message_uuid).first()
if message:
return {"check": True}
else:
return {"check": False}
@app.post("/image")
def upload_image(image: UploadFile = File(...)):
filename = uuid.uuid4().hex + "."
ext = image.filename.split(".")[-1]
print(ext)
if ext not in ALLOWED_IMAGES_EXT:
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail=f"Image with extension {ext} not acceptable",
)
full_name = filename.join(image.filename.rsplit(".", 1))
path = f"images/{filename}{ext}"
with open(path, "w+b") as buffer:
shutil.copyfileobj(image.file, buffer)
return {"filename": path}
@app.post("/chat_image", response_model=ImageDisplay)
def post_chat_image(request: ChatImage, db: Session = Depends(get_db)):
new_image = Images(
image_name=request.image_name,
sender_image=request.sender_id,
receiver_image=request.receiver_id,
room_id=request.room_id,
)
db.add(new_image)
db.commit()
db.refresh(new_image)
return new_image
@app.post("/documents")
def upload_image(document: UploadFile = File(...)):
filename = uuid.uuid4().hex + "."
ext = document.filename.split(".")[-1]
if ext not in ALLOWED_DOCUMENTS_EXT:
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail=f"Document with extension {ext} not acceptable",
)
full_name = filename.join(document.filename.rsplit(".", 1))
path = f"documents/{filename}{ext}"
with open(path, "w+b") as buffer:
shutil.copyfileobj(document.file, buffer)
return {"filename": path}
@app.post("/chat_documents", response_model=DocumentDisplay)
def post_chat_image(request: ChatDocuments, db: Session = Depends(get_db)):
new_document = Documents(
document_name=request.document_name,
sender_document=request.sender_id,
receiver_document=request.receiver_id,
room_id=request.room_id,
)
db.add(new_document)
db.commit()
db.refresh(new_document)
return new_document
@app.post("/videos")
def upload_image(video: UploadFile = File(...)):
filename = uuid.uuid4().hex + "."
ext = video.filename.split(".")[-1]
if ext not in ALLOWED_VIDEOS_EXT:
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail=f"Document with extension {ext} not acceptable",
)
full_name = filename.join(video.filename.rsplit(".", 1))
path = f"videos/{filename}{ext}"
with open(path, "w+b") as buffer:
shutil.copyfileobj(video.file, buffer)
return {"filename": path}
@app.post("/chat_video", response_model=VideoDisplay)
def post_chat_image(request: ChatVideo, db: Session = Depends(get_db)):
new_video = Videos(
video_name=request.video_name,
sender_video=request.sender_id,
receiver_video=request.receiver_id,
room_id=request.room_id,
)
db.add(new_video)
db.commit()
db.refresh(new_video)
return new_video
app.mount("/documents", StaticFiles(directory="documents"), name="documents")
app.mount("/images", StaticFiles(directory="images"), name="images")
app.mount("/videos", StaticFiles(directory="videos"), name="videos")