post.py 7.7 KB

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