post.py 7.8 KB

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