core/resolvers/inbox/search.py

50 lines
1.7 KiB
Python
Raw Normal View History

2022-11-11 21:27:17 +00:00
import json
from auth.authenticate import login_required
from base.redis import redis
2022-11-12 07:13:51 +00:00
from base.resolvers import query
from base.orm import local_session
2022-11-29 12:36:46 +00:00
from orm.user import AuthorFollower, User
2022-11-11 21:27:17 +00:00
2022-11-21 08:13:57 +00:00
@query.field("searchRecipients")
2022-11-11 21:27:17 +00:00
@login_required
2022-11-21 08:13:57 +00:00
async def search_recipients(_, info, query: str, limit: int = 50, offset: int = 0):
2022-11-11 21:27:17 +00:00
result = []
# TODO: maybe redis scan?
user = info.context["request"].user
talk_before = await redis.execute("GET", f"/chats_by_user/{user.slug}")
if talk_before:
2022-11-16 07:32:24 +00:00
talk_before = list(json.loads(talk_before))[offset:offset + limit]
2022-11-11 21:27:17 +00:00
for chat_id in talk_before:
members = await redis.execute("GET", f"/chats/{chat_id}/users")
if members:
members = list(json.loads(members))
for member in members:
if member.startswith(query):
if member not in result:
result.append(member)
user = info.context["request"].user
2022-11-16 07:32:24 +00:00
more_amount = limit - len(result)
2022-11-11 21:27:17 +00:00
2022-11-12 07:13:51 +00:00
with local_session() as session:
# followings
2022-11-29 12:36:46 +00:00
result += session.query(AuthorFollower.author).join(
User, User.id == AuthorFollower.follower
2022-11-29 12:36:46 +00:00
).where(
User.slug.startswith(query)
).offset(offset + len(result)).limit(more_amount)
2022-11-11 21:27:17 +00:00
2022-11-16 07:32:24 +00:00
more_amount = limit
2022-11-12 07:13:51 +00:00
# followers
2022-11-29 12:36:46 +00:00
result += session.query(AuthorFollower.follower).join(
User, User.id == AuthorFollower.author
2022-11-29 12:36:46 +00:00
).where(
User.slug.startswith(query)
).offset(offset + len(result)).limit(offset + len(result) + limit)
2022-11-11 21:27:17 +00:00
return {
2022-11-21 08:13:57 +00:00
"members": list(result),
2022-11-11 21:27:17 +00:00
"error": None
}