inbox/resolvers/search.py
Untone 2253bcf956
Some checks failed
deploy / deploy (push) Failing after 1m1s
cached-request-9
2023-12-19 20:19:16 +03:00

81 lines
2.6 KiB
Python

import json
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Union
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("search_recipients")
@login_required
async def search_recipients(_, info, text: str, limit: int = 50, offset: int = 0):
result = set([])
# TODO: maybe redis scan?
author_id = info.context["author_id"]
authors = get_all_authors()
authors_by_id = {a["id"]: a for a in authors}
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:
author = authors_by_id.get(member_id)
if author:
if author["name"].startswith(text):
result.add(author)
more_amount = limit - len(result)
if more_amount > 0:
result.update(authors_by_id.values()[0:more_amount])
return {"members": list(result), "error": None}
@query.field("search_messages")
@login_required
async def search_messages(
_, 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}