From 7c3e59feec3007e50baae1dc91ede45993ec6f00 Mon Sep 17 00:00:00 2001 From: cuom1999 Date: Sun, 21 Nov 2021 21:01:35 -0600 Subject: [PATCH] Add chat notification to navbar --- chat_box/views.py | 22 +++++++++++++++++++++- dmoj/urls.py | 1 + resources/chatbox.scss | 7 +++++++ templates/base.html | 14 ++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/chat_box/views.py b/chat_box/views.py index 703d8a1..95a3582 100644 --- a/chat_box/views.py +++ b/chat_box/views.py @@ -424,4 +424,24 @@ def toggle_ignore(request, **kwargs): Ignore.toggle_ignore(request.profile, other_user) next_url = request.GET.get('next', '/') - return HttpResponseRedirect(next_url) \ No newline at end of file + return HttpResponseRedirect(next_url) + + +@login_required +def get_unread_boxes(request): + if (request.method != 'GET'): + return HttpResponseBadRequest() + + mess = Message.objects.filter(room=OuterRef('room'), + time__gte=OuterRef('last_seen'))\ + .exclude(author=request.profile)\ + .order_by().values('room')\ + .annotate(unread_count=Count('pk')).values('unread_count') + + unread_boxes = UserRoom.objects\ + .filter(user=request.profile, room__isnull=False)\ + .annotate( + unread_count=Coalesce(Subquery(mess, output_field=IntegerField()), 0), + ).filter(unread_count__gte=1).count() + + return JsonResponse({'unread_boxes': unread_boxes}) \ No newline at end of file diff --git a/dmoj/urls.py b/dmoj/urls.py index b063e0d..444d393 100644 --- a/dmoj/urls.py +++ b/dmoj/urls.py @@ -383,6 +383,7 @@ urlpatterns = [ url(r'^update_last_seen$', update_last_seen, name='update_last_seen'), url(r'^online_status/user/ajax$', user_online_status_ajax, name='user_online_status_ajax'), url(r'^toggle_ignore/(?P\d+)$', toggle_ignore, name='toggle_ignore'), + url(r'^get_unread_boxes$', get_unread_boxes, name='get_unread_boxes'), ])), url(r'^notifications/', diff --git a/resources/chatbox.scss b/resources/chatbox.scss index 6b31bd1..7c19264 100644 --- a/resources/chatbox.scss +++ b/resources/chatbox.scss @@ -171,6 +171,13 @@ cursor: pointer; margin-top: 0.5em; } +.unread_boxes { + background-color: darkcyan; + color: white; + border-radius: 50%; + padding: 0 3px; + margin-left: -4px; +} @media (max-width: 799px) { #chat-area { height: 500px; diff --git a/templates/base.html b/templates/base.html index 4e5dea0..a6d22a4 100644 --- a/templates/base.html +++ b/templates/base.html @@ -150,6 +150,20 @@ id: '{{ request.user.id|escapejs }}', name: '{{ request.user.username|escapejs }}' }; + $(function() { + if ($('.nav-chat').length) { + $.get("{{url('get_unread_boxes')}}") + .done(function(data) { + if (data.unread_boxes) { + var html = `${data.unread_boxes}`; + $('.nav-chat').append(html); + } + }) + .fail(function(data) { + console.log('Fail to get unread boxes'); + }); + } + }); {% else %}