Commits

Alexander Shorin committed b3d7c6e

Ooops, missed files of 6c0452311bac changeset.

  • Participants
  • Parent commits 3869360

Comments (0)

Files changed (2)

xmppflask/ext/sleekxmpp.py

+# -*- coding: utf-8 -*-
+"""
+    xmppflask.ext.sleekxmpp
+    ~~~~~~~~~~~~~~~~~~~~~~~
+
+    XMPPWSGI server routines based on SleekXMPP lib.
+
+    :copyright: (c) 2012 Alexander Shorin <kxepal@gmail.com>
+    :license: BSD.
+"""
+
+import time
+
+from xmppflask.server import XmppWsgiServerInterface, maybe_unicode
+
+class SleekXmppWsgiInterface(XmppWsgiServerInterface):
+    """XMPPWSGI interface based on SleekXMPP library."""
+    def __init__(self):
+        sleekxmpp = __import__('sleekxmpp')
+        self.module = sleekxmpp
+        self.message_class = sleekxmpp.Message
+        self.presence_class = sleekxmpp.Presence
+        self.iq_class = sleekxmpp.Iq
+        super(SleekXmppWsgiInterface, self).__init__()
+
+    def connect(self, jid, pwd, use_tls=True, use_ssl=False):
+        self.client = self.module.ClientXMPP(jid, pwd)
+
+        self.client.add_event_handler('session_start', self.session_start)
+
+        if 'message' in self.event_handlers:
+            handler = self.event_handlers['message']
+            self.client.add_event_handler('message', handler)
+        if 'presence' in self.event_handlers:
+            handler = self.event_handlers['presence']
+            self.client.add_event_handler('presence', handler)
+
+        self.client.register_plugin('xep_0030') # Service Discovery
+        self.client.register_plugin('xep_0199') # XMPP Ping
+        self.client.register_plugin('xep_0203') # XMPP Delay
+
+        self.client.connect(use_tls=use_tls, use_ssl=use_ssl)
+
+    def session_start(self, session):
+        self.client.send_presence()
+
+    def serve_forever(self):
+        self.client.process(block=False)
+
+    def make_environ(self, event):
+        """Creates XMPPWSGI environ.
+
+        :param event: XMPP event that would be base for environ.
+        """
+        environ = super(SleekXmppWsgiInterface, self).make_environ(event)
+
+        environ['APP_JID'] = unicode(self.client.boundjid.full)
+
+        if event['id']:
+            environ['XMPP_ID'] = maybe_unicode(event['id'])
+        environ['from'] = maybe_unicode(event['from'])
+        environ['to'] = maybe_unicode(event['to'])
+        environ['type'] = maybe_unicode(event['type'])
+        if 'delay' in event.plugins:
+            delay = time.mktime(
+                event.plugins['delay'].get_stamp().utctimetuple()
+            )
+            environ['XMPP_DELAY'] =  environ['XMPP_TIMESTAMP'] - delay
+
+        if environ['from']:
+            environ['XMPP_JID'] = environ['from'].split('/')[0]
+
+        if isinstance(event, self.message_class):
+            environ['body'] = environ['MESSAGE'] = maybe_unicode(event['body'])
+            environ['subject'] = maybe_unicode(event['subject'])
+            environ['mucroom'] = maybe_unicode(event['mucroom'])
+            environ['mucnick'] = maybe_unicode(event['mucnick'])
+        elif isinstance(event, self.presence_class):
+            environ['priority'] = event['priority']
+            environ['status'] = maybe_unicode(event['status'])
+            environ['type'] = maybe_unicode(environ['type'] or event['show'])
+
+        return environ
+
+    def send_message(self, environ, payload):
+        """Sends XMPP messages.
+
+        :param environ: XMPPWSGI environ.
+        :type environ: dict
+
+        :param payload: Presence payload data.
+        :type payload: dict
+        """
+        self.client.send_message(mto=payload['to'],
+                                 mbody=payload['body'],
+                                 mtype=environ['type'])
+
+    def send_presence(self, environ, payload):
+        """Sends XMPP presence event.
+
+        :param environ: XMPPWSGI environ.
+        :type environ: dict
+
+        :param payload: Presence payload data.
+        :type payload: dict
+        """
+        to_jid = payload.get('to', environ['XMPP_JID'])
+        if to_jid == 'all':
+            to_jid = None
+        if 'type' not in payload:
+            self.client.send_presence(pto=to_jid)
+        elif payload['type'] in ('available', 'unavailable'):
+            self.client.send_presence(pto=to_jid, ptype=payload['type'])
+        elif payload['type'] in ('subscribe', 'subscribed',
+                                 'unsubscribe', 'unsubscribed'):
+            self.client.send_presence(pto=to_jid,
+                                      ptype=payload['type'])
+        elif payload['type'] in ('probe',):
+            self.client.send_presence(pto=to_jid,
+                                      ptype=payload['type'])
+        else:
+            self.client.send_presence(pto=to_jid,
+                                      pstatus=payload.get('status', ''),
+                                      pshow=payload['type'])

xmppflask/ext/xmpppy.py

