restructured,inbox-removed
This commit is contained in:
@@ -1,124 +0,0 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.redis import redis
|
||||
from base.resolvers import mutation
|
||||
from validations.inbox import Chat
|
||||
|
||||
|
||||
@mutation.field("updateChat")
|
||||
@login_required
|
||||
async def update_chat(_, info, chat_new: Chat):
|
||||
"""
|
||||
updating chat
|
||||
requires info["request"].user.slug to be in chat["admins"]
|
||||
|
||||
:param info: GraphQLInfo with request
|
||||
:param chat_new: dict with chat data
|
||||
:return: Result { error chat }
|
||||
"""
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
chat_id = chat_new["id"]
|
||||
chat = await redis.execute("GET", f"chats/{chat_id}")
|
||||
if not chat:
|
||||
return {
|
||||
"error": "chat not exist"
|
||||
}
|
||||
chat = dict(json.loads(chat))
|
||||
|
||||
# TODO
|
||||
if auth.user_id in chat["admins"]:
|
||||
chat.update({
|
||||
"title": chat_new.get("title", chat["title"]),
|
||||
"description": chat_new.get("description", chat["description"]),
|
||||
"updatedAt": int(datetime.now(tz=timezone.utc).timestamp()),
|
||||
"admins": chat_new.get("admins", chat.get("admins") or []),
|
||||
"users": chat_new.get("users", chat["users"])
|
||||
})
|
||||
await redis.execute("SET", f"chats/{chat.id}", json.dumps(chat))
|
||||
await redis.execute("COMMIT")
|
||||
|
||||
return {
|
||||
"error": None,
|
||||
"chat": chat
|
||||
}
|
||||
|
||||
|
||||
@mutation.field("createChat")
|
||||
@login_required
|
||||
async def create_chat(_, info, title="", members=[]):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
chat = {}
|
||||
print('create_chat members: %r' % members)
|
||||
if auth.user_id not in members:
|
||||
members.append(int(auth.user_id))
|
||||
|
||||
# reuse chat craeted before if exists
|
||||
if len(members) == 2 and title == "":
|
||||
chat = None
|
||||
print(members)
|
||||
chatset1 = await redis.execute("SMEMBERS", f"chats_by_user/{members[0]}")
|
||||
if not chatset1:
|
||||
chatset1 = set([])
|
||||
print(chatset1)
|
||||
chatset2 = await redis.execute("SMEMBERS", f"chats_by_user/{members[1]}")
|
||||
if not chatset2:
|
||||
chatset2 = set([])
|
||||
print(chatset2)
|
||||
chatset = chatset1.intersection(chatset2)
|
||||
print(chatset)
|
||||
for c in chatset:
|
||||
chat = await redis.execute("GET", f"chats/{c.decode('utf-8')}")
|
||||
if chat:
|
||||
chat = json.loads(chat)
|
||||
if chat['title'] == "":
|
||||
print('[inbox] createChat found old chat')
|
||||
print(chat)
|
||||
break
|
||||
if chat:
|
||||
return {
|
||||
"chat": chat,
|
||||
"error": "existed"
|
||||
}
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
chat = {
|
||||
"id": chat_id,
|
||||
"users": members,
|
||||
"title": title,
|
||||
"createdBy": auth.user_id,
|
||||
"createdAt": int(datetime.now(tz=timezone.utc).timestamp()),
|
||||
"updatedAt": int(datetime.now(tz=timezone.utc).timestamp()),
|
||||
"admins": members if (len(members) == 2 and title == "") else []
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@mutation.field("deleteChat")
|
||||
@login_required
|
||||
async def delete_chat(_, info, chat_id: str):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
chat = await redis.execute("GET", f"/chats/{chat_id}")
|
||||
if chat:
|
||||
chat = dict(json.loads(chat))
|
||||
if auth.user_id in chat['admins']:
|
||||
await redis.execute("DEL", f"chats/{chat_id}")
|
||||
await redis.execute("SREM", "chats_by_user/" + str(auth.user_id), chat_id)
|
||||
await redis.execute("COMMIT")
|
||||
else:
|
||||
return {
|
||||
"error": "chat not exist"
|
||||
}
|
@@ -1,152 +0,0 @@
|
||||
import json
|
||||
# from datetime import datetime, timedelta, timezone
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.redis import redis
|
||||
from base.orm import local_session
|
||||
from base.resolvers import query
|
||||
from orm.user import User
|
||||
from resolvers.zine.profile import followed_authors
|
||||
from .unread import get_unread_counter
|
||||
|
||||
|
||||
async def load_messages(chat_id: str, limit: int = 5, offset: int = 0, ids=[]):
|
||||
''' load :limit messages for :chat_id with :offset '''
|
||||
messages = []
|
||||
message_ids = []
|
||||
if ids:
|
||||
message_ids += ids
|
||||
try:
|
||||
if limit:
|
||||
mids = await redis.lrange(f"chats/{chat_id}/message_ids",
|
||||
offset,
|
||||
offset + limit
|
||||
)
|
||||
mids = [mid.decode("utf-8") for mid in mids]
|
||||
message_ids += mids
|
||||
except Exception as e:
|
||||
print(e)
|
||||
if message_ids:
|
||||
message_keys = [f"chats/{chat_id}/messages/{mid}" for mid in message_ids]
|
||||
messages = await redis.mget(*message_keys)
|
||||
messages = [json.loads(msg.decode('utf-8')) for msg in messages]
|
||||
replies = []
|
||||
for m in messages:
|
||||
rt = m.get('replyTo')
|
||||
if rt:
|
||||
rt = int(rt)
|
||||
if rt not in message_ids:
|
||||
replies.append(rt)
|
||||
if replies:
|
||||
messages += await load_messages(chat_id, limit=0, ids=replies)
|
||||
return messages
|
||||
|
||||
|
||||
@query.field("loadChats")
|
||||
@login_required
|
||||
async def load_chats(_, info, limit: int = 50, offset: int = 0):
|
||||
""" load :limit chats of current user with :offset """
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
cids = await redis.execute("SMEMBERS", "chats_by_user/" + str(auth.user_id))
|
||||
if cids:
|
||||
cids = list(cids)[offset:offset + limit]
|
||||
if not cids:
|
||||
print('[inbox.load] no chats were found')
|
||||
cids = []
|
||||
onliners = await redis.execute("SMEMBERS", "users-online")
|
||||
if not onliners:
|
||||
onliners = []
|
||||
chats = []
|
||||
for cid in cids:
|
||||
cid = cid.decode("utf-8")
|
||||
c = await redis.execute("GET", "chats/" + cid)
|
||||
if c:
|
||||
c = dict(json.loads(c))
|
||||
c['messages'] = await load_messages(cid, 5, 0)
|
||||
c['unread'] = await get_unread_counter(cid, auth.user_id)
|
||||
with local_session() as session:
|
||||
c['members'] = []
|
||||
for uid in c["users"]:
|
||||
a = session.query(User).where(User.id == uid).first()
|
||||
if a:
|
||||
c['members'].append({
|
||||
"id": a.id,
|
||||
"slug": a.slug,
|
||||
"userpic": a.userpic,
|
||||
"name": a.name,
|
||||
"lastSeen": a.lastSeen,
|
||||
"online": a.id in onliners
|
||||
})
|
||||
chats.append(c)
|
||||
return {
|
||||
"chats": chats,
|
||||
"error": None
|
||||
}
|
||||
|
||||
|
||||
@query.field("loadMessagesBy")
|
||||
@login_required
|
||||
async def load_messages_by(_, info, by, limit: int = 10, offset: int = 0):
|
||||
''' load :limit messages of :chat_id with :offset '''
|
||||
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
userchats = await redis.execute("SMEMBERS", "chats_by_user/" + str(auth.user_id))
|
||||
userchats = [c.decode('utf-8') for c in userchats]
|
||||
# print('[inbox] userchats: %r' % userchats)
|
||||
if userchats:
|
||||
# print('[inbox] loading messages by...')
|
||||
messages = []
|
||||
by_chat = by.get('chat')
|
||||
if by_chat in userchats:
|
||||
chat = await redis.execute("GET", f"chats/{by_chat}")
|
||||
# print(chat)
|
||||
if not chat:
|
||||
return {
|
||||
"messages": [],
|
||||
"error": "chat not exist"
|
||||
}
|
||||
# everyone's messages in filtered chat
|
||||
messages = await load_messages(by_chat, limit, offset)
|
||||
return {
|
||||
"messages": sorted(
|
||||
list(messages),
|
||||
key=lambda m: m['createdAt']
|
||||
),
|
||||
"error": None
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"error": "Cannot access messages of this chat"
|
||||
}
|
||||
|
||||
|
||||
@query.field("loadRecipients")
|
||||
async def load_recipients(_, info, limit=50, offset=0):
|
||||
chat_users = []
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
onliners = await redis.execute("SMEMBERS", "users-online")
|
||||
if not onliners:
|
||||
onliners = []
|
||||
try:
|
||||
chat_users += await followed_authors(auth.user_id)
|
||||
limit = limit - len(chat_users)
|
||||
except Exception:
|
||||
pass
|
||||
with local_session() as session:
|
||||
chat_users += session.query(User).where(User.emailConfirmed).limit(limit).offset(offset)
|
||||
members = []
|
||||
for a in chat_users:
|
||||
members.append({
|
||||
"id": a.id,
|
||||
"slug": a.slug,
|
||||
"userpic": a.userpic,
|
||||
"name": a.name,
|
||||
"lastSeen": a.lastSeen,
|
||||
"online": a.id in onliners
|
||||
})
|
||||
return {
|
||||
"members": members,
|
||||
"error": None
|
||||
}
|
@@ -1,179 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
from datetime import datetime, timezone
|
||||
from graphql.type import GraphQLResolveInfo
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.redis import redis
|
||||
from base.resolvers import mutation, subscription
|
||||
from services.following import FollowingManager, FollowingResult, Following
|
||||
from validations.inbox import Message
|
||||
|
||||
|
||||
@mutation.field("createMessage")
|
||||
@login_required
|
||||
async def create_message(_, info, chat: str, body: str, replyTo=None):
|
||||
""" create message with :body for :chat_id replying to :replyTo optionally """
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
chat = await redis.execute("GET", f"chats/{chat}")
|
||||
if not chat:
|
||||
return {
|
||||
"error": "chat is not exist"
|
||||
}
|
||||
else:
|
||||
chat = dict(json.loads(chat))
|
||||
message_id = await redis.execute("GET", f"chats/{chat['id']}/next_message_id")
|
||||
message_id = int(message_id)
|
||||
new_message = {
|
||||
"chatId": chat['id'],
|
||||
"id": message_id,
|
||||
"author": auth.user_id,
|
||||
"body": body,
|
||||
"createdAt": int(datetime.now(tz=timezone.utc).timestamp())
|
||||
}
|
||||
if replyTo:
|
||||
new_message['replyTo'] = replyTo
|
||||
chat['updatedAt'] = new_message['createdAt']
|
||||
await redis.execute("SET", f"chats/{chat['id']}", json.dumps(chat))
|
||||
print(f"[inbox] creating message {new_message}")
|
||||
await redis.execute(
|
||||
"SET", f"chats/{chat['id']}/messages/{message_id}", json.dumps(new_message)
|
||||
)
|
||||
await redis.execute("LPUSH", f"chats/{chat['id']}/message_ids", str(message_id))
|
||||
await redis.execute("SET", f"chats/{chat['id']}/next_message_id", str(message_id + 1))
|
||||
|
||||
users = chat["users"]
|
||||
for user_slug in users:
|
||||
await redis.execute(
|
||||
"LPUSH", f"chats/{chat['id']}/unread/{user_slug}", str(message_id)
|
||||
)
|
||||
|
||||
result = FollowingResult("NEW", 'chat', new_message)
|
||||
await FollowingManager.push('chat', result)
|
||||
|
||||
return {
|
||||
"message": new_message,
|
||||
"error": None
|
||||
}
|
||||
|
||||
|
||||
@mutation.field("updateMessage")
|
||||
@login_required
|
||||
async def update_message(_, info, chat_id: str, message_id: int, body: str):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
chat = await redis.execute("GET", f"chats/{chat_id}")
|
||||
if not chat:
|
||||
return {"error": "chat not exist"}
|
||||
|
||||
message = await redis.execute("GET", f"chats/{chat_id}/messages/{message_id}")
|
||||
if not message:
|
||||
return {"error": "message not exist"}
|
||||
|
||||
message = json.loads(message)
|
||||
if message["author"] != auth.user_id:
|
||||
return {"error": "access denied"}
|
||||
|
||||
message["body"] = body
|
||||
message["updatedAt"] = int(datetime.now(tz=timezone.utc).timestamp())
|
||||
|
||||
await redis.execute("SET", f"chats/{chat_id}/messages/{message_id}", json.dumps(message))
|
||||
|
||||
result = FollowingResult("UPDATED", 'chat', message)
|
||||
await FollowingManager.push('chat', result)
|
||||
|
||||
return {
|
||||
"message": message,
|
||||
"error": None
|
||||
}
|
||||
|
||||
|
||||
@mutation.field("deleteMessage")
|
||||
@login_required
|
||||
async def delete_message(_, info, chat_id: str, message_id: int):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
chat = await redis.execute("GET", f"chats/{chat_id}")
|
||||
if not chat:
|
||||
return {"error": "chat not exist"}
|
||||
chat = json.loads(chat)
|
||||
|
||||
message = await redis.execute("GET", f"chats/{chat_id}/messages/{str(message_id)}")
|
||||
if not message:
|
||||
return {"error": "message not exist"}
|
||||
message = json.loads(message)
|
||||
if message["author"] != auth.user_id:
|
||||
return {"error": "access denied"}
|
||||
|
||||
await redis.execute("LREM", f"chats/{chat_id}/message_ids", 0, str(message_id))
|
||||
await redis.execute("DEL", f"chats/{chat_id}/messages/{str(message_id)}")
|
||||
|
||||
users = chat["users"]
|
||||
for user_id in users:
|
||||
await redis.execute("LREM", f"chats/{chat_id}/unread/{user_id}", 0, str(message_id))
|
||||
|
||||
result = FollowingResult("DELETED", 'chat', message)
|
||||
await FollowingManager.push(result)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
@mutation.field("markAsRead")
|
||||
@login_required
|
||||
async def mark_as_read(_, info, chat_id: str, messages: [int]):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
chat = await redis.execute("GET", f"chats/{chat_id}")
|
||||
if not chat:
|
||||
return {"error": "chat not exist"}
|
||||
|
||||
chat = json.loads(chat)
|
||||
users = set(chat["users"])
|
||||
if auth.user_id not in users:
|
||||
return {"error": "access denied"}
|
||||
|
||||
for message_id in messages:
|
||||
await redis.execute("LREM", f"chats/{chat_id}/unread/{auth.user_id}", 0, str(message_id))
|
||||
|
||||
return {
|
||||
"error": None
|
||||
}
|
||||
|
||||
|
||||
@subscription.source("newMessage")
|
||||
async def message_generator(_, info: GraphQLResolveInfo):
|
||||
print(f"[resolvers.messages] generator {info}")
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
try:
|
||||
user_following_chats = await redis.execute("GET", f"chats_by_user/{user_id}")
|
||||
if user_following_chats:
|
||||
user_following_chats = list(json.loads(user_following_chats)) # chat ids
|
||||
else:
|
||||
user_following_chats = []
|
||||
tasks = []
|
||||
updated = {}
|
||||
for chat_id in user_following_chats:
|
||||
chat = await redis.execute("GET", f"chats/{chat_id}")
|
||||
updated[chat_id] = chat['updatedAt']
|
||||
user_following_chats_sorted = sorted(user_following_chats, key=lambda x: updated[x], reverse=True)
|
||||
|
||||
for chat_id in user_following_chats_sorted:
|
||||
following_chat = Following('chat', chat_id)
|
||||
await FollowingManager.register('chat', following_chat)
|
||||
chat_task = following_chat.queue.get()
|
||||
tasks.append(chat_task)
|
||||
|
||||
while True:
|
||||
msg = await asyncio.gather(*tasks)
|
||||
yield msg
|
||||
finally:
|
||||
await FollowingManager.remove('chat', following_chat)
|
||||
|
||||
|
||||
@subscription.field("newMessage")
|
||||
@login_required
|
||||
async def message_resolver(message: Message, info: Any):
|
||||
return message
|
@@ -1,95 +0,0 @@
|
||||
import json
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.redis import redis
|
||||
from base.resolvers import query
|
||||
from base.orm import local_session
|
||||
from orm.user import AuthorFollower, User
|
||||
from resolvers.inbox.load import load_messages
|
||||
|
||||
|
||||
@query.field("searchRecipients")
|
||||
@login_required
|
||||
async def search_recipients(_, info, query: str, limit: int = 50, offset: int = 0):
|
||||
result = []
|
||||
# TODO: maybe redis scan?
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
talk_before = await redis.execute("GET", f"/chats_by_user/{auth.user_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}/users")
|
||||
if members:
|
||||
members = list(json.loads(members))
|
||||
for member in members:
|
||||
if member.startswith(query):
|
||||
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(
|
||||
User, User.id == AuthorFollower.follower
|
||||
).where(
|
||||
User.slug.startswith(query)
|
||||
).offset(offset + len(result)).limit(more_amount)
|
||||
|
||||
more_amount = limit
|
||||
# followers
|
||||
result += session.query(AuthorFollower.follower).join(
|
||||
User, User.id == AuthorFollower.author
|
||||
).where(
|
||||
User.slug.startswith(query)
|
||||
).offset(offset + len(result)).limit(offset + len(result) + limit)
|
||||
return {
|
||||
"members": list(result),
|
||||
"error": None
|
||||
}
|
||||
|
||||
|
||||
@query.field("searchMessages")
|
||||
@login_required
|
||||
async def search_user_chats(by, messages, user_id: int, limit, offset):
|
||||
cids = set([])
|
||||
cids.union(set(await redis.execute("SMEMBERS", "chats_by_user/" + str(user_id))))
|
||||
messages = []
|
||||
|
||||
by_author = by.get('author')
|
||||
if by_author:
|
||||
# all author's messages
|
||||
cids.union(set(await redis.execute("SMEMBERS", f"chats_by_user/{by_author}")))
|
||||
# author's messages in filtered chat
|
||||
messages.union(set(filter(lambda m: m["author"] == by_author, list(messages))))
|
||||
for c in cids:
|
||||
c = c.decode('utf-8')
|
||||
messages = await load_messages(c, limit, offset)
|
||||
|
||||
body_like = by.get('body')
|
||||
if body_like:
|
||||
# search in all messages in all user's chats
|
||||
for c in cids:
|
||||
# FIXME: use redis scan here
|
||||
c = c.decode('utf-8')
|
||||
mmm = await load_messages(c, limit, offset)
|
||||
for m in mmm:
|
||||
if body_like in m["body"]:
|
||||
messages.add(m)
|
||||
else:
|
||||
# search in chat's messages
|
||||
messages.extend(filter(lambda m: body_like in m["body"], list(messages)))
|
||||
|
||||
days = by.get("days")
|
||||
if days:
|
||||
messages.extend(filter(
|
||||
list(messages),
|
||||
key=lambda m: (
|
||||
datetime.now(tz=timezone.utc) - int(m["createdAt"]) < timedelta(days=by["days"])
|
||||
)
|
||||
))
|
||||
return {
|
||||
"messages": messages,
|
||||
"error": None
|
||||
}
|
@@ -1,22 +0,0 @@
|
||||
from base.redis import redis
|
||||
import json
|
||||
|
||||
|
||||
async def get_unread_counter(chat_id: str, user_id: int):
|
||||
try:
|
||||
unread = await redis.execute("LLEN", f"chats/{chat_id.decode('utf-8')}/unread/{user_id}")
|
||||
if unread:
|
||||
return unread
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
async def get_total_unread_counter(user_id: int):
|
||||
chats = await redis.execute("GET", f"chats_by_user/{str(user_id)}")
|
||||
unread = 0
|
||||
if chats:
|
||||
chats = json.loads(chats)
|
||||
for chat_id in chats:
|
||||
n = await get_unread_counter(chat_id.decode('utf-8'), user_id)
|
||||
unread += n
|
||||
return unread
|
Reference in New Issue
Block a user