-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Feat] create websocket for user status online/offline
- Loading branch information
Showing
12 changed files
with
2,020 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,48 +1,116 @@ | ||
import sys | ||
from channels.generic.websocket import AsyncWebsocketConsumer | ||
import json | ||
from django.contrib.auth.models import AnonymousUser | ||
from channels.generic.websocket import AsyncWebsocketConsumer | ||
from rest_framework_simplejwt.tokens import AccessToken | ||
from .serializer import FriendsSerializer | ||
from django.contrib.auth import get_user_model | ||
from django.contrib.auth.models import AnonymousUser | ||
from channels.db import database_sync_to_async | ||
from authentication.models import User | ||
from django.db.models import F | ||
|
||
@database_sync_to_async | ||
def get_user(user_id): | ||
try: | ||
return User.objects.get(id=user_id) | ||
except User.DoesNotExist: | ||
return AnonymousUser() | ||
|
||
@database_sync_to_async | ||
def get_friends(user_id): | ||
return FriendsSerializer(instance=User.objects.get(id=user_id)).data | ||
|
||
@database_sync_to_async | ||
def update_user_online(user_id): | ||
try: | ||
User.objects.filter(id=user_id).update(is_online = F('is_online') + 1) | ||
except User.DoesNotExist: | ||
pass | ||
|
||
@database_sync_to_async | ||
def update_user_offline(user_id): | ||
try: | ||
User.objects.filter(id=user_id).update(is_online = F('is_online') - 1) | ||
except User.DoesNotExist: | ||
pass | ||
|
||
async def send_online_notification(self, user_id): | ||
await self.channel_layer.group_send( | ||
"online_users", | ||
{ | ||
"type": "send_online_notification", | ||
"user_id": user_id, | ||
} | ||
) | ||
|
||
async def send_online_notification_to_socket(self, event): | ||
user_id = event["user_id"] | ||
user = await get_user(user_id) | ||
await self.send(text_data=json.dumps({ | ||
"type": "online_notification", | ||
"user": { | ||
"id": user.id, | ||
"username": user.username, | ||
"image_url": user.image_url, | ||
# Add any other relevant user data | ||
} | ||
})) | ||
|
||
async def send_online_notification(self, event): | ||
await self.send_online_notification_to_socket(event) | ||
|
||
class UserStatusConsumer(AsyncWebsocketConsumer): | ||
async def connect(self): | ||
# Get the user and authentication data from the scope | ||
user = self.scope["user"] | ||
auth_headers = self.scope.get("headers", []) | ||
auth_header = None | ||
for header in auth_headers: | ||
if header[0].decode() == "authorization": | ||
if header[0].decode() == "access": | ||
auth_header = header[1].decode() | ||
break | ||
|
||
if user.is_authenticated: | ||
# User is authenticated | ||
print(f"Authenticated user: {user.username}", file=sys.stderr) | ||
self.accept() | ||
elif auth_header: | ||
# Try to authenticate the user with the provided token | ||
if auth_header: | ||
try: | ||
token = auth_header.split(" ")[1] | ||
access_token = AccessToken(token) | ||
user = access_token.payload["user_id"] | ||
print(f"Authenticated user: {user}", file=sys.stderr) | ||
self.accept() | ||
access_token = AccessToken(auth_header) | ||
user_id = access_token.payload["user_id"] | ||
print(user_id, file = sys.stderr) | ||
self.user = get_user(user_id) | ||
self.user_id = user_id | ||
await self.accept() | ||
await update_user_online(self.user_id) | ||
await self.send_online_notification(self.user_id) # Send online notification | ||
await self.channel_layer.group_add( | ||
"online_users", | ||
self.channel_name | ||
) | ||
except Exception as e: | ||
print(f"Authentication error: {e}", file=sys.stderr) | ||
self.close() | ||
await self.close() | ||
else: | ||
# Anonymous user | ||
print("Anonymous user", file=sys.stderr) | ||
self.accept() | ||
await self.accept() | ||
|
||
async def disconnect(self, close_code): | ||
pass | ||
await self.channel_layer.group_discard( | ||
"online_users", | ||
self.channel_name | ||
) | ||
await update_user_offline(self.user_id) | ||
|
||
async def receive(self, text_data): | ||
print(f"Received message: {text_data}", file=sys.stderr) | ||
try: | ||
text_data_json = json.loads(text_data) | ||
message = text_data_json['message'] | ||
except json.JSONDecodeError: | ||
message = text_data | ||
await self.send(text_data=json.dumps({'message': message})) | ||
if self.user: | ||
try: | ||
text_data_json = json.loads(text_data) | ||
if text_data_json.get("action") == "get_friends": | ||
data = await get_friends(self.user_id) | ||
await self.send(text_data=json.dumps({ | ||
"friends": data | ||
})) | ||
else: | ||
await self.send(text_data=json.dumps({ | ||
"error": "Invalid action" | ||
})) | ||
except json.JSONDecodeError: | ||
await self.send(text_data=json.dumps({ | ||
"error": "Invalid JSON data" | ||
})) | ||
else: | ||
await self.close() |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,6 @@ | ||
from django.urls import re_path | ||
from . import consumers | ||
from dashboards.jwt_middleware_auth import JwtAthenticationMiddleware | ||
|
||
websocket_urlpatterns = [ | ||
re_path(r'ws/data/$', JwtAthenticationMiddleware(consumers.GameConsumer.as_asgi())), | ||
re_path(r'ws/data$', consumers.GameConsumer.as_asgi()), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,4 +19,6 @@ asgiref | |
daphne | ||
requests-mock | ||
channels | ||
faker | ||
faker | ||
asgi_redis | ||
channels_redis |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
FROM debian:bullseye | ||
|
||
RUN apt-get update -y && apt-get install -y \ | ||
--no-install-recommends \ | ||
redis-server=5:6.0.16-1+deb11u2 \ | ||
&& apt-get clean && rm -rf /var/lib/apt/lists/* | ||
|
||
COPY ./conf/redis.conf /etc/redis/ | ||
|
||
EXPOSE 6379 | ||
|
||
CMD ["redis-server", "--protected-mode", "no"] |
Oops, something went wrong.