+# -*- coding: utf-8 -*-
+"""
+    xmppflask.ext.xmpppy
+    ~~~~~~~~~~~~~~~~~~~~
+
+    XMPPWSGI server routines based on xmpppy lib.
+
+    :copyright: (c) 2012 Alexander Shorin <kxepal@gmail.com>
+    :license: BSD.
+"""
+
+import datetime
+import time
+
+from xmppflask.server import XmppWsgiServerInterface, maybe_unicode
+
+class XmpppyWsgiInterface(XmppWsgiServerInterface):
+    """XMPPWSGI interface based on xmpppy library."""
+    def __init__(self):
+        import xmpp
+        self.module = xmpp
+        self.message_class = xmpp.Message
+        self.presence_class = xmpp.Presence
+        self.iq_class = xmpp.Iq
+        super(XmpppyWsgiInterface, self).__init__()
+
+    def connect(self, jid, pwd, use_tls=True, use_ssl=False):
+        jid = self.module.JID(jid)
+        user, server, password = jid.getNode(), jid.getDomain(), pwd
+
+        self.client = self.module.Client(server)
+
+        conn_type = self.client.connect()
+
+        if conn_type is None:
+            raise Exception(u'Unable to connect to server %s!' % server)
+
+        auth_type = self.client.auth(user, password)
+
+        if auth_type is None:
+            raise Exception((u'Unable to authorize on %s - '
+                             u'check login/password.') % server)
+
+        if 'message' in self.event_handlers:
+            handler = self.event_handlers['message']
+            self.client.RegisterHandler('message',
+                                        lambda c, m: handler(m))
+        if 'presence' in self.event_handlers:
+            handler = self.event_handlers['presence']
+            self.client.RegisterHandler('presence',
+                                        lambda c, m: handler(m))
+
+        self.client.sendInitPresence()
+
+    def serve_forever(self):
+        def step_on(conn):
+            try:
+                conn.Process(1)
+            except KeyboardInterrupt:
+                return False
+            return True
+
+        while step_on(self.client):
+            pass
+
+    def make_environ(self, event):
+        """Creates XMPPWSGI environ.
+
+        :param event: XMPP event that would be base for environ.
+        """
+        environ = super(XmpppyWsgiInterface, self).make_environ(event)
+        environ['id'] = maybe_unicode(event.getID())
+        environ['from'] = maybe_unicode(event.getFrom())
+        environ['to'] = maybe_unicode(event.getTo())
+        environ['type'] = maybe_unicode(event.getType())
+        delay = event.getTimestamp()
+        if delay:
+            delay = time.mktime(
+                datetime.datetime.strptime(delay,
+                                           '%Y%m%dT%H:%M:%S').utctimetuple()
+            )
+            environ['XMPP_DELAY'] =  environ['XMPP_TIMESTAMP'] - delay
+
+        if environ['from']:
+            environ['XMPP_JID'] = environ['from'].split('/')[0]
+
+        if isinstance(event, self.message_class):
+            environ['body'] = environ['MESSAGE'] = maybe_unicode(event.getBody())
+            environ['subject'] = maybe_unicode(event.getSubject())
+            if environ['type'] == 'groupchat':
+                environ['mucroom'] = environ['from'].split('/')[0]
+                environ['mucnick'] = environ['from'].split('/')[1]
+            else:
+                environ['mucroom'] = None
+                environ['mucnick'] = None
+        elif isinstance(event, self.presence_class):
+            environ['priority'] = event.getPriority()
+            environ['status'] = maybe_unicode(event.getStatus())
+            environ['type'] = maybe_unicode(environ['type'] or event.getShow())
+
+        return environ
+
+    def send_message(self, environ, payload):
+        """Sends XMPP messages.
+
+        :param environ: XMPPWSGI environ.
+        :type environ: dict
+
+        :param payload: Message payload data.
+        :type payload: dict
+        """
+        jid = self.module.JID(payload['to'])
+        self.client.send(self.message_class(jid,
+                                            payload['body'],
+                                            typ=environ['type']))
+
+    def send_presence(self, environ, payload):
+        """Sends XMPP presence event.
+
+        :param environ: XMPPWSGI environ.
+        :type environ: dict
+
+        :param payload: Presence payload data.
+        :type payload: dict
+        """
+        to_jid = payload.get('to', environ['XMPP_JID'])
+        if to_jid == 'all':
+            to_jid = None
+        if 'type' not in payload:
+            presence = self.presence_class(to=to_jid)
+        elif payload['type'] in ('available', 'unavailable'):
+            presence = self.presence_class(to=to_jid, typ=payload['type'])
+        elif payload['type'] in ('subscribe', 'subscribed',
+                                 'unsubscribe', 'unsubscribed'):
+            presence = self.presence_class(to=to_jid, typ=payload['type'])
+        elif payload['type'] in ('probe',):
+            presence = self.presence_class(to=to_jid, typ=payload['type'])
+        else:
+            presence = self.presence_class(to=to_jid,
+                                           status=payload.get('status', ''),
+                                           show=payload['type'])
+        self.client.send(presence)