validators

This commit is contained in:
2023-10-14 09:38:12 +03:00
parent ee195d4ec7
commit d6e52d9465
9 changed files with 116 additions and 95 deletions

View File

@@ -4,13 +4,15 @@ from services.core import get_author, get_network
from services.redis import redis
from services.auth import login_required
from services.schema import query
from validators.chat import Message
from validators.chat import Message, Chat, ChatMember
from .chats import create_chat
from .unread import get_unread_counter
import asyncio
# NOTE: not an API handler
async def load_messages(chat_id: str, limit: int = 5, offset: int = 0, ids: Optional[List[str]] = None) -> List[Message]:
async def load_messages(
chat_id: str, limit: int = 5, offset: int = 0, ids: Optional[List[str]] = None
) -> List[Message]:
"""load :limit messages for :chat_id with :offset"""
if ids is None:
ids = []
@@ -18,9 +20,11 @@ async def load_messages(chat_id: str, limit: int = 5, offset: int = 0, ids: Opti
try:
message_ids = [] + ids
if limit:
mids = (await redis.lrange(
f"chats/{chat_id}/message_ids", offset, offset + limit
)) or []
mids = (
await redis.lrange(
f"chats/{chat_id}/message_ids", offset, offset + limit
)
) or []
mids = [mid for mid in mids]
message_ids += mids
if message_ids:
@@ -40,18 +44,21 @@ async def load_messages(chat_id: str, limit: int = 5, offset: int = 0, ids: Opti
print(f"Error loading messages for chat {chat_id}: {e}")
return messages
@query.field("loadChats")
@login_required
async def load_chats(_, info, limit: int = 50, offset: int = 0) -> Dict[str, Union[List[Dict[str, Any]], None]]:
async def load_chats(
_, info, limit: int = 50, offset: int = 0
) -> Dict[str, Union[List[Dict[str, Any]], None]]:
"""load :limit chats of current user with :offset"""
author_id = info.context["author_id"]
cids = (await redis.execute("SMEMBERS", f"chats_by_author/{author_id}")) or []
members_online = (await redis.execute("SMEMBERS", "authors-online")) or []
cids = list(cids)[offset:(offset + limit)]
cids = list(cids)[offset : (offset + limit)]
chats = []
lock = asyncio.Lock()
if len(cids) == 0:
print(f"[resolvers.load] no chats for user with id={author_id}, create one with Discours (id=2)")
print(f"[resolvers.load] no chats for user with id={author_id}")
r = await create_chat(None, info, members=[2]) # member with id = 2 is discours
print(f"[resolvers.load] created chat: {r}")
cids.append(r["chat"]["id"])
@@ -60,7 +67,7 @@ async def load_chats(_, info, limit: int = 50, offset: int = 0) -> Dict[str, Uni
c = await redis.execute("GET", f"chats/{cid}")
print(f"[resolvers.load] redis GET by {cid}: {c}")
if c:
c = json.loads(c)
c: Chat = json.loads(c)
c["messages"] = await load_messages(cid, 5, 0)
c["unread"] = await get_unread_counter(cid, author_id)
member_ids = c["members"].copy()
@@ -80,7 +87,9 @@ async def load_chats(_, info, limit: int = 50, offset: int = 0) -> Dict[str, Uni
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"]
user_chats = (await redis.execute("SMEMBERS", "chats_by_author/" + str(author_id))) or []
user_chats = (
await redis.execute("SMEMBERS", "chats_by_author/" + str(author_id))
) or []
user_chats = [c for c in user_chats]
if user_chats:
messages = []
@@ -92,7 +101,10 @@ async def load_messages_by(_, info, by, limit: int = 10, offset: int = 0):
# everyone's messages in filtered chat
messages = await load_messages(by_chat, limit, offset)
return {
"messages": sorted([m for m in messages if m.get("createdAt")], key=lambda m: m.get("createdAt")),
"messages": sorted(
[m for m in messages if m.get("createdAt")],
key=lambda m: m.get("createdAt"),
),
"error": None,
}
else:
@@ -104,18 +116,10 @@ async def load_recipients(_, _info, limit=50, offset=0):
"""load possible chat participants"""
onliners = (await redis.execute("SMEMBERS", "authors-online")) or []
members = []
all_authors = await get_network(limit, offset)
all_authors: List[ChatMember] = await get_network(limit, offset)
for a in all_authors:
members.append(
{
"id": a.id,
"slug": a.slug,
"userpic": a.userpic,
"name": a.name,
"lastSeen": a.lastSeen,
"online": a.id in onliners,
}
)
a["online"] = a["id"] in onliners
members.append(a)
# NOTE: maybe sort members here