NDOJ/chat_box/utils.py

52 lines
1.3 KiB
Python
Raw Normal View History

2021-11-21 04:23:03 +00:00
from cryptography.fernet import Fernet
2023-08-28 19:20:35 +00:00
import hmac
import hashlib
2021-11-21 04:23:03 +00:00
from django.conf import settings
2023-08-28 19:20:35 +00:00
from django.db.models import OuterRef, Count, Subquery, IntegerField, Q
2022-09-01 04:18:38 +00:00
from django.db.models.functions import Coalesce
2023-08-28 19:20:35 +00:00
from chat_box.models import Ignore, Message, UserRoom, Room
2021-11-21 04:23:03 +00:00
2023-10-11 00:37:36 +00:00
from judge.caching import cache_wrapper
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
2023-08-28 19:20:35 +00:00
def encrypt_channel(channel):
return (
hmac.new(
settings.CHAT_SECRET_KEY.encode(),
channel.encode(),
hashlib.sha512,
).hexdigest()[:16]
+ "%s" % channel
2022-09-01 04:18:38 +00:00
)
2023-08-28 19:20:35 +00:00
2023-10-11 00:37:36 +00:00
@cache_wrapper(prefix="gub")
2023-08-28 19:20:35 +00:00
def get_unread_boxes(profile):
ignored_rooms = Ignore.get_ignored_rooms(profile)
2022-09-01 04:18:38 +00:00
unread_boxes = (
2023-08-28 19:20:35 +00:00
UserRoom.objects.filter(user=profile, unread_count__gt=0)
.exclude(room__in=ignored_rooms)
2022-09-01 04:18:38 +00:00
.count()
)
return unread_boxes