8d8adf0ca0eb11e410370fd571fad9572127c900
[zzz-floof.git] / floof / controllers / user_settings.py
1 import logging
2
3 import elixir
4 from pylons import request, response, session, tmpl_context as c
5 from pylons.controllers.util import abort, redirect_to
6 from sqlalchemy import func
7 from sqlalchemy.orm.exc import NoResultFound
8
9 import floof.lib.helpers as h
10 from floof.lib.base import BaseController, render
11 from floof.model.users import User, UserRelationship
12 from floof.model.forms import UserRelationshipToggleForm
13
14 log = logging.getLogger(__name__)
15
16 class UserSettingsController(BaseController):
17
18 def rel_toggle(self, name):
19 """Adds or removes a single relationship with a single user.
20
21 Expects to be called as a POST with `target_user_id`,
22 `type`, and `add_remove` as parameters.
23 """
24 try:
25 user = User.query.filter(func.lower(User.name) == name).one()
26 except NoResultFound:
27 abort(404)
28
29 schema = UserRelationshipToggleForm()
30 try:
31 form_result = schema.to_python(request.params)
32 except BaseException, e:
33 # The data for this form is generated entirely by the app. If
34 # there are errors, the user has been dicking around.
35 abort(400)
36
37 # Grab any existing relationship row
38 rel = None
39 try:
40 rel = UserRelationship.query.filter_by(
41 user_id=user.id,
42 target_user_id=form_result['target_user'].id,
43 type=form_result['type'],
44 ).one()
45 except:
46 pass
47
48 # XXX shouldn't include "watching"...
49 target_name = form_result['target_user'].name
50 if form_result['add_remove'] == u'add':
51 # Adding
52 if rel:
53 # Already exists! Nothing to do.
54 h.flash("You're already watching {name}..."
55 .format(name=target_name))
56 else:
57 # Add it
58 UserRelationship(
59 user_id=user.id,
60 target_user_id=form_result['target_user'].id,
61 type=form_result['type'],
62 )
63 h.flash("Now watching {name}."
64 .format(name=target_name))
65 else:
66 # Removing
67 if rel:
68 # Toss it
69 rel.delete()
70 h.flash("No longer watching {name}. How cruel!."
71 .format(name=target_name))
72 else:
73 # Already gone! Nothing to do.
74 h.flash("You're not watching {name}..."
75 .format(name=target_name))
76
77 elixir.session.commit()
78
79 self.redirect_to_referrer()