Beispiel #1
0
    def handle_message(self, msg):
        """Handle message
        """

        if 'presence' in msg:
            pass

        if 'body' in msg and check_stoplist(msg['body']):
            return

        try:
            jid, resource = msg['from'].split('/', 1)
        except ValueError:
            jid = msg['from']
            resource = None

        env.user = ImUser('xmpp', jid)
        env.jid = jid
        env.resource = resource

        try:
            if 'receipt' in msg and msg['receipt']:
                try:
                    uid, post_id, comment_id = msg['receipt'].split('_')
                    posts.clear_unread_comments(post_id, int(comment_id))
                    return
                except ValueError:
                    try:
                        uid, post_id = msg['receipt'].split('_')
                        posts.clear_unread_posts(post_id)
                        return
                    except ValueError:
                        pass
        except NotAuthorized:
            pass

        if env.user.get_profile('im.auto_switch'):
            bare_from = msg['from'].split('/', 1)[0]
            env.user.set_active_account('xmpp', bare_from)

        def _route(user, jid, msg):
            session = env.user.session()
            try:
                return session(msg['body'])
            except SessionCallError:
                pass

            message = env.user.resolve_aliases(msg['body'])

            args = {}
            for r in self.route:
                m = re.search(r['resource'], msg['resource'])
                if m:
                    args = m.groupdict()
                    route = r['route']
                    break

            for regex, view in route:
                match = re.search(regex, message)
                if match:
                    for g, val in match.groupdict().iteritems():
                        args[g] = val
                    log.debug(">>> %s routed to %s(%s) via '%s'" % \
                              (jid, view.__name__, str(args), regex.pattern))
                    return view(**args)

        _presence = False

        try:
            reply = _route(env.user, jid, msg)
            if 'body' in reply and reply['body']:
                reply['body'] = re.sub(r'&#(\d+);',
                                       lambda c: chr(int(c.group(1))),
                                       reply['body'])
                reply['body'] = u''.join([ c if c == '\n' or ord(c) > 16 else ' ' \
                                           for c  in reply['body'] ])

            if '_presence' in reply and reply['_presence']:
                _presence = True

            if isinstance(reply, (str, unicode)):
                reply = {'body': reply}
        except NotAuthorized:
            reply = xmpp_template('user_not_authorized')
        except PointError, e:
            reply = {'body': "%s: %s" % (e.__class__.__name__, e.message)}
Beispiel #2
0
 def handle_tune(self, data):
     user = ImUser('xmpp', data['from'])
     user.update_tune_data(data['tune'])
Beispiel #3
0
    def handle_message(self, channel, data):
        tmpl = {}

        #if channel == 'msg' and 'author' in data:
        #redis = RedisPool(settings.redis_socket)
        #avatar = redis.get('avatar32.%s' % data['author'])
        #if not avatar:
        #av_path = os.path.join(settings.avatars_path, '32',
        #'%s.png' % data['author'])
        #if not os.path.exists(av_path):
        #av_path = os.path.join(settings.avatars_path, '32.png')

        #avfd = open(av_path)
        #avatar = 'data:image/png;base64,%s' % b64encode(avfd.read())
        #avfd.close()

        #data['avatar'] = avatar

        if channel == 'confirm':
            if 'type' not in data or data['type'] != 'xmpp' or \
                    not 'address' in data or not data['address'].strip():
                return
            body = xmpp_template('confirm_code', settings.lang, None, **data)
            out = {
                'to': data['address'],
                'body': body['body'],
                '_authorize': True
            }
            self.xout.push(json.dumps(out))
            return

        if channel == 'remember':
            body = xmpp_template('remember', settings.lang, None, **data)
            out = {
                'to': data['address'],
                'body': body['body'],
                '_authorize': True
            }
            self.xout.push(json.dumps(out))
            return

        if not isinstance(data['to'], (list, tuple)):
            data['to'] = [data['to']]

        res = db.fetchall(
            "SELECT * FROM users.profile_im "
            "WHERE id=ANY(%s);", [data['to']])
        profile = {r['id']: dict(r) for r in res}

        for i in data['to']:
            cdata = data.copy()

            user = ImUser.from_data(i, None)
            try:
                jid = user.get_active_account('xmpp')
                if not jid:
                    continue
            except TypeError:
                continue

            if i not in profile:
                profile[i] = user.profile_defaults()
            if profile[i]['off']:
                continue
            lang = user.get_profile('lang')

            cut = None
            if ('type' not in cdata or cdata['type'] != 'feed') and \
                'cut' in data and 'text' in data:
                cut = user.get_profile('im.cut')
                if cut and len(cdata['text']) > cut - 3:
                    cdata['text'] = cdata['text'][:cut] + '...'

            if cut:
                ctmpl = xmpp_template("%s_%s" % (channel, cdata['a']), lang,
                                      'html', **cdata)
            else:
                if not lang in tmpl:
                    tmpl[lang] = xmpp_template("%s_%s" % (channel, cdata['a']),
                                               lang, 'html', **cdata)
                ctmpl = tmpl[lang]

            if profile[i]['xhtml']:
                out = {'to': jid, 'body': ctmpl['body'], 'html': ctmpl['html']}
            else:
                out = {'to': jid, 'body': ctmpl['body']}

            if 'post_id' in cdata and 'comment_id' in cdata:
                out['_msg_id'] = 'post_%s_%s_%s' % (i, cdata['post_id'],
                                                    cdata['comment_id'])
            elif 'post_id' in cdata:
                out['_msg_id'] = 'post_%s_%s' % (i, cdata['post_id'])

            #if channel == 'msg':
            #    if profile[i]['post_resource']:
            #        out['_resource'] = '#%s' % data['id']
            #    elif profile[i]['user_resource']:
            #        out['_resource'] = '@%s' % data['author']

            self.xout.push(json.dumps(out))
