2023-10-14 12:59:43 +00:00
|
|
|
import asyncio
|
2023-10-03 14:15:17 +00:00
|
|
|
import json
|
2023-10-13 16:45:30 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Union
|
2023-10-14 12:59:43 +00:00
|
|
|
|
|
|
|
from services.auth import login_required
|
2023-11-14 18:25:55 +00:00
|
|
|
from services.core import get_my_followings, get_all_authors
|
2023-10-14 14:55:51 +00:00
|
|
|
from services.rediscache import redis
|
2023-10-04 21:43:07 +00:00
|
|
|
from services.schema import query
|
2023-10-14 14:55:51 +00:00
|
|
|
from validators.chat import Message, ChatPayload
|
|
|
|
from validators.member import ChatMember
|
2023-10-03 14:15:17 +00:00
|
|
|
from .chats import create_chat
|
2023-10-14 14:55:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def get_unread_counter(chat_id: str, author_id: int) -> int:
|
|
|
|
unread = await redis.execute("LLEN", f"chats/{chat_id}/unread/{author_id}")
|
|
|
|
return unread or 0
|
2023-10-14 12:59:43 +00:00
|
|
|
|
2023-10-13 00:16:54 +00:00
|
|
|
|
2023-10-03 14:15:17 +00:00
|
|
|
# NOTE: not an API handler
|
2023-11-14 18:25:55 +00:00
|
|
|
async def load_messages(
|
|
|
|
chat_id: str, limit: int = 5, offset: int = 0, ids: Optional[List[int]] = None
|
|
|
|
) -> List[Message]:
|
2023-10-03 14:15:17 +00:00
|
|
|
"""load :limit messages for :chat_id with :offset"""
|
2023-10-11 19:12:55 +00:00
|
|
|
if ids is None:
|
|
|
|
ids = []
|
2023-10-03 14:15:17 +00:00
|
|
|
messages = []
|
|
|
|
try:
|
|
|
|
message_ids = [] + ids
|
|
|
|
if limit:
|
2023-10-14 14:55:51 +00:00
|
|
|
mids = (await redis.lrange(f"chats/{chat_id}/message_ids", offset, offset + limit)) or []
|
2023-10-03 14:15:17 +00:00
|
|
|
message_ids += mids
|
|
|
|
if message_ids:
|
|
|
|
message_keys = [f"chats/{chat_id}/messages/{mid}" for mid in message_ids]
|
2023-10-13 16:45:30 +00:00
|
|
|
messages = (await redis.mget(*message_keys)) or []
|
2023-10-16 18:49:26 +00:00
|
|
|
messages = [json.loads(m) if isinstance(m, str) else m for m in messages]
|
2023-10-03 14:15:17 +00:00
|
|
|
replies = []
|
|
|
|
for m in messages:
|
2023-10-13 16:45:30 +00:00
|
|
|
if m:
|
2023-10-16 20:14:07 +00:00
|
|
|
reply_to = m.get("replyTo")
|
2023-10-16 20:00:07 +00:00
|
|
|
if reply_to:
|
|
|
|
reply_to = int(reply_to)
|
|
|
|
if reply_to not in message_ids:
|
|
|
|
replies.append(reply_to)
|
2023-10-03 14:15:17 +00:00
|
|
|
if replies:
|
2023-10-11 19:12:55 +00:00
|
|
|
messages += await load_messages(chat_id, offset, limit, replies)
|
2023-11-06 16:02:16 +00:00
|
|
|
except Exception:
|
2023-10-16 20:05:24 +00:00
|
|
|
import traceback
|
2023-11-14 18:25:55 +00:00
|
|
|
|
2023-10-16 20:05:24 +00:00
|
|
|
traceback.print_exc()
|
2023-10-03 14:15:17 +00:00
|
|
|
return messages
|
|
|
|
|
2023-10-14 06:38:12 +00:00
|
|
|
|
2023-10-03 14:15:17 +00:00
|
|
|
@query.field("loadChats")
|
|
|
|
@login_required
|
2023-10-14 14:55:51 +00:00
|
|
|
async def load_chats(_, info, limit: int = 50, offset: int = 0) -> Dict[str, Union[List[Dict[str, Any]], None]]:
|
2023-10-03 14:15:17 +00:00
|
|
|
"""load :limit chats of current user with :offset"""
|
|
|
|
author_id = info.context["author_id"]
|
2023-10-12 23:29:08 +00:00
|
|
|
cids = (await redis.execute("SMEMBERS", f"chats_by_author/{author_id}")) or []
|
2023-10-03 14:15:17 +00:00
|
|
|
members_online = (await redis.execute("SMEMBERS", "authors-online")) or []
|
2023-10-14 14:55:51 +00:00
|
|
|
cids = list(cids)[offset : (offset + limit)]
|
2023-10-03 14:15:17 +00:00
|
|
|
chats = []
|
2023-10-13 00:28:00 +00:00
|
|
|
lock = asyncio.Lock()
|
2023-10-03 14:15:17 +00:00
|
|
|
if len(cids) == 0:
|
2023-10-14 06:38:12 +00:00
|
|
|
print(f"[resolvers.load] no chats for user with id={author_id}")
|
2023-10-12 23:20:10 +00:00
|
|
|
r = await create_chat(None, info, members=[2]) # member with id = 2 is discours
|
2023-11-17 05:00:57 +00:00
|
|
|
print(f"[resolvers.load] created chat: {r['chat_id']}")
|
2023-10-03 14:15:17 +00:00
|
|
|
cids.append(r["chat"]["id"])
|
2023-11-14 19:12:39 +00:00
|
|
|
all_authors: List[ChatMember] = await get_all_authors()
|
|
|
|
authors = {a["id"]: a for a in all_authors}
|
2023-10-04 20:52:43 +00:00
|
|
|
for cid in cids:
|
2023-10-13 00:16:54 +00:00
|
|
|
async with lock:
|
2023-10-14 14:55:51 +00:00
|
|
|
chat_str = await redis.execute("GET", f"chats/{cid}")
|
|
|
|
print(f"[resolvers.load] redis GET by {cid}: {chat_str}")
|
|
|
|
if chat_str:
|
|
|
|
c: ChatPayload = json.loads(chat_str)
|
2023-10-13 00:16:54 +00:00
|
|
|
c["messages"] = await load_messages(cid, 5, 0)
|
|
|
|
c["unread"] = await get_unread_counter(cid, author_id)
|
|
|
|
member_ids = c["members"].copy()
|
|
|
|
c["members"] = []
|
|
|
|
for member_id in member_ids:
|
2023-11-14 19:12:39 +00:00
|
|
|
a = authors.get(member_id)
|
|
|
|
if a:
|
2023-10-13 13:39:13 +00:00
|
|
|
a["online"] = a.get("id") in members_online
|
2023-10-13 13:37:42 +00:00
|
|
|
c["members"].append(a)
|
2023-10-13 00:16:54 +00:00
|
|
|
chats.append(c)
|
2023-10-03 14:15:17 +00:00
|
|
|
return {"chats": chats, "error": None}
|
|
|
|
|
|
|
|
|
|
|
|
@query.field("loadMessagesBy")
|
|
|
|
@login_required
|
|
|
|
async def load_messages_by(_, info, by, limit: int = 10, offset: int = 0):
|
|
|
|
"""load :limit messages of :chat_id with :offset"""
|
|
|
|
author_id = info.context["author_id"]
|
2023-10-14 14:55:51 +00:00
|
|
|
user_chats = (await redis.execute("SMEMBERS", "chats_by_author/" + str(author_id))) or []
|
2023-10-13 17:32:51 +00:00
|
|
|
user_chats = [c for c in user_chats]
|
2023-10-03 14:15:17 +00:00
|
|
|
if user_chats:
|
|
|
|
messages = []
|
|
|
|
by_chat = by.get("chat")
|
|
|
|
if by_chat in user_chats:
|
|
|
|
chat = await redis.execute("GET", f"chats/{by_chat}")
|
|
|
|
if not chat:
|
|
|
|
return {"messages": [], "error": "chat not exist"}
|
|
|
|
# everyone's messages in filtered chat
|
|
|
|
messages = await load_messages(by_chat, limit, offset)
|
|
|
|
return {
|
2023-10-14 06:38:12 +00:00
|
|
|
"messages": sorted(
|
2023-11-16 14:58:14 +00:00
|
|
|
[m for m in messages if m.get("created_at")],
|
|
|
|
key=lambda m: m.get("created_at"),
|
2023-10-14 06:38:12 +00:00
|
|
|
),
|
2023-10-03 14:15:17 +00:00
|
|
|
"error": None,
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
return {"error": "Cannot access messages of this chat"}
|
|
|
|
|
|
|
|
|
|
|
|
@query.field("loadRecipients")
|
|
|
|
async def load_recipients(_, _info, limit=50, offset=0):
|
|
|
|
"""load possible chat participants"""
|
|
|
|
onliners = (await redis.execute("SMEMBERS", "authors-online")) or []
|
2023-11-14 18:20:45 +00:00
|
|
|
r = []
|
2023-11-14 18:25:55 +00:00
|
|
|
all_authors: List[ChatMember] = await get_all_authors()
|
2023-11-14 18:20:45 +00:00
|
|
|
my_followings = await get_my_followings()
|
|
|
|
if len(my_followings) < limit:
|
2023-11-14 18:25:55 +00:00
|
|
|
my_followings = my_followings + all_authors[0 : limit - len(my_followings)]
|
2023-11-14 18:20:45 +00:00
|
|
|
for a in my_followings:
|
2023-10-14 06:38:12 +00:00
|
|
|
a["online"] = a["id"] in onliners
|
2023-11-14 18:20:45 +00:00
|
|
|
r.append(a)
|
2023-11-14 18:25:55 +00:00
|
|
|
|
2023-10-11 19:12:55 +00:00
|
|
|
# NOTE: maybe sort members here
|
2023-10-03 14:15:17 +00:00
|
|
|
|
2023-11-14 18:20:45 +00:00
|
|
|
print(f"[resolvers.load] loadRecipients found {len(r)} members")
|
2023-11-14 18:25:55 +00:00
|
|
|
|
2023-11-14 18:20:45 +00:00
|
|
|
return {"members": r, "error": None}
|