inbox/resolvers/search.py
Untone 1d44b2e336
All checks were successful
deploy / deploy (push) Successful in 1m14s
workaround-get-author
2023-11-14 18:56:37 +03:00

77 lines
2.6 KiB
Python

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_network
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}")
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:
for author in (await get_network(member_id), 1):
if author["name"].startswith(text):
if author not in result:
result.append(author)
more_amount = limit - len(result)
if more_amount > 0:
result += await get_network(author_id, 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["createdAt"])
< int(timedelta(days=days_ago)),
mmm,
)
)
messages_set.union(set(mmm))
messages_sorted = sorted(list(messages_set))
return {"messages": messages_sorted, "error": None}