NDOJ/chat_box/utils.py

50 lines
1.4 KiB
Python
Raw Normal View History

2021-11-21 04:23:03 +00:00
from cryptography.fernet import Fernet
from django.conf import settings
2022-09-01 04:18:38 +00:00
from django.db.models import OuterRef, Count, Subquery, IntegerField
from django.db.models.functions import Coalesce
from chat_box.models import Ignore, Message, UserRoom
2021-11-21 04:23:03 +00:00
secret_key = settings.CHAT_SECRET_KEY
fernet = Fernet(secret_key)
2022-05-14 17:57:27 +00:00
2021-11-21 04:23:03 +00:00
def encrypt_url(creator_id, other_id):
2022-05-14 17:57:27 +00:00
message = str(creator_id) + "_" + str(other_id)
2021-11-21 04:23:03 +00:00
return fernet.encrypt(message.encode()).decode()
2022-05-14 17:57:27 +00:00
2021-11-21 04:23:03 +00:00
def decrypt_url(message_encrypted):
try:
dec_message = fernet.decrypt(message_encrypted.encode()).decode()
2022-05-14 17:57:27 +00:00
creator_id, other_id = dec_message.split("_")
2021-11-21 04:23:03 +00:00
return int(creator_id), int(other_id)
except Exception as e:
2022-05-14 17:57:27 +00:00
return None, None
2022-09-01 04:18:38 +00:00
def get_unread_boxes(profile):
ignored_users = Ignore.get_ignored_users(profile)
mess = (
Message.objects.filter(room=OuterRef("room"), time__gte=OuterRef("last_seen"))
.exclude(author=profile)
.exclude(author__in=ignored_users)
.order_by()
.values("room")
.annotate(unread_count=Count("pk"))
.values("unread_count")
)
unread_boxes = (
UserRoom.objects.filter(user=profile, room__isnull=False)
.annotate(
unread_count=Coalesce(Subquery(mess, output_field=IntegerField()), 0),
)
.filter(unread_count__gte=1)
.count()
)
return unread_boxes