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