import json from datetime import datetime, timezone, timedelta from typing import Dict, Union, List, Any from resolvers.load import load_messages from services.auth import login_required from services.core import get_all_authors from services.rediscache import redis from services.schema import query @query.field("searchRecipients") @login_required async def search_recipients(_, info, text: str, limit: int = 50, offset: int = 0): result = [] # TODO: maybe redis scan? author_id = info.context["author_id"] existed_chats = await redis.execute("SMEMBERS", f"/chats_by_author/{author_id}") authors = await get_all_authors() members = {a["id"]: a for a in authors} if existed_chats: for chat_id in list(json.loads(existed_chats))[offset : (offset + limit)]: members_ids = await redis.execute("GET", f"/chats/{chat_id}/members") for member_id in members_ids: author = members.get(member_id) if author: if author["name"].startswith(text): if author not in result: result.append(author) more_amount = limit - len(result) if more_amount > 0: result += authors[0:more_amount] return {"members": list(result), "error": None} @query.field("searchMessages") @login_required async def search_in_chats( _, info, by: Dict[str, Union[str, int]], limit: int, offset: int ) -> Dict[str, Union[List[Dict[str, Any]], None]]: author_id = info.context["author_id"] lookup_chats = set((await redis.execute("SMEMBERS", f"chats_by_author/{author_id}")) or []) messages_set = set([]) by_member = by.get("author") body_like = by.get("body") days_ago = by.get("days") # pre-filter lookup chats if by_member: lookup_chats = filter( lambda ca: by_member in ca["members"], list(lookup_chats), ) # load the messages from lookup chats for c in lookup_chats: chat_id = c.decode() mmm = await load_messages(chat_id, limit, offset) if by_member: mmm = list(filter(lambda mx: mx["author"] == by_member, mmm)) if body_like: mmm = list(filter(lambda mx: body_like in mx["body"], mmm)) if days_ago: mmm = list( filter( lambda msg: int(datetime.now(tz=timezone.utc)) - int(msg["created_at"]) < int(timedelta(days=days_ago)), mmm, ) ) messages_set.union(set(mmm)) messages_sorted = sorted(list(messages_set)) return {"messages": messages_sorted, "error": None}