Debian Codegraph @

tx_xmpp/data_form.py

raw
1 # -*- test-case-name: tx_xmpp.test.test_data_form -*-
2 #
3 # Copyright (c) Ralph Meijer, 2007-2021
4 # Copyright (c) Jérôme Poisson, 2019-2026
5 # See LICENSE for details.
6
7 """
8 Data Forms.
9
10 Support for Data Forms as described in
11 U{XEP-0004<http://xmpp.org/extensions/xep-0004.html>}, along with support
12 for Field Standardization for Data Forms as described in
13 U{XEP-0068<http://xmpp.org/extensions/xep-0068.html>}.
14 """
15
16 from zope.interface import implementer
17 from zope.interface.common import mapping
18
19 from twisted.words.protocols.jabber.jid import JID
20 from twisted.words.xish import domish
21
22 NS_X_DATA = "jabber:x:data"
23 NS_XML_ELEMENT = "urn:xmpp:xml-element"
24
25
26 class Error(Exception):
27 """
28 Data Forms error.
29 """
30
31
32 class FieldNameRequiredError(Error):
33 """
34 A field name is required for this field type.
35 """
36
37
38 class TooManyValuesError(Error):
39 """
40 This field is single-value.
41 """
42
43
44 class Option:
45 """
46 Data Forms field option.
47
48 @ivar value: Value of this option.
49 @type value: L{str}
50 @ivar label: Optional label for this option.
51 @type label: L{str} or L{NoneType}
52 """
53
54 def __init__(self, value, label=None):
55 self.value = value
56 self.label = label
57
58 def __repr__(self):
59 r = ["Option(", repr(self.value)]
60 if self.label:
61 r.append(", ")
62 r.append(repr(self.label))
63 r.append(")")
64 return "".join(r)
65
66 def toElement(self):
67 """
68 Return the DOM representation of this option.
69
70 @rtype: L{domish.Element}.
71 """
72 option = domish.Element((NS_X_DATA, "option"))
73 option.addElement("value", content=self.value)
74 if self.label:
75 option["label"] = self.label
76 return option
77
78 @staticmethod
79 def fromElement(element):
80 valueElements = list(
81 domish.generateElementsQNamed(element.children, "value", NS_X_DATA)
82 )
83 if not valueElements:
84 raise Error("Option has no value")
85
86 label = element.getAttribute("label")
87 return Option(str(valueElements[0]), label)
88
89
90 class Field:
91 """
92 Data Forms field.
93
94 @ivar fieldType: Type of this field. One of C{'boolean'}, C{'fixed'},
95 C{'hidden'}, C{'jid-multi'}, C{'jid-single'},
96 C{'list-multi'}, C{'list-single'}, C{'text-multi'},
97 C{'text-private'}, C{'text-single'}.
98
99 The default is C{'text-single'}.
100 @type fieldType: L{str}
101 @ivar var: Field name. Optional if C{fieldType} is C{'fixed'}.
102 @type var: L{str}
103 @ivar label: Human readable label for this field.
104 @type label: L{str}
105 @ivar values: The values for this field, for multi-valued field
106 types, as a list of L{bool}, L{str} or L{JID}.
107 @type values: L{list}
108 @ivar _raw_values: Original XML character data of each <value/> element,
109 as a list of L{str}. Populated only for boolean and
110 jid types (where normalization changes the value).
111 Needed for XEP-0115 cap hash. L{None} otherwise.
112 @type _raw_values: L{list} or L{None}
113 @ivar options: List of possible values to choose from in a response
114 to this form as a list of L{Option}s.
115 @type options: L{list}
116 @ivar desc: Human readable description for this field.
117 @type desc: L{str}
118 @ivar required: Whether the field is required to be provided in a
119 response to this form.
120 @type required: L{bool}
121 """
122
123 def __init__(
124 self,
125 fieldType="text-single",
126 var=None,
127 value=None,
128 values=None,
129 options=None,
130 label=None,
131 desc=None,
132 required=False,
133 ext_type=None,
134 ):
135 """
136 Initialize this field.
137
138 See the identically named instance variables for descriptions.
139
140 If C{value} is not L{None}, it overrides C{values}, setting the
141 given value as the only value for this field.
142
143 @param ext_type(None, unicode): extended type, can be:
144 - xml: field is an XML Element
145 - None: field is a base (XEP-0004) type
146 """
147
148 self.fieldType = fieldType
149 self.var = var
150 self._raw_values: list[str] | None = None
151
152 if value is not None:
153 self.value = value
154 else:
155 self.values = values or []
156
157 self.label = label
158
159 try:
160 self.options = [
161 Option(optionValue, optionLabel)
162 for optionValue, optionLabel in options.items()
163 ]
164 except AttributeError:
165 self.options = options or []
166
167 self.desc = desc
168 self.required = required
169 self.ext_type = ext_type
170
171 def __repr__(self):
172 r = ["Field(fieldType=", repr(self.fieldType)]
173 if self.var:
174 r.append(", var=")
175 r.append(repr(self.var))
176 if self.label:
177 r.append(", label=")
178 r.append(repr(self.label))
179 if self.desc:
180 r.append(", desc=")
181 r.append(repr(self.desc))
182 if self.required:
183 r.append(", required=")
184 r.append(repr(self.required))
185 if self.values:
186 r.append(", values=")
187 r.append(repr(self.values))
188 if self.options:
189 r.append(", options=")
190 r.append(repr(self.options))
191 r.append(")")
192 return "".join(r)
193
194 def __value_set(self, value):
195 """
196 Setter of value property.
197
198 Sets C{value} as the only element of L{values}.
199
200 @type value: L{bool}, L{str} or L{JID}
201 """
202 self.values = [value]
203
204 def __value_get(self):
205 """
206 Getter of value property.
207
208 Returns the first element of L{values}, if present, or L{None}.
209 """
210
211 if self.values:
212 return self.values[0]
213 else:
214 return None
215
216 value = property(
217 __value_get,
218 __value_set,
219 doc="""
220 The value for this field, for single-valued field types.
221
222 This is a special property accessing L{values}. Writing to this
223 property empties L{values} and then sets the given value as the
224 only element of L{values}. Reading from this propery returns the
225 first element of L{values}.
226 """,
227 )
228
229 def typeCheck(self):
230 """
231 Check field properties agains the set field type.
232 """
233 if self.ext_type is not None:
234 # we use an extended type
235 if self.fieldType not in (None, "hidden"):
236 raise ValueError("Invalid main type for a extended type field")
237 if len(self.values) != 1:
238 raise ValueError("extended type must have one and only one value")
239 if self.options:
240 raise ValueError("options must not be set for extented type")
241 if self.ext_type == "xml":
242 if not isinstance(self.values[0], domish.Element):
243 raise ValueError("invalid value, a domish.Element is expected")
244 else:
245 raise ValueError(
246 "Unknown extended type: {ext_type}".format(ext_type=self.ext_type)
247 )
248
249 if self.var is None and self.fieldType != "fixed":
250 raise FieldNameRequiredError()
251
252 if self.values:
253 if (
254 self.fieldType
255 not in ("hidden", "jid-multi", "list-multi", "text-multi", None)
256 and len(self.values) > 1
257 ):
258 raise TooManyValuesError()
259
260 newValues = []
261 for value in self.values:
262 if self.fieldType == "boolean":
263 if isinstance(value, str):
264 checkValue = value.lower()
265 if not checkValue in ("0", "1", "false", "true"):
266 raise ValueError("Not a boolean")
267 value = checkValue in ("1", "true")
268 value = bool(value)
269 elif self.fieldType in ("jid-single", "jid-multi"):
270 if not hasattr(value, "full"):
271 value = JID(value)
272
273 newValues.append(value)
274
275 self.values = newValues
276
277 def toElement(self, asForm=False):
278 """
279 Return the DOM representation of this Field.
280
281 @rtype: L{domish.Element}.
282 """
283 if self.ext_type is None:
284 return self._toElementBase(asForm)
285 else:
286 self.typeCheck()
287 field_elt = domish.Element((NS_X_DATA, "field"))
288 if self.fieldType:
289 field_elt["type"] = self.fieldType
290
291 if self.var is not None:
292 field_elt["var"] = self.var
293
294 wrapper_elt = field_elt.addElement((NS_XML_ELEMENT, "wrapper"))
295 wrapper_elt.addChild(self.values[0])
296
297 if asForm:
298 if self.label is not None:
299 field_elt["label"] = self.label
300
301 if self.desc is not None:
302 field_elt.addElement("desc", content=self.desc)
303
304 if self.required:
305 field_elt.addElement("required")
306
307 return field_elt
308
309 def _toElementBase(self, asForm=False):
310 """
311 Return the DOM representation of this Field (base implementation).
312
313 @rtype: L{domish.Element}.
314 """
315 self.typeCheck()
316
317 field = domish.Element((NS_X_DATA, "field"))
318
319 if self.fieldType:
320 field["type"] = self.fieldType
321
322 if self.var is not None:
323 field["var"] = self.var
324
325 for value in self.values:
326 if isinstance(value, bool):
327 value = str(value).lower()
328 else:
329 value = str(value)
330
331 field.addElement("value", content=value)
332
333 if asForm:
334 if self.fieldType in ("list-single", "list-multi"):
335 for option in self.options:
336 field.addChild(option.toElement())
337
338 if self.label is not None:
339 field["label"] = self.label
340
341 if self.desc is not None:
342 field.addElement("desc", content=self.desc)
343
344 if self.required:
345 field.addElement("required")
346
347 return field
348
349 @staticmethod
350 def _parse_desc(field, element):
351 desc = str(element)
352 if desc:
353 field.desc = desc
354
355 @staticmethod
356 def _parse_option(field, element):
357 field.options.append(Option.fromElement(element))
358
359 @staticmethod
360 def _parse_required(field, element):
361 field.required = True
362
363 @staticmethod
364 def _parse_value(field, element):
365 value = str(element)
366 field.values.append(value)
367 if field.fieldType in ("boolean", "jid-single", "jid-multi"):
368 if field._raw_values is None:
369 field._raw_values = []
370 field._raw_values.append(value)
371
372 @property
373 def raw_values(self) -> list[str]:
374 """Return original XML text for boolean/jid fields, else values."""
375 if self._raw_values is not None:
376 return self._raw_values
377 return self.values
378
379 @staticmethod
380 def fromElement(element):
381 field = Field(None)
382
383 for eAttr, fAttr in {"type": "fieldType", "var": "var", "label": "label"}.items():
384 value = element.getAttribute(eAttr)
385 if value:
386 setattr(field, fAttr, value)
387
388 for child in element.elements():
389 if child.uri != NS_X_DATA and child.uri != NS_XML_ELEMENT:
390 continue
391
392 # Check for XML element wrapper
393 if child.uri == NS_XML_ELEMENT and child.name == "wrapper":
394 field.ext_type = "xml"
395 field.values = [child.firstChildElement()]
396 continue
397
398 func = getattr(Field, "_parse_" + child.name, None)
399 if func:
400 func(field, child)
401
402 return field
403
404 @staticmethod
405 def fromDict(fieldDict):
406 """
407 Create a field from a dictionary.
408
409 This is a short hand for passing arguments directly on Field object
410 creation. The field type is represented by the C{'type'} key. For
411 C{'options'} the value is not a list of L{Option}s, but a dictionary
412 keyed by value, with an optional label as value.
413 """
414 kwargs = fieldDict.copy()
415
416 if "type" in fieldDict:
417 kwargs["fieldType"] = fieldDict["type"]
418 del kwargs["type"]
419
420 if "options" in fieldDict:
421 options = []
422 for value, label in fieldDict["options"].items():
423 options.append(Option(value, label))
424 kwargs["options"] = options
425
426 return Field(**kwargs)
427
428
429 @implementer(
430 mapping.IIterableMapping,
431 mapping.IEnumerableMapping,
432 mapping.IReadMapping,
433 mapping.IItemMapping,
434 )
435 class Form:
436 """
437 Data Form.
438
439 There are two similarly named properties of forms. The C{formType} is the
440 the so-called type of the form, and is set as the C{'type'} attribute
441 on the form's root element.
442
443 The Field Standardization specification in XEP-0068, defines a way to
444 provide a context for the field names used in this form, by setting a
445 special hidden field named C{'FORM_TYPE'}, to put the names of all
446 other fields in the namespace of the value of that field. This namespace
447 is recorded in the C{formNamespace} instance variable.
448
449 A L{Form} also acts as read-only dictionary, with the values of fields
450 keyed by their name. See L{__getitem__}.
451
452 @ivar formType: Type of form. One of C{'form'}, C{'submit'}, {'cancel'},
453 or {'result'}.
454 @type formType: L{str}
455
456 @ivar title: Natural language title of the form.
457 @type title: L{str}
458
459 @ivar instructions: Natural language instructions as a list of L{str}
460 strings without line breaks.
461 @type instructions: L{list}
462
463 @ivar formNamespace: The optional namespace of the field names for this
464 form. This goes in the special field named C{'FORM_TYPE'}, if set.
465 @type formNamespace: L{str}
466
467 @ivar fields: Dictionary of named fields. Note that this is meant to be
468 used for reading, only. One should use L{addField} or L{makeFields} and
469 L{removeField} for adding and removing fields.
470 @type fields: L{dict}
471
472 @ivar fieldList: List of all fields, in the order they are added. Like
473 C{fields}, this is meant to be used for reading, only.
474 @type fieldList: L{list}
475 """
476
477 def __init__(
478 self, formType, title=None, instructions=None, formNamespace=None, fields=None
479 ):
480 self.formType = formType
481 self.title = title
482 self.instructions = instructions or []
483 self.formNamespace = formNamespace
484
485 self.fieldList = []
486 self.fields = {}
487
488 if fields:
489 for field in fields:
490 self.addField(field)
491
492 def __repr__(self):
493 r = ["Form(formType=", repr(self.formType)]
494
495 if self.title:
496 r.append(", title=")
497 r.append(repr(self.title))
498 if self.instructions:
499 r.append(", instructions=")
500 r.append(repr(self.instructions))
501 if self.formNamespace:
502 r.append(", formNamespace=")
503 r.append(repr(self.formNamespace))
504 if self.fieldList:
505 r.append(", fields=")
506 r.append(repr(self.fieldList))
507 r.append(")")
508 return "".join(r)
509
510 def addField(self, field):
511 """
512 Add a field to this form.
513
514 Fields are added in order, and C{fields} is a dictionary of the
515 named fields, that is kept in sync only if this method is used for
516 adding new fields. Multiple fields with the same name are disallowed.
517 """
518 if field.var is not None:
519 if field.var in self.fields:
520 raise Error("Duplicate field %r" % field.var)
521
522 self.fields[field.var] = field
523
524 self.fieldList.append(field)
525
526 def removeField(self, field):
527 """
528 Remove a field from this form.
529 """
530 self.fieldList.remove(field)
531
532 if field.var is not None:
533 del self.fields[field.var]
534
535 def makeFields(self, values, fieldDefs=None, filterUnknown=True):
536 """
537 Create fields from values and add them to this form.
538
539 This creates fields from a mapping of name to value(s) and adds them to
540 this form. It is typically used for generating outgoing forms.
541
542 If C{fieldDefs} is not L{None}, this is used to fill in
543 additional properties of fields, like the field types, labels and
544 possible options.
545
546 If C{filterUnknown} is L{True} and C{fieldDefs} is not L{None}, fields
547 will only be created from C{values} with a corresponding entry in
548 C{fieldDefs}.
549
550 If the field type is unknown, the field type is L{None}. When the form
551 is rendered using L{toElement}, these fields will have no C{'type'}
552 attribute, and it is up to the receiving party to interpret the values
553 properly (e.g. by knowing about the FORM_TYPE in C{formNamespace} and
554 the field name).
555
556 @param values: Values to create fields from.
557 @type values: L{dict}
558
559 @param fieldDefs: Field definitions as a dictionary. See
560 L{tx_xmpp.itx_xmpp.IPubSubService.getConfigurationOptions}
561 @type fieldDefs: L{dict}
562
563 @param filterUnknown: If L{True}, ignore fields that are not in
564 C{fieldDefs}.
565 @type filterUnknown: L{bool}
566 """
567 for name, value in values.items():
568 fieldDict = {"var": name, "type": None}
569
570 if fieldDefs is not None:
571 if name in fieldDefs:
572 fieldDict.update(fieldDefs[name])
573 elif filterUnknown:
574 continue
575
576 if isinstance(value, list):
577 fieldDict["values"] = value
578 else:
579 fieldDict["value"] = value
580
581 self.addField(Field.fromDict(fieldDict))
582
583 def toElement(self):
584 """
585 Return the DOM representation of this Form.
586
587 @rtype: L{domish.Element}
588 """
589 form = domish.Element((NS_X_DATA, "x"))
590 form["type"] = self.formType
591
592 if self.title:
593 form.addElement("title", content=self.title)
594
595 for instruction in self.instructions:
596 form.addElement("instructions", content=instruction)
597
598 if self.formNamespace is not None:
599 field = Field("hidden", "FORM_TYPE", self.formNamespace)
600 form.addChild(field.toElement())
601
602 for field in self.fieldList:
603 form.addChild(field.toElement(self.formType == "form"))
604
605 return form
606
607 @staticmethod
608 def _parse_title(form, element):
609 title = str(element)
610 if title:
611 form.title = title
612
613 @staticmethod
614 def _parse_instructions(form, element):
615 instructions = str(element)
616 if instructions:
617 form.instructions.append(instructions)
618
619 @staticmethod
620 def _parse_field(form, element):
621 field = Field.fromElement(element)
622 if field.var == "FORM_TYPE" and field.fieldType == "hidden" and field.value:
623 form.formNamespace = field.value
624 else:
625 form.addField(field)
626
627 @staticmethod
628 def fromElement(element):
629 if (element.uri, element.name) != ((NS_X_DATA, "x")):
630 raise Error("Element provided is not a Data Form")
631
632 form = Form(element.getAttribute("type"))
633
634 for child in element.elements():
635 if child.uri != NS_X_DATA:
636 continue
637
638 func = getattr(Form, "_parse_" + child.name, None)
639 if func:
640 func(form, child)
641
642 return form
643
644 def __iter__(self):
645 return iter(self.fields)
646
647 def __len__(self):
648 return len(self.fields)
649
650 def __getitem__(self, key):
651 """
652 Called to implement evaluation of self[key].
653
654 This returns the value of the field with the name in C{key}. For
655 multi-value fields, the value is a list, otherwise a single value.
656
657 If a field has no type, and the field has multiple values, the value
658 of the list of values. Otherwise, it will be a single value.
659
660 Raises C{KeyError} if there is no field with the name in C{key}.
661 """
662 field = self.fields[key]
663
664 if field.fieldType in ("jid-multi", "list-multi", "text-multi") or (
665 field.fieldType is None and len(field.values) > 1
666 ):
667 value = field.values
668 else:
669 value = field.value
670
671 return value
672
673 def get(self, key, default=None):
674 try:
675 return self[key]
676 except KeyError:
677 return default
678
679 def __contains__(self, key):
680 return key in self.fields
681
682 def keys(self):
683 return iter(self)
684
685 def values(self):
686 for key in self:
687 yield self[key]
688
689 def items(self):
690 for key in self:
691 yield (key, self[key])
692
693 def getValues(self):
694 """
695 Extract values from the named form fields.
696
697 For all named fields, the corresponding value or values are
698 returned in a dictionary keyed by the field name. This is equivalent
699 do L{dict(f)}, where C{f} is a L{Form}.
700
701 @see: L{__getitem__}
702 @rtype: L{dict}
703 """
704 return dict(self)
705
706 def typeCheck(self, fieldDefs=None, filterUnknown=False):
707 """
708 Check values of fields according to the field definition.
709
710 This method walks all named fields to check their values against their
711 type, and is typically used for forms received from other entities. The
712 field definition in C{fieldDefs} is used to check the field type.
713
714 If C{filterUnknown} is L{True}, fields that are not present in
715 C{fieldDefs} are removed from the form.
716
717 If the field type is L{None} (when not set by the sending entity),
718 the type from the field definitition is used, or C{'text-single'} if
719 that is not set.
720
721 If C{fieldDefs} is None, an empty dictionary is assumed. This is
722 useful for coercing boolean and JID values on forms with type
723 C{'form'}.
724
725 @param fieldDefs: Field definitions as a dictionary. See
726 L{tx_xmpp.itx_xmpp.IPubSubService.getConfigurationOptions}
727 @type fieldDefs: L{dict}
728
729 @param filterUnknown: If L{True}, remove fields that are not in
730 C{fieldDefs}.
731 @type filterUnknown: L{bool}
732 """
733
734 if fieldDefs is None:
735 fieldDefs = {}
736
737 filtered = []
738
739 for name, field in self.fields.items():
740 if name in fieldDefs:
741 fieldDef = fieldDefs[name]
742 if "type" not in fieldDef:
743 fieldDef["type"] = "text-single"
744
745 if field.fieldType is None:
746 field.fieldType = fieldDef["type"]
747 elif field.fieldType != fieldDef["type"]:
748 raise TypeError(
749 "Field type for %r is %r, expected %r"
750 % (name, field.fieldType, fieldDef["type"])
751 )
752 else:
753 # Field type is correct
754 pass
755 field.typeCheck()
756 elif filterUnknown:
757 filtered.append(field)
758 elif field.fieldType is not None:
759 field.typeCheck()
760 else:
761 # Unknown field without type, no checking, no filtering
762 pass
763
764 for field in filtered:
765 self.removeField(field)
766
767
768 def findForm(element, formNamespace):
769 """
770 Find a Data Form.
771
772 Look for an element that represents a Data Form with the specified
773 form namespace as a child element of the given element.
774 """
775 if not element:
776 return None
777
778 for child in element.elements():
779 if (child.uri, child.name) == ((NS_X_DATA, "x")):
780 form = Form.fromElement(child)
781
782 if (
783 form.formNamespace == formNamespace
784 or not form.formNamespace
785 and form.formType == "cancel"
786 ):
787 return form
788
789 return None