fixes-for-inbox-auth-and-startup-faster

This commit is contained in:
2022-11-26 01:35:42 +03:00
parent 6e073d5dd1
commit 152c3362a0
14 changed files with 168 additions and 138 deletions

View File

@@ -7,43 +7,6 @@ from base.redis import redis
from base.resolvers import mutation
async def add_user_to_chat(user_slug: str, chat_id: str, chat=None):
for member in chat["users"]:
chats_ids = await redis.execute("GET", f"chats_by_user/{member}")
if chats_ids:
chats_ids = list(json.loads(chats_ids))
else:
chats_ids = []
if chat_id not in chats_ids:
chats_ids.append(chat_id)
await redis.execute("SET", f"chats_by_user/{member}", json.dumps(chats_ids))
@mutation.field("inviteChat")
async def invite_to_chat(_, info, invited: str, chat_id: str):
''' invite user with :slug to chat with :chat_id '''
user = info.context["request"].user
chat = await redis.execute("GET", f"chats/{chat_id}")
if not chat:
return {
"error": "chat not exist"
}
chat = dict(json.loads(chat))
if not chat['private'] and user.slug not in chat['admins']:
return {
"error": "only admins can invite to private chat",
"chat": chat
}
else:
chat["users"].append(invited)
await add_user_to_chat(user.slug, chat_id, chat)
await redis.execute("SET", f"chats/{chat_id}", json.dumps(chat))
return {
"error": None,
"chat": chat
}
@mutation.field("updateChat")
@login_required
async def update_chat(_, info, chat_new: dict):
@@ -71,9 +34,8 @@ async def update_chat(_, info, chat_new: dict):
"admins": chat_new.get("admins", chat["admins"]),
"users": chat_new.get("users", chat["users"])
})
await add_user_to_chat(user.slug, chat_id, chat)
await redis.execute("SET", f"chats/{chat.id}", json.dumps(chat))
await redis.execute("SET", f"chats/{chat.id}/next_message_id", 0)
await redis.execute("COMMIT")
return {
"error": None,
@@ -97,11 +59,22 @@ async def create_chat(_, info, title="", members=[]):
"users": members,
"admins": [user.slug, ]
}
# double creation protection
cids = await redis.execute("SMEMBERS", f"chats_by_user/{user.slug}")
for cid in cids:
c = await redis.execute("GET", F"chats/{cid.decode('utf-8')}")
isc = [x for x in c["users"] if x not in chat["users"]]
if isc == [] and chat["title"] == c["title"]:
return {
"error": "chat was created before",
"chat": chat
}
await add_user_to_chat(user.slug, chat_id, chat)
for m in members:
await redis.execute("SADD", f"chats_by_user/{m}", chat_id)
await redis.execute("SET", f"chats/{chat_id}", json.dumps(chat))
await redis.execute("SET", f"chats/{chat_id}/next_message_id", str(0))
await redis.execute("COMMIT")
return {
"error": None,
"chat": chat
@@ -117,6 +90,8 @@ async def delete_chat(_, info, chat_id: str):
chat = dict(json.loads(chat))
if user.slug in chat['admins']:
await redis.execute("DEL", f"chats/{chat_id}")
await redis.execute("SREM", "chats_by_user/" + user, chat_id)
await redis.execute("COMMIT")
else:
return {
"error": "chat not exist"

View File

@@ -5,52 +5,51 @@ from auth.authenticate import login_required
from base.redis import redis
from base.orm import local_session
from base.resolvers import query
from base.exceptions import ObjectNotExist
from orm.user import User
from resolvers.zine.profile import followed_authors
from .unread import get_unread_counter
async def load_messages(chatId: str, limit: int, offset: int):
''' load :limit messages for :chatId with :offset '''
async def load_messages(chat_id: str, limit: int, offset: int):
''' load :limit messages for :chat_id with :offset '''
messages = []
message_ids = await redis.lrange(
f"chats/{chatId}/message_ids", 0 - offset - limit, 0 - offset
f"chats/{chat_id}/message_ids", offset + limit, offset
)
if message_ids:
message_keys = [
f"chats/{chatId}/messages/{mid}" for mid in message_ids
f"chats/{chat_id}/messages/{mid}" for mid in message_ids
]
messages = await redis.mget(*message_keys)
messages = [json.loads(msg) for msg in messages]
return {
"messages": messages,
"error": None
}
return messages
@query.field("loadChats")
@login_required
async def load_chats(_, info, limit: int, offset: int):
async def load_chats(_, info, limit: int = 50, offset: int = 0):
""" load :limit chats of current user with :offset """
user = info.context["request"].user
if user:
chats = await redis.execute("GET", f"chats_by_user/{user.slug}")
if chats:
chats = list(json.loads(chats))[offset:offset + limit]
if not chats:
chats = []
for c in chats:
c['messages'] = await load_messages(c['id'], limit, offset)
c['unread'] = await get_unread_counter(c['id'], user.slug)
return {
"chats": chats,
"error": None
}
else:
return {
"error": "please login",
"chats": []
}
print('[inbox] load user\'s chats')
cids = await redis.execute("SMEMBERS", "chats_by_user/" + user.slug)
if cids:
cids = list(cids)[offset:offset + limit]
if not cids:
print('[inbox.load] no chats were found')
cids = []
chats = []
for cid in cids:
c = await redis.execute("GET", "chats/" + cid.decode("utf-8"))
if c:
c = json.loads(c)
c['messages'] = await load_messages(cid, 50, 0)
c['unread'] = await get_unread_counter(cid, user.slug)
chats.append(c)
return {
"chats": chats,
"error": None
}
@query.field("loadMessagesBy")
@@ -58,28 +57,36 @@ async def load_chats(_, info, limit: int, offset: int):
async def load_messages_by(_, info, by, limit: int = 50, offset: int = 0):
''' load :amolimitunt messages of :chat_id with :offset '''
user = info.context["request"].user
my_chats = await redis.execute("GET", f"chats_by_user/{user.slug}")
chat_id = by.get('chat')
if chat_id:
chat = await redis.execute("GET", f"chats/{chat_id}")
cids = await redis.execute("SMEMBERS", "chats_by_user/" + user.slug)
by_chat = by.get('chat')
messages = []
if by_chat:
chat = await redis.execute("GET", f"chats/{by_chat}")
if not chat:
return {
"error": "chat not exist"
}
messages = await load_messages(chat_id, limit, offset)
user_id = by.get('author')
if user_id:
chats = await redis.execute("GET", f"chats_by_user/{user_id}")
our_chats = list(set(chats) & set(my_chats))
for c in our_chats:
messages += await load_messages(c, limit, offset)
raise ObjectNotExist("Chat not exists")
messages = await load_messages(by_chat, limit, offset)
by_author = by.get('author')
if by_author:
if not by_chat:
# all author's messages
by_author_cids = await redis.execute("SMEMBERS", f"chats_by_user/{by_author}")
for c in list(by_author_cids & cids):
messages += await load_messages(c, limit, offset)
else:
# author's messages in chat
messages = filter(lambda m: m["author"] == by_author, messages)
body_like = by.get('body')
if body_like:
for c in my_chats:
mmm = await load_messages(c, limit, offset)
for m in mmm:
if body_like in m["body"]:
messages.append(m)
if not by_chat:
# search in all messages in all user's chats
for c in list(cids):
mmm = await load_messages(c, limit, offset)
for m in mmm:
if body_like in m["body"]:
messages.append(m)
else:
# search in chat's messages
messages = filter(lambda m: body_like in m["body"], messages)
days = by.get("days")
if days:
messages = filter(

View File

@@ -17,6 +17,6 @@ async def get_total_unread_counter(user_slug: str):
if chats:
chats = json.loads(chats)
for chat_id in chats:
n = await get_unread_counter(chat_id, user_slug)
n = await get_unread_counter(chat_id.decode('utf-8'), user_slug)
unread += n
return unread