post.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 self.poster_id != other_post.poster_id:
  102. raise ValueError("post can't be merged with other user's post")
  103. elif (self.poster_id is None and other_post.poster_id is None and
  104. self.poster_name != other_post.poster_name):
  105. raise ValueError("post can't be merged with other user's post")
  106. if self.thread_id != other_post.thread_id:
  107. raise ValueError("only posts belonging to same thread can be merged")
  108. if self.is_event or other_post.is_event:
  109. raise ValueError("can't merge events")
  110. if self.pk == other_post.pk:
  111. raise ValueError("post can't be merged with itself")
  112. other_post.original = six.text_type('\n\n').join((other_post.original, self.original))
  113. other_post.parsed = six.text_type('\n').join((other_post.parsed, self.parsed))
  114. update_post_checksum(other_post)
  115. if self.thread.best_answer_id == self.id:
  116. self.thread.best_answer = other_post
  117. from misago.threads.signals import merge_post
  118. merge_post.send(sender=self, other_post=other_post)
  119. def move(self, new_thread):
  120. from misago.threads.signals import move_post
  121. if self.thread.best_answer_id == self.id:
  122. self.thread.clear_best_answer()
  123. self.category = new_thread.category
  124. self.thread = new_thread
  125. move_post.send(sender=self)
  126. @property
  127. def attachments(self):
  128. if hasattr(self, '_hydrated_attachments_cache'):
  129. return self._hydrated_attachments_cache
  130. self._hydrated_attachments_cache = []
  131. if self.attachments_cache:
  132. for attachment in copy.deepcopy(self.attachments_cache):
  133. attachment['uploaded_on'] = parse_iso8601_string(attachment['uploaded_on'])
  134. self._hydrated_attachments_cache.append(attachment)
  135. return self._hydrated_attachments_cache
  136. @property
  137. def content(self):
  138. if not hasattr(self, '_finalised_parsed'):
  139. self._finalised_parsed = finalise_markup(self.parsed)
  140. return self._finalised_parsed
  141. @property
  142. def thread_type(self):
  143. return self.category.thread_type
  144. def get_api_url(self):
  145. return self.thread_type.get_post_api_url(self)
  146. def get_likes_api_url(self):
  147. return self.thread_type.get_post_likes_api_url(self)
  148. def get_editor_api_url(self):
  149. return self.thread_type.get_post_editor_api_url(self)
  150. def get_edits_api_url(self):
  151. return self.thread_type.get_post_edits_api_url(self)
  152. def get_read_api_url(self):
  153. return self.thread_type.get_post_read_api_url(self)
  154. def get_absolute_url(self):
  155. return self.thread_type.get_post_absolute_url(self)
  156. def set_search_document(self, thread_title=None):
  157. if thread_title:
  158. self.search_document = filter_search('\n\n'.join([thread_title, self.original]))
  159. else:
  160. self.search_document = filter_search(self.original)
  161. def update_search_vector(self):
  162. self.search_vector = SearchVector(
  163. 'search_document',
  164. config=settings.MISAGO_SEARCH_CONFIG,
  165. )
  166. @property
  167. def short(self):
  168. if self.is_valid:
  169. if len(self.original) > 150:
  170. return six.text_type('%s...') % self.original[:150].strip()
  171. else:
  172. return self.original
  173. else:
  174. return ''
  175. @property
  176. def is_valid(self):
  177. return is_post_valid(self)
  178. @property
  179. def is_first_post(self):
  180. return self.id == self.thread.first_post_id
  181. @property
  182. def is_best_answer(self):
  183. return self.id == self.thread.best_answer_id