Debian Codegraph @

tx_xmpp/rsm.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_rsm -*-
2 #
3 # Copyright (c) Adrien Cossa, 2016
4 # Copyright (c) Jérôme Poisson, 2019-2026
5 # See LICENSE for details.
6
7 """
8 XMPP Result Set Management protocol.
9
10 This protocol is specified in
11 U{XEP-0059<http://xmpp.org/extensions/xep-0059.html>}.
12 """
13
14 from twisted.words.xish import domish
15 from twisted.words.protocols.jabber import error
16 from . import disco, pubsub
17 import copy
18
19 NS_RSM = "http://jabber.org/protocol/rsm"
20 NS_PUBSUB_RSM = "http://jabber.org/protocol/pubsub#rsm"
21
22
23 class RSMError(error.StanzaError):
24 """
25 RSM error.
26 """
27
28 def __init__(self, text=None):
29 error.StanzaError.__init__(self, "bad-request", text=text)
30
31
32 class RSMNotFoundError(Exception):
33 """
34 An expected RSM element has not been found.
35 """
36
37
38 class RSMRequest:
39 """
40 A Result Set Management request.
41
42 @ivar max_: limit on the number of retrieved items.
43 @itype max_: C{int} or C{unicode}
44
45 @ivar index: starting index of the requested page.
46 @itype index: C{int} or C{unicode} or C{None}
47
48 @ivar after: ID of the element immediately preceding the page.
49 @itype after: C{unicode}
50
51 @ivar before: ID of the element immediately following the page.
52 @itype before: C{unicode}
53 """
54
55 def __init__(self, max_=10, after=None, before=None, index=None):
56 self.max = int(max_)
57
58 if index is not None:
59 assert after is None and before is None
60 index = int(index)
61 self.index = index
62
63 if after is not None:
64 assert before is None
65 assert isinstance(after, str)
66 self.after = after
67
68 if before is not None:
69 assert isinstance(before, str)
70 self.before = before
71
72 def __str__(self):
73 return "RSM Request: max={0.max} after={0.after} before={0.before} index={0.index}".format(
74 self
75 )
76
77 @classmethod
78 def fromElement(cls, element):
79 """Parse the given request element.
80
81 @param element: request containing a set element, or set element itself.
82 @type element: L{domish.Element}
83
84 @return: RSMRequest instance.
85 @rtype: L{RSMRequest}
86 """
87
88 if element.name == "set" and element.uri == NS_RSM:
89 set_elt = element
90 else:
91 try:
92 set_elt = next(element.elements(NS_RSM, "set"))
93 except StopIteration:
94 raise RSMNotFoundError()
95
96 try:
97 before_elt = next(set_elt.elements(NS_RSM, "before"))
98 except StopIteration:
99 before = None
100 else:
101 before = str(before_elt)
102
103 try:
104 after_elt = next(set_elt.elements(NS_RSM, "after"))
105 except StopIteration:
106 after = None
107 else:
108 after = str(after_elt)
109 if not after:
110 raise RSMError("<after/> element can't be empty in RSM request")
111
112 try:
113 max_elt = next(set_elt.elements(NS_RSM, "max"))
114 except StopIteration:
115 # FIXME: even if it doesn't make a lot of sense without it
116 # <max/> element is not mandatory in XEP-0059
117 raise RSMError("RSM request is missing its 'max' element")
118 else:
119 try:
120 max_ = int(str(max_elt))
121 except ValueError:
122 raise RSMError("bad value for 'max' element")
123
124 try:
125 index_elt = next(set_elt.elements(NS_RSM, "index"))
126 except StopIteration:
127 index = None
128 else:
129 try:
130 index = int(str(index_elt))
131 except ValueError:
132 raise RSMError("bad value for 'index' element")
133
134 return RSMRequest(max_, after, before, index)
135
136 def toElement(self):
137 """
138 Return the DOM representation of this RSM request.
139
140 @rtype: L{domish.Element}
141 """
142 set_elt = domish.Element((NS_RSM, "set"))
143 set_elt.addElement("max", content=str(self.max))
144
145 if self.index is not None:
146 set_elt.addElement("index", content=str(self.index))
147
148 if self.before is not None:
149 if self.before == "": # request the last page
150 set_elt.addElement("before")
151 else:
152 set_elt.addElement("before", content=self.before)
153
154 if self.after is not None:
155 set_elt.addElement("after", content=self.after)
156
157 return set_elt
158
159 def render(self, element):
160 """Embed the DOM representation of this RSM request in the given element.
161
162 @param element: Element to contain the RSM request.
163 @type element: L{domish.Element}
164
165 @return: RSM request element.
166 @rtype: L{domish.Element}
167 """
168 set_elt = self.toElement()
169 element.addChild(set_elt)
170
171 return set_elt
172
173
174 class RSMResponse:
175 """
176 A Result Set Management response.
177
178 @ivar first: ID of the first element of the returned page.
179 @itype first: C{unicode}
180
181 @ivar last: ID of the last element of the returned page.
182 @itype last: C{unicode}
183
184 @ivar index: starting index of the returned page.
185 @itype index: C{int}
186
187 @ivar count: total number of items.
188 @itype count: C{int}
189
190 """
191
192 def __init__(self, first=None, last=None, index=None, count=None):
193 if first is None:
194 assert last is None and index is None
195 if last is None:
196 assert first is None
197 self.first = first
198 self.last = last
199 if count is not None:
200 self.count = int(count)
201 else:
202 self.count = None
203 if index is not None:
204 self.index = int(index)
205 else:
206 self.index = None
207
208 def __str__(self):
209 return "RSM Request: first={0.first} last={0.last} index={0.index} count={0.count}".format(
210 self
211 )
212
213 @classmethod
214 def fromElement(cls, element):
215 """Parse the given response element.
216
217 @param element: response element.
218 @type element: L{domish.Element}
219
220 @return: RSMResponse instance.
221 @rtype: L{RSMResponse}
222 """
223 try:
224 set_elt = next(element.elements(NS_RSM, "set"))
225 except StopIteration:
226 raise RSMNotFoundError()
227
228 try:
229 first_elt = next(set_elt.elements(NS_RSM, "first"))
230 except StopIteration:
231 first = None
232 index = None
233 else:
234 first = str(first_elt)
235 try:
236 index = int(first_elt["index"])
237 except KeyError:
238 index = None
239 except ValueError:
240 raise RSMError("bad index in RSM response")
241
242 try:
243 last_elt = next(set_elt.elements(NS_RSM, "last"))
244 except StopIteration:
245 if first is not None:
246 raise RSMError("RSM response is missing its 'last' element")
247 else:
248 last = None
249 else:
250 if first is None:
251 raise RSMError("RSM response is missing its 'first' element")
252 last = str(last_elt)
253
254 try:
255 count_elt = next(set_elt.elements(NS_RSM, "count"))
256 except StopIteration:
257 count = None
258 else:
259 try:
260 count = int(str(count_elt))
261 except ValueError:
262 raise RSMError("invalid count in RSM response")
263
264 return RSMResponse(first, last, index, count)
265
266 def toElement(self):
267 """
268 Return the DOM representation of this RSM request.
269
270 @rtype: L{domish.Element}
271 """
272 set_elt = domish.Element((NS_RSM, "set"))
273 if self.first is not None:
274 first_elt = set_elt.addElement("first", content=self.first)
275 if self.index is not None:
276 first_elt["index"] = str(self.index)
277
278 set_elt.addElement("last", content=self.last)
279
280 if self.count is not None:
281 set_elt.addElement("count", content=str(self.count))
282
283 return set_elt
284
285 def render(self, element):
286 """Embed the DOM representation of this RSM response in the given element.
287
288 @param element: Element to contain the RSM response.
289 @type element: L{domish.Element}
290
291 @return: RSM request element.
292 @rtype: L{domish.Element}
293 """
294 set_elt = self.toElement()
295 element.addChild(set_elt)
296 return set_elt
297
298 def toDict(self):
299 """Return a dict representation of the object.
300
301 @return: a dict of strings.
302 @rtype: C{dict} binding C{unicode} to C{unicode}
303 """
304 result = {}
305 for attr in ("first", "last", "index", "count"):
306 value = getattr(self, attr)
307 if value is not None:
308 result[attr] = value
309 return result
310
311
312 class PubSubRequest(pubsub.PubSubRequest):
313 """PubSubRequest extension to handle RSM.
314
315 @ivar rsm: RSM request instance.
316 @type rsm: L{RSMRequest}
317 """
318
319 rsm = None
320 _parameters = copy.deepcopy(pubsub.PubSubRequest._parameters)
321 _parameters["items"].append("rsm")
322
323 def _parse_rsm(self, verbElement):
324 try:
325 self.rsm = RSMRequest.fromElement(verbElement.parent)
326 except RSMNotFoundError:
327 self.rsm = None
328
329 def _render_rsm(self, verbElement):
330 if self.rsm:
331 self.rsm.render(verbElement.parent)
332
333
334 class PubSubClient(pubsub.PubSubClient):
335 """PubSubClient extension to handle RSM."""
336
337 _request_class = PubSubRequest
338
339 def items(
340 self,
341 service,
342 nodeIdentifier,
343 maxItems=None,
344 subscriptionIdentifier=None,
345 sender=None,
346 itemIdentifiers=None,
347 orderBy=None,
348 rsm_request=None,
349 ):
350 """
351 Retrieve previously published items from a publish subscribe node.
352
353 @param service: The publish subscribe service that keeps the node.
354 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
355
356 @param nodeIdentifier: The identifier of the node.
357 @type nodeIdentifier: C{unicode}
358
359 @param maxItems: Optional limit on the number of retrieved items.
360 @type maxItems: C{int}
361
362 @param subscriptionIdentifier: Optional subscription identifier. In
363 case the node has been subscribed to multiple times, this narrows
364 the results to the specific subscription.
365 @type subscriptionIdentifier: C{unicode}
366
367 @param sender: Optional sender address.
368 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
369
370 @param itemIdentifiers: Identifiers of the items to be retrieved.
371 @type itemIdentifiers: C{set}
372
373 @param orderBy: Keys to order by
374 @type orderBy: L{list} of L{unicode}
375
376 @param rsm_request: RSM request instance.
377 @type rsm_request: L{RSMRequest}
378
379 @return: a Deferred that fires a C{list} of C{tuple} of L{domish.Element}, L{RSMResponse}.
380 @rtype: L{defer.Deferred}
381 """
382 # XXX: we have to copy initial method instead of calling it,
383 # as original cb remove all non item elements
384 request = self._request_class("items")
385 request.recipient = service
386 request.nodeIdentifier = nodeIdentifier
387 if maxItems:
388 request.maxItems = str(int(maxItems))
389 request.subscriptionIdentifier = subscriptionIdentifier
390 request.sender = sender
391 request.itemIdentifiers = itemIdentifiers
392 request.orderBy = orderBy
393 request.rsm = rsm_request
394
395 def cb(iq):
396 items = []
397 pubsub_elt = iq.pubsub
398 if pubsub_elt.items:
399 for element in pubsub_elt.items.elements(pubsub.NS_PUBSUB, "item"):
400 items.append(element)
401
402 try:
403 rsm_response = RSMResponse.fromElement(pubsub_elt)
404 except RSMNotFoundError:
405 rsm_response = None
406 return (items, rsm_response)
407
408 d = request.send(self.xmlstream)
409 d.addCallback(cb)
410 return d
411
412
413 class PubSubService(pubsub.PubSubService):
414 """PubSubService extension to handle RSM."""
415
416 _request_class = PubSubRequest
417
418 def _toResponse_items(self, resp_tuple, resource, request):
419 # Handle both tuple (elts, rsm_response) and plain list (elts)
420 if isinstance(resp_tuple, tuple):
421 elts, rsm_response = resp_tuple
422 else:
423 elts = resp_tuple
424 rsm_response = None
425
426 response = pubsub.PubSubService._toResponse_items(self, elts, resource, request)
427 if rsm_response is not None:
428 response.addChild(rsm_response.toElement())
429
430 return response
431
432 def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
433 def appendRSMFeatures(info):
434 for ns in (NS_RSM, NS_PUBSUB_RSM):
435 feature = disco.DiscoFeature(ns)
436 if feature not in info:
437 info.append(feature)
438 return info
439
440 d = super().getDiscoInfo(requestor, target, nodeIdentifier)
441 d.addCallback(appendRSMFeatures)
442 return d
443
444
445 PubSubService._legacyHandlers = copy.deepcopy(pubsub.PubSubService._legacyHandlers)
446 PubSubService._legacyHandlers["items"][1].append("rsm")