Skip to content

Commit

Permalink
Merge: 알림 확인 메서드 수정, 채팅 메시지 올바르게 내려주도록 변경
Browse files Browse the repository at this point in the history
[Fix/notification-chat] 알림 확인 메서드 수정, 채팅 메시지 올바르게 내려주도록 변경
  • Loading branch information
yyysolhhh authored May 27, 2024
2 parents 3a00e2e + 97df8fa commit bc97576
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 27 deletions.
8 changes: 4 additions & 4 deletions apps/chat/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ def test_채팅에_참여한_유저가_get요청을_보낼때_redis에만_데이

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data.get("messages")), 30)
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 40")
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 11")
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 11")
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 40")
# 테스트가 끝나면 레디스의 자원을 정리
self.redis_conn.delete(key)

Expand Down Expand Up @@ -175,8 +175,8 @@ def test_채팅메시지가_db_redis에_분산되어_있는경우(self) -> None:

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data.get("messages")), 30)
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 40")
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 11")
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 11")
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 40")

# 테스트가 끝나면 레디스의 자원을 정리
self.redis_conn.delete(key)
Expand Down
28 changes: 16 additions & 12 deletions apps/chat/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,34 +159,38 @@ def get_chatroom_message(chatroom_id: int) -> Any:
# 레디스에 저장된 메시지가 30개가 넘으면 가장 마지막에 저장된 메시지부터 30개를 가져옴
if stored_message_num >= 30:
stored_messages = redis_conn.lrange(key, 0, 29)
messages = [json.loads(msg) for msg in reversed(stored_messages)]
messages = [json.loads(msg) for msg in stored_messages[::-1]]
return messages

# 30개가 넘지않으면 레디스에 저장된 메시지들을 가져오고
stored_messages = redis_conn.lrange(key, 0, -1)
messages = [json.loads(msg) for msg in reversed(stored_messages)]
stored_messages = redis_conn.lrange(key, 0, stored_message_num)
messages = [json.loads(msg) for msg in stored_messages[::-1]]

# 데이터베이스에서 30 - stored_message_num을 뺀 개수만큼 가져옴
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("created_at")
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("-created_at")

# db에 저장된 메시지가 없으면 레디스에 캐싱된 메시지만 가져옴
if not db_messages.exists():
return messages

# 디비에 저장된 메시지가 30-stored_message_num 보다 많으면 슬라이싱해서 필요한 만큼의 데이터를 가져옴
if db_messages.count() >= 30 - stored_message_num:
if len(db_messages) >= 30 - stored_message_num:
serialized_messages = MessageSerializer(db_messages[: 30 - stored_message_num], many=True).data
return serialized_messages + messages # type: ignore
return serialized_messages[::-1] + messages

# 디비에 저장된 메시지가 30-stored_message_num 보다 적으면 db에 저장된 채팅방의 모든 메시지를 가져옴
serialized_messages = MessageSerializer(db_messages.order_by("created_at"), many=True).data
return serialized_messages + messages # type: ignore
serialized_messages = MessageSerializer(db_messages, many=True).data
return serialized_messages[::-1] + messages

# 레디스에 해당 채팅방 그룹 네임으로 지정된 키값이 없으면 데이터베이스에서 채팅 메시지를 가져옴
db_messages = Message.objects.filter(chatroom_id=chatroom_id)
if db_messages:
if db_messages.count() >= 30:
serialized_messages = MessageSerializer(db_messages.order_by("created_at")[:30], many=True).data
return serialized_messages
serialized_messages = MessageSerializer(db_messages[:30], many=True).data
return serialized_messages[::-1]

serialized_messages = MessageSerializer(db_messages.order_by("created_at"), many=True).data
return serialized_messages
serialized_messages = MessageSerializer(db_messages, many=True).data
return serialized_messages[::-1]

