+import logging
+
+import elixir
+from pylons import request, response, session, tmpl_context as c
+from pylons.controllers.util import abort, redirect_to
+from sqlalchemy import func
+from sqlalchemy.orm.exc import NoResultFound
+
+import floof.lib.helpers as h
+from floof.lib.base import BaseController, render
+from floof.model.users import User, UserRelationship
+from floof.model.forms import UserRelationshipToggleForm
+
+log = logging.getLogger(__name__)
+
+class UserSettingsController(BaseController):
+
+ def rel_toggle(self, name):
+ """Adds or removes a single relationship with a single user.
+
+ Expects to be called as a POST with `target_user_id`,
+ `type`, and `add_remove` as parameters.
+ """
+ try:
+ user = User.query.filter(func.lower(User.name) == name).one()
+ except NoResultFound:
+ abort(404)
+
+ schema = UserRelationshipToggleForm()
+ try:
+ form_result = schema.to_python(request.params)
+ except BaseException, e:
+ # The data for this form is generated entirely by the app. If
+ # there are errors, the user has been dicking around.
+ abort(400)
+
+ # Grab any existing relationship row
+ rel = None
+ try:
+ rel = UserRelationship.query.filter_by(
+ user_id=user.id,
+ target_user_id=form_result['target_user'].id,
+ type=form_result['type'],
+ ).one()
+ except:
+ pass
+
+ # XXX shouldn't include "watching"...
+ target_name = form_result['target_user'].name
+ if form_result['add_remove'] == u'add':
+ # Adding
+ if rel:
+ # Already exists! Nothing to do.
+ h.flash("You're already watching {name}..."
+ .format(name=target_name))
+ else:
+ # Add it
+ UserRelationship(
+ user_id=user.id,
+ target_user_id=form_result['target_user'].id,
+ type=form_result['type'],
+ )
+ h.flash("Now watching {name}."
+ .format(name=target_name))
+ else:
+ # Removing
+ if rel:
+ # Toss it
+ rel.delete()
+ h.flash("No longer watching {name}. How cruel!."
+ .format(name=target_name))
+ else:
+ # Already gone! Nothing to do.
+ h.flash("You're not watching {name}..."
+ .format(name=target_name))
+
+ elixir.session.commit()
+
+ self.redirect_to_referrer()