item.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. class RosterItem(object):
  8. """
  9. A RosterItem is a single entry in a roster node, and tracks
  10. the subscription state and user annotations of a single JID.
  11. Roster items may use an external datastore to persist roster data
  12. across sessions. Client applications will not need to use this
  13. functionality, but is intended for components that do not have their
  14. roster persisted automatically by the XMPP server.
  15. Roster items provide many methods for handling incoming presence
  16. stanzas that ensure that response stanzas are sent according to
  17. RFC 3921.
  18. The external datastore is accessed through a provided interface
  19. object which is stored in self.db. The interface object MUST
  20. provide two methods: load and save, both of which are responsible
  21. for working with a single roster item. A private dictionary,
  22. self._db_state, is used to store any metadata needed by the
  23. interface, such as the row ID of a roster item, etc.
  24. Interface for self.db.load:
  25. load(owner_jid, jid, db_state):
  26. owner_jid -- The JID that owns the roster.
  27. jid -- The JID of the roster item.
  28. db_state -- A dictionary containing any data saved
  29. by the interface object after a save()
  30. call. Will typically have the equivalent
  31. of a 'row_id' value.
  32. Interface for self.db.save:
  33. save(owner_jid, jid, item_state, db_state):
  34. owner_jid -- The JID that owns the roster.
  35. jid -- The JID of the roster item.
  36. item_state -- A dictionary containing the fields:
  37. 'from', 'to', 'pending_in', 'pending_out',
  38. 'whitelisted', 'subscription', 'name',
  39. and 'groups'.
  40. db_state -- A dictionary provided for persisting
  41. datastore specific information. Typically,
  42. a value equivalent to 'row_id' will be
  43. stored here.
  44. State Fields:
  45. from -- Indicates if a subscription of type 'from'
  46. has been authorized.
  47. to -- Indicates if a subscription of type 'to' has
  48. been authorized.
  49. pending_in -- Indicates if a subscription request has been
  50. received from this JID and it has not been
  51. authorized yet.
  52. pending_out -- Indicates if a subscription request has been sent
  53. to this JID and it has not been accepted yet.
  54. subscription -- Returns one of: 'to', 'from', 'both', or 'none'
  55. based on the states of from, to, pending_in,
  56. and pending_out. Assignment to this value does
  57. not affect the states of the other values.
  58. whitelisted -- Indicates if a subscription request from this
  59. JID should be automatically accepted.
  60. name -- A user supplied alias for the JID.
  61. groups -- A list of group names for the JID.
  62. Attributes:
  63. xmpp -- The main SleekXMPP instance.
  64. owner -- The JID that owns the roster.
  65. jid -- The JID for the roster item.
  66. db -- Optional datastore interface object.
  67. last_status -- The last presence sent to this JID.
  68. resources -- A dictionary of online resources for this JID.
  69. Will contain the fields 'show', 'status',
  70. and 'priority'.
  71. Methods:
  72. load -- Retrieve the roster item from an
  73. external datastore, if one was provided.
  74. save -- Save the roster item to an external
  75. datastore, if one was provided.
  76. remove -- Remove a subscription to the JID and revoke
  77. its whitelisted status.
  78. subscribe -- Subscribe to the JID.
  79. authorize -- Accept a subscription from the JID.
  80. unauthorize -- Deny a subscription from the JID.
  81. unsubscribe -- Unsubscribe from the JID.
  82. send_presence -- Send a directed presence to the JID.
  83. send_last_presence -- Resend the last sent presence.
  84. handle_available -- Update the JID's resource information.
  85. handle_unavailable -- Update the JID's resource information.
  86. handle_subscribe -- Handle a subscription request.
  87. handle_subscribed -- Handle a notice that a subscription request
  88. was authorized by the JID.
  89. handle_unsubscribe -- Handle an unsubscribe request.
  90. handle_unsubscribed -- Handle a notice that a subscription was
  91. removed by the JID.
  92. handle_probe -- Handle a presence probe query.
  93. """
  94. def __init__(self, xmpp, jid, owner=None,
  95. state=None, db=None, roster=None):
  96. """
  97. Create a new roster item.
  98. Arguments:
  99. xmpp -- The main SleekXMPP instance.
  100. jid -- The item's JID.
  101. owner -- The roster owner's JID. Defaults
  102. so self.xmpp.boundjid.bare.
  103. state -- A dictionary of initial state values.
  104. db -- An optional interface to an external datastore.
  105. roster -- The roster object containing this entry.
  106. """
  107. self.xmpp = xmpp
  108. self.jid = jid
  109. self.owner = owner or self.xmpp.boundjid.bare
  110. self.last_status = None
  111. self.resources = {}
  112. self.roster = roster
  113. self.db = db
  114. self._state = state or {
  115. 'from': False,
  116. 'to': False,
  117. 'pending_in': False,
  118. 'pending_out': False,
  119. 'whitelisted': False,
  120. 'subscription': 'none',
  121. 'name': '',
  122. 'groups': []}
  123. self._db_state = {}
  124. self.load()
  125. def set_backend(self, db=None, save=True):
  126. """
  127. Set the datastore interface object for the roster item.
  128. Arguments:
  129. db -- The new datastore interface.
  130. save -- If True, save the existing state to the new
  131. backend datastore. Defaults to True.
  132. """
  133. self.db = db
  134. if save:
  135. self.save()
  136. self.load()
  137. def load(self):
  138. """
  139. Load the item's state information from an external datastore,
  140. if one has been provided.
  141. """
  142. if self.db:
  143. item = self.db.load(self.owner, self.jid,
  144. self._db_state)
  145. if item:
  146. self['name'] = item['name']
  147. self['groups'] = item['groups']
  148. self['from'] = item['from']
  149. self['to'] = item['to']
  150. self['whitelisted'] = item['whitelisted']
  151. self['pending_out'] = item['pending_out']
  152. self['pending_in'] = item['pending_in']
  153. self['subscription'] = self._subscription()
  154. return self._state
  155. return None
  156. def save(self, remove=False):
  157. """
  158. Save the item's state information to an external datastore,
  159. if one has been provided.
  160. Arguments:
  161. remove -- If True, expunge the item from the datastore.
  162. """
  163. self['subscription'] = self._subscription()
  164. if remove:
  165. self._state['removed'] = True
  166. if self.db:
  167. self.db.save(self.owner, self.jid,
  168. self._state, self._db_state)
  169. # Finally, remove the in-memory copy if needed.
  170. if remove:
  171. del self.xmpp.roster[self.owner][self.jid]
  172. def __getitem__(self, key):
  173. """Return a state field's value."""
  174. if key in self._state:
  175. if key == 'subscription':
  176. return self._subscription()
  177. return self._state[key]
  178. else:
  179. raise KeyError
  180. def __setitem__(self, key, value):
  181. """
  182. Set the value of a state field.
  183. For boolean states, the values True, 'true', '1', 'on',
  184. and 'yes' are accepted as True; all others are False.
  185. Arguments:
  186. key -- The state field to modify.
  187. value -- The new value of the state field.
  188. """
  189. if key in self._state:
  190. if key in ['name', 'subscription', 'groups']:
  191. self._state[key] = value
  192. else:
  193. value = str(value).lower()
  194. self._state[key] = value in ('true', '1', 'on', 'yes')
  195. else:
  196. raise KeyError
  197. def _subscription(self):
  198. """Return the proper subscription type based on current state."""
  199. if self['to'] and self['from']:
  200. return 'both'
  201. elif self['from']:
  202. return 'from'
  203. elif self['to']:
  204. return 'to'
  205. else:
  206. return 'none'
  207. def remove(self):
  208. """
  209. Remove a JID's whitelisted status and unsubscribe if a
  210. subscription exists.
  211. """
  212. if self['to']:
  213. p = self.xmpp.Presence()
  214. p['to'] = self.jid
  215. p['type'] = 'unsubscribe'
  216. if self.xmpp.is_component:
  217. p['from'] = self.owner
  218. p.send()
  219. self['to'] = False
  220. self['whitelisted'] = False
  221. self.save()
  222. def subscribe(self):
  223. """Send a subscription request to the JID."""
  224. p = self.xmpp.Presence()
  225. p['to'] = self.jid
  226. p['type'] = 'subscribe'
  227. if self.xmpp.is_component:
  228. p['from'] = self.owner
  229. self['pending_out'] = True
  230. self.save()
  231. p.send()
  232. def authorize(self):
  233. """Authorize a received subscription request from the JID."""
  234. self['from'] = True
  235. self['pending_in'] = False
  236. self.save()
  237. self._subscribed()
  238. self.send_last_presence()
  239. def unauthorize(self):
  240. """Deny a received subscription request from the JID."""
  241. self['from'] = False
  242. self['pending_in'] = False
  243. self.save()
  244. self._unsubscribed()
  245. p = self.xmpp.Presence()
  246. p['to'] = self.jid
  247. p['type'] = 'unavailable'
  248. if self.xmpp.is_component:
  249. p['from'] = self.owner
  250. p.send()
  251. def _subscribed(self):
  252. """Handle acknowledging a subscription."""
  253. p = self.xmpp.Presence()
  254. p['to'] = self.jid
  255. p['type'] = 'subscribed'
  256. if self.xmpp.is_component:
  257. p['from'] = self.owner
  258. p.send()
  259. def unsubscribe(self):
  260. """Unsubscribe from the JID."""
  261. p = self.xmpp.Presence()
  262. p['to'] = self.jid
  263. p['type'] = 'unsubscribe'
  264. if self.xmpp.is_component:
  265. p['from'] = self.owner
  266. self.save()
  267. p.send()
  268. def _unsubscribed(self):
  269. """Handle acknowledging an unsubscribe request."""
  270. p = self.xmpp.Presence()
  271. p['to'] = self.jid
  272. p['type'] = 'unsubscribed'
  273. if self.xmpp.is_component:
  274. p['from'] = self.owner
  275. p.send()
  276. def send_presence(self, **kwargs):
  277. """
  278. Create, initialize, and send a Presence stanza.
  279. If no recipient is specified, send the presence immediately.
  280. Otherwise, forward the send request to the recipient's roster
  281. entry for processing.
  282. Arguments:
  283. pshow -- The presence's show value.
  284. pstatus -- The presence's status message.
  285. ppriority -- This connections' priority.
  286. pto -- The recipient of a directed presence.
  287. pfrom -- The sender of a directed presence, which should
  288. be the owner JID plus resource.
  289. ptype -- The type of presence, such as 'subscribe'.
  290. pnick -- Optional nickname of the presence's sender.
  291. """
  292. if self.xmpp.is_component and not kwargs.get('pfrom', ''):
  293. kwargs['pfrom'] = self.owner
  294. if not kwargs.get('pto', ''):
  295. kwargs['pto'] = self.jid
  296. self.xmpp.send_presence(**kwargs)
  297. def send_last_presence(self):
  298. if self.last_status is None:
  299. pres = self.roster.last_status
  300. if pres is None:
  301. self.send_presence()
  302. else:
  303. pres['to'] = self.jid
  304. if self.xmpp.is_component:
  305. pres['from'] = self.owner
  306. else:
  307. del pres['from']
  308. pres.send()
  309. else:
  310. self.last_status.send()
  311. def handle_available(self, presence):
  312. resource = presence['from'].resource
  313. data = {'status': presence['status'],
  314. 'show': presence['show'],
  315. 'priority': presence['priority']}
  316. got_online = not self.resources
  317. if resource not in self.resources:
  318. self.resources[resource] = {}
  319. old_status = self.resources[resource].get('status', '')
  320. old_show = self.resources[resource].get('show', None)
  321. self.resources[resource].update(data)
  322. if got_online:
  323. self.xmpp.event('got_online', presence)
  324. if old_show != presence['show'] or old_status != presence['status']:
  325. self.xmpp.event('changed_status', presence)
  326. def handle_unavailable(self, presence):
  327. resource = presence['from'].resource
  328. if not self.resources:
  329. return
  330. if resource in self.resources:
  331. del self.resources[resource]
  332. self.xmpp.event('changed_status', presence)
  333. if not self.resources:
  334. self.xmpp.event('got_offline', presence)
  335. def handle_subscribe(self, presence):
  336. """
  337. +------------------------------------------------------------------+
  338. | EXISTING STATE | DELIVER? | NEW STATE |
  339. +------------------------------------------------------------------+
  340. | "None" | yes | "None + Pending In" |
  341. | "None + Pending Out" | yes | "None + Pending Out/In" |
  342. | "None + Pending In" | no | no state change |
  343. | "None + Pending Out/In" | no | no state change |
  344. | "To" | yes | "To + Pending In" |
  345. | "To + Pending In" | no | no state change |
  346. | "From" | no * | no state change |
  347. | "From + Pending Out" | no * | no state change |
  348. | "Both" | no * | no state change |
  349. +------------------------------------------------------------------+
  350. """
  351. if self.xmpp.is_component:
  352. if not self['from'] and not self['pending_in']:
  353. self['pending_in'] = True
  354. self.xmpp.event('roster_subscription_request', presence)
  355. elif self['from']:
  356. self._subscribed()
  357. self.save()
  358. else:
  359. #server shouldn't send an invalid subscription request
  360. self.xmpp.event('roster_subscription_request', presence)
  361. def handle_subscribed(self, presence):
  362. """
  363. +------------------------------------------------------------------+
  364. | EXISTING STATE | DELIVER? | NEW STATE |
  365. +------------------------------------------------------------------+
  366. | "None" | no | no state change |
  367. | "None + Pending Out" | yes | "To" |
  368. | "None + Pending In" | no | no state change |
  369. | "None + Pending Out/In" | yes | "To + Pending In" |
  370. | "To" | no | no state change |
  371. | "To + Pending In" | no | no state change |
  372. | "From" | no | no state change |
  373. | "From + Pending Out" | yes | "Both" |
  374. | "Both" | no | no state change |
  375. +------------------------------------------------------------------+
  376. """
  377. if self.xmpp.is_component:
  378. if not self['to'] and self['pending_out']:
  379. self['pending_out'] = False
  380. self['to'] = True
  381. self.xmpp.event('roster_subscription_authorized', presence)
  382. self.save()
  383. else:
  384. self.xmpp.event('roster_subscription_authorized', presence)
  385. def handle_unsubscribe(self, presence):
  386. """
  387. +------------------------------------------------------------------+
  388. | EXISTING STATE | DELIVER? | NEW STATE |
  389. +------------------------------------------------------------------+
  390. | "None" | no | no state change |
  391. | "None + Pending Out" | no | no state change |
  392. | "None + Pending In" | yes * | "None" |
  393. | "None + Pending Out/In" | yes * | "None + Pending Out" |
  394. | "To" | no | no state change |
  395. | "To + Pending In" | yes * | "To" |
  396. | "From" | yes * | "None" |
  397. | "From + Pending Out" | yes * | "None + Pending Out |
  398. | "Both" | yes * | "To" |
  399. +------------------------------------------------------------------+
  400. """
  401. if self.xmpp.is_component:
  402. if not self['from'] and self['pending_in']:
  403. self['pending_in'] = False
  404. self._unsubscribed()
  405. elif self['from']:
  406. self['from'] = False
  407. self._unsubscribed()
  408. self.xmpp.event('roster_subscription_remove', presence)
  409. self.save()
  410. else:
  411. self.xmpp.event('roster_subscription_remove', presence)
  412. def handle_unsubscribed(self, presence):
  413. """
  414. +------------------------------------------------------------------+
  415. | EXISTING STATE | DELIVER? | NEW STATE |
  416. +------------------------------------------------------------------+
  417. | "None" | no | no state change |
  418. | "None + Pending Out" | yes | "None" |
  419. | "None + Pending In" | no | no state change |
  420. | "None + Pending Out/In" | yes | "None + Pending In" |
  421. | "To" | yes | "None" |
  422. | "To + Pending In" | yes | "None + Pending In" |
  423. | "From" | no | no state change |
  424. | "From + Pending Out" | yes | "From" |
  425. | "Both" | yes | "From" |
  426. +------------------------------------------------------------------
  427. """
  428. if self.xmpp.is_component:
  429. if not self['to'] and self['pending_out']:
  430. self['pending_out'] = False
  431. elif self['to'] and not self['pending_out']:
  432. self['to'] = False
  433. self.xmpp.event('roster_subscription_removed', presence)
  434. self.save()
  435. else:
  436. self.xmpp.event('roster_subscription_removed', presence)
  437. def handle_probe(self, presence):
  438. if self['from']:
  439. self.send_last_presence()
  440. if self['pending_out']:
  441. self.subscribe()
  442. if not self['from']:
  443. self._unsubscribed()
  444. def reset(self):
  445. """
  446. Forgot current resource presence information as part of
  447. a roster reset request.
  448. """
  449. self.resources = {}
  450. def __repr__(self):
  451. return repr(self._state)