post.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. PgPartialIndex(
  88. fields=['is_event', 'event_type'],
  89. where={'is_event': True},
  90. ),
  91. GinIndex(fields=['search_vector']),
  92. ]
  93. index_together = [
  94. ('thread', 'id'), # speed up threadview for team members
  95. ('is_event', 'is_hidden'),
  96. ('poster', 'posted_on'),
  97. ]
  98. def __str__(self):
  99. return '%s...' % self.original[10:].strip()
  100. def delete(self, *args, **kwargs):
  101. from misago.threads.signals import delete_post
  102. delete_post.send(sender=self)
  103. super(Post, self).delete(*args, **kwargs)
  104. def merge(self, other_post):
  105. if self.poster_id != other_post.poster_id:
  106. raise ValueError("post can't be merged with other user's post")
  107. elif (self.poster_id is None and other_post.poster_id is None and
  108. self.poster_name != other_post.poster_name):
  109. raise ValueError("post can't be merged with other user's post")
  110. if self.thread_id != other_post.thread_id:
  111. raise ValueError("only posts belonging to same thread can be merged")
  112. if self.is_event or other_post.is_event:
  113. raise ValueError("can't merge events")
  114. if self.pk == other_post.pk:
  115. raise ValueError("post can't be merged with itself")
  116. other_post.original = six.text_type('\n\n').join((other_post.original, self.original))
  117. other_post.parsed = six.text_type('\n').join((other_post.parsed, self.parsed))
  118. update_post_checksum(other_post)
  119. if self.is_protected:
  120. other_post.is_protected = True
  121. if self.is_best_answer:
  122. self.thread.best_answer = other_post
  123. if other_post.is_best_answer:
  124. self.thread.best_answer_is_protected = other_post.is_protected
  125. from misago.threads.signals import merge_post
  126. merge_post.send(sender=self, other_post=other_post)
  127. def move(self, new_thread):
  128. from misago.threads.signals import move_post
  129. if self.is_best_answer:
  130. self.thread.clear_best_answer()
  131. self.category = new_thread.category
  132. self.thread = new_thread
  133. move_post.send(sender=self)
  134. @property
  135. def attachments(self):
  136. if hasattr(self, '_hydrated_attachments_cache'):
  137. return self._hydrated_attachments_cache
  138. self._hydrated_attachments_cache = []
  139. if self.attachments_cache:
  140. for attachment in copy.deepcopy(self.attachments_cache):
  141. attachment['uploaded_on'] = parse_iso8601_string(attachment['uploaded_on'])
  142. self._hydrated_attachments_cache.append(attachment)
  143. return self._hydrated_attachments_cache
  144. @property
  145. def content(self):
  146. if not hasattr(self, '_finalised_parsed'):
  147. self._finalised_parsed = finalise_markup(self.parsed)
  148. return self._finalised_parsed
  149. @property
  150. def thread_type(self):
  151. return self.category.thread_type
  152. def get_api_url(self):
  153. return self.thread_type.get_post_api_url(self)
  154. def get_likes_api_url(self):
  155. return self.thread_type.get_post_likes_api_url(self)
  156. def get_editor_api_url(self):
  157. return self.thread_type.get_post_editor_api_url(self)
  158. def get_edits_api_url(self):
  159. return self.thread_type.get_post_edits_api_url(self)
  160. def get_read_api_url(self):
  161. return self.thread_type.get_post_read_api_url(self)
  162. def get_absolute_url(self):
  163. return self.thread_type.get_post_absolute_url(self)
  164. def set_search_document(self, thread_title=None):
  165. if thread_title:
  166. self.search_document = filter_search('\n\n'.join([thread_title, self.original]))
  167. else:
  168. self.search_document = filter_search(self.original)
  169. def update_search_vector(self):
  170. self.search_vector = SearchVector(
  171. 'search_document',
  172. config=settings.MISAGO_SEARCH_CONFIG,
  173. )
  174. @property
  175. def short(self):
  176. if self.is_valid:
  177. if len(self.original) > 150:
  178. return six.text_type('%s...') % self.original[:150].strip()
  179. else:
  180. return self.original
  181. else:
  182. return ''
  183. @property
  184. def is_valid(self):
  185. return is_post_valid(self)
  186. @property
  187. def is_first_post(self):
  188. return self.id == self.thread.first_post_id
  189. @property
  190. def is_best_answer(self):
  191. return self.id == self.thread.best_answer_id