post.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. from __future__ import unicode_literals
  2. import copy
  3. from django.contrib.postgres.indexes import GinIndex
  4. from django.contrib.postgres.fields import JSONField
  5. from django.contrib.postgres.search import SearchVector, SearchVectorField
  6. from django.db import models
  7. from django.utils import six, timezone
  8. from django.utils.encoding import python_2_unicode_compatible
  9. from misago.conf import settings
  10. from misago.core.pgutils import PgPartialIndex
  11. from misago.core.utils import parse_iso8601_string
  12. from misago.markup import finalise_markup
  13. from misago.threads.checksums import is_post_valid, update_post_checksum
  14. from misago.threads.filtersearch import filter_search
  15. @python_2_unicode_compatible
  16. class Post(models.Model):
  17. category = models.ForeignKey(
  18. 'misago_categories.Category',
  19. on_delete=models.CASCADE,
  20. )
  21. thread = models.ForeignKey(
  22. 'misago_threads.Thread',
  23. on_delete=models.CASCADE,
  24. )
  25. poster = models.ForeignKey(
  26. settings.AUTH_USER_MODEL,
  27. blank=True,
  28. null=True,
  29. on_delete=models.SET_NULL,
  30. )
  31. poster_name = models.CharField(max_length=255)
  32. poster_ip = models.GenericIPAddressField()
  33. original = models.TextField()
  34. parsed = models.TextField()
  35. checksum = models.CharField(max_length=64, default='-')
  36. mentions = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="mention_set")
  37. attachments_cache = JSONField(null=True, blank=True)
  38. posted_on = models.DateTimeField(db_index=True)
  39. updated_on = models.DateTimeField()
  40. hidden_on = models.DateTimeField(default=timezone.now)
  41. edits = models.PositiveIntegerField(default=0)
  42. last_editor = models.ForeignKey(
  43. settings.AUTH_USER_MODEL,
  44. blank=True,
  45. null=True,
  46. on_delete=models.SET_NULL,
  47. related_name='+',
  48. )
  49. last_editor_name = models.CharField(max_length=255, null=True, blank=True)
  50. last_editor_slug = models.SlugField(max_length=255, null=True, blank=True)
  51. hidden_by = models.ForeignKey(
  52. settings.AUTH_USER_MODEL,
  53. blank=True,
  54. null=True,
  55. on_delete=models.SET_NULL,
  56. related_name='+',
  57. )
  58. hidden_by_name = models.CharField(max_length=255, null=True, blank=True)
  59. hidden_by_slug = models.SlugField(max_length=255, null=True, blank=True)
  60. has_reports = models.BooleanField(default=False)
  61. has_open_reports = models.BooleanField(default=False)
  62. is_unapproved = models.BooleanField(default=False, db_index=True)
  63. is_hidden = models.BooleanField(default=False)
  64. is_protected = models.BooleanField(default=False)
  65. is_event = models.BooleanField(default=False, db_index=True)
  66. event_type = models.CharField(max_length=255, null=True, blank=True)
  67. event_context = JSONField(null=True, blank=True)
  68. likes = models.PositiveIntegerField(default=0)
  69. last_likes = JSONField(null=True, blank=True)
  70. liked_by = models.ManyToManyField(
  71. settings.AUTH_USER_MODEL,
  72. related_name='liked_post_set',
  73. through='misago_threads.PostLike',
  74. )
  75. search_document = models.TextField(null=True, blank=True)
  76. search_vector = SearchVectorField()
  77. class Meta:
  78. indexes = [
  79. PgPartialIndex(
  80. fields=['has_open_reports'],
  81. where={'has_open_reports': True},
  82. ),
  83. PgPartialIndex(
  84. fields=['is_hidden'],
  85. where={'is_hidden': False},
  86. ),
  87. GinIndex(fields=['search_vector']),
  88. ]
  89. index_together = [
  90. ('thread', 'id'), # speed up threadview for team members
  91. ('is_event', 'is_hidden'),
  92. ('poster', 'posted_on'),
  93. ]
  94. def __str__(self):
  95. return '%s...' % self.original[10:].strip()
  96. def delete(self, *args, **kwargs):
  97. from misago.threads.signals import delete_post
  98. delete_post.send(sender=self)
  99. super(Post, self).delete(*args, **kwargs)
  100. def merge(self, other_post):
  101. if not self.poster_id or self.poster_id != other_post.poster_id:
  102. raise ValueError("post can't be merged with other user's post")
  103. if self.thread_id != other_post.thread_id:
  104. raise ValueError("only posts belonging to same thread can be merged")
  105. if self.is_event or other_post.is_event:
  106. raise ValueError("can't merge events")
  107. if self.pk == other_post.pk:
  108. raise ValueError("post can't be merged with itself")
  109. other_post.original = six.text_type('\n\n').join((other_post.original, self.original))
  110. other_post.parsed = six.text_type('\n').join((other_post.parsed, self.parsed))
  111. update_post_checksum(other_post)
  112. if self.thread.answer_id == self.id:
  113. self.thread.answer = other_post
  114. from misago.threads.signals import merge_post
  115. merge_post.send(sender=self, other_post=other_post)
  116. def move(self, new_thread):
  117. from misago.threads.signals import move_post
  118. if self.thread.answer_id == self.id:
  119. self.thread.answer = None
  120. self.category = new_thread.category
  121. self.thread = new_thread
  122. move_post.send(sender=self)
  123. @property
  124. def attachments(self):
  125. if hasattr(self, '_hydrated_attachments_cache'):
  126. return self._hydrated_attachments_cache
  127. self._hydrated_attachments_cache = []
  128. if self.attachments_cache:
  129. for attachment in copy.deepcopy(self.attachments_cache):
  130. attachment['uploaded_on'] = parse_iso8601_string(attachment['uploaded_on'])
  131. self._hydrated_attachments_cache.append(attachment)
  132. return self._hydrated_attachments_cache
  133. @property
  134. def content(self):
  135. if not hasattr(self, '_finalised_parsed'):
  136. self._finalised_parsed = finalise_markup(self.parsed)
  137. return self._finalised_parsed
  138. @property
  139. def thread_type(self):
  140. return self.category.thread_type
  141. def get_api_url(self):
  142. return self.thread_type.get_post_api_url(self)
  143. def get_likes_api_url(self):
  144. return self.thread_type.get_post_likes_api_url(self)
  145. def get_editor_api_url(self):
  146. return self.thread_type.get_post_editor_api_url(self)
  147. def get_edits_api_url(self):
  148. return self.thread_type.get_post_edits_api_url(self)
  149. def get_read_api_url(self):
  150. return self.thread_type.get_post_read_api_url(self)
  151. def get_absolute_url(self):
  152. return self.thread_type.get_post_absolute_url(self)
  153. def set_search_document(self, thread_title=None):
  154. if thread_title:
  155. self.search_document = filter_search('\n\n'.join([thread_title, self.original]))
  156. else:
  157. self.search_document = filter_search(self.original)
  158. def update_search_vector(self):
  159. self.search_vector = SearchVector(
  160. 'search_document',
  161. config=settings.MISAGO_SEARCH_CONFIG,
  162. )
  163. @property
  164. def short(self):
  165. if self.is_valid:
  166. if len(self.original) > 150:
  167. return six.text_type('%s...') % self.original[:150].strip()
  168. else:
  169. return self.original
  170. else:
  171. return ''
  172. @property
  173. def is_valid(self):
  174. return is_post_valid(self)
  175. @property
  176. def is_first_post(self):
  177. return self.id == self.thread.first_post_id
  178. @property
  179. def is_answer(self):
  180. return self.id == self.thread.answer_id