pubsub.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. """
  2. SleekXMPP: The Sleek XMPP Library
  3. Copyright (C) 2011 Nathanael C. Fritz
  4. This file is part of SleekXMPP.
  5. See the file LICENSE for copying permission.
  6. """
  7. import logging
  8. from sleekxmpp.xmlstream import JID
  9. from sleekxmpp.xmlstream.handler import Callback
  10. from sleekxmpp.xmlstream.matcher import StanzaPath
  11. from sleekxmpp.plugins.base import BasePlugin
  12. from sleekxmpp.plugins.xep_0060 import stanza
  13. log = logging.getLogger(__name__)
  14. class XEP_0060(BasePlugin):
  15. """
  16. XEP-0060 Publish Subscribe
  17. """
  18. name = 'xep_0060'
  19. description = 'XEP-0060: Publish-Subscribe'
  20. dependencies = set(['xep_0030', 'xep_0004', 'xep_0082', 'xep_0131'])
  21. stanza = stanza
  22. def plugin_init(self):
  23. self.node_event_map = {}
  24. self.xmpp.register_handler(
  25. Callback('Pubsub Event: Items',
  26. StanzaPath('message/pubsub_event/items'),
  27. self._handle_event_items))
  28. self.xmpp.register_handler(
  29. Callback('Pubsub Event: Purge',
  30. StanzaPath('message/pubsub_event/purge'),
  31. self._handle_event_purge))
  32. self.xmpp.register_handler(
  33. Callback('Pubsub Event: Delete',
  34. StanzaPath('message/pubsub_event/delete'),
  35. self._handle_event_delete))
  36. self.xmpp.register_handler(
  37. Callback('Pubsub Event: Configuration',
  38. StanzaPath('message/pubsub_event/configuration'),
  39. self._handle_event_configuration))
  40. self.xmpp.register_handler(
  41. Callback('Pubsub Event: Subscription',
  42. StanzaPath('message/pubsub_event/subscription'),
  43. self._handle_event_subscription))
  44. self.xmpp['xep_0131'].supported_headers.add('SubID')
  45. def plugin_end(self):
  46. self.xmpp.remove_handler('Pubsub Event: Items')
  47. self.xmpp.remove_handler('Pubsub Event: Purge')
  48. self.xmpp.remove_handler('Pubsub Event: Delete')
  49. self.xmpp.remove_handler('Pubsub Event: Configuration')
  50. self.xmpp.remove_handler('Pubsub Event: Subscription')
  51. def _handle_event_items(self, msg):
  52. """Raise events for publish and retraction notifications."""
  53. node = msg['pubsub_event']['items']['node']
  54. multi = len(msg['pubsub_event']['items']) > 1
  55. values = {}
  56. if multi:
  57. values = msg.values
  58. del values['pubsub_event']
  59. for item in msg['pubsub_event']['items']:
  60. event_name = self.node_event_map.get(node, None)
  61. event_type = 'publish'
  62. if item.name == 'retract':
  63. event_type = 'retract'
  64. if multi:
  65. condensed = self.xmpp.Message()
  66. condensed.values = values
  67. condensed['pubsub_event']['items']['node'] = node
  68. condensed['pubsub_event']['items'].append(item)
  69. self.xmpp.event('pubsub_%s' % event_type, msg)
  70. if event_name:
  71. self.xmpp.event('%s_%s' % (event_name, event_type),
  72. condensed)
  73. else:
  74. self.xmpp.event('pubsub_%s' % event_type, msg)
  75. if event_name:
  76. self.xmpp.event('%s_%s' % (event_name, event_type), msg)
  77. def _handle_event_purge(self, msg):
  78. """Raise events for node purge notifications."""
  79. node = msg['pubsub_event']['purge']['node']
  80. event_name = self.node_event_map.get(node, None)
  81. self.xmpp.event('pubsub_purge', msg)
  82. if event_name:
  83. self.xmpp.event('%s_purge' % event_name, msg)
  84. def _handle_event_delete(self, msg):
  85. """Raise events for node deletion notifications."""
  86. node = msg['pubsub_event']['delete']['node']
  87. event_name = self.node_event_map.get(node, None)
  88. self.xmpp.event('pubsub_delete', msg)
  89. if event_name:
  90. self.xmpp.event('%s_delete' % event_name, msg)
  91. def _handle_event_configuration(self, msg):
  92. """Raise events for node configuration notifications."""
  93. node = msg['pubsub_event']['configuration']['node']
  94. event_name = self.node_event_map.get(node, None)
  95. self.xmpp.event('pubsub_config', msg)
  96. if event_name:
  97. self.xmpp.event('%s_config' % event_name, msg)
  98. def _handle_event_subscription(self, msg):
  99. """Raise events for node subscription notifications."""
  100. node = msg['pubsub_event']['subscription']['node']
  101. event_name = self.node_event_map.get(node, None)
  102. self.xmpp.event('pubsub_subscription', msg)
  103. if event_name:
  104. self.xmpp.event('%s_subscription' % event_name, msg)
  105. def map_node_event(self, node, event_name):
  106. """
  107. Map node names to events.
  108. When a pubsub event is received for the given node,
  109. raise the provided event.
  110. For example::
  111. map_node_event('http://jabber.org/protocol/tune',
  112. 'user_tune')
  113. will produce the events 'user_tune_publish' and 'user_tune_retract'
  114. when the respective notifications are received from the node
  115. 'http://jabber.org/protocol/tune', among other events.
  116. Arguments:
  117. node -- The node name to map to an event.
  118. event_name -- The name of the event to raise when a
  119. notification from the given node is received.
  120. """
  121. self.node_event_map[node] = event_name
  122. def create_node(self, jid, node, config=None, ntype=None, ifrom=None,
  123. block=True, callback=None, timeout=None):
  124. """
  125. Create and configure a new pubsub node.
  126. A server MAY use a different name for the node than the one provided,
  127. so be sure to check the result stanza for a server assigned name.
  128. If no configuration form is provided, the node will be created using
  129. the server's default configuration. To get the default configuration
  130. use get_node_config().
  131. Arguments:
  132. jid -- The JID of the pubsub service.
  133. node -- Optional name of the node to create. If no name is
  134. provided, the server MAY generate a node ID for you.
  135. The server can also assign a different name than the
  136. one you provide; check the result stanza to see if
  137. the server assigned a name.
  138. config -- Optional XEP-0004 data form of configuration settings.
  139. ntype -- The type of node to create. Servers typically default
  140. to using 'leaf' if no type is provided.
  141. ifrom -- Specify the sender's JID.
  142. block -- Specify if the send call will block until a response
  143. is received, or a timeout occurs. Defaults to True.
  144. timeout -- The length of time (in seconds) to wait for a response
  145. before exiting the send call if blocking is used.
  146. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  147. callback -- Optional reference to a stream handler function. Will
  148. be executed when a reply stanza is received.
  149. """
  150. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  151. iq['pubsub']['create']['node'] = node
  152. if config is not None:
  153. form_type = 'http://jabber.org/protocol/pubsub#node_config'
  154. if 'FORM_TYPE' in config['fields']:
  155. config.field['FORM_TYPE']['value'] = form_type
  156. else:
  157. config.add_field(var='FORM_TYPE',
  158. ftype='hidden',
  159. value=form_type)
  160. if ntype:
  161. if 'pubsub#node_type' in config['fields']:
  162. config.field['pubsub#node_type']['value'] = ntype
  163. else:
  164. config.add_field(var='pubsub#node_type', value=ntype)
  165. iq['pubsub']['configure'].append(config)
  166. return iq.send(block=block, callback=callback, timeout=timeout)
  167. def subscribe(self, jid, node, bare=True, subscribee=None, options=None,
  168. ifrom=None, block=True, callback=None, timeout=None):
  169. """
  170. Subscribe to updates from a pubsub node.
  171. The rules for determining the JID that is subscribing to the node are:
  172. 1. If subscribee is given, use that as provided.
  173. 2. If ifrom was given, use the bare or full version based on bare.
  174. 3. Otherwise, use self.xmpp.boundjid based on bare.
  175. Arguments:
  176. jid -- The pubsub service JID.
  177. node -- The node to subscribe to.
  178. bare -- Indicates if the subscribee is a bare or full JID.
  179. Defaults to True for a bare JID.
  180. subscribee -- The JID that is subscribing to the node.
  181. options --
  182. ifrom -- Specify the sender's JID.
  183. block -- Specify if the send call will block until a response
  184. is received, or a timeout occurs. Defaults to True.
  185. timeout -- The length of time (in seconds) to wait for a
  186. response before exiting the send call if blocking
  187. is used.
  188. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  189. callback -- Optional reference to a stream handler function. Will
  190. be executed when a reply stanza is received.
  191. """
  192. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  193. iq['pubsub']['subscribe']['node'] = node
  194. if subscribee is None:
  195. if ifrom:
  196. if bare:
  197. subscribee = JID(ifrom).bare
  198. else:
  199. subscribee = ifrom
  200. else:
  201. if bare:
  202. subscribee = self.xmpp.boundjid.bare
  203. else:
  204. subscribee = self.xmpp.boundjid
  205. iq['pubsub']['subscribe']['jid'] = subscribee
  206. if options is not None:
  207. iq['pubsub']['options'].append(options)
  208. return iq.send(block=block, callback=callback, timeout=timeout)
  209. def unsubscribe(self, jid, node, subid=None, bare=True, subscribee=None,
  210. ifrom=None, block=True, callback=None, timeout=None):
  211. """
  212. Unubscribe from updates from a pubsub node.
  213. The rules for determining the JID that is unsubscribing
  214. from the node are:
  215. 1. If subscribee is given, use that as provided.
  216. 2. If ifrom was given, use the bare or full version based on bare.
  217. 3. Otherwise, use self.xmpp.boundjid based on bare.
  218. Arguments:
  219. jid -- The pubsub service JID.
  220. node -- The node to subscribe to.
  221. subid -- The specific subscription, if multiple subscriptions
  222. exist for this JID/node combination.
  223. bare -- Indicates if the subscribee is a bare or full JID.
  224. Defaults to True for a bare JID.
  225. subscribee -- The JID that is subscribing to the node.
  226. ifrom -- Specify the sender's JID.
  227. block -- Specify if the send call will block until a response
  228. is received, or a timeout occurs. Defaults to True.
  229. timeout -- The length of time (in seconds) to wait for a
  230. response before exiting the send call if blocking
  231. is used.
  232. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  233. callback -- Optional reference to a stream handler function. Will
  234. be executed when a reply stanza is received.
  235. """
  236. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  237. iq['pubsub']['unsubscribe']['node'] = node
  238. if subscribee is None:
  239. if ifrom:
  240. if bare:
  241. subscribee = JID(ifrom).bare
  242. else:
  243. subscribee = ifrom
  244. else:
  245. if bare:
  246. subscribee = self.xmpp.boundjid.bare
  247. else:
  248. subscribee = self.xmpp.boundjid
  249. iq['pubsub']['unsubscribe']['jid'] = subscribee
  250. iq['pubsub']['unsubscribe']['subid'] = subid
  251. return iq.send(block=block, callback=callback, timeout=timeout)
  252. def get_subscriptions(self, jid, node=None, ifrom=None, block=True,
  253. callback=None, timeout=None):
  254. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  255. iq['pubsub']['subscriptions']['node'] = node
  256. return iq.send(block=block, callback=callback, timeout=timeout)
  257. def get_affiliations(self, jid, node=None, ifrom=None, block=True,
  258. callback=None, timeout=None):
  259. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  260. iq['pubsub']['affiliations']['node'] = node
  261. return iq.send(block=block, callback=callback, timeout=timeout)
  262. def get_subscription_options(self, jid, node=None, user_jid=None,
  263. ifrom=None, block=True, callback=None,
  264. timeout=None):
  265. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  266. if user_jid is None:
  267. iq['pubsub']['default']['node'] = node
  268. else:
  269. iq['pubsub']['options']['node'] = node
  270. iq['pubsub']['options']['jid'] = user_jid
  271. return iq.send(block=block, callback=callback, timeout=timeout)
  272. def set_subscription_options(self, jid, node, user_jid, options,
  273. ifrom=None, block=True, callback=None,
  274. timeout=None):
  275. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  276. iq['pubsub']['options']['node'] = node
  277. iq['pubsub']['options']['jid'] = user_jid
  278. iq['pubsub']['options'].append(options)
  279. return iq.send(block=block, callback=callback, timeout=timeout)
  280. def get_node_config(self, jid, node=None, ifrom=None, block=True,
  281. callback=None, timeout=None):
  282. """
  283. Retrieve the configuration for a node, or the pubsub service's
  284. default configuration for new nodes.
  285. Arguments:
  286. jid -- The JID of the pubsub service.
  287. node -- The node to retrieve the configuration for. If None,
  288. the default configuration for new nodes will be
  289. requested. Defaults to None.
  290. ifrom -- Specify the sender's JID.
  291. block -- Specify if the send call will block until a response
  292. is received, or a timeout occurs. Defaults to True.
  293. timeout -- The length of time (in seconds) to wait for a response
  294. before exiting the send call if blocking is used.
  295. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  296. callback -- Optional reference to a stream handler function. Will
  297. be executed when a reply stanza is received.
  298. """
  299. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  300. if node is None:
  301. iq['pubsub_owner']['default']
  302. else:
  303. iq['pubsub_owner']['configure']['node'] = node
  304. return iq.send(block=block, callback=callback, timeout=timeout)
  305. def get_node_subscriptions(self, jid, node, ifrom=None, block=True,
  306. callback=None, timeout=None):
  307. """
  308. Retrieve the subscriptions associated with a given node.
  309. Arguments:
  310. jid -- The JID of the pubsub service.
  311. node -- The node to retrieve subscriptions from.
  312. ifrom -- Specify the sender's JID.
  313. block -- Specify if the send call will block until a response
  314. is received, or a timeout occurs. Defaults to True.
  315. timeout -- The length of time (in seconds) to wait for a response
  316. before exiting the send call if blocking is used.
  317. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  318. callback -- Optional reference to a stream handler function. Will
  319. be executed when a reply stanza is received.
  320. """
  321. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  322. iq['pubsub_owner']['subscriptions']['node'] = node
  323. return iq.send(block=block, callback=callback, timeout=timeout)
  324. def get_node_affiliations(self, jid, node, ifrom=None, block=True,
  325. callback=None, timeout=None):
  326. """
  327. Retrieve the affiliations associated with a given node.
  328. Arguments:
  329. jid -- The JID of the pubsub service.
  330. node -- The node to retrieve affiliations from.
  331. ifrom -- Specify the sender's JID.
  332. block -- Specify if the send call will block until a response
  333. is received, or a timeout occurs. Defaults to True.
  334. timeout -- The length of time (in seconds) to wait for a response
  335. before exiting the send call if blocking is used.
  336. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  337. callback -- Optional reference to a stream handler function. Will
  338. be executed when a reply stanza is received.
  339. """
  340. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  341. iq['pubsub_owner']['affiliations']['node'] = node
  342. return iq.send(block=block, callback=callback, timeout=timeout)
  343. def delete_node(self, jid, node, ifrom=None, block=True,
  344. callback=None, timeout=None):
  345. """
  346. Delete a a pubsub node.
  347. Arguments:
  348. jid -- The JID of the pubsub service.
  349. node -- The node to delete.
  350. ifrom -- Specify the sender's JID.
  351. block -- Specify if the send call will block until a response
  352. is received, or a timeout occurs. Defaults to True.
  353. timeout -- The length of time (in seconds) to wait for a response
  354. before exiting the send call if blocking is used.
  355. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  356. callback -- Optional reference to a stream handler function. Will
  357. be executed when a reply stanza is received.
  358. """
  359. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  360. iq['pubsub_owner']['delete']['node'] = node
  361. return iq.send(block=block, callback=callback, timeout=timeout)
  362. def set_node_config(self, jid, node, config, ifrom=None, block=True,
  363. callback=None, timeout=None):
  364. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  365. iq['pubsub_owner']['configure']['node'] = node
  366. iq['pubsub_owner']['configure'].append(config)
  367. return iq.send(block=block, callback=callback, timeout=timeout)
  368. def publish(self, jid, node, id=None, payload=None, options=None,
  369. ifrom=None, block=True, callback=None, timeout=None):
  370. """
  371. Add a new item to a node, or edit an existing item.
  372. For services that support it, you can use the publish command
  373. as an event signal by not including an ID or payload.
  374. When including a payload and you do not provide an ID then
  375. the service will generally create an ID for you.
  376. Publish options may be specified, and how those options
  377. are processed is left to the service, such as treating
  378. the options as preconditions that the node's settings
  379. must match.
  380. Arguments:
  381. jid -- The JID of the pubsub service.
  382. node -- The node to publish the item to.
  383. id -- Optionally specify the ID of the item.
  384. payload -- The item content to publish.
  385. options -- A form of publish options.
  386. ifrom -- Specify the sender's JID.
  387. block -- Specify if the send call will block until a response
  388. is received, or a timeout occurs. Defaults to True.
  389. timeout -- The length of time (in seconds) to wait for a response
  390. before exiting the send call if blocking is used.
  391. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT
  392. callback -- Optional reference to a stream handler function. Will
  393. be executed when a reply stanza is received.
  394. """
  395. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  396. iq['pubsub']['publish']['node'] = node
  397. if id is not None:
  398. iq['pubsub']['publish']['item']['id'] = id
  399. if payload is not None:
  400. iq['pubsub']['publish']['item']['payload'] = payload
  401. iq['pubsub']['publish_options'] = options
  402. return iq.send(block=block, callback=callback, timeout=timeout)
  403. def retract(self, jid, node, id, notify=None, ifrom=None, block=True,
  404. callback=None, timeout=None):
  405. """
  406. Delete a single item from a node.
  407. """
  408. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  409. iq['pubsub']['retract']['node'] = node
  410. iq['pubsub']['retract']['notify'] = notify
  411. iq['pubsub']['retract']['item']['id'] = id
  412. return iq.send(block=block, callback=callback, timeout=timeout)
  413. def purge(self, jid, node, ifrom=None, block=True, callback=None,
  414. timeout=None):
  415. """
  416. Remove all items from a node.
  417. """
  418. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  419. iq['pubsub_owner']['purge']['node'] = node
  420. return iq.send(block=block, callback=callback, timeout=timeout)
  421. def get_nodes(self, *args, **kwargs):
  422. """
  423. Discover the nodes provided by a Pubsub service, using disco.
  424. """
  425. return self.xmpp['xep_0030'].get_items(*args, **kwargs)
  426. def get_item(self, jid, node, item_id, ifrom=None, block=True,
  427. callback=None, timeout=None):
  428. """
  429. Retrieve the content of an individual item.
  430. """
  431. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  432. item = stanza.Item()
  433. item['id'] = item_id
  434. iq['pubsub']['items']['node'] = node
  435. iq['pubsub']['items'].append(item)
  436. return iq.send(block=block, callback=callback, timeout=timeout)
  437. def get_items(self, jid, node, item_ids=None, max_items=None,
  438. iterator=False, ifrom=None, block=False,
  439. callback=None, timeout=None):
  440. """
  441. Request the contents of a node's items.
  442. The desired items can be specified, or a query for the last
  443. few published items can be used.
  444. Pubsub services may use result set management for nodes with
  445. many items, so an iterator can be returned if needed.
  446. """
  447. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get')
  448. iq['pubsub']['items']['node'] = node
  449. iq['pubsub']['items']['max_items'] = max_items
  450. if item_ids is not None:
  451. for item_id in item_ids:
  452. item = stanza.Item()
  453. item['id'] = item_id
  454. iq['pubsub']['items'].append(item)
  455. if iterator:
  456. return self.xmpp['xep_0059'].iterate(iq, 'pubsub')
  457. else:
  458. return iq.send(block=block, callback=callback, timeout=timeout)
  459. def get_item_ids(self, jid, node, ifrom=None, block=True,
  460. callback=None, timeout=None, iterator=False):
  461. """
  462. Retrieve the ItemIDs hosted by a given node, using disco.
  463. """
  464. return self.xmpp['xep_0030'].get_items(jid, node,
  465. ifrom=ifrom,
  466. block=block,
  467. callback=callback,
  468. timeout=timeout,
  469. iterator=iterator)
  470. def modify_affiliations(self, jid, node, affiliations=None, ifrom=None,
  471. block=True, callback=None, timeout=None):
  472. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  473. iq['pubsub_owner']['affiliations']['node'] = node
  474. if affiliations is None:
  475. affiliations = []
  476. for jid, affiliation in affiliations:
  477. aff = stanza.OwnerAffiliation()
  478. aff['jid'] = jid
  479. aff['affiliation'] = affiliation
  480. iq['pubsub_owner']['affiliations'].append(aff)
  481. return iq.send(block=block, callback=callback, timeout=timeout)
  482. def modify_subscriptions(self, jid, node, subscriptions=None, ifrom=None,
  483. block=True, callback=None, timeout=None):
  484. iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='set')
  485. iq['pubsub_owner']['subscriptions']['node'] = node
  486. if subscriptions is None:
  487. subscriptions = []
  488. for jid, subscription in subscriptions:
  489. sub = stanza.OwnerSubscription()
  490. sub['jid'] = jid
  491. sub['subscription'] = subscription
  492. iq['pubsub_owner']['subscriptions'].append(sub)
  493. return iq.send(block=block, callback=callback, timeout=timeout)