Added MIT license.
[zzz-floof.git] / floof / controllers / comments.py
1 import logging
2
3 import elixir
4 from pylons import config, request, response, session, tmpl_context as c
5 from pylons.controllers.util import abort, redirect, redirect_to
6 from sqlalchemy import and_
7
8 from floof.lib.base import BaseController, render
9 from floof.model.art import Art
10 from floof.model.comments import Comment
11
12 log = logging.getLogger(__name__)
13
14 def find_owner(owner_url):
15 """Returns whatever thing owns a group of comments."""
16
17 # Need to prepend a slash to make this an absolute URL
18 route = config['routes.map'].match('/' + owner_url)
19
20 if route['action'] not in ('show', 'view'):
21 abort(404)
22
23 if route['controller'] == 'art':
24 model = Art
25 else:
26 abort(404)
27
28 owner = model.query.get(route['id'])
29 if not owner:
30 abort(404)
31
32 return owner
33
34
35 class CommentsController(BaseController):
36
37 def thread(self, owner_url, id=None):
38 """View a thread of comments, either attached to an item or starting
39 from a parent comment belonging to that item.
40 """
41 owner_object = find_owner(owner_url)
42 c.owner_url = owner_url
43 c.root_comment_id = id
44
45 if id:
46 # Get a thread starting from a certain point
47 c.root_comment = Comment.query.get(id)
48 if c.root_comment.discussion != owner_object.discussion:
49 abort(404)
50
51 c.comments = Comment.query.filter(and_(
52 Comment.discussion_id == owner_object.discussion_id,
53 Comment.left > c.root_comment.left,
54 Comment.right < c.root_comment.right
55 )).all()
56 else:
57 # Get everything
58 c.root_comment = None
59 c.comments = owner_object.discussion.comments
60
61 return render('/comments/thread.mako')
62
63 def reply(self, owner_url, id=None):
64 """Reply to a comment or discussion."""
65
66 c.parent_comment_id = id
67 if id:
68 c.parent_comment = Comment.query.get(id)
69 else:
70 c.parent_comment = None
71
72 return render('/comments/reply.mako')
73
74 def reply_done(self, owner_url, id=None):
75 """Finish replying to a comment or discussion."""
76 # XXX form validation woo
77
78 owner_object = find_owner(owner_url)
79
80 if id:
81 parent_comment = Comment.query.get(id)
82 else:
83 parent_comment = None
84
85 new_comment = Comment(
86 text=request.params['text'],
87 user=c.user,
88 discussion=owner_object.discussion,
89 parent=parent_comment,
90 )
91 elixir.session.commit()
92
93 return redirect('/' + owner_url, code=301)