97 lines
3.1 KiB
Python
97 lines
3.1 KiB
Python
import json
|
|
from datetime import datetime, timezone, timedelta
|
|
from services.auth import login_required
|
|
from services.redis import redis
|
|
from resolvers import query
|
|
from services.db import local_session
|
|
from orm.author import AuthorFollower, Author
|
|
from resolvers.load import load_messages
|
|
|
|
|
|
@query.field("searchRecipients")
|
|
@login_required
|
|
async def search_recipients(_, info, text: str, limit: int = 50, offset: int = 0):
|
|
result = []
|
|
# TODO: maybe redis scan?
|
|
author = info.context["author"]
|
|
talk_before = await redis.execute("GET", f"/chats_by_author/{author.id}")
|
|
if talk_before:
|
|
talk_before = list(json.loads(talk_before))[offset : (offset + limit)]
|
|
for chat_id in talk_before:
|
|
members = await redis.execute("GET", f"/chats/{chat_id}/members")
|
|
if members:
|
|
members = list(json.loads(members))
|
|
for member in members:
|
|
if member.startswith(text):
|
|
if member not in result:
|
|
result.append(member)
|
|
|
|
more_amount = limit - len(result)
|
|
|
|
with local_session() as session:
|
|
# followings
|
|
result += (
|
|
session.query(AuthorFollower.author)
|
|
.join(Author, Author.id == AuthorFollower.follower)
|
|
.where(Author.slug.startswith(text))
|
|
.offset(offset + len(result))
|
|
.limit(more_amount)
|
|
)
|
|
|
|
# followers
|
|
result += (
|
|
session.query(AuthorFollower.follower)
|
|
.join(Author, Author.id == AuthorFollower.author)
|
|
.where(Author.slug.startswith(text))
|
|
.offset(offset + len(result))
|
|
.limit(offset + len(result) + limit)
|
|
)
|
|
return {"members": list(result), "error": None}
|
|
|
|
|
|
@query.field("searchMessages")
|
|
@login_required
|
|
async def search_in_chats(_, info, by, limit, offset):
|
|
author_id = info.context["author_id"]
|
|
lookup_chats = set(await redis.execute("SMEMBERS", f"chats_by_author/{author_id}"))
|
|
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:
|
|
# all author's chats where reqeusting author is participating
|
|
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("utf-8")
|
|
mmm = await load_messages(chat_id, limit, offset)
|
|
if by_member:
|
|
mmm = filter(lambda mx: mx["author"] == by_member, mmm)
|
|
if body_like:
|
|
mmm = filter(lambda mx: body_like in mx["body"], mmm)
|
|
if days_ago:
|
|
mmm = filter(
|
|
lambda msg: datetime.now(tz=timezone.utc) - int(msg["createdAt"])
|
|
< timedelta(days=days_ago),
|
|
mmm,
|
|
)
|
|
|
|
messages_set.union(set(mmm))
|
|
|
|
return {"messages": messages_sorted, "error": None}
|
|
|
|
|
|
search_resolvers = {
|
|
"Query": {
|
|
"searchMessages": search_in_chats,
|
|
"searchRecipients": search_recipients,
|
|
}
|
|
}
|