post.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from django.core.urlresolvers import reverse
  2. from rest_framework import serializers
  3. from misago.threads.models import Post
  4. from misago.users.serializers import UserSerializer
  5. __all__ = [
  6. 'PostSerializer',
  7. 'ThreadPostSerializer',
  8. ]
  9. class PostSerializer(serializers.ModelSerializer):
  10. poster = UserSerializer(many=False, read_only=True)
  11. parsed = serializers.SerializerMethodField()
  12. attachments_cache = serializers.SerializerMethodField()
  13. last_editor = UserSerializer(many=False, read_only=True)
  14. last_editor_id = serializers.SerializerMethodField()
  15. last_editor_url = serializers.SerializerMethodField()
  16. hidden_by = UserSerializer(many=False, read_only=True)
  17. hidden_by_id = serializers.SerializerMethodField()
  18. hidden_by_url = serializers.SerializerMethodField()
  19. acl = serializers.SerializerMethodField()
  20. class Meta:
  21. model = Post
  22. fields = (
  23. 'id',
  24. )
  25. def get_parsed(self, obj):
  26. if obj.is_valid and not obj.is_event and (not obj.is_hidden or obj.acl['can_see_hidden']):
  27. return obj.parsed
  28. else:
  29. return None
  30. def get_attachments_cache(self, obj):
  31. # TODO: check if user can download attachments before we'll expose them here
  32. return None
  33. def get_last_editor_id(self, obj):
  34. return obj.last_editor_id
  35. def get_last_editor_url(self, obj):
  36. if obj.last_editor_id:
  37. return reverse('misago:user', kwargs={
  38. 'pk': obj.last_editor_id,
  39. 'slug': obj.last_editor_slug
  40. })
  41. else:
  42. return None
  43. def get_hidden_by_id(self, obj):
  44. return obj.hidden_by_id
  45. def get_hidden_by_url(self, obj):
  46. if obj.hidden_by:
  47. return reverse('misago:user', kwargs={
  48. 'pk': obj.hidden_by_id,
  49. 'slug': obj.hidden_by_slug
  50. })
  51. else:
  52. return None
  53. def get_acl(self, obj):
  54. try:
  55. return obj.acl
  56. except AttributeError:
  57. return None
  58. class ThreadPostSerializer(PostSerializer):
  59. class Meta:
  60. model = Post
  61. fields = (
  62. 'id',
  63. 'poster',
  64. 'poster_name',
  65. 'poster_ip',
  66. 'parsed',
  67. 'has_attachments',
  68. 'attachments_cache',
  69. 'posted_on',
  70. 'updated_on',
  71. 'hidden_on',
  72. 'edits',
  73. 'last_editor_id',
  74. 'last_editor_name',
  75. 'last_editor_slug',
  76. 'last_editor_url',
  77. 'hidden_by_id',
  78. 'hidden_by_name',
  79. 'hidden_by_slug',
  80. 'hidden_by_url',
  81. 'is_unapproved',
  82. 'is_hidden',
  83. 'is_protected',
  84. 'is_event',
  85. 'event_type',
  86. 'event_context',
  87. 'acl',
  88. )