summaryrefslogtreecommitdiff
path: root/slixmpp/plugins/xep_0060/pubsub.py
blob: 7394834c1ece13779d482a54dafa3d1eb26bee3a (plain)
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

# Slixmpp: The Slick XMPP Library
# Copyright (C) 2011  Nathanael C. Fritz
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
import logging

from slixmpp.xmlstream import JID
from slixmpp.xmlstream.handler import Callback
from slixmpp.xmlstream.matcher import StanzaPath
from slixmpp.plugins.base import BasePlugin
from slixmpp.plugins.xep_0060 import stanza


log = logging.getLogger(__name__)


class XEP_0060(BasePlugin):

    """
    XEP-0060 Publish Subscribe
    """

    name = 'xep_0060'
    description = 'XEP-0060: Publish-Subscribe'
    dependencies = {'xep_0030', 'xep_0004', 'xep_0082', 'xep_0131'}
    stanza = stanza

    def plugin_init(self):
        self.node_event_map = {}

        self.xmpp.register_handler(
                Callback('Pubsub Event: Items',
                    StanzaPath('message/pubsub_event/items'),
                    self._handle_event_items))
        self.xmpp.register_handler(
                Callback('Pubsub Event: Purge',
                    StanzaPath('message/pubsub_event/purge'),
                    self._handle_event_purge))
        self.xmpp.register_handler(
                Callback('Pubsub Event: Delete',
                    StanzaPath('message/pubsub_event/delete'),
                    self._handle_event_delete))
        self.xmpp.register_handler(
                Callback('Pubsub Event: Configuration',
                    StanzaPath('message/pubsub_event/configuration'),
                    self._handle_event_configuration))
        self.xmpp.register_handler(
                Callback('Pubsub Event: Subscription',
                    StanzaPath('message/pubsub_event/subscription'),
                    self._handle_event_subscription))

        self.xmpp['xep_0131'].supported_headers.add('SubID')

    def plugin_end(self):
        self.xmpp.remove_handler('Pubsub Event: Items')
        self.xmpp.remove_handler('Pubsub Event: Purge')
        self.xmpp.remove_handler('Pubsub Event: Delete')
        self.xmpp.remove_handler('Pubsub Event: Configuration')
        self.xmpp.remove_handler('Pubsub Event: Subscription')

    def _handle_event_items(self, msg):
        """Raise events for publish and retraction notifications."""
        node = msg['pubsub_event']['items']['node']

        multi = len(msg['pubsub_event']['items']) > 1
        values = {}
        if multi:
            values = msg.values
            del values['pubsub_event']

        for item in msg['pubsub_event']['items']:
            event_name = self.node_event_map.get(node, None)
            event_type = 'publish'
            if item.name == 'retract':
                event_type = 'retract'

            if multi:
                condensed = self.xmpp.Message()
                condensed.values = values
                condensed['pubsub_event']['items']['node'] = node
                condensed['pubsub_event']['items'].append(item)
                self.xmpp.event('pubsub_%s' % event_type, msg)
                if event_name:
                    self.xmpp.event('%s_%s' % (event_name, event_type),
                                    condensed)
            else:
                self.xmpp.event('pubsub_%s' % event_type, msg)
                if event_name:
                    self.xmpp.event('%s_%s' % (event_name, event_type), msg)

    def _handle_event_purge(self, msg):
        """Raise events for node purge notifications."""
        node = msg['pubsub_event']['purge']['node']
        event_name = self.node_event_map.get(node, None)

        self.xmpp.event('pubsub_purge', msg)
        if event_name:
            self.xmpp.event('%s_purge' % event_name, msg)

    def _handle_event_delete(self, msg):
        """Raise events for node deletion notifications."""
        node = msg['pubsub_event']['delete']['node']
        event_name = self.node_event_map.get(node, None)

        self.xmpp.event('pubsub_delete', msg)
        if event_name:
            self.xmpp.event('%s_delete' % event_name, msg)

    def _handle_event_configuration(self, msg):
        """Raise events for node configuration notifications."""
        node = msg['pubsub_event']['configuration']['node']
        event_name = self.node_event_map.get(node, None)

        self.xmpp.event('pubsub_config', msg)
        if event_name:
            self.xmpp.event('%s_config' % event_name, msg)

    def _handle_event_subscription(self, msg):
        """Raise events for node subscription notifications."""
        node = msg['pubsub_event']['subscription']['node']
        event_name = self.node_event_map.get(node, None)

        self.xmpp.event('pubsub_subscription', msg)
        if event_name:
            self.xmpp.event('%s_subscription' % event_name, msg)

    def map_node_event(self, node, event_name):
        """
        Map node names to events.

        When a pubsub event is received for the given node,
        raise the provided event.

        For example::

            map_node_event('http://jabber.org/protocol/tune',
                           'user_tune')

        will produce the events 'user_tune_publish' and 'user_tune_retract'
        when the respective notifications are received from the node
        'http://jabber.org/protocol/tune', among other events.

        :param node: The node name to map to an event.
        :param event_name: The name of the event to raise when a
                          notification from the given node is received.
        """
        self.node_event_map[node] = event_name

    def create_node(self, jid, node, config=None, ntype=None, ifrom=None,
                    timeout_callback=None, callback=None, timeout=None):
        """
        Create and configure a new pubsub node.

        A server MAY use a different name for the node than the one provided,
        so be sure to check the result stanza for a server assigned name.

        If no configuration form is provided, the node will be created using
        the server's default configuration. To get the default configuration
        use get_node_config().

        :param jid: The JID of the pubsub service.
        :param node: Optional name of the node to create. If no name is
                     provided, the server MAY generate a node ID for you.
                     The server can also assign a different name than the
                     one you provide; check the result stanza to see if
                     the server assigned a name.
        :param config: Optional XEP-0004 data form of configuration settings.
        :param ntype: The type of node to create. Servers typically default
                      to using 'leaf' if no type is provided.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub']['create']['node'] = node

        if config is not None:
            form_type = 'http://jabber.org/protocol/pubsub#node_config'
            if 'FORM_TYPE' in config.get_fields():
                config.field['FORM_TYPE']['value'] = form_type
            else:
                config.add_field(var='FORM_TYPE',
                                 ftype='hidden',
                                 value=form_type)
            if ntype:
                if 'pubsub#node_type' in config.get_fields():
                    config.field['pubsub#node_type']['value'] = ntype
                else:
                    config.add_field(var='pubsub#node_type', value=ntype)
            iq['pubsub']['configure'].append(config)

        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def subscribe(self, jid, node, bare=True, subscribee=None, options=None,
                  ifrom=None, timeout_callback=None, callback=None,
                  timeout=None):
        """
        Subscribe to updates from a pubsub node.

        The rules for determining the JID that is subscribing to the node are:
        1. If subscribee is given, use that as provided.
        2. If ifrom was given, use the bare or full version based on bare.
        3. Otherwise, use self.xmpp.boundjid based on bare.

        :param jid: The pubsub service JID.
        :param node: The node to subscribe to.
        :param bare: Indicates if the subscribee is a bare or full JID.
                     Defaults to True for a bare JID.
        :param subscribee: The JID that is subscribing to the node.
        :param options:
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub']['subscribe']['node'] = node

        if subscribee is None:
            if ifrom:
                if bare:
                    subscribee = JID(ifrom).bare
                else:
                    subscribee = ifrom
            else:
                if bare:
                    subscribee = self.xmpp.boundjid.bare
                else:
                    subscribee = self.xmpp.boundjid

        iq['pubsub']['subscribe']['jid'] = subscribee
        if options is not None:
            iq['pubsub']['options'].append(options)
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def unsubscribe(self, jid, node, subid=None, bare=True, subscribee=None,
                    ifrom=None, timeout_callback=None, callback=None,
                    timeout=None):
        """
        Unubscribe from updates from a pubsub node.

        The rules for determining the JID that is unsubscribing
        from the node are:
        1. If subscribee is given, use that as provided.
        2. If ifrom was given, use the bare or full version based on bare.
        3. Otherwise, use self.xmpp.boundjid based on bare.

        :param jid: The pubsub service JID.
        :param node: The node to unsubscribe from.
        :param subid: The specific subscription, if multiple subscriptions
                      exist for this JID/node combination.
        :param bare: Indicates if the subscribee is a bare or full JID.
                     Defaults to True for a bare JID.
        :param subscribee: The JID that is unsubscribing from the node.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub']['unsubscribe']['node'] = node

        if subscribee is None:
            if ifrom:
                if bare:
                    subscribee = JID(ifrom).bare
                else:
                    subscribee = ifrom
            else:
                if bare:
                    subscribee = self.xmpp.boundjid.bare
                else:
                    subscribee = self.xmpp.boundjid

        iq['pubsub']['unsubscribe']['jid'] = subscribee
        iq['pubsub']['unsubscribe']['subid'] = subid
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_subscriptions(self, jid, node=None, ifrom=None,
                          timeout_callback=None, callback=None,
                          timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub']['subscriptions']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_affiliations(self, jid, node=None, ifrom=None,
                         timeout_callback=None, callback=None, timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub']['affiliations']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_subscription_options(self, jid, node=None, user_jid=None,
                                 ifrom=None, timeout_callback=None,
                                 callback=None, timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        if user_jid is None:
            iq['pubsub']['default']['node'] = node
        else:
            iq['pubsub']['options']['node'] = node
            iq['pubsub']['options']['jid'] = user_jid
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def set_subscription_options(self, jid, node, user_jid, options,
                                 ifrom=None, timeout_callback=None,
                                 callback=None, timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub']['options']['node'] = node
        iq['pubsub']['options']['jid'] = user_jid
        iq['pubsub']['options'].append(options)
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_node_config(self, jid, node=None, ifrom=None,
                        timeout_callback=None, callback=None, timeout=None):
        """
        Retrieve the configuration for a node, or the pubsub service's
        default configuration for new nodes.

        :param jid: The JID of the pubsub service.
        :param node: The node to retrieve the configuration for. If None,
                     the default configuration for new nodes will be
                     requested. Defaults to None.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        if node is None:
            iq['pubsub_owner']['default']
        else:
            iq['pubsub_owner']['configure']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_node_subscriptions(self, jid, node, ifrom=None,
                               timeout_callback=None, callback=None,
                               timeout=None):
        """
        Retrieve the subscriptions associated with a given node.

        :param jid: The JID of the pubsub service.
        :param node: The node to retrieve subscriptions from.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub_owner']['subscriptions']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_node_affiliations(self, jid, node, ifrom=None, timeout_callback=None,
                              callback=None, timeout=None):
        """
        Retrieve the affiliations associated with a given node.

        :param jid: The JID of the pubsub service.
        :param node: The node to retrieve affiliations from.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub_owner']['affiliations']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def delete_node(self, jid, node, ifrom=None, timeout_callback=None, callback=None,
                    timeout=None):
        """
        Delete a a pubsub node.

        :param jid: The JID of the pubsub service.
        :param node: The node to delete.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub_owner']['delete']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def set_node_config(self, jid, node, config, ifrom=None,
                        timeout_callback=None, callback=None, timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub_owner']['configure']['node'] = node
        iq['pubsub_owner']['configure'].append(config)
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def publish(self, jid, node, id=None, payload=None, options=None,
                ifrom=None, timeout_callback=None, callback=None,
                timeout=None):
        """
        Add a new item to a node, or edit an existing item.

        For services that support it, you can use the publish command
        as an event signal by not including an ID or payload.

        When including a payload and you do not provide an ID then
        the service will generally create an ID for you.

        Publish options may be specified, and how those options
        are processed is left to the service, such as treating
        the options as preconditions that the node's settings
        must match.

        :param jid: The JID of the pubsub service.
        :param node: The node to publish the item to.
        :param id: Optionally specify the ID of the item.
        :param payload: The item content to publish.
        :param options: A form of publish options.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub']['publish']['node'] = node
        if id is not None:
            iq['pubsub']['publish']['item']['id'] = id
        if payload is not None:
            iq['pubsub']['publish']['item']['payload'] = payload
        iq['pubsub']['publish_options'] = options
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def retract(self, jid, node, id, notify=None, ifrom=None,
                timeout_callback=None, callback=None, timeout=None):
        """
        Delete a single item from a node.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')

        iq['pubsub']['retract']['node'] = node
        iq['pubsub']['retract']['notify'] = notify
        iq['pubsub']['retract']['item']['id'] = id
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def purge(self, jid, node, ifrom=None, timeout_callback=None, callback=None,
              timeout=None):
        """
        Remove all items from a node.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub_owner']['purge']['node'] = node
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_nodes(self, *args, **kwargs):
        """
        Discover the nodes provided by a Pubsub service, using disco.
        """
        return self.xmpp['xep_0030'].get_items(*args, **kwargs)

    def get_item(self, jid, node, item_id, ifrom=None,
                 timeout_callback=None, callback=None, timeout=None):
        """
        Retrieve the content of an individual item.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        item = stanza.Item()
        item['id'] = item_id
        iq['pubsub']['items']['node'] = node
        iq['pubsub']['items'].append(item)
        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_items(self, jid, node, item_ids=None, max_items=None,
                  iterator=False, ifrom=None, timeout_callback=None,
                  callback=None, timeout=None):
        """
        Request the contents of a node's items.

        The desired items can be specified, or a query for the last
        few published items can be used.

        Pubsub services may use result set management for nodes with
        many items, so an iterator can be returned if needed.
        """
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
        iq['pubsub']['items']['node'] = node
        iq['pubsub']['items']['max_items'] = max_items

        if item_ids is not None:
            for item_id in item_ids:
                item = stanza.Item()
                item['id'] = item_id
                iq['pubsub']['items'].append(item)

        if iterator:
            return self.xmpp['xep_0059'].iterate(iq, 'pubsub')
        else:
            return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def get_item_ids(self, jid, node, ifrom=None, timeout_callback=None, callback=None,
                     timeout=None, iterator=False):
        """
        Retrieve the ItemIDs hosted by a given node, using disco.
        """
        self.xmpp['xep_0030'].get_items(jid, node, ifrom=ifrom,
                                        callback=callback, timeout=timeout,
                                        iterator=iterator,
                                        timeout_callback=timeout_callback)

    def modify_affiliations(self, jid, node, affiliations=None, ifrom=None,
                            timeout_callback=None, callback=None,
                            timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub_owner']['affiliations']['node'] = node

        if affiliations is None:
            affiliations = []

        for jid, affiliation in affiliations:
            aff = stanza.OwnerAffiliation()
            aff['jid'] = jid
            aff['affiliation'] = affiliation
            iq['pubsub_owner']['affiliations'].append(aff)

        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)

    def modify_subscriptions(self, jid, node, subscriptions=None,
                             ifrom=None, timeout_callback=None,
                             callback=None, timeout=None):
        iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
        iq['pubsub_owner']['subscriptions']['node'] = node

        if subscriptions is None:
            subscriptions = []

        for jid, subscription in subscriptions:
            sub = stanza.OwnerSubscription()
            sub['jid'] = jid
            sub['subscription'] = subscription
            iq['pubsub_owner']['subscriptions'].append(sub)

        return iq.send(callback=callback, timeout=timeout, timeout_callback=timeout_callback)