1
|
|
|
from django.contrib import messages |
2
|
|
|
from django.http import HttpResponseRedirect |
3
|
|
|
from django.shortcuts import get_object_or_404 |
4
|
|
|
from django.views.generic import View |
5
|
|
|
|
6
|
|
|
from simple_forums import models as forum_models |
7
|
|
|
from simple_forums.mixins import LoginRequiredMixin |
8
|
|
|
from simple_forums.notifications import models |
9
|
|
|
from simple_forums.utils import thread_detail_url |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class ThreadNotificationCreate(LoginRequiredMixin, View): |
13
|
|
|
|
14
|
|
|
raise_exception = True |
15
|
|
|
|
16
|
|
|
def _follow_thread(self, user, thread): |
17
|
|
|
""" Create thread notification if it doesn't exist """ |
18
|
|
|
duplicate = models.ThreadNotification.objects.filter( |
19
|
|
|
user=user, thread=thread).exists() |
20
|
|
|
|
21
|
|
|
if not duplicate: |
22
|
|
|
models.ThreadNotification.objects.create(user=user, thread=thread) |
23
|
|
|
messages.success( |
24
|
|
|
self.request, "You are now following '%s'" % thread) |
25
|
|
|
else: |
26
|
|
|
messages.warning( |
27
|
|
|
self.request, "You are already following '%s'" % thread) |
28
|
|
|
|
29
|
|
|
def _unfollow_thread(self, user, thread): |
30
|
|
|
""" Delete notifications for the given user and thread """ |
31
|
|
|
qs = models.ThreadNotification.objects.filter( |
32
|
|
|
user=user, thread=thread) |
33
|
|
|
|
34
|
|
|
if qs.exists(): |
35
|
|
|
qs.delete() |
36
|
|
|
messages.success( |
37
|
|
|
self.request, "You are no longer following '%s'" % thread) |
38
|
|
|
|
39
|
|
|
def post(self, request, *args, **kwargs): |
40
|
|
|
""" Create a new thread notification """ |
41
|
|
|
self.request = request |
42
|
|
|
|
43
|
|
|
follow = self.request.POST.get('follow', None) |
44
|
|
|
|
45
|
|
|
pk = kwargs.get('pk') |
46
|
|
|
thread = get_object_or_404(forum_models.Thread, pk=pk) |
47
|
|
|
|
48
|
|
|
if follow: |
49
|
|
|
self._follow_thread(request.user, thread) |
50
|
|
|
else: |
51
|
|
|
self._unfollow_thread(request.user, thread) |
52
|
|
|
|
53
|
|
|
redirect_url = thread_detail_url(thread=thread) |
54
|
|
|
|
55
|
|
|
return HttpResponseRedirect(redirect_url) |
56
|
|
|
|