This commit is contained in:
tonyrewin 2022-11-16 10:32:24 +03:00
parent edb68dc0dd
commit 2dd6327edd
6 changed files with 36 additions and 33 deletions

View File

@ -26,11 +26,11 @@ async def get_total_unread_counter(user_slug: str):
return unread return unread
async def load_messages(chatId: str, offset: int, amount: int): async def load_messages(chatId: str, limit: int, offset: int):
''' load :amount messages for :chatId with :offset ''' ''' load :limit messages for :chatId with :offset '''
messages = [] messages = []
message_ids = await redis.lrange( message_ids = await redis.lrange(
f"chats/{chatId}/message_ids", 0 - offset - amount, 0 - offset f"chats/{chatId}/message_ids", 0 - offset - limit, 0 - offset
) )
if message_ids: if message_ids:
message_keys = [ message_keys = [
@ -46,16 +46,16 @@ async def load_messages(chatId: str, offset: int, amount: int):
@query.field("loadChats") @query.field("loadChats")
@login_required @login_required
async def load_chats(_, info, offset: int, amount: int): async def load_chats(_, info, limit: int, offset: int):
""" load :amount chats of current user with :offset """ """ load :limit chats of current user with :offset """
user = info.context["request"].user user = info.context["request"].user
chats = await redis.execute("GET", f"chats_by_user/{user.slug}") chats = await redis.execute("GET", f"chats_by_user/{user.slug}")
if chats: if chats:
chats = list(json.loads(chats))[offset:offset + amount] chats = list(json.loads(chats))[offset:offset + limit]
if not chats: if not chats:
chats = [] chats = []
for c in chats: for c in chats:
c['messages'] = await load_messages(c['id'], offset, amount) c['messages'] = await load_messages(c['id'], limit, offset)
c['unread'] = await get_unread_counter(c['id'], user.slug) c['unread'] = await get_unread_counter(c['id'], user.slug)
return { return {
"chats": chats, "chats": chats,
@ -65,8 +65,8 @@ async def load_chats(_, info, offset: int, amount: int):
@query.field("loadMessagesBy") @query.field("loadMessagesBy")
@login_required @login_required
async def load_messages_by(_, info, by, offset: int = 0, amount: int = 50): async def load_messages_by(_, info, by, limit: int = 50, offset: int = 0):
''' load :amount messages of :chat_id with :offset ''' ''' load :amolimitunt messages of :chat_id with :offset '''
user = info.context["request"].user user = info.context["request"].user
my_chats = await redis.execute("GET", f"chats_by_user/{user.slug}") my_chats = await redis.execute("GET", f"chats_by_user/{user.slug}")
chat_id = by.get('chat') chat_id = by.get('chat')
@ -76,17 +76,17 @@ async def load_messages_by(_, info, by, offset: int = 0, amount: int = 50):
return { return {
"error": "chat not exist" "error": "chat not exist"
} }
messages = await load_messages(chat_id, offset, amount) messages = await load_messages(chat_id, limit, offset)
user_id = by.get('author') user_id = by.get('author')
if user_id: if user_id:
chats = await redis.execute("GET", f"chats_by_user/{user_id}") chats = await redis.execute("GET", f"chats_by_user/{user_id}")
our_chats = list(set(chats) & set(my_chats)) our_chats = list(set(chats) & set(my_chats))
for c in our_chats: for c in our_chats:
messages += await load_messages(c, offset, amount) messages += await load_messages(c, limit, offset)
body_like = by.get('body') body_like = by.get('body')
if body_like: if body_like:
for c in my_chats: for c in my_chats:
mmm = await load_messages(c, offset, amount) mmm = await load_messages(c, limit, offset)
for m in mmm: for m in mmm:
if body_like in m["body"]: if body_like in m["body"]:
messages.append(m) messages.append(m)

View File

@ -9,13 +9,13 @@ from orm.user import AuthorFollower
@query.field("searchUsers") @query.field("searchUsers")
@login_required @login_required
async def search_users(_, info, query: str, offset: int = 0, amount: int = 50): async def search_users(_, info, query: str, limit: int = 50, offset: int = 0):
result = [] result = []
# TODO: maybe redis scan? # TODO: maybe redis scan?
user = info.context["request"].user user = info.context["request"].user
talk_before = await redis.execute("GET", f"/chats_by_user/{user.slug}") talk_before = await redis.execute("GET", f"/chats_by_user/{user.slug}")
if talk_before: if talk_before:
talk_before = list(json.loads(talk_before))[offset:offset + amount] talk_before = list(json.loads(talk_before))[offset:offset + limit]
for chat_id in talk_before: for chat_id in talk_before:
members = await redis.execute("GET", f"/chats/{chat_id}/users") members = await redis.execute("GET", f"/chats/{chat_id}/users")
if members: if members:
@ -26,17 +26,17 @@ async def search_users(_, info, query: str, offset: int = 0, amount: int = 50):
result.append(member) result.append(member)
user = info.context["request"].user user = info.context["request"].user
more_amount = amount - len(result) more_amount = limit - len(result)
with local_session() as session: with local_session() as session:
# followings # followings
result += session.query(AuthorFollower.author).where(AuthorFollower.follower.startswith(query))\ result += session.query(AuthorFollower.author).where(AuthorFollower.follower.startswith(query))\
.offset(offset + len(result)).limit(more_amount) .offset(offset + len(result)).limit(more_amount)
more_amount = amount more_amount = limit
# followers # followers
result += session.query(AuthorFollower.follower).where(AuthorFollower.author.startswith(query))\ result += session.query(AuthorFollower.follower).where(AuthorFollower.author.startswith(query))\
.offset(offset + len(result)).limit(offset + len(result) + amount) .offset(offset + len(result)).limit(offset + len(result) + limit)
return { return {
"slugs": list(result), "slugs": list(result),
"error": None "error": None

View File

@ -185,7 +185,7 @@ async def get_authors_all(_, _info):
@query.field("loadAuthorsBy") @query.field("loadAuthorsBy")
async def load_authors_by(_, info, by, amount, offset): async def load_authors_by(_, info, by, limit, offset):
authors = [] authors = []
with local_session() as session: with local_session() as session:
aq = session.query(User) aq = session.query(User)
@ -206,7 +206,7 @@ async def load_authors_by(_, info, by, amount, offset):
User.id User.id
).order_by( ).order_by(
by.get("order") or "createdAt" by.get("order") or "createdAt"
).limit(amount).offset(offset) ).limit(limit).offset(offset)
authors = list(map(lambda r: r.User, session.execute(aq))) authors = list(map(lambda r: r.User, session.execute(aq)))
if by.get("stat"): if by.get("stat"):
for a in authors: for a in authors:

View File

@ -1,6 +1,6 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from sqlalchemy import and_, desc, select, text from sqlalchemy import and_, desc, select, text, func
from sqlalchemy.orm import selectinload from sqlalchemy.orm import selectinload
from auth.authenticate import login_required from auth.authenticate import login_required
@ -202,7 +202,7 @@ async def delete_reaction(_, info, rid):
@query.field("loadReactionsBy") @query.field("loadReactionsBy")
async def load_reactions_by(_, info, by, amount=50, offset=0): async def load_reactions_by(_, info, by, limit=50, offset=0):
""" """
:param by: { :param by: {
shout: 'some-slug' shout: 'some-slug'
@ -212,7 +212,7 @@ async def load_reactions_by(_, info, by, amount=50, offset=0):
stat: 'rating' | 'comments' | 'reacted' | 'views', stat: 'rating' | 'comments' | 'reacted' | 'views',
days: 30 days: 30
} }
:param amount: int amount of shouts :param limit: int amount of shouts
:param offset: int offset in this order :param offset: int offset in this order
:return: Reaction[] :return: Reaction[]
""" """
@ -236,13 +236,16 @@ async def load_reactions_by(_, info, by, amount=50, offset=0):
if by.get("topic"): if by.get("topic"):
q = q.filter(Shout.topics.contains(by["topic"])) q = q.filter(Shout.topics.contains(by["topic"]))
if by.get("body"): if by.get("body"):
if by["body"] is True:
q = q.filter(func.length(Reaction.body) > 0)
else:
q = q.filter(Reaction.body.ilike(f'%{by["body"]}%')) q = q.filter(Reaction.body.ilike(f'%{by["body"]}%'))
if by.get("days"): if by.get("days"):
before = datetime.now() - timedelta(days=int(by["days"]) or 30) before = datetime.now() - timedelta(days=int(by["days"]) or 30)
q = q.filter(Reaction.createdAt > before) q = q.filter(Reaction.createdAt > before)
q = q.group_by(Shout.id).order_by( q = q.group_by(Shout.id).order_by(
desc(by.get("order") or "createdAt") desc(by.get("order") or "createdAt")
).limit(amount).offset(offset) ).limit(limit).offset(offset)
rrr = [] rrr = []
with local_session() as session: with local_session() as session:

View File

@ -17,7 +17,7 @@ from services.stat.reacted import ReactedStorage
@query.field("loadShoutsBy") @query.field("loadShoutsBy")
async def load_shouts_by(_, info, by, amount=50, offset=0): async def load_shouts_by(_, info, by, limit=50, offset=0):
""" """
:param by: { :param by: {
layout: 'audio', layout: 'audio',
@ -29,7 +29,7 @@ async def load_shouts_by(_, info, by, amount=50, offset=0):
stat: 'rating' | 'comments' | 'reacted' | 'views', stat: 'rating' | 'comments' | 'reacted' | 'views',
days: 30 days: 30
} }
:param amount: int amount of shouts :param limit: int amount of shouts
:param offset: int offset in this order :param offset: int offset in this order
:return: Shout[] :return: Shout[]
""" """
@ -69,7 +69,7 @@ async def load_shouts_by(_, info, by, amount=50, offset=0):
q = q.filter(Shout.createdAt > before) q = q.filter(Shout.createdAt > before)
q = q.group_by(Shout.id, Reaction.id).order_by( q = q.group_by(Shout.id, Reaction.id).order_by(
desc(by.get("order") or "createdAt") desc(by.get("order") or "createdAt")
).limit(amount).offset(offset) ).limit(limit).offset(offset)
print(q) print(q)
shouts = [] shouts = []
with local_session() as session: with local_session() as session:

View File

@ -239,9 +239,9 @@ input ReactionBy {
type Query { type Query {
# inbox # inbox
loadChats(offset: Int, amount: Int): Result! # your chats loadChats( limit: Int, offset: Int): Result! # your chats
loadMessagesBy(by: MessagesBy!, amount: Int, offset: Int): Result! loadMessagesBy(by: MessagesBy!, limit: Int, offset: Int): Result!
searchUsers(query: String!, amount: Int, offset: Int): Result! searchUsers(query: String!, limit: Int, offset: Int): Result!
# auth # auth
isEmailUsed(email: String!): Boolean! isEmailUsed(email: String!): Boolean!
@ -249,9 +249,9 @@ type Query {
signOut: AuthResult! signOut: AuthResult!
# zine # zine
loadAuthorsBy(by: AuthorsBy, amount: Int, offset: Int): [Author]! loadAuthorsBy(by: AuthorsBy, limit: Int, offset: Int): [Author]!
loadShoutsBy(by: ShoutsBy, amount: Int, offset: Int): [Shout]! loadShoutsBy(by: ShoutsBy, limit: Int, offset: Int): [Shout]!
loadReactionsBy(by: ReactionBy!, amount: Int, limit: Int): [Reaction]! loadReactionsBy(by: ReactionBy!, limit: Int, offset: Int): [Reaction]!
userFollowers(slug: String!): [Author]! userFollowers(slug: String!): [Author]!
userFollowedAuthors(slug: String!): [Author]! userFollowedAuthors(slug: String!): [Author]!
userFollowedTopics(slug: String!): [Topic]! userFollowedTopics(slug: String!): [Topic]!