Source

openju / openju / message_bus.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import xmpp
from mongoengine.queryset import DoesNotExist

# from openju.util import none_or_int
from openju import g, _
from openju.validators import UserAlertError
from openju.routes import *
from openju.model import User

def error_handler(f):
    def new_f(conn, *args, **kw):
        try:
            f(conn, *args, **kw)
        except UserAlertError, e:
            conn.send(xmpp.Message(g.xmpp_user, unicode(e)))
    return new_f

@error_handler
def message_bus(conn, mess):
    """ kind a routing thing """
    
    text = mess.getBody()
    xmpp_user = mess.getFrom()
    user_jid = u'%(node)s@%(domain)s' % dict(
        node=xmpp_user.getNode(),
        domain=xmpp_user.getDomain())
    
    if text is not None: # don't know why, but sometimes it's None. TODO: debug it
        def call_list(*f_list):
            for f in f_list:
                res = f(text)
                if isinstance(res, unicode):
                    conn.send(xmpp.Message(xmpp_user, res))
                if res is not None:
                    return
        
        # should be only place to put some g.-stuff
        g.xmpp_user = xmpp_user
        g.text = text
        g.user_jid = user_jid
        try:
            g.auth_user = User.objects.get(jid=user_jid)
        except DoesNotExist:
            g.auth_user = None
        
        call_list(
            cmd_register,
            cmd_last_messages,
            cmd_read_message,
            cmd_read_message_with_replies,
            cmd_post_reply,
            cmd_user_info,
            cmd_post_message,
            )