thread.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. from django.core.urlresolvers import reverse
  2. from django import forms
  3. from django.db.models import F
  4. from django.forms import ValidationError
  5. from django.shortcuts import redirect
  6. from django.template import RequestContext
  7. from django.utils import timezone
  8. from django.utils.translation import ugettext as _
  9. from misago.acl.utils import ACLError403, ACLError404
  10. from misago.forms import Form, FormLayout, FormFields
  11. from misago.forums.models import Forum
  12. from misago.markdown import post_markdown
  13. from misago.messages import Message
  14. from misago.readstracker.trackers import ThreadsTracker
  15. from misago.threads.forms import MoveThreadsForm, SplitThreadForm, MovePostsForm, QuickReplyForm
  16. from misago.threads.models import Thread, Post, Change, Checkpoint
  17. from misago.threads.views.base import BaseView
  18. from misago.views import error403, error404
  19. from misago.utils import make_pagination, slugify
  20. class ThreadView(BaseView):
  21. def fetch_thread(self, thread):
  22. self.thread = Thread.objects.get(pk=thread)
  23. self.forum = self.thread.forum
  24. self.proxy = Forum.objects.parents_aware_forum(self.forum)
  25. self.request.acl.forums.allow_forum_view(self.forum)
  26. self.request.acl.threads.allow_thread_view(self.request.user, self.thread)
  27. self.parents = Forum.objects.forum_parents(self.forum.pk, True)
  28. self.tracker = ThreadsTracker(self.request, self.forum)
  29. def fetch_posts(self, page):
  30. self.count = self.request.acl.threads.filter_posts(self.request, self.thread, Post.objects.filter(thread=self.thread)).count()
  31. self.posts = self.request.acl.threads.filter_posts(self.request, self.thread, Post.objects.filter(thread=self.thread)).prefetch_related('checkpoint_set', 'user', 'user__rank')
  32. if self.thread.merges > 0:
  33. self.posts = self.posts.order_by('merge', 'pk')
  34. else:
  35. self.posts = self.posts.order_by('pk')
  36. self.pagination = make_pagination(page, self.count, self.request.settings.posts_per_page)
  37. if self.request.settings.posts_per_page < self.count:
  38. self.posts = self.posts[self.pagination['start']:self.pagination['stop']]
  39. self.read_date = self.tracker.get_read_date(self.thread)
  40. for post in self.posts:
  41. post.message = self.request.messages.get_message('threads_%s' % post.pk)
  42. post.is_read = post.date <= self.read_date
  43. last_post = self.posts[len(self.posts) - 1]
  44. if not self.tracker.is_read(self.thread):
  45. self.tracker.set_read(self.thread, last_post)
  46. self.tracker.sync()
  47. def get_post_actions(self):
  48. acl = self.request.acl.threads.get_role(self.thread.forum_id)
  49. actions = []
  50. try:
  51. if acl['can_approve'] and self.thread.replies_moderated > 0:
  52. actions.append(('accept', _('Accept posts')))
  53. if acl['can_move_threads_posts']:
  54. actions.append(('merge', _('Merge posts into one')))
  55. actions.append(('split', _('Split posts to new thread')))
  56. actions.append(('move', _('Move posts to other thread')))
  57. if acl['can_protect_posts']:
  58. actions.append(('protect', _('Protect posts')))
  59. actions.append(('unprotect', _('Remove posts protection')))
  60. if acl['can_delete_posts']:
  61. if self.thread.replies_deleted > 0:
  62. actions.append(('undelete', _('Undelete posts')))
  63. actions.append(('soft', _('Soft delete posts')))
  64. if acl['can_delete_posts'] == 2:
  65. actions.append(('hard', _('Hard delete posts')))
  66. except KeyError:
  67. pass
  68. return actions
  69. def make_posts_form(self):
  70. self.posts_form = None
  71. list_choices = self.get_post_actions();
  72. if (not self.request.user.is_authenticated()
  73. or not list_choices):
  74. return
  75. form_fields = {}
  76. form_fields['list_action'] = forms.ChoiceField(choices=list_choices)
  77. list_choices = []
  78. for item in self.posts:
  79. list_choices.append((item.pk, None))
  80. if not list_choices:
  81. return
  82. form_fields['list_items'] = forms.MultipleChoiceField(choices=list_choices, widget=forms.CheckboxSelectMultiple)
  83. self.posts_form = type('PostsViewForm', (Form,), form_fields)
  84. def handle_posts_form(self):
  85. if self.request.method == 'POST' and self.request.POST.get('origin') == 'posts_form':
  86. self.posts_form = self.posts_form(self.request.POST, request=self.request)
  87. if self.posts_form.is_valid():
  88. checked_items = []
  89. for post in self.posts:
  90. if str(post.pk) in self.posts_form.cleaned_data['list_items']:
  91. checked_items.append(post.pk)
  92. if checked_items:
  93. form_action = getattr(self, 'post_action_' + self.posts_form.cleaned_data['list_action'])
  94. try:
  95. response = form_action(checked_items)
  96. if response:
  97. return response
  98. return redirect(self.request.path)
  99. except forms.ValidationError as e:
  100. self.message = Message(e.messages[0], 'error')
  101. else:
  102. self.message = Message(_("You have to select at least one post."), 'error')
  103. else:
  104. if 'list_action' in self.posts_form.errors:
  105. self.message = Message(_("Action requested is incorrect."), 'error')
  106. else:
  107. self.message = Message(posts_form.non_field_errors()[0], 'error')
  108. else:
  109. self.posts_form = self.posts_form(request=self.request)
  110. def post_action_accept(self, ids):
  111. accepted = 0
  112. for post in self.posts:
  113. if post.pk in ids and post.moderated:
  114. accepted += 1
  115. if accepted:
  116. self.thread.post_set.filter(id__in=ids).update(moderated=False)
  117. self.thread.sync()
  118. self.thread.save(force_update=True)
  119. self.request.messages.set_flash(Message(_('Selected posts have been accepted and made visible to other members.')), 'success', 'threads')
  120. def post_action_merge(self, ids):
  121. users = []
  122. posts = []
  123. for post in self.posts:
  124. if post.pk in ids:
  125. posts.append(post)
  126. if not post.user_id in users:
  127. users.append(post.user_id)
  128. if len(users) > 1:
  129. raise forms.ValidationError(_("You cannot merge replies made by different members!"))
  130. if len(posts) < 2:
  131. raise forms.ValidationError(_("You have to select two or more posts you want to merge."))
  132. new_post = posts[0]
  133. for post in posts[1:]:
  134. post.merge_with(new_post)
  135. post.delete()
  136. new_post.post_preparsed = post_markdown(self.request, new_post.post)
  137. new_post.save(force_update=True)
  138. self.thread.sync()
  139. self.thread.save(force_update=True)
  140. self.forum.sync()
  141. self.forum.save(force_update=True)
  142. self.request.messages.set_flash(Message(_('Selected posts have been merged into one message.')), 'success', 'threads')
  143. def post_action_split(self, ids):
  144. for id in ids:
  145. if id == self.thread.start_post_id:
  146. raise forms.ValidationError(_("You cannot split first post from thread."))
  147. message = None
  148. if self.request.POST.get('do') == 'split':
  149. form = SplitThreadForm(self.request.POST, request=self.request)
  150. if form.is_valid():
  151. new_thread = Thread()
  152. new_thread.forum = form.cleaned_data['thread_forum']
  153. new_thread.name = form.cleaned_data['thread_name']
  154. new_thread.slug = slugify(form.cleaned_data['thread_name'])
  155. new_thread.start = timezone.now()
  156. new_thread.last = timezone.now()
  157. new_thread.start_poster_name = 'n'
  158. new_thread.start_poster_slug = 'n'
  159. new_thread.last_poster_name = 'n'
  160. new_thread.last_poster_slug = 'n'
  161. new_thread.save(force_insert=True)
  162. prev_merge = -1
  163. merge = -1
  164. for post in self.posts:
  165. if post.pk in ids:
  166. if prev_merge != post.merge:
  167. prev_merge = post.merge
  168. merge += 1
  169. post.merge = merge
  170. post.move_to(new_thread)
  171. post.save(force_update=True)
  172. new_thread.sync()
  173. new_thread.save(force_update=True)
  174. self.thread.sync()
  175. self.thread.save(force_update=True)
  176. self.forum.sync()
  177. self.forum.save(force_update=True)
  178. if new_thread.forum != self.forum:
  179. new_thread.forum.sync()
  180. new_thread.forum.save(force_update=True)
  181. self.request.messages.set_flash(Message(_("Selected posts have been split to new thread.")), 'success', 'threads')
  182. return redirect(reverse('thread', kwargs={'thread': new_thread.pk, 'slug': new_thread.slug}))
  183. message = Message(form.non_field_errors()[0], 'error')
  184. else:
  185. form = SplitThreadForm(request=self.request, initial={
  186. 'thread_name': _('[Split] %s') % self.thread.name,
  187. 'thread_forum': self.forum,
  188. })
  189. return self.request.theme.render_to_response('threads/split.html',
  190. {
  191. 'message': message,
  192. 'forum': self.forum,
  193. 'parents': self.parents,
  194. 'thread': self.thread,
  195. 'posts': ids,
  196. 'form': FormLayout(form),
  197. },
  198. context_instance=RequestContext(self.request));
  199. def post_action_move(self, ids):
  200. message = None
  201. if self.request.POST.get('do') == 'move':
  202. form = MovePostsForm(self.request.POST, request=self.request, thread=self.thread)
  203. if form.is_valid():
  204. thread = form.cleaned_data['thread_url']
  205. prev_merge = -1
  206. merge = -1
  207. for post in self.posts:
  208. if post.pk in ids:
  209. if prev_merge != post.merge:
  210. prev_merge = post.merge
  211. merge += 1
  212. post.merge = merge + thread.merges
  213. post.move_to(thread)
  214. post.save(force_update=True)
  215. if self.thread.post_set.count() == 0:
  216. self.thread.delete()
  217. else:
  218. self.thread.sync()
  219. self.thread.save(force_update=True)
  220. thread.sync()
  221. thread.save(force_update=True)
  222. thread.forum.sync()
  223. thread.forum.save(force_update=True)
  224. if self.forum.pk != thread.forum.pk:
  225. self.forum.sync()
  226. self.forum.save(force_update=True)
  227. self.request.messages.set_flash(Message(_("Selected posts have been moved to new thread.")), 'success', 'threads')
  228. return redirect(reverse('thread', kwargs={'thread': thread.pk, 'slug': thread.slug}))
  229. message = Message(form.non_field_errors()[0], 'error')
  230. else:
  231. form = MovePostsForm(request=self.request)
  232. return self.request.theme.render_to_response('threads/move.html',
  233. {
  234. 'message': message,
  235. 'forum': self.forum,
  236. 'parents': self.parents,
  237. 'thread': self.thread,
  238. 'posts': ids,
  239. 'form': FormLayout(form),
  240. },
  241. context_instance=RequestContext(self.request));
  242. def post_action_undelete(self, ids):
  243. undeleted = []
  244. for post in self.posts:
  245. if post.pk in ids and post.deleted:
  246. undeleted.append(post.pk)
  247. if undeleted:
  248. self.thread.post_set.filter(id__in=undeleted).update(deleted=False)
  249. self.thread.sync()
  250. self.thread.save(force_update=True)
  251. self.forum.sync()
  252. self.forum.save(force_update=True)
  253. self.request.messages.set_flash(Message(_('Selected posts have been restored.')), 'success', 'threads')
  254. def post_action_protect(self, ids):
  255. protected = 0
  256. for post in self.posts:
  257. if post.pk in ids and not post.protected:
  258. protected += 1
  259. if protected:
  260. self.thread.post_set.filter(id__in=ids).update(protected=True)
  261. self.request.messages.set_flash(Message(_('Selected posts have been protected from edition.')), 'success', 'threads')
  262. def post_action_unprotect(self, ids):
  263. unprotected = 0
  264. for post in self.posts:
  265. if post.pk in ids and post.protected:
  266. unprotected += 1
  267. if unprotected:
  268. self.thread.post_set.filter(id__in=ids).update(protected=False)
  269. self.request.messages.set_flash(Message(_('Protection from editions has been removed from selected posts.')), 'success', 'threads')
  270. def post_action_soft(self, ids):
  271. deleted = []
  272. for post in self.posts:
  273. if post.pk in ids and not post.deleted:
  274. if post.pk == self.thread.start_post_id:
  275. raise forms.ValidationError(_("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."))
  276. deleted.append(post.pk)
  277. if deleted:
  278. self.thread.post_set.filter(id__in=deleted).update(deleted=True)
  279. self.thread.sync()
  280. self.thread.save(force_update=True)
  281. self.forum.sync()
  282. self.forum.save(force_update=True)
  283. self.request.messages.set_flash(Message(_('Selected posts have been deleted.')), 'success', 'threads')
  284. def post_action_hard(self, ids):
  285. deleted = []
  286. for post in self.posts:
  287. if post.pk in ids and not post.deleted:
  288. if post.pk == self.thread.start_post_id:
  289. raise forms.ValidationError(_("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."))
  290. deleted.append(post.pk)
  291. if deleted:
  292. for post in deleted:
  293. post.delete()
  294. self.thread.post_set.filter(id__in=deleted).delete()
  295. Change.objects.d(post__in=ids).delete()
  296. Checkpoint.objects.filter(post__in=ids).delete()
  297. self.thread.sync()
  298. self.thread.save(force_update=True)
  299. self.forum.sync()
  300. self.forum.save(force_update=True)
  301. self.request.messages.set_flash(Message(_('Selected posts have been deleted.')), 'success', 'threads')
  302. def get_thread_actions(self):
  303. acl = self.request.acl.threads.get_role(self.thread.forum_id)
  304. actions = []
  305. try:
  306. if acl['can_approve'] and self.thread.moderated:
  307. actions.append(('accept', _('Accept this thread')))
  308. if acl['can_pin_threads'] == 2 and self.thread.weight < 2:
  309. actions.append(('annouce', _('Change this thread to annoucement')))
  310. if acl['can_pin_threads'] > 0 and self.thread.weight != 1:
  311. actions.append(('sticky', _('Change this thread to sticky')))
  312. if acl['can_pin_threads'] > 0:
  313. if self.thread.weight == 2:
  314. actions.append(('normal', _('Change this thread to normal')))
  315. if self.thread.weight == 1:
  316. actions.append(('normal', _('Unpin this thread')))
  317. if acl['can_move_threads_posts']:
  318. actions.append(('move', _('Move this thread')))
  319. if acl['can_close_threads']:
  320. if self.thread.closed:
  321. actions.append(('open', _('Open this thread')))
  322. else:
  323. actions.append(('close', _('Close this thread')))
  324. if acl['can_delete_threads']:
  325. if self.thread.deleted:
  326. actions.append(('undelete', _('Undelete this thread')))
  327. else:
  328. actions.append(('soft', _('Soft delete this thread')))
  329. if acl['can_delete_threads'] == 2:
  330. actions.append(('hard', _('Hard delete this thread')))
  331. except KeyError:
  332. pass
  333. return actions
  334. def make_thread_form(self):
  335. self.thread_form = None
  336. list_choices = self.get_thread_actions();
  337. if (not self.request.user.is_authenticated()
  338. or not list_choices):
  339. return
  340. form_fields = {'thread_action': forms.ChoiceField(choices=list_choices)}
  341. self.thread_form = type('ThreadViewForm', (Form,), form_fields)
  342. def handle_thread_form(self):
  343. if self.request.method == 'POST' and self.request.POST.get('origin') == 'thread_form':
  344. self.thread_form = self.thread_form(self.request.POST, request=self.request)
  345. if self.thread_form.is_valid():
  346. form_action = getattr(self, 'thread_action_' + self.thread_form.cleaned_data['thread_action'])
  347. try:
  348. response = form_action()
  349. if response:
  350. return response
  351. return redirect(self.request.path)
  352. except forms.ValidationError as e:
  353. self.message = Message(e.messages[0], 'error')
  354. else:
  355. if 'thread_action' in self.thread_form.errors:
  356. self.message = Message(_("Action requested is incorrect."), 'error')
  357. else:
  358. self.message = Message(form.non_field_errors()[0], 'error')
  359. else:
  360. self.thread_form = self.thread_form(request=self.request)
  361. def thread_action_accept(self):
  362. # Sync thread and post
  363. self.thread.moderated = False
  364. self.thread.replies_moderated -= 1
  365. self.thread.save(force_update=True)
  366. self.thread.start_post.moderated = False
  367. self.thread.start_post.save(force_update=True)
  368. self.thread.last_post.set_checkpoint(self.request, 'accepted')
  369. # Sync user
  370. if self.thread.last_post.user:
  371. self.thread.start_post.user.threads += 1
  372. self.thread.start_post.user.posts += 1
  373. self.thread.start_post.user.save(force_update=True)
  374. # Sync forum
  375. self.forum.threads_delta += 1
  376. self.forum.posts_delta += self.thread.replies + 1
  377. self.forum.sync()
  378. self.forum.save(force_update=True)
  379. # Update monitor
  380. self.request.monitor['threads'] = int(self.request.monitor['threads']) + 1
  381. self.request.monitor['posts'] = int(self.request.monitor['posts']) + self.thread.replies + 1
  382. self.request.messages.set_flash(Message(_('Thread has been marked as reviewed and made visible to other members.')), 'success', 'threads')
  383. def thread_action_annouce(self):
  384. self.thread.weight = 2
  385. self.thread.save(force_update=True)
  386. self.request.messages.set_flash(Message(_('Thread has been turned into annoucement.')), 'success', 'threads')
  387. def thread_action_sticky(self):
  388. self.thread.weight = 1
  389. self.thread.save(force_update=True)
  390. self.request.messages.set_flash(Message(_('Thread has been turned into sticky.')), 'success', 'threads')
  391. def thread_action_normal(self):
  392. self.thread.weight = 0
  393. self.thread.save(force_update=True)
  394. self.request.messages.set_flash(Message(_('Thread weight has been changed to normal.')), 'success', 'threads')
  395. def thread_action_move(self):
  396. message = None
  397. if self.request.POST.get('do') == 'move':
  398. form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum)
  399. if form.is_valid():
  400. new_forum = form.cleaned_data['new_forum']
  401. self.thread.move_to(new_forum)
  402. self.thread.save(force_update=True)
  403. self.forum.sync()
  404. self.forum.save(force_update=True)
  405. new_forum.sync()
  406. new_forum.save(force_update=True)
  407. self.request.messages.set_flash(Message(_('Thread has been moved to "%(forum)s".') % {'forum': new_forum.name}), 'success', 'threads')
  408. return None
  409. message = Message(form.non_field_errors()[0], 'error')
  410. else:
  411. form = MoveThreadsForm(request=self.request, forum=self.forum)
  412. return self.request.theme.render_to_response('threads/move.html',
  413. {
  414. 'message': message,
  415. 'forum': self.forum,
  416. 'parents': self.parents,
  417. 'thread': self.thread,
  418. 'form': FormLayout(form),
  419. },
  420. context_instance=RequestContext(self.request));
  421. def thread_action_open(self):
  422. self.thread.closed = False
  423. self.thread.save(force_update=True)
  424. self.thread.last_post.set_checkpoint(self.request, 'opened')
  425. self.request.messages.set_flash(Message(_('Thread has been opened.')), 'success', 'threads')
  426. def thread_action_close(self):
  427. self.thread.closed = True
  428. self.thread.save(force_update=True)
  429. self.thread.last_post.set_checkpoint(self.request, 'closed')
  430. self.request.messages.set_flash(Message(_('Thread has been closed.')), 'success', 'threads')
  431. def thread_action_undelete(self):
  432. # Update thread
  433. self.thread.deleted = False
  434. self.thread.replies_deleted -= 1
  435. self.thread.save(force_update=True)
  436. # Update first post in thread
  437. self.thread.start_post.deleted = False
  438. self.thread.start_post.save(force_update=True)
  439. # Set checkpoint
  440. self.thread.last_post.set_checkpoint(self.request, 'undeleted')
  441. # Update forum
  442. self.forum.sync()
  443. self.forum.save(force_update=True)
  444. # Update monitor
  445. self.request.monitor['threads'] = int(self.request.monitor['threads']) + 1
  446. self.request.monitor['posts'] = int(self.request.monitor['posts']) + self.thread.replies + 1
  447. self.request.messages.set_flash(Message(_('Thread has been undeleted.')), 'success', 'threads')
  448. def thread_action_soft(self):
  449. # Update thread
  450. self.thread.deleted = True
  451. self.thread.replies_deleted += 1
  452. self.thread.save(force_update=True)
  453. # Update first post in thread
  454. self.thread.start_post.deleted = True
  455. self.thread.start_post.save(force_update=True)
  456. # Set checkpoint
  457. self.thread.last_post.set_checkpoint(self.request, 'deleted')
  458. # Update forum
  459. self.forum.sync()
  460. self.forum.save(force_update=True)
  461. # Update monitor
  462. self.request.monitor['threads'] = int(self.request.monitor['threads']) - 1
  463. self.request.monitor['posts'] = int(self.request.monitor['posts']) - self.thread.replies - 1
  464. self.request.messages.set_flash(Message(_('Thread has been deleted.')), 'success', 'threads')
  465. def thread_action_hard(self):
  466. # Delete thread
  467. self.thread.delete()
  468. # Update forum
  469. self.forum.sync()
  470. self.forum.save(force_update=True)
  471. # Update monitor
  472. self.request.monitor['threads'] = int(self.request.monitor['threads']) - 1
  473. self.request.monitor['posts'] = int(self.request.monitor['posts']) - self.thread.replies - 1
  474. self.request.messages.set_flash(Message(_('Thread "%(thread)s" has been deleted.') % {'thread': self.thread.name}), 'success', 'threads')
  475. return redirect(reverse('forum', kwargs={'forum': self.forum.pk, 'slug': self.forum.slug}))
  476. def __call__(self, request, slug=None, thread=None, page=0):
  477. self.request = request
  478. self.pagination = None
  479. self.parents = None
  480. try:
  481. self.fetch_thread(thread)
  482. self.fetch_posts(page)
  483. self.message = request.messages.get_message('threads')
  484. self.make_thread_form()
  485. if self.thread_form:
  486. response = self.handle_thread_form()
  487. if response:
  488. return response
  489. self.make_posts_form()
  490. if self.posts_form:
  491. response = self.handle_posts_form()
  492. if response:
  493. return response
  494. except Thread.DoesNotExist:
  495. return error404(self.request)
  496. except ACLError403 as e:
  497. return error403(request, e.message)
  498. except ACLError404 as e:
  499. return error404(request, e.message)
  500. # Merge proxy into forum
  501. self.forum.closed = self.proxy.closed
  502. return request.theme.render_to_response('threads/thread.html',
  503. {
  504. 'message': self.message,
  505. 'forum': self.forum,
  506. 'parents': self.parents,
  507. 'thread': self.thread,
  508. 'is_read': self.tracker.is_read(self.thread),
  509. 'count': self.count,
  510. 'posts': self.posts,
  511. 'pagination': self.pagination,
  512. 'quick_reply': FormFields(QuickReplyForm(request=request)).fields,
  513. 'thread_form': FormFields(self.thread_form).fields if self.thread_form else None,
  514. 'posts_form': FormFields(self.posts_form).fields if self.posts_form else None,
  515. },
  516. context_instance=RequestContext(request));