This commit is contained in:
2022-12-04 17:03:55 +03:00
parent 5b67d372ad
commit a034eda220
10 changed files with 83 additions and 22 deletions

14
services/inbox/helpers.py Normal file
View File

@@ -0,0 +1,14 @@
import asyncio
class MessageResult:
def __init__(self, status, message):
self.status = status
self.message = message
class ChatFollowing:
queue = asyncio.Queue()
def __init__(self, chat_id):
self.chat_id = chat_id

View File

@@ -0,0 +1,43 @@
from base.exceptions import Unauthorized
from auth.tokenstorage import SessionToken
from base.redis import redis
async def set_online_status(user_id, status):
if user_id:
if status:
await redis.execute("SADD", "users-online", user_id)
else:
await redis.execute("SREM", "users-online", user_id)
async def on_connect(websocket, params):
if not isinstance(params, dict):
websocket.scope["connection_params"] = {}
return
token = params.get('token')
if not token:
raise Unauthorized("Please login")
else:
payload = await SessionToken.verify(token)
if payload and payload.user_id:
websocket.scope["user_id"] = payload.user_id
await set_online_status(payload.user_id, True)
async def on_disconnect(websocket):
user_id = websocket.scope.get("user_id")
await set_online_status(user_id, False)
# FIXME: not used yet
def context_value(request):
context = {}
print(f"[inbox.presense] request debug: {request}")
if request.scope["type"] == "websocket":
# request is an instance of WebSocket
context.update(request.scope["connection_params"])
else:
context["token"] = request.META.get("authorization")
return context

23
services/inbox/storage.py Normal file
View File

@@ -0,0 +1,23 @@
import asyncio
class MessagesStorage:
lock = asyncio.Lock()
chats = []
@staticmethod
async def register_chat(chat):
async with MessagesStorage.lock:
MessagesStorage.chats.append(chat)
@staticmethod
async def remove_chat(chat):
async with MessagesStorage.lock:
MessagesStorage.chats.remove(chat)
@staticmethod
async def put(message_result):
async with MessagesStorage.lock:
for chat in MessagesStorage.chats:
if message_result.message["chatId"] == chat.chat_id:
chat.queue.put_nowait(message_result)