-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathmessaging.py
561 lines (504 loc) · 22 KB
/
messaging.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
import json
from django.http.response import JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import api_view, parser_classes
from rest_framework import status, generics
import time
from .utils import send_centrifugo_data
from .db import *
from rest_framework.views import (
APIView,
exception_handler,
)
from .resmodels import *
from .serializers import *
from drf_yasg.utils import swagger_auto_schema
from datetime import datetime
from .centrifugo_handler import centrifugo_client
from rest_framework.pagination import PageNumberPagination
from .decorators import db_init_with_credentials
from typing import OrderedDict, Any
class MessageList(APIView):
queryset = None
serializer_class = MessageSerializer
@swagger_auto_schema(
operation_summary="Fetches all messages in a particular room of a particular organization.",
responses={
200: FilterMessageResponse(many=True),
204: "No message in the specified room",
400: "Error: Bad Request",
404: "No such room"
},
)
def get(self, request: dict, room_id: str, org_id: str) -> OrderedDict[str, Any]:
"""Fetches all messages in a particular room of a particular organization.
Args:
request (dict): The incoming request object.
room_id (str): The id of the room where the request is being made.
org_id (str): The id of the organization of the user.
Returns:
A list of available messages(list[FilterMessageResponse]).
{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"_id": "618c0dd4660aa90fb295e368",
"created_at": "2021-11-10T18:18:47.494000Z",
"media": [],
"message": "Cash App Load am",
"pinned": false,
"reactions": [],
"read": false,
"replied_message": [],
"room_id": "6169dbcef5998a09e3bbbcd3",
"saved_by": [],
"sender_id": "61695d8bb2cc8a9af4833d47",
"sent_from_thread": false,
"threads": []
},
...
]
}
Raises:
204: No message in the specified room.
404: Room does not exist.
400: Bad Request.
"""
# Set the page size for the response
paginator = PageNumberPagination()
paginator.page_size = 20
date = request.GET.get("date", None)
params_serializer = GetMessageSerializer(data=request.GET.dict())
if params_serializer.is_valid():
DB.organization_id = org_id
# Check if the room exists in the database
room = DB.read_query("dm_rooms", query={"_id": room_id})
# FIXME: This statement will always be true
# room is a non-empty dict
# we should check if room contains a status_code key or not
if room:
# Fetch the messages from the room
messages = get_room_messages(room_id, org_id)
if date is not None:
messages_by_date = get_messages(room_id, org_id, date)
# Paginate the response
messages_page = paginator.paginate_queryset(
messages_by_date, request)
return paginator.get_paginated_response(messages_page)
else:
# There's no messages in the room.
if messages is None or "message" in messages:
return Response(
data="No messages available",
status=status.HTTP_204_NO_CONTENT,
)
result_page = paginator.paginate_queryset(messages, request)
return paginator.get_paginated_response(result_page)
else:
# FIXME: As a result, this branch will never be reached
# because if room will always return True
return Response(data="No such room", status=status.HTTP_404_NOT_FOUND)
else:
return Response(
params_serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
@swagger_auto_schema(
operation_summary="Creates a message in a specified room of a specified organization.",
request_body=MessageSerializer,
responses={
201: MessageResponse,
400: "Error: Bad Request",
404: "Room does not exist"
},
)
def post(self, request: dict, room_id: str, org_id: str) -> MessageResponse:
"""Creates a message in a specified room of a specified organization.
Args:
request (dict): The request body
room_id (str): The id of the room where the request is being made
org_id (str): The id of the organization of the user
Returns:
A dict containing data about the message that was created (MessageResponse).
{
"status": "success",
"event": "message_create",
"message_id": "61696f43c4133ddga309dcf6",
"room_id": "61696f43c4193ddga309dcf7",
"thread": False,
"data": {
"sender_id": "61696f43c4133ddaa309dcf6",
"message": "Hi",
"created_at": "2021-10-15T19:51:41.928908Z",
},
}
Raises:
424: Failed dependency.
404: Sender not in room.
404: Room does not exist.
400: Error: Bad Request.
"""
# add the room_id to the request data
request.data["room_id"] = room_id
serializer = MessageSerializer(data=request.data)
if serializer.is_valid():
data = serializer.data
room_id = data["room_id"] # room id gotten from client request
DB.organization_id = org_id
# Check to see if the room exists in the database
room = DB.read_query("dm_rooms", query={"_id": room_id})
if room and room.get("status_code", None) is None:
# Check if the sender is in the specified room
if data["sender_id"] in room.get("room_user_ids", []):
response = DB.write("dm_messages", data=serializer.data)
# Check if message was sent successfully.
if response.get("status", None) == 200:
response_output = {
"status": response["message"],
"event": "message_create",
"message_id": response["data"]["object_id"],
"room_id": room_id,
"thread": False,
"data": {
"sender_id": data["sender_id"],
"message": data["message"],
"created_at": data["created_at"],
},
}
try:
centrifugo_data = centrifugo_client.publish(
room=room_id, data=response_output
) # publish data to centrifugo
if (
centrifugo_data
and centrifugo_data.get("status_code") == 200
):
return Response(
data=response_output, status=status.HTTP_201_CREATED
)
else:
return Response(
data="Message not sent",
status=status.HTTP_424_FAILED_DEPENDENCY,
)
except:
return Response(
data="Centrifugo server not available",
status=status.HTTP_424_FAILED_DEPENDENCY,
)
return Response(
data="Message not saved and not sent",
status=status.HTTP_424_FAILED_DEPENDENCY,
)
return Response(
"Sender not found in this room", status=status.HTTP_404_NOT_FOUND
)
return Response("Room not found", status=status.HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_400_BAD_REQUEST)
@swagger_auto_schema(
methods=["post"],
operation_summary="Schedules messages in rooms",
request_body=ScheduleMessageSerializer,
responses={
201: "Success: Message Scheduled",
400: "Error: Bad Request",
},
)
@api_view(["POST"])
@db_init_with_credentials
def scheduled_messages(request, room_id):
ORG_ID = DB.organization_id
schedule_serializer = ScheduleMessageSerializer(data=request.data)
if schedule_serializer.is_valid():
data = schedule_serializer.data
sender_id = data["sender_id"]
room_id = data["room_id"]
message = data["message"]
timer = data["timer"]
now = datetime.now()
timer = datetime.strptime(timer, "%Y-%m-%d %H:%M:%S")
duration = timer - now
duration = duration.total_seconds()
url = f"https://dm.zuri.chat/api/v1/org/{ORG_ID}/rooms/{room_id}/messages"
payload = json.dumps(
{
"sender_id": f"{sender_id}",
"room_id": f"{room_id}",
"message": f"{message}",
}
)
headers = {"Content-Type": "application/json"}
time.sleep(duration)
response = requests.request("POST", url, headers=headers, data=payload)
else:
return Response(schedule_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
if response.status_code == 201:
return Response(response.json(), status=status.HTTP_201_CREATED)
return Response(response.json(), status=response.status_code)
@swagger_auto_schema(
methods=["put"],
operation_summary="Marks a message as read or unread",
responses={
200: "Ok: Success",
400: "Error: Bad Request",
503: "Server Error: Service Unavailable",
},
)
@api_view(["PUT"])
@db_init_with_credentials
def mark_read(request, message_id):
"""
Marks a message as read and unread
Queries the dm_messages collection using a unique message id
Checks read status of the message and updates the collection
"""
try:
message = DB.read("dm_messages", {"id": message_id})
read = message["read"]
except Exception as e:
print(e)
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)
data = {"read": not read}
response = DB.update("dm_messages", message_id, data=data)
message = DB.read("dm_messages", {"id": message_id})
if response.get("status") == 200:
return Response(data=data, status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
@swagger_auto_schema(
methods=["put"],
operation_summary="Pins a message in a room",
responses={
200: PinMessageResponse,
400: "Error: Bad Request",
503: "Server Error: Service Unavailable",
},
)
@api_view(["PUT"])
@db_init_with_credentials
def pinned_message(request, message_id):
"""
This is used to pin a message.
The message_id is passed to it which
reads through the database, gets the room id,
generates a link and then add it to the pinned key value.
If the link already exist, it will unpin that particular message already pinned.
"""
try:
message = DB.read("dm_messages", {"id": message_id})
if message:
room_id = message["room_id"]
room = DB.read("dm_rooms", {"id": room_id})
pin = room["pinned"] or []
else:
return Response(status=status.HTTP_404_NOT_FOUND)
except Exception as e:
print(e)
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)
if message_id in pin:
pin.remove(message_id)
data = {
"message_id": message_id,
"pinned": pin,
"Event": "unpin_message",
} # this event key is in capslock
response = DB.update("dm_rooms", room_id, {"pinned": pin})
# room = DB.read("dm_rooms", {"id": room_id})
if response["status"] == 200:
centrifugo_data = send_centrifugo_data(
room=room_id, data=data
) # publish data to centrifugo
if centrifugo_data.get("error", None) == None:
return Response(data=data, status=status.HTTP_201_CREATED)
else:
return Response(status=response.status_code)
else:
pin.append(message_id)
data = {"message_id": message_id, "pinned": pin, "Event": "pin_message"}
response = DB.update("dm_rooms", room_id, {"pinned": pin})
# room = DB.read("dm_rooms", {"id": room_id})
centrifugo_data = send_centrifugo_data(
room=room_id, data=data
) # publish data to centrifugo
if centrifugo_data.get("error", None) == None:
return Response(data=data, status=status.HTTP_201_CREATED)
@swagger_auto_schema(
methods=["get"],
operation_summary="Returns all messages in the dm collection",
responses={200: "success", 424: "Failed Dependency"},
)
@api_view(["GET"])
@db_init_with_credentials
def all_messages(request):
"""This endpoint is used to get all the messages in the dm_messages collection.
Also returns a messages with the read and unread status"""
res = DB.read("dm_messages")
if res and "status_code" not in res:
all_messages = res
read_messages = [
message for message in all_messages if message["read"] == "true"
]
unread_messages = [
message for message in all_messages if message["read"] == "false"
]
message_data = {
"all_messages": all_messages,
"read_messages": read_messages,
"unread_messages": unread_messages,
}
return Response(message_data, status=status.HTTP_200_OK)
else:
return Response(
f"something went wrong. message collection returned{res}",
status=status.HTTP_424_FAILED_DEPENDENCY,
)
class MessageDetailsView(APIView):
@swagger_auto_schema(
operation_summary="Retrieves a message in a particular room of a particular organization.",
responses={
200: FilterMessageResponse,
204: "No message in the specified room",
400: "Error: Bad Request",
404: "No such room"
},
)
def get(self, request: dict, message_id: str, org_id: str):
"""Gets a single message from a room.
It access room with the 'message_id' and then displays the message if it exists.
The id of the organization (org_id) where the room is located is also needed.
Args:
request (dict): The incoming request
org_id (str): This is the id of the organization th user belongs to.
message_id (str): This is the unique id of the message to be fetched.
Returns:
A dict object the message data.
Example:
{
"status" : "success",
"room_id" : "6169dbcef5998a09e3bbbcd3",
"message_id" : "616ad4f989454c2006018af2"
"message" : "The message"
}
Raises:
Not Found: If there is no message with specified id in the specified room, it returns 'message not found' and a '404' error message.
"""
data_storage = DataStorage()
data_storage.organization_id = org_id
data = request.data
request.data["message_id"] = message_id
try:
message = data_storage.read("dm_messages", {"_id": message_id})
room_id = message["room_id"]
data = {
"status": "success",
"message": message,
}
return Response(data, status=status.HTTP_200_OK)
except:
return JsonResponse(
{"message": "The room does not exist"}, status=status.HTTP_404_NOT_FOUND
)
def put(self, request, message_id, org_id):
"""
This is used to update message context using message id as identifier,
Updates a message from a room.
It access room with the 'room_id' and the message in the room with 'message_id' and then the new message.
The id of the organization (org_id) where the room is located is also needed.
Parameters:
org_id (str) : This is the id of the organization th user belongs to.
message (str) : This is the unique id of the message to be sent to a given room.
room_id(str) : This is the unique id of the room in the message
Returns:
A dict object indicating the the message has been updated. Example:
{
"status" : "success",
"room_id" : "6169dbcef5998a09e3bbbcd3",
"message_id" : "616ad4f989454c2006018af2"
"message" : "The message"
}
Raises:
Not Found: If there is no message with specified id in the specified room, it returns 'message not found' and a '404' error message.
IOError: An error occurred while deleteing the message.
"""
data_storage = DataStorage()
data_storage.organization_id = org_id
data = request.data
data["message_id"] = message_id
room_id = data["room_id"]
message_get = data_storage.read("dm_messages", {"_id": message_id})
# Checks DB for message using the message_id
room_serializer = MessageSerializer(
message_get, data=request.data, partial=True
)
# validates room_serializer with MessageSerializer.
if room_serializer.is_valid():
room_data = room_serializer.data
new_data = {"message": data["message"]}
response = DB.update(
"dm_messages", message_id, new_data
) # moves on to update the mesage
if response.get("status") == 200:
data = {
"sender_id": request.data["sender_id"],
"message_id": message_id,
"room_id": room_id,
"message": new_data["message"],
"event": "edited_message",
}
centrifugo_data = send_centrifugo_data(room=room_id, data=data)
if centrifugo_data.get("error", None) is None:
return Response(data=data, status=status.HTTP_201_CREATED)
return Response(data)
return Response(room_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request: dict, message_id: str, org_id: str):
"""Deletes a message from a room.
It access room with the 'room_id' and the message in the room with 'message_id' and then deletes the message if it exists.
The id of the organization (org_id) where the room is located is also needed.
Parameters:
org_id (str) : This is the id of the organization th user belongs to.
room_id (str) : This is the unique id of the room the message to be deleted is in.
message_id (str) : This is the unique id of the message to be deleted from a given room.
Returns:
A dict object indicating the the message has been deleted. Example:
{
"status" : "success",
"event" : "message_delete",
"room_id" : "6169dbcef5998a09e3bbbcd3",
"message_id" : "616ad4f989454c2006018af2"
}
Raises:
Not Found: If there is no message with specified id in the specified room, it returns 'message not found' and a '404' error message.
"""
try:
# Sends a get request to the database to fetch the message and the room of the message from.
data_storage = DataStorage()
data_storage.organization_id = org_id
data = request.data
data["message_id"] = message_id
message = data_storage.read("dm_messages", {"_id": message_id})
room_id = message["room_id"]
# Checks if the room exists and if the message exists in the room.
if message:
response = data_storage.delete("dm_messages", message_id)
# Check if the delete operation was successful
if response.get("status") == 200:
response_output = {
"status": response["message"],
"event": "message_delete",
"room_id": room_id,
"message_id": message_id,
}
# Publish data via centrifugo
centrifugo_data = centrifugo_client.publish(
room=room_id, data=response
)
# Checks if the publish was successful
if centrifugo_data.get("status_code") == 200:
return Response(response_output, status=status.HTTP_200_OK)
return Response(
data="message not sent",
status=status.HTTP_424_FAILED_DEPENDENCY,
)
return Response("message not found", status=status.HTTP_404_NOT_FOUND)
except Exception as e:
return Response(str(e), status=status.HTTP_400_BAD_REQUEST)