Source

xmppflask / xmppflask / server.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# -*- coding: utf-8 -*-
"""
    xmppflask.server
    ~~~~~~~~~~~~~~~~

    XMPPWSGI server implementation to serve XmppFlask apps.

    :copyright: (c) 2012 Alexander Shorin <kxepal@gmail.com>
    :license: BSD.
"""

import datetime
import time
from collections import namedtuple
from pprint import pformat

JID = namedtuple('JID', 'user,domain,resource')

class XmppWsgiServer(object):
    """Base XMPPWSGI server."""

    #: Proxy to XMPP module
    module = None
    #: Proxy to active XMPP client instance
    client = None
    message_class = None
    presence_class = None
    iq_class = None

    def __init__(self, app):
        self.app = app

    def _connect(self, *args, **kwargs):
        """Handles internal connection routine specific."""
        raise NotImplementedError

    def make_environ(self, event):
        """Creates XMPPWSGI environ.

        :param event: XMPP event that would be base for environ.
        """
        environ = {}
        if isinstance(event, self.message_class):
            event_type = u'message'
        elif isinstance(event, self.presence_class):
            event_type = u'presence'
        elif isinstance(event, self.iq_class):
            event_type = u'iq'
        environ['XMPP_EVENT'] = event_type
        environ['XMPP_TIMESTAMP'] = time.time()
        return environ

    def connect(self, jid, pwd, use_tls=True, use_ssl=False):
        """Activates connection for XMPPWSGI server."""
        self.app.logger.info('connecting...')
        self._connect(jid, pwd, use_tls, use_ssl)

    def serve_forever(self):
        raise NotImplementedError

    def dispatch_app_response(self, environ, response):
        """Response object dispatcher."""
        for item in response:
            if isinstance(item, basestring):
                cmd, payload = 'message', item
            else:
                cmd, payload = item
            if cmd == 'message' and payload:
                func = self.send_message
            elif cmd == 'presence':
                func = self.send_presence
            elif cmd == 'iq':
                func = self.send_iq
            elif cmd == 'join_muc':
                func = self.join_muc
            else:
                raise ValueError('unknown command %r' % cmd)
            func(environ, payload)

    def handle_message(self, message):
        """Handles message events."""
        environ = self.make_environ(message)
        self.app.logger.debug(pformat(environ))
        if not environ['MESSAGE']:
            return
        if environ['XMPP_TIMESTAMP'] < time.time() - 3: # skip old messages
            return
        notification_queue = []
        response = self.app(environ, notification_queue)
        self.dispatch_app_response(environ, response)
        for jid, resp in notification_queue:
            self.dispatch_app_response({'XMPP_JID': jid}, resp)

    def send_message(self, environ, body):
        """Sends XMPP messages. Should be overriden with library specific
        routine.

        :param environ: XMPPWSGI environ.
        :type environ: dict

        :param body: Message body.
        :type body: unicode
        """
        raise NotImplementedError

    def handle_presence(self, presence):
        """Handles presence events."""
        environ = self.make_environ(presence)
        self.app.logger.debug(pformat(environ))
        if environ['from'] == environ['to']: # we don't want infinity loop there
            return
        notification_queue = []
        response = self.app(environ, notification_queue)
        self.dispatch_app_response(environ, response)
        for jid, resp in notification_queue:
            self.dispatch_app_response({'XMPP_JID': jid}, resp)

    def send_presence(self, environ, payload):
        """Sends XMPP presence event.

        :param environ: XMPPWSGI environ. Should contains 'XMPP_JID' key.
        :type environ: dict

        :param payload: Presence payload data.
        :type payload: dict
        """
        raise NotImplementedError

    def handle_iq(self, iq):
        raise NotImplementedError

    def send_iq(self, environ, payload):
        raise NotImplementedError

    def join_muc(self, environ, payload):
        """Join App to specified MUC. Should be overriden with library specific
        routine.

        :param environ: XMPPWSGI environ.
        :type environ: dict

        :param payload: Presence payload data.
        :type payload: dict
        """
        raise NotImplementedError


