This commit is contained in:
parent
22a9b44612
commit
b7cb93a746
|
@ -12,23 +12,26 @@ from validators.chat import Message
|
||||||
@mutation.field("createMessage")
|
@mutation.field("createMessage")
|
||||||
@login_required
|
@login_required
|
||||||
async def create_message(_, info, chat: str, body: str, reply_to=None):
|
async def create_message(_, info, chat: str, body: str, reply_to=None):
|
||||||
"""
|
"""Создание сообщения с телом :body для чата :chat_id с возможным ответом на :reply_to"""
|
||||||
create message with
|
|
||||||
:body for
|
|
||||||
:chat_id replying to
|
|
||||||
:reply_to optionally
|
|
||||||
"""
|
|
||||||
author_id = info.context["author_id"]
|
author_id = info.context["author_id"]
|
||||||
|
|
||||||
|
# Получение данных чата из Redis
|
||||||
chat_data = await redis.execute("GET", f"chats/{chat}")
|
chat_data = await redis.execute("GET", f"chats/{chat}")
|
||||||
print(f"[resolvers.messages] debug chat data: {chat_data}")
|
print(f"[resolvers.messages] debug chat data: {chat_data}")
|
||||||
|
|
||||||
|
# Если данных чата нет, возвращаем ошибку
|
||||||
if not chat_data:
|
if not chat_data:
|
||||||
return {"error": "chat is not exist"}
|
return {"error": "chat is not exist"}
|
||||||
else:
|
else:
|
||||||
|
# Преобразование данных чата из строки JSON в словарь
|
||||||
chat_dict = json.loads(chat_data)
|
chat_dict = json.loads(chat_data)
|
||||||
print(chat_dict)
|
print(chat_dict)
|
||||||
|
|
||||||
|
# Получение ID следующего сообщения
|
||||||
message_id = await redis.execute("GET", f"chats/{chat_dict['id']}/next_message_id")
|
message_id = await redis.execute("GET", f"chats/{chat_dict['id']}/next_message_id")
|
||||||
message_id = int(message_id) if message_id else 0
|
message_id = int(message_id) if message_id else 0
|
||||||
|
|
||||||
|
# Создание нового сообщения
|
||||||
new_message: Message = {
|
new_message: Message = {
|
||||||
"chat": chat_dict["id"],
|
"chat": chat_dict["id"],
|
||||||
"id": message_id,
|
"id": message_id,
|
||||||
|
@ -37,24 +40,37 @@ async def create_message(_, info, chat: str, body: str, reply_to=None):
|
||||||
"createdAt": int(datetime.now(tz=timezone.utc).timestamp()),
|
"createdAt": int(datetime.now(tz=timezone.utc).timestamp()),
|
||||||
"updatedAt": None,
|
"updatedAt": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Если есть ответ, добавляем его в сообщение
|
||||||
if reply_to:
|
if reply_to:
|
||||||
new_message["replyTo"] = reply_to
|
new_message["replyTo"] = reply_to
|
||||||
|
|
||||||
|
# Обновление времени последнего обновления чата
|
||||||
chat_dict["updatedAt"] = new_message["createdAt"]
|
chat_dict["updatedAt"] = new_message["createdAt"]
|
||||||
await redis.execute("SET", f"chats/{chat_dict['id']}", json.dumps(chat))
|
|
||||||
|
# Запись обновленных данных чата обратно в Redis
|
||||||
|
await redis.execute("SET", f"chats/{chat_dict['id']}", json.dumps(chat_dict))
|
||||||
print(f"[inbox] creating message {new_message}")
|
print(f"[inbox] creating message {new_message}")
|
||||||
|
|
||||||
|
# Запись нового сообщения в Redis
|
||||||
await redis.execute(
|
await redis.execute(
|
||||||
"SET",
|
"SET",
|
||||||
f"chats/{chat_dict['id']}/messages/{message_id}",
|
f"chats/{chat_dict['id']}/messages/{message_id}",
|
||||||
json.dumps(new_message),
|
json.dumps(new_message),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Добавление ID нового сообщения в список ID сообщений чата
|
||||||
await redis.execute("LPUSH", f"chats/{chat_dict['id']}/message_ids", str(message_id))
|
await redis.execute("LPUSH", f"chats/{chat_dict['id']}/message_ids", str(message_id))
|
||||||
|
|
||||||
|
# Обновление ID следующего сообщения
|
||||||
await redis.execute("SET", f"chats/{chat_dict['id']}/next_message_id", str(message_id + 1))
|
await redis.execute("SET", f"chats/{chat_dict['id']}/next_message_id", str(message_id + 1))
|
||||||
|
|
||||||
|
# Добавление нового сообщения в список непрочитанных сообщений для каждого участника чата
|
||||||
members = chat_dict["members"]
|
members = chat_dict["members"]
|
||||||
for member_id in members:
|
for member_id in members:
|
||||||
await redis.execute("LPUSH", f"chats/{chat_dict['id']}/unread/{member_id}", str(message_id))
|
await redis.execute("LPUSH", f"chats/{chat_dict['id']}/unread/{member_id}", str(message_id))
|
||||||
|
|
||||||
# subscribe on updates
|
# Отправка уведомления о новом сообщении
|
||||||
await notify_message(new_message, chat_dict["id"])
|
await notify_message(new_message, chat_dict["id"])
|
||||||
|
|
||||||
return {"message": new_message, "error": None}
|
return {"message": new_message, "error": None}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user