# 어디에도 데이터가 존재하지않으면 None을 반환
return None
Expand Down
37 changes: 32 additions & 5 deletions apps/notification/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
from apps.chat.models import Chatroom
from apps.chat.utils import get_group_name
from apps.notification.consumers import NotificationConsumer
from apps.notification.models import GlobalNotification, GlobalNotificationConfirm
from apps.notification.models import (
GlobalNotification,
GlobalNotificationConfirm,
RentalNotification,
)
from apps.product.models import Product, ProductImage, RentalHistory
from apps.user.models import Account

Expand Down Expand Up @@ -109,6 +113,29 @@ async def test_RentalHistory가_처음_생성될때_알림메시지_테스트(se
self.assertEqual(req_notification["return_date"], rental_history.return_date.isoformat())
self.assertEqual(req_notification["rental_date"], rental_history.rental_date.isoformat())

# 대여 알림이 생성되었는지 테스트
self.assertTrue(
await database_sync_to_async(
RentalNotification.objects.filter(
recipient=self.lender, rental_history=rental_history, confirm=False
).exists
)()
)

rental_notification = await database_sync_to_async(RentalNotification.objects.get)(
recipient=self.lender, rental_history=rental_history, confirm=False
)

# 알림읽기테스트
await communicator2.send_json_to(
{"command": "rental_notification_confirm", "notification_id": rental_notification.id}
)
updated_confirm = await database_sync_to_async(RentalNotification.objects.get)(
rental_history=rental_history, recipient=self.lender
)
self.assertFalse(updated_confirm.confirm)

# 소켓 연결 해제
await communicator1.disconnect()
await communicator2.disconnect()

Expand Down Expand Up @@ -240,16 +267,16 @@ async def test_모든_사용자에게_공통으로_적용되는_알림_테스트
# 유저1의 알림 읽기 테스트
await communicator1.send_json_to({"command": "global_notification_confirm", "notification_id": notification.id})
user1_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
notification=notification, user=self.user1, confirm=False
notification=notification, user=self.user1
)
self.assertFalse(user1_confirm_instance.confirm)

# 유저2의 알림 읽기 테스트
await communicator1.send_json_to({"command": "global_notification_confirm", "notification_id": notification.id})
user1_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
notification=notification, user=self.user1, confirm=False
user2_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
notification=notification, user=self.user2
)
self.assertFalse(user1_confirm_instance.confirm)
self.assertFalse(user2_confirm_instance.confirm)

# 소켓 정리
await communicator1.disconnect()
Expand Down
16 changes: 10 additions & 6 deletions apps/notification/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,12 @@ def confirm_notification(command: str, notification_id: int, user_id: int) -> No
"""
유저가 확인한 알림을 가져와서 comfirm = True 로 변경
"""
if command == "RentalNotificationConfirm":
RentalNotification.objects.filter(id=notification_id, recipient_id=user_id).update(confirm=True)
if command == "globalNotificationConfirm":
GlobalNotificationConfirm.objects.filter(notification_id=notification_id, user_id=user_id).update(confirm=True)
if command == "rental_notification_confirm":
RentalNotification.objects.filter(id=notification_id, recipient_id=user_id, confirm=False).update(confirm=True)
if command == "global_notification_confirm":
GlobalNotificationConfirm.objects.filter(
notification_id=notification_id, user_id=user_id, confirm=False
).update(confirm=True)


def create_rental_notification(
Expand Down Expand Up @@ -167,9 +169,11 @@ def get_unread_chat_notifications(user_id: int) -> list[ReturnDict[Any, Any]]:

def get_unread_notifications(user_id: int) -> dict[str, Any]:
result: dict[str, Any] = {}
unread_global_notification = GlobalNotificationConfirm.objects.filter(user_id=user_id, confirm=False)
unread_global_notification = GlobalNotification.objects.filter(
globalnotificationconfirm__user_id=user_id, globalnotificationconfirm__confirm=False
)
if unread_global_notification:
result["global_notification"] = serializers.GlobalNotificationConfirmSerializer(
result["global_notification"] = serializers.GlobalNotificationSerializer(
unread_global_notification, many=True
).data

Expand Down

0 comments on commit bc97576

Please sign in to comment.