class XmpppyServer(XmppWsgiServer):
    """XMPPWSGI Server based on xmpppy library."""
    def __init__(self, app):
        import xmpp
        self.module = xmpp
        self.message_class = xmpp.Message
        self.presence_class = xmpp.Presence
        self.iq_class = xmpp.Iq
        super(XmpppyServer, self).__init__(app)

    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)
        self.app.logger.info('done.')

        self.client.RegisterHandler('message',
                                    lambda c, m: self.handle_message(m))
        self.client.RegisterHandler('presence',
                                    lambda c, m: self.handle_presence(m))
        self.on_start()

    def on_start(self, *args, **kwargs):
        self.client.sendInitPresence()
        self.app.logger.info('started!')

    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(XmpppyServer, 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())
        dt = event.getTimestamp()
        if dt:
            environ['XMPP_TIMESTAMP'] = time.mktime(
                datetime.datetime.strptime(dt, '%Y%m%dT%H:%M:%S').utctimetuple()
            )

        xmpp_user = event.getFrom()
        jid = JID(
            xmpp_user.getNode(),
            xmpp_user.getDomain(),
            xmpp_user.getResource()
        )
        environ['XMPP_JID'] = u'%s@%s' % (jid.user, jid.domain)

        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'] = u'%s@%s' % (jid.user, jid.domain)
                environ['mucnick'] = maybe_unicode(jid.resource)
            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. Should contains 'XMPP_JID' key.
        :type environ: dict

        :param payload: Presence payload data. Should contain ``body`` key
                        with unicode message.
        :type payload: dict
        """
        if not isinstance(payload, dict):
            payload = {'body': payload}
        if environ['type'] == 'groupchat':
            to_jid = environ['mucroom']
        else:
            to_jid = environ['from']
        jid = self.module.JID(to_jid)
        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. Should contains 'XMPP_JID' key.
        :type environ: dict

        :param payload: Presence payload data. Mostly, could contain keys:
                        ``to``, ``type`` and ``status``.
        :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)

    def join_muc(self, environ, payload):
        """Join App to specified MUC.

        :param environ: XMPPWSGI environ.
        :type environ: dict

        :param payload: Presence payload data. Should contain ``room`` and
                        ``nick`` keys.
        :type payload: dict
        """
        presence = self.presence_class(
            to='%s/%s' % (payload['room'], payload['nick'])
        )
        self.client.send(presence)


class SleekXmppServer(XmppWsgiServer):
    """XMPPWSGI Server based on SleekXMPP library."""
    def __init__(self, app):
        import sleekxmpp
        self.module = sleekxmpp
        self.message_class = sleekxmpp.Message
        self.presence_class = sleekxmpp.Presence
        self.iq_class = sleekxmpp.Iq
        super(SleekXmppServer, self).__init__(app)

    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.on_start)
        self.client.add_event_handler('message', self.handle_message)
        self.client.add_event_handler('presence', self.handle_presence)

        self.client.register_plugin('xep_0030') # Service Discovery
        self.client.register_plugin('xep_0045') # Multi-User Chat
        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)
        self.app.logger.info('done.')

    def on_start(self, *args, **kwargs):
        self.client.send_presence()
        self.client.get_roster()
        self.app.logger.info('started!')

    def serve_forever(self):
        self.client.process(threading=False)

    def make_environ(self, event):
        """Creates XMPPWSGI environ.

        :param event: XMPP event that would be base for environ.
        """
        environ = super(SleekXmppServer, self).make_environ(event)
        environ['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:
            environ['XMPP_TIMESTAMP'] =  time.mktime(
                event.plugins['delay'].get_stamp().utctimetuple()
            )

        jid = JID(
            event['from'].user,
            event['from'].domain,
            event['from'].resource
        )
        environ['XMPP_JID'] = u'%s@%s' % (jid.user, jid.domain)

        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. Should contains 'XMPP_JID' key.
        :type environ: dict

        :param payload: Presence payload data. Should contain ``body`` key
                        with unicode message.
        :type payload: dict
        """
        if not isinstance(payload, dict):
            payload = {'body': payload}
        if environ['type'] == 'groupchat':
            to_jid = environ['mucroom']
        else:
            to_jid = environ['from']
        self.client.send_message(mto=to_jid,
                                 mbody=payload['body'],
                                 mtype=environ['type'])

    def send_presence(self, environ, payload):
        """Sends XMPP presence event.

        :param environ: XMPPWSGI environ. Should contains 'XMPP_JID' key.
        :type environ: dict

        :param payload: Presence payload data. Mostly, could contain keys:
                        ``to``, ``type`` and ``status``.
        :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'])

    def join_muc(self, environ, payload):
        """Join App to specified MUC.

        :param environ: XMPPWSGI environ.
        :type environ: dict

        :param payload: Presence payload data. Should contain ``room`` and
                        ``nick`` keys.
        :type payload: dict
        """
        self.client.plugin['xep_0045'].joinMUC(
            room=payload['room'],
            nick=payload['nick']
        )


def maybe_unicode(value):
    if value is None:
        return value
    if not value:
        return None
    return unicode(value)