Beispiel #4
0
 def handle_tune(self, data):
     user = ImUser("xmpp", data["from"])
     user.update_tune_data(data["tune"])
Beispiel #5
0
    def handle_message(self, channel, data):
        tmpl = {}

        #if channel == 'msg' and 'author' in data:
            #redis = RedisPool(settings.redis_socket)
            #avatar = redis.get('avatar32.%s' % data['author'])
            #if not avatar:
                #av_path = os.path.join(settings.avatars_path, '32',
                                       #'%s.png' % data['author'])
                #if not os.path.exists(av_path):
                    #av_path = os.path.join(settings.avatars_path, '32.png')

                #avfd = open(av_path)
                #avatar = 'data:image/png;base64,%s' % b64encode(avfd.read())
                #avfd.close()

            #data['avatar'] = avatar

        if channel == 'confirm':
            if 'type' not in data or data['type'] != 'xmpp' or \
                    not 'address' in data or not data['address'].strip():
                return
            body = xmpp_template('confirm_code', settings.lang, None, **data)
            out = {
                'to': data['address'],
                'body': body['body'],
                '_authorize': True
            }
            self.xout.push(json.dumps(out))
            return

        if channel == 'remember':
            body = xmpp_template('remember', settings.lang, None, **data)
            out = {
                'to': data['address'],
                'body': body['body'],
                '_authorize': True
            }
            self.xout.push(json.dumps(out))
            return

        if not isinstance(data['to'], (list, tuple)):
            data['to'] = [data['to']]

        res = db.fetchall("SELECT * FROM users.profile_im "
                          "WHERE id=ANY(%s);", [data['to']])
        profile = {r['id']:dict(r) for r in res}

        for i in data['to']:
            cdata = data.copy()

            user = ImUser.from_data(i, None)
            try:
                jid = user.get_active_account('xmpp')
                if not jid:
                    continue
            except TypeError:
                continue

            if i not in profile:
                profile[i] = user.profile_defaults()
            if profile[i]['off']:
                continue
            lang = user.get_profile('lang')

            cut = None
            if ('type' not in cdata or cdata['type'] != 'feed') and \
                'cut' in data and 'text' in data:
                cut = user.get_profile('im.cut')
                if cut and len(cdata['text']) > cut-3:
                    cdata['text'] = cdata['text'][:cut] + '...'

            if cut:
                ctmpl = xmpp_template("%s_%s"%(channel, cdata['a']),
                                      lang, 'html', **cdata)
            else:
                if not lang in tmpl:
                    tmpl[lang] = xmpp_template("%s_%s"%(channel, cdata['a']),
                                               lang, 'html', **cdata)
                ctmpl = tmpl[lang]

            if profile[i]['xhtml']:
                out = {'to':jid, 'body':ctmpl['body'],
                                 'html':ctmpl['html']}
            else:
                out = {'to':jid, 'body':ctmpl['body']}

            if 'post_id' in cdata and 'comment_id' in cdata:
                out['_msg_id'] = 'post_%s_%s_%s' % (i, cdata['post_id'], cdata['comment_id'])
            elif 'post_id' in cdata:
                out['_msg_id'] = 'post_%s_%s' % (i, cdata['post_id'])

            #if channel == 'msg':
            #    if profile[i]['post_resource']:
            #        out['_resource'] = '#%s' % data['id']
            #    elif profile[i]['user_resource']:
            #        out['_resource'] = '@%s' % data['author']

            self.xout.push(json.dumps(out))