single.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. """
  2. SleekXMPP: The Sleek XMPP Library
  3. Copyright (C) 2010 Nathanael C. Fritz
  4. This file is part of SleekXMPP.
  5. See the file LICENSE for copying permission.
  6. """
  7. import threading
  8. from sleekxmpp.xmlstream import JID
  9. from sleekxmpp.roster import RosterItem
  10. class RosterNode(object):
  11. """
  12. A roster node is a roster for a single JID.
  13. Attributes:
  14. xmpp -- The main SleekXMPP instance.
  15. jid -- The JID that owns the roster node.
  16. db -- Optional interface to an external datastore.
  17. auto_authorize -- Determines how authorizations are handled:
  18. True -- Accept all subscriptions.
  19. False -- Reject all subscriptions.
  20. None -- Subscriptions must be
  21. manually authorized.
  22. Defaults to True.
  23. auto_subscribe -- Determines if bi-directional subscriptions
  24. are created after automatically authrorizing
  25. a subscription request.
  26. Defaults to True
  27. last_status -- The last sent presence status that was broadcast
  28. to all contact JIDs.
  29. Methods:
  30. add -- Add a JID to the roster.
  31. update -- Update a JID's subscription information.
  32. subscribe -- Subscribe to a JID.
  33. unsubscribe -- Unsubscribe from a JID.
  34. remove -- Remove a JID from the roster.
  35. presence -- Return presence information for a JID's resources.
  36. send_presence -- Shortcut for sending a presence stanza.
  37. """
  38. def __init__(self, xmpp, jid, db=None):
  39. """
  40. Create a roster node for a JID.
  41. Arguments:
  42. xmpp -- The main SleekXMPP instance.
  43. jid -- The JID that owns the roster.
  44. db -- Optional interface to an external datastore.
  45. """
  46. self.xmpp = xmpp
  47. self.jid = jid
  48. self.db = db
  49. self.auto_authorize = True
  50. self.auto_subscribe = True
  51. self.last_status = None
  52. self._version = ''
  53. self._jids = {}
  54. self._last_status_lock = threading.Lock()
  55. if self.db:
  56. if hasattr(self.db, 'version'):
  57. self._version = self.db.version(self.jid)
  58. for jid in self.db.entries(self.jid):
  59. self.add(jid)
  60. @property
  61. def version(self):
  62. """Retrieve the roster's version ID."""
  63. if self.db and hasattr(self.db, 'version'):
  64. self._version = self.db.version(self.jid)
  65. return self._version
  66. @version.setter
  67. def version(self, version):
  68. """Set the roster's version ID."""
  69. self._version = version
  70. if self.db and hasattr(self.db, 'set_version'):
  71. self.db.set_version(self.jid, version)
  72. def __getitem__(self, key):
  73. """
  74. Return the roster item for a subscribed JID.
  75. A new item entry will be created if one does not already exist.
  76. """
  77. if key is None:
  78. key = JID('')
  79. if not isinstance(key, JID):
  80. key = JID(key)
  81. key = key.bare
  82. if key not in self._jids:
  83. self.add(key, save=True)
  84. return self._jids[key]
  85. def __delitem__(self, key):
  86. """
  87. Remove a roster item from the local storage.
  88. To remove an item from the server, use the remove() method.
  89. """
  90. if key is None:
  91. key = JID('')
  92. if not isinstance(key, JID):
  93. key = JID(key)
  94. key = key.bare
  95. if key in self._jids:
  96. del self._jids[key]
  97. def __len__(self):
  98. """Return the number of JIDs referenced by the roster."""
  99. return len(self._jids)
  100. def keys(self):
  101. """Return a list of all subscribed JIDs."""
  102. return self._jids.keys()
  103. def has_jid(self, jid):
  104. """Returns whether the roster has a JID."""
  105. return jid in self._jids
  106. def groups(self):
  107. """Return a dictionary mapping group names to JIDs."""
  108. result = {}
  109. for jid in self._jids:
  110. groups = self._jids[jid]['groups']
  111. if not groups:
  112. if '' not in result:
  113. result[''] = []
  114. result[''].append(jid)
  115. for group in groups:
  116. if group not in result:
  117. result[group] = []
  118. result[group].append(jid)
  119. return result
  120. def __iter__(self):
  121. """Iterate over the roster items."""
  122. return self._jids.__iter__()
  123. def set_backend(self, db=None, save=True):
  124. """
  125. Set the datastore interface object for the roster node.
  126. Arguments:
  127. db -- The new datastore interface.
  128. save -- If True, save the existing state to the new
  129. backend datastore. Defaults to True.
  130. """
  131. self.db = db
  132. existing_entries = set(self._jids)
  133. new_entries = set(self.db.entries(self.jid, {}))
  134. for jid in existing_entries:
  135. self._jids[jid].set_backend(db, save)
  136. for jid in new_entries - existing_entries:
  137. self.add(jid)
  138. def add(self, jid, name='', groups=None, afrom=False, ato=False,
  139. pending_in=False, pending_out=False, whitelisted=False,
  140. save=False):
  141. """
  142. Add a new roster item entry.
  143. Arguments:
  144. jid -- The JID for the roster item.
  145. name -- An alias for the JID.
  146. groups -- A list of group names.
  147. afrom -- Indicates if the JID has a subscription state
  148. of 'from'. Defaults to False.
  149. ato -- Indicates if the JID has a subscription state
  150. of 'to'. Defaults to False.
  151. pending_in -- Indicates if the JID has sent a subscription
  152. request to this connection's JID.
  153. Defaults to False.
  154. pending_out -- Indicates if a subscription request has been sent
  155. to this JID.
  156. Defaults to False.
  157. whitelisted -- Indicates if a subscription request from this JID
  158. should be automatically authorized.
  159. Defaults to False.
  160. save -- Indicates if the item should be persisted
  161. immediately to an external datastore,
  162. if one is used.
  163. Defaults to False.
  164. """
  165. if isinstance(jid, JID):
  166. key = jid.bare
  167. else:
  168. key = jid
  169. state = {'name': name,
  170. 'groups': groups or [],
  171. 'from': afrom,
  172. 'to': ato,
  173. 'pending_in': pending_in,
  174. 'pending_out': pending_out,
  175. 'whitelisted': whitelisted,
  176. 'subscription': 'none'}
  177. self._jids[key] = RosterItem(self.xmpp, jid, self.jid,
  178. state=state, db=self.db,
  179. roster=self)
  180. if save:
  181. self._jids[key].save()
  182. def subscribe(self, jid):
  183. """
  184. Subscribe to the given JID.
  185. Arguments:
  186. jid -- The JID to subscribe to.
  187. """
  188. self[jid].subscribe()
  189. def unsubscribe(self, jid):
  190. """
  191. Unsubscribe from the given JID.
  192. Arguments:
  193. jid -- The JID to unsubscribe from.
  194. """
  195. self[jid].unsubscribe()
  196. def remove(self, jid):
  197. """
  198. Remove a JID from the roster.
  199. Arguments:
  200. jid -- The JID to remove.
  201. """
  202. self[jid].remove()
  203. if not self.xmpp.is_component:
  204. return self.update(jid, subscription='remove')
  205. def update(self, jid, name=None, subscription=None, groups=None, block=True, timeout=None, callback=None):
  206. """
  207. Update a JID's subscription information.
  208. Arguments:
  209. jid -- The JID to update.
  210. name -- Optional alias for the JID.
  211. subscription -- The subscription state. May be one of: 'to',
  212. 'from', 'both', 'none', or 'remove'.
  213. groups -- A list of group names.
  214. block -- Specify if the roster request will block
  215. until a response is received, or a timeout
  216. occurs. Defaults to True.
  217. timeout -- The length of time (in seconds) to wait
  218. for a response before continuing if blocking
  219. is used. Defaults to self.response_timeout.
  220. callback -- Optional reference to a stream handler function.
  221. Will be executed when the roster is received.
  222. Implies block=False.
  223. """
  224. if not groups:
  225. groups = []
  226. self[jid]['name'] = name
  227. self[jid]['groups'] = groups
  228. self[jid].save()
  229. if not self.xmpp.is_component:
  230. iq = self.xmpp.Iq()
  231. iq['type'] = 'set'
  232. iq['roster']['items'] = {jid: {'name': name,
  233. 'subscription': subscription,
  234. 'groups': groups}}
  235. return iq.send(block, timeout, callback)
  236. def presence(self, jid, resource=None):
  237. """
  238. Retrieve the presence information of a JID.
  239. May return either all online resources' status, or
  240. a single resource's status.
  241. Arguments:
  242. jid -- The JID to lookup.
  243. resource -- Optional resource for returning
  244. only the status of a single connection.
  245. """
  246. if resource is None:
  247. return self[jid].resources
  248. default_presence = {'status': '',
  249. 'priority': 0,
  250. 'show': ''}
  251. return self[jid].resources.get(resource,
  252. default_presence)
  253. def reset(self):
  254. """
  255. Reset the state of the roster to forget any current
  256. presence information. Useful after a disconnection occurs.
  257. """
  258. for jid in self:
  259. self[jid].reset()
  260. def send_presence(self, **kwargs):
  261. """
  262. Create, initialize, and send a Presence stanza.
  263. If no recipient is specified, send the presence immediately.
  264. Otherwise, forward the send request to the recipient's roster
  265. entry for processing.
  266. Arguments:
  267. pshow -- The presence's show value.
  268. pstatus -- The presence's status message.
  269. ppriority -- This connections' priority.
  270. pto -- The recipient of a directed presence.
  271. pfrom -- The sender of a directed presence, which should
  272. be the owner JID plus resource.
  273. ptype -- The type of presence, such as 'subscribe'.
  274. pnick -- Optional nickname of the presence's sender.
  275. """
  276. if self.xmpp.is_component and not kwargs.get('pfrom', ''):
  277. kwargs['pfrom'] = self.jid
  278. self.xmpp.send_presence(**kwargs)
  279. def send_last_presence(self):
  280. if self.last_status is None:
  281. self.send_presence()
  282. else:
  283. pres = self.last_status
  284. if self.xmpp.is_component:
  285. pres['from'] = self.jid
  286. else:
  287. del pres['from']
  288. pres.send()
  289. def __repr__(self):
  290. return repr(self._jids)