core/resolvers/inbox.py

339 lines
9.7 KiB
Python
Raw Normal View History

2022-11-09 11:46:00 +00:00
import asyncio
2022-09-04 17:20:38 +00:00
import json
import uuid
2022-01-23 11:02:57 +00:00
from datetime import datetime
from auth.authenticate import login_required
2022-08-11 05:53:14 +00:00
from base.redis import redis
from base.resolvers import mutation, query, subscription
2022-11-09 11:46:00 +00:00
from services.inbox import ChatFollowing, MessageResult, MessagesStorage
2022-09-03 10:50:14 +00:00
2021-07-08 07:58:49 +00:00
2022-11-02 13:36:10 +00:00
async def get_unread_counter(chat_id: str, user_slug: str):
2022-11-02 09:46:25 +00:00
try:
return int(await redis.execute("LLEN", f"chats/{chat_id}/unread/{user_slug}"))
except Exception:
return 0
2022-11-02 13:36:10 +00:00
async def get_total_unread_counter(user_slug: str):
2022-09-03 10:50:14 +00:00
chats = await redis.execute("GET", f"chats_by_user/{user_slug}")
if not chats:
return 0
chats = json.loads(chats)
unread = 0
for chat_id in chats:
2022-11-02 09:46:25 +00:00
n = await get_unread_counter(chat_id, user_slug)
2022-09-03 10:50:14 +00:00
unread += n
return unread
2022-11-11 06:32:13 +00:00
async def add_user_to_chat(user_slug: str, chat_id: str, chat=None):
2022-11-02 13:36:10 +00:00
chats_ids = await redis.execute("GET", f"chats_by_user/{user_slug}")
2022-11-11 06:32:13 +00:00
if not chat:
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-11-11 06:58:40 +00:00
if chat:
2022-11-11 07:04:16 +00:00
chat = dict(json.loads(chat))
2022-11-02 13:36:10 +00:00
if chats_ids:
chats_ids = list(json.loads(chats_ids))
2022-09-03 10:50:14 +00:00
else:
2022-11-02 13:36:10 +00:00
chats_ids = []
2022-11-11 06:32:13 +00:00
if chat_id not in chats_ids:
chats_ids.append(chat_id)
2022-11-02 13:36:10 +00:00
await redis.execute("SET", f"chats_by_user/{user_slug}", json.dumps(chats_ids))
2022-11-02 09:23:14 +00:00
if user_slug not in chat["users"]:
chat["users"].append(user_slug)
2022-11-11 07:12:09 +00:00
chat["updatedAt"] = int(datetime.now().timestamp())
2022-11-11 06:32:13 +00:00
await redis.execute("SET", f"chats/{chat_id}", json.dumps(chat))
2022-11-02 13:36:10 +00:00
return chat
2022-09-03 10:50:14 +00:00
2022-04-13 11:43:22 +00:00
2022-11-09 11:46:00 +00:00
async def get_chats_by_user(slug: str):
chats = await redis.execute("GET", f"chats_by_user/{slug}")
return chats or []
2022-10-03 23:43:08 +00:00
@mutation.field("inviteChat")
2022-11-02 13:36:10 +00:00
async def invite_to_chat(_, info, invited: str, chat_id: str):
2022-10-03 23:25:11 +00:00
user = info.context["request"].user
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-11-02 13:36:10 +00:00
if user.slug not in chat['users']:
# TODO: check right to invite here
chat = await add_user_to_chat(invited, chat_id, chat)
return {
"error": None,
"chat": chat
}
2022-10-03 23:25:11 +00:00
2022-11-02 13:36:10 +00:00
@mutation.field("updateChat")
2022-01-23 11:02:57 +00:00
@login_required
2022-11-02 13:36:10 +00:00
async def update_chat(_, info, chat_new):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_new.id}")
chat.update({
"title": chat_new.title,
"description": chat_new.description,
2022-11-11 07:12:09 +00:00
"updatedAt": int(datetime.now().timestamp()),
2022-11-02 13:36:10 +00:00
})
await redis.execute("SET", f"chats/{chat.id}", json.dumps(chat))
await redis.execute("SET", f"chats/{chat.id}/next_message_id", 0)
chat = await add_user_to_chat(user.slug, chat.id)
return {
"error": None,
"chat": chat
}
@mutation.field("createChat")
@login_required
async def create_chat(_, info, title="", members=[]):
user = info.context["request"].user
if user.slug not in members:
members.append(user.slug)
chat_id = str(uuid.uuid4())
2022-09-03 10:50:14 +00:00
chat = {
2022-10-03 23:25:11 +00:00
"title": title,
2022-11-11 07:12:09 +00:00
"createdAt": int(datetime.now().timestamp()),
"updatedAt": int(datetime.now().timestamp()),
2022-09-03 10:50:14 +00:00
"createdBy": user.slug,
2022-11-02 13:36:10 +00:00
"id": chat_id,
"users": members,
2022-09-03 10:50:14 +00:00
}
2022-01-23 11:02:57 +00:00
2022-09-03 10:50:14 +00:00
await redis.execute("SET", f"chats/{chat_id}", json.dumps(chat))
2022-11-02 13:36:10 +00:00
await redis.execute("SET", f"chats/{chat_id}/next_message_id", str(0))
chat = await add_user_to_chat(user.slug, chat_id)
2022-01-23 11:02:57 +00:00
2022-11-02 10:00:04 +00:00
return {
"error": None,
"chat": chat
}
2022-04-13 11:43:22 +00:00
2022-01-23 11:02:57 +00:00
2022-11-08 15:50:28 +00:00
async def load_messages(chatId: str, offset: int, amount: int):
2022-11-02 10:00:04 +00:00
messages = []
2022-09-03 10:50:14 +00:00
message_ids = await redis.lrange(
2022-11-02 13:36:10 +00:00
f"chats/{chatId}/message_ids", 0 - offset - amount, 0 - offset
2022-09-03 10:50:14 +00:00
)
if message_ids:
message_keys = [
2022-11-02 09:23:14 +00:00
f"chats/{chatId}/messages/{mid}" for mid in message_ids
2022-09-03 10:50:14 +00:00
]
messages = await redis.mget(*message_keys)
messages = [json.loads(msg) for msg in messages]
2022-11-02 10:00:04 +00:00
return {
"messages": messages,
"error": None
}
2022-09-03 10:50:14 +00:00
2022-01-28 12:52:14 +00:00
2022-10-03 23:25:11 +00:00
@query.field("myChats")
2022-06-11 14:35:10 +00:00
@login_required
async def user_chats(_, info):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chats = await get_chats_by_user(user.slug)
2022-11-02 13:52:35 +00:00
if not chats:
chats = []
2022-10-03 23:25:11 +00:00
for c in chats:
2022-11-02 13:36:10 +00:00
c['messages'] = await load_messages(c['id'])
2022-11-02 09:46:25 +00:00
c['unread'] = await get_unread_counter(c['id'], user.slug)
2022-11-02 10:00:04 +00:00
return {
"chats": chats,
"error": None
}
2022-06-11 14:35:10 +00:00
2022-11-02 13:36:10 +00:00
@mutation.field("enterChat")
2022-01-23 11:02:57 +00:00
@login_required
2022-11-02 13:36:10 +00:00
async def enter_chat(_, info, chat_id: str):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
2022-11-02 10:00:04 +00:00
return {
"error": "chat not exist"
}
else:
chat = json.loads(chat)
2022-11-02 13:36:10 +00:00
chat = await add_user_to_chat(user.slug, chat_id, chat)
chat['messages'] = await load_messages(chat_id)
2022-11-02 10:00:04 +00:00
return {
"chat": chat,
"error": None
}
2022-04-13 11:43:22 +00:00
2021-07-02 09:16:43 +00:00
2021-07-01 18:26:04 +00:00
@mutation.field("createMessage")
@login_required
2022-11-02 13:36:10 +00:00
async def create_message(_, info, chat_id: str, body: str, replyTo=None):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
2022-11-02 10:00:04 +00:00
return {
2022-11-02 13:36:10 +00:00
"error": "chat not exist"
}
2022-01-23 11:02:57 +00:00
2022-11-02 13:36:10 +00:00
message_id = await redis.execute("GET", f"chats/{chat_id}/next_message_id")
2022-09-03 10:50:14 +00:00
message_id = int(message_id)
2022-01-23 11:02:57 +00:00
2022-09-03 10:50:14 +00:00
new_message = {
2022-11-02 13:36:10 +00:00
"chatId": chat_id,
2022-09-03 10:50:14 +00:00
"id": message_id,
"author": user.slug,
"body": body,
"replyTo": replyTo,
2022-11-11 07:12:09 +00:00
"createdAt": int(datetime.now().timestamp()),
2022-09-03 10:50:14 +00:00
}
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
await redis.execute(
2022-11-02 13:36:10 +00:00
"SET", f"chats/{chat_id}/messages/{message_id}", json.dumps(new_message)
2022-09-03 10:50:14 +00:00
)
2022-11-02 13:36:10 +00:00
await redis.execute("LPUSH", f"chats/{chat_id}/message_ids", str(message_id))
await redis.execute("SET", f"chats/{chat_id}/next_message_id", str(message_id + 1))
2022-01-23 11:02:57 +00:00
2022-09-03 10:50:14 +00:00
chat = json.loads(chat)
users = chat["users"]
for user_slug in users:
await redis.execute(
2022-11-02 13:36:10 +00:00
"LPUSH", f"chats/{chat_id}/unread/{user_slug}", str(message_id)
2022-09-03 10:50:14 +00:00
)
2022-01-23 11:02:57 +00:00
2022-09-03 10:50:14 +00:00
result = MessageResult("NEW", new_message)
await MessagesStorage.put(result)
2022-04-13 11:43:22 +00:00
2022-11-02 10:00:04 +00:00
return {
"message": new_message,
"error": None
}
2022-01-24 14:02:44 +00:00
2022-10-03 23:25:11 +00:00
@query.field("loadChat")
2021-07-01 18:26:04 +00:00
@login_required
2022-11-02 13:36:10 +00:00
async def load_chat_messages(_, info, chat_id: str, offset: int = 0, amount: int = 50):
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
2022-11-02 13:36:10 +00:00
return {
"error": "chat not exist"
}
2022-11-02 13:36:10 +00:00
messages = await load_messages(chat_id, offset, amount)
2022-09-03 10:50:14 +00:00
2022-11-02 10:00:04 +00:00
return {
"messages": messages,
"error": None
}
2022-01-28 12:52:14 +00:00
2021-07-01 18:26:04 +00:00
@mutation.field("updateMessage")
@login_required
2022-11-02 13:36:10 +00:00
async def update_message(_, info, chat_id: str, message_id: int, body: str):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
return {"error": "chat not exist"}
2022-01-24 11:56:55 +00:00
2022-11-02 13:36:10 +00:00
message = await redis.execute("GET", f"chats/{chat_id}/messages/{message_id}")
2022-09-03 10:50:14 +00:00
if not message:
return {"error": "message not exist"}
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
message = json.loads(message)
if message["author"] != user.slug:
return {"error": "access denied"}
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
message["body"] = body
2022-11-11 07:12:09 +00:00
message["updatedAt"] = int(datetime.now().timestamp())
2022-01-25 11:16:13 +00:00
2022-11-02 13:36:10 +00:00
await redis.execute("SET", f"chats/{chat_id}/messages/{message_id}", json.dumps(message))
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
result = MessageResult("UPDATED", message)
await MessagesStorage.put(result)
2022-01-24 11:56:55 +00:00
2022-11-02 10:00:04 +00:00
return {
"message": message,
"error": None
}
2022-01-24 11:56:55 +00:00
2021-07-01 18:26:04 +00:00
@mutation.field("deleteMessage")
@login_required
2022-11-02 13:36:10 +00:00
async def delete_message(_, info, chat_id: str, message_id: int):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
return {"error": "chat not exist"}
2022-11-02 13:36:10 +00:00
chat = json.loads(chat)
2022-01-24 11:56:55 +00:00
2022-11-02 13:36:10 +00:00
message = await redis.execute("GET", f"chats/{chat_id}/messages/{str(message_id)}")
2022-09-03 10:50:14 +00:00
if not message:
return {"error": "message not exist"}
message = json.loads(message)
if message["author"] != user.slug:
return {"error": "access denied"}
2022-01-24 11:56:55 +00:00
2022-11-02 13:36:10 +00:00
await redis.execute("LREM", f"chats/{chat_id}/message_ids", 0, str(message_id))
await redis.execute("DEL", f"chats/{chat_id}/messages/{str(message_id)}")
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
users = chat["users"]
for user_slug in users:
2022-11-02 13:36:10 +00:00
await redis.execute("LREM", f"chats/{chat_id}/unread/{user_slug}", 0, str(message_id))
2022-01-24 11:56:55 +00:00
2022-09-03 10:50:14 +00:00
result = MessageResult("DELETED", message)
await MessagesStorage.put(result)
2022-04-13 11:43:22 +00:00
2022-09-03 10:50:14 +00:00
return {}
2022-01-24 14:02:44 +00:00
2021-07-02 09:16:43 +00:00
2022-04-13 11:43:22 +00:00
@mutation.field("markAsRead")
@login_required
2022-11-02 13:36:10 +00:00
async def mark_as_read(_, info, chat_id: str, messages: [int]):
2022-09-03 10:50:14 +00:00
user = info.context["request"].user
2022-04-13 11:43:22 +00:00
2022-11-02 13:36:10 +00:00
chat = await redis.execute("GET", f"chats/{chat_id}")
2022-09-03 10:50:14 +00:00
if not chat:
return {"error": "chat not exist"}
2022-04-13 11:43:22 +00:00
2022-09-03 10:50:14 +00:00
chat = json.loads(chat)
users = set(chat["users"])
2022-09-04 17:20:38 +00:00
if user.slug not in users:
2022-09-03 10:50:14 +00:00
return {"error": "access denied"}
2022-04-13 11:43:22 +00:00
2022-11-02 13:36:10 +00:00
for message_id in messages:
await redis.execute("LREM", f"chats/{chat_id}/unread/{user.slug}", 0, str(message_id))
2022-09-03 10:50:14 +00:00
2022-11-02 10:00:04 +00:00
return {
"error": None
}
2022-04-13 11:43:22 +00:00
2022-11-02 13:36:10 +00:00
@subscription.source("newMessage")
2022-08-12 12:50:59 +00:00
@login_required
2022-11-02 13:36:10 +00:00
async def message_generator(obj, info):
2022-09-03 10:50:14 +00:00
try:
2022-11-02 13:36:10 +00:00
user = info.context["request"].user
user_following_chats = await get_chats_by_user(user.slug) # chat ids
tasks = []
updated = {}
for chat_id in user_following_chats:
chat = await redis.execute("GET", f"chats/{chat_id}")
updated[chat_id] = chat['updatedAt']
user_following_chats_sorted = sorted(user_following_chats, key=lambda x: updated[x], reverse=True)
for chat_id in user_following_chats_sorted:
following_chat = ChatFollowing(chat_id)
await MessagesStorage.register_chat(following_chat)
chat_task = following_chat.queue.get()
tasks.append(chat_task)
2022-09-03 10:50:14 +00:00
while True:
2022-11-02 13:36:10 +00:00
msg = await asyncio.gather(*tasks)
2022-09-03 10:50:14 +00:00
yield msg
finally:
await MessagesStorage.remove_chat(following_chat)