threads.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from django.db import transaction
  2. from rest_framework import viewsets
  3. from rest_framework.decorators import detail_route
  4. from rest_framework.parsers import JSONParser
  5. from rest_framework.response import Response
  6. from misago.acl import add_acl
  7. from misago.categories.models import CATEGORIES_TREE_ID
  8. from misago.users.rest_permissions import IsAuthenticatedOrReadOnly
  9. from misago.core.shortcuts import get_int_or_404, get_object_or_404
  10. from misago.threads.api.threadendpoints.list import threads_list_endpoint
  11. from misago.threads.models import Thread, Subscription
  12. from misago.threads.permissions.threads import allow_see_thread
  13. from misago.threads.serializers import ThreadSerializer
  14. from misago.threads.subscriptions import make_subscription_aware
  15. class ThreadViewSet(viewsets.ViewSet):
  16. permission_classes = (IsAuthenticatedOrReadOnly, )
  17. parser_classes=(JSONParser, )
  18. TREE_ID = CATEGORIES_TREE_ID
  19. def validate_thread_visible(self, user, thread):
  20. allow_see_thread(user, thread)
  21. def get_thread(self, user, thread_id):
  22. thread = get_object_or_404(Thread.objects.select_related('category'),
  23. id=get_int_or_404(thread_id),
  24. category__tree_id=self.TREE_ID,
  25. )
  26. add_acl(user, thread.category)
  27. add_acl(user, thread)
  28. self.validate_thread_visible(user, thread)
  29. return thread
  30. def list(self, request):
  31. return threads_list_endpoint(request)
  32. def retrieve(self, request, pk=None):
  33. thread = self.get_thread(request.user, pk)
  34. make_subscription_aware(request.user, thread)
  35. return Response(ThreadSerializer(thread).data)
  36. @detail_route(methods=['post'])
  37. def subscribe(self, request, pk=None):
  38. thread = self.get_thread(request.user, pk)
  39. with transaction.atomic():
  40. request.user.subscription_set.filter(thread=thread).delete()
  41. if request.data.get('notify'):
  42. request.user.subscription_set.create(
  43. thread=thread,
  44. category=thread.category,
  45. last_read_on=thread.last_post_on,
  46. send_email=False,
  47. )
  48. elif request.data.get('email'):
  49. request.user.subscription_set.create(
  50. thread=thread,
  51. category=thread.category,
  52. last_read_on=thread.last_post_on,
  53. send_email=True,
  54. )
  55. return Response({
  56. 'detail': 'ok',
  57. })