data_forms.rs

  1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
  2//
  3// This Source Code Form is subject to the terms of the Mozilla Public
  4// License, v. 2.0. If a copy of the MPL was not distributed with this
  5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6
  7use crate::media_element::MediaElement;
  8use crate::ns;
  9use crate::util::error::Error;
 10use crate::Element;
 11
 12generate_element!(
 13    /// Represents one of the possible values for a list- field.
 14    Option_, "option", DATA_FORMS,
 15    attributes: [
 16        /// The optional label to be displayed to the user for this option.
 17        label: Option<String> = "label"
 18    ],
 19    children: [
 20        /// The value returned to the server when selecting this option.
 21        value: Required<String> = ("value", DATA_FORMS) => String
 22    ]
 23);
 24
 25generate_attribute!(
 26    /// The type of a [field](struct.Field.html) element.
 27    FieldType, "type", {
 28        /// This field can only take the values "0" or "false" for a false
 29        /// value, and "1" or "true" for a true value.
 30        Boolean => "boolean",
 31
 32        /// This field describes data, it must not be sent back to the
 33        /// requester.
 34        Fixed => "fixed",
 35
 36        /// This field is hidden, it should not be displayed to the user but
 37        /// should be sent back to the requester.
 38        Hidden => "hidden",
 39
 40        /// This field accepts one or more [JIDs](../../jid/struct.Jid.html).
 41        /// A client may want to let the user autocomplete them based on their
 42        /// contacts list for instance.
 43        JidMulti => "jid-multi",
 44
 45        /// This field accepts one [JID](../../jid/struct.Jid.html).  A client
 46        /// may want to let the user autocomplete it based on their contacts
 47        /// list for instance.
 48        JidSingle => "jid-single",
 49
 50        /// This field accepts one or more values from the list provided as
 51        /// [options](struct.Option_.html).
 52        ListMulti => "list-multi",
 53
 54        /// This field accepts one value from the list provided as
 55        /// [options](struct.Option_.html).
 56        ListSingle => "list-single",
 57
 58        /// This field accepts one or more free form text lines.
 59        TextMulti => "text-multi",
 60
 61        /// This field accepts one free form password, a client should hide it
 62        /// in its user interface.
 63        TextPrivate => "text-private",
 64
 65        /// This field accepts one free form text line.
 66        TextSingle => "text-single",
 67    }, Default = TextSingle
 68);
 69
 70/// Represents a field in a [data form](struct.DataForm.html).
 71#[derive(Debug, Clone, PartialEq)]
 72pub struct Field {
 73    /// The unique identifier for this field, in the form.
 74    pub var: String,
 75
 76    /// The type of this field.
 77    pub type_: FieldType,
 78
 79    /// The label to be possibly displayed to the user for this field.
 80    pub label: Option<String>,
 81
 82    /// The form will be rejected if this field isn’t present.
 83    pub required: bool,
 84
 85    /// A list of allowed values.
 86    pub options: Vec<Option_>,
 87
 88    /// The values provided for this field.
 89    pub values: Vec<String>,
 90
 91    /// A list of media related to this field.
 92    pub media: Vec<MediaElement>,
 93}
 94
 95impl Field {
 96    /// Create a new Field, of the given var and type.
 97    pub fn new(var: &str, type_: FieldType) -> Field {
 98        Field {
 99            var: String::from(var),
100            type_,
101            label: None,
102            required: false,
103            options: Vec::new(),
104            media: Vec::new(),
105            values: Vec::new(),
106        }
107    }
108
109    /// Set only one value in this Field.
110    pub fn with_value(mut self, value: &str) -> Field {
111        self.values.push(String::from(value));
112        self
113    }
114
115    /// Create a text-single Field with the given var and unique value.
116    pub fn text_single(var: &str, value: &str) -> Field {
117        Field::new(var, FieldType::TextSingle).with_value(value)
118    }
119
120    fn is_list(&self) -> bool {
121        self.type_ == FieldType::ListSingle || self.type_ == FieldType::ListMulti
122    }
123
124    /// Return true if this field is a valid form type specifier as per
125    /// [XEP-0068](https://xmpp.org/extensions/xep-0068.html).
126    ///
127    /// This function requires knowledge of the form's type attribute as the
128    /// criteria differ slightly among form types.
129    pub fn is_form_type(&self, ty: &DataFormType) -> bool {
130        // 1. A field must have the var FORM_TYPE
131        if self.var != "FORM_TYPE" {
132            return false;
133        }
134
135        match ty {
136            // https://xmpp.org/extensions/xep-0068.html#usecases-incorrect
137            // > If the FORM_TYPE field is not hidden in a form with
138            // > type="form" or type="result", it MUST be ignored as a context
139            // > indicator.
140            DataFormType::Form | DataFormType::Result_ => self.type_ == FieldType::Hidden,
141
142            // https://xmpp.org/extensions/xep-0068.html#impl
143            // > Data forms with the type "submit" are free to omit any
144            // > explicit field type declaration (as per Data Forms (XEP-0004)
145            // > § 3.2), as the type is implied by the corresponding
146            // > "form"-type data form. As consequence, implementations MUST
147            // > treat a FORM_TYPE field without an explicit type attribute,
148            // > in data forms of type "submit", as the FORM_TYPE field with
149            // > the special meaning defined herein.
150            DataFormType::Submit => match self.type_ {
151                FieldType::Hidden => true,
152                FieldType::TextSingle => true,
153                _ => false,
154            },
155
156            // XEP-0068 does not explicitly mention cancel type forms.
157            // However, XEP-0004 states:
158            // > a data form of type "cancel" SHOULD NOT contain any <field/>
159            // > elements.
160            // thus we ignore those.
161            DataFormType::Cancel => false,
162        }
163    }
164}
165
166impl TryFrom<Element> for Field {
167    type Error = Error;
168
169    fn try_from(elem: Element) -> Result<Field, Error> {
170        check_self!(elem, "field", DATA_FORMS);
171        check_no_unknown_attributes!(elem, "field", ["label", "type", "var"]);
172        let mut field = Field {
173            var: get_attr!(elem, "var", Required),
174            type_: get_attr!(elem, "type", Default),
175            label: get_attr!(elem, "label", Option),
176            required: false,
177            options: vec![],
178            values: vec![],
179            media: vec![],
180        };
181        for element in elem.children() {
182            if element.is("value", ns::DATA_FORMS) {
183                check_no_children!(element, "value");
184                check_no_attributes!(element, "value");
185                field.values.push(element.text());
186            } else if element.is("required", ns::DATA_FORMS) {
187                if field.required {
188                    return Err(Error::ParseError("More than one required element."));
189                }
190                check_no_children!(element, "required");
191                check_no_attributes!(element, "required");
192                field.required = true;
193            } else if element.is("option", ns::DATA_FORMS) {
194                if !field.is_list() {
195                    return Err(Error::ParseError("Option element found in non-list field."));
196                }
197                let option = Option_::try_from(element.clone())?;
198                field.options.push(option);
199            } else if element.is("media", ns::MEDIA_ELEMENT) {
200                let media_element = MediaElement::try_from(element.clone())?;
201                field.media.push(media_element);
202            } else {
203                return Err(Error::ParseError(
204                    "Field child isn’t a value, option or media element.",
205                ));
206            }
207        }
208        Ok(field)
209    }
210}
211
212impl From<Field> for Element {
213    fn from(field: Field) -> Element {
214        Element::builder("field", ns::DATA_FORMS)
215            .attr("var", field.var)
216            .attr("type", field.type_)
217            .attr("label", field.label)
218            .append_all(if field.required {
219                Some(Element::builder("required", ns::DATA_FORMS))
220            } else {
221                None
222            })
223            .append_all(field.options.iter().cloned().map(Element::from))
224            .append_all(
225                field
226                    .values
227                    .into_iter()
228                    .map(|value| Element::builder("value", ns::DATA_FORMS).append(value)),
229            )
230            .append_all(field.media.iter().cloned().map(Element::from))
231            .build()
232    }
233}
234
235generate_attribute!(
236    /// Represents the type of a [data form](struct.DataForm.html).
237    DataFormType, "type", {
238        /// This is a cancel request for a prior type="form" data form.
239        Cancel => "cancel",
240
241        /// This is a request for the recipient to fill this form and send it
242        /// back as type="submit".
243        Form => "form",
244
245        /// This is a result form, which contains what the requester asked for.
246        Result_ => "result",
247
248        /// This is a complete response to a form received before.
249        Submit => "submit",
250    }
251);
252
253/// This is a form to be sent to another entity for filling.
254#[derive(Debug, Clone, PartialEq)]
255pub struct DataForm {
256    /// The type of this form, telling the other party which action to execute.
257    pub type_: DataFormType,
258
259    /// An easy accessor for the FORM_TYPE of this form, see
260    /// [XEP-0068](https://xmpp.org/extensions/xep-0068.html) for more
261    /// information.
262    pub form_type: Option<String>,
263
264    /// The title of this form.
265    pub title: Option<String>,
266
267    /// The instructions given with this form.
268    pub instructions: Option<String>,
269
270    /// A list of fields comprising this form.
271    pub fields: Vec<Field>,
272}
273
274impl DataForm {
275    /// Create a new DataForm.
276    pub fn new(type_: DataFormType, form_type: &str, fields: Vec<Field>) -> DataForm {
277        DataForm {
278            type_,
279            form_type: Some(String::from(form_type)),
280            title: None,
281            instructions: None,
282            fields,
283        }
284    }
285}
286
287impl TryFrom<Element> for DataForm {
288    type Error = Error;
289
290    fn try_from(elem: Element) -> Result<DataForm, Error> {
291        check_self!(elem, "x", DATA_FORMS);
292        check_no_unknown_attributes!(elem, "x", ["type"]);
293        let type_ = get_attr!(elem, "type", Required);
294        let mut form = DataForm {
295            type_,
296            form_type: None,
297            title: None,
298            instructions: None,
299            fields: vec![],
300        };
301        for child in elem.children() {
302            if child.is("title", ns::DATA_FORMS) {
303                if form.title.is_some() {
304                    return Err(Error::ParseError("More than one title in form element."));
305                }
306                check_no_children!(child, "title");
307                check_no_attributes!(child, "title");
308                form.title = Some(child.text());
309            } else if child.is("instructions", ns::DATA_FORMS) {
310                if form.instructions.is_some() {
311                    return Err(Error::ParseError(
312                        "More than one instructions in form element.",
313                    ));
314                }
315                check_no_children!(child, "instructions");
316                check_no_attributes!(child, "instructions");
317                form.instructions = Some(child.text());
318            } else if child.is("field", ns::DATA_FORMS) {
319                let field = Field::try_from(child.clone())?;
320                if field.is_form_type(&form.type_) {
321                    let mut field = field;
322                    if form.form_type.is_some() {
323                        return Err(Error::ParseError("More than one FORM_TYPE in a data form."));
324                    }
325                    if field.values.len() != 1 {
326                        return Err(Error::ParseError("Wrong number of values in FORM_TYPE."));
327                    }
328                    form.form_type = field.values.pop();
329                } else {
330                    form.fields.push(field);
331                }
332            } else {
333                return Err(Error::ParseError("Unknown child in data form element."));
334            }
335        }
336        Ok(form)
337    }
338}
339
340impl From<DataForm> for Element {
341    fn from(form: DataForm) -> Element {
342        Element::builder("x", ns::DATA_FORMS)
343            .attr("type", form.type_)
344            .append_all(
345                form.title
346                    .map(|title| Element::builder("title", ns::DATA_FORMS).append(title)),
347            )
348            .append_all(
349                form.instructions
350                    .map(|text| Element::builder("instructions", ns::DATA_FORMS).append(text)),
351            )
352            .append_all(form.form_type.map(|form_type| {
353                Element::builder("field", ns::DATA_FORMS)
354                    .attr("var", "FORM_TYPE")
355                    .attr("type", "hidden")
356                    .append(Element::builder("value", ns::DATA_FORMS).append(form_type))
357            }))
358            .append_all(form.fields.iter().cloned().map(Element::from))
359            .build()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[cfg(target_pointer_width = "32")]
368    #[test]
369    fn test_size() {
370        assert_size!(Option_, 24);
371        assert_size!(FieldType, 1);
372        assert_size!(Field, 64);
373        assert_size!(DataFormType, 1);
374        assert_size!(DataForm, 52);
375    }
376
377    #[cfg(target_pointer_width = "64")]
378    #[test]
379    fn test_size() {
380        assert_size!(Option_, 48);
381        assert_size!(FieldType, 1);
382        assert_size!(Field, 128);
383        assert_size!(DataFormType, 1);
384        assert_size!(DataForm, 104);
385    }
386
387    #[test]
388    fn test_simple() {
389        let elem: Element = "<x xmlns='jabber:x:data' type='result'/>".parse().unwrap();
390        let form = DataForm::try_from(elem).unwrap();
391        assert_eq!(form.type_, DataFormType::Result_);
392        assert!(form.form_type.is_none());
393        assert!(form.fields.is_empty());
394    }
395
396    #[test]
397    fn test_invalid() {
398        let elem: Element = "<x xmlns='jabber:x:data'/>".parse().unwrap();
399        let error = DataForm::try_from(elem).unwrap_err();
400        let message = match error {
401            Error::ParseError(string) => string,
402            _ => panic!(),
403        };
404        assert_eq!(message, "Required attribute 'type' missing.");
405
406        let elem: Element = "<x xmlns='jabber:x:data' type='coucou'/>".parse().unwrap();
407        let error = DataForm::try_from(elem).unwrap_err();
408        let message = match error {
409            Error::ParseError(string) => string,
410            _ => panic!(),
411        };
412        assert_eq!(message, "Unknown value for 'type' attribute.");
413    }
414
415    #[test]
416    fn test_wrong_child() {
417        let elem: Element = "<x xmlns='jabber:x:data' type='cancel'><coucou/></x>"
418            .parse()
419            .unwrap();
420        let error = DataForm::try_from(elem).unwrap_err();
421        let message = match error {
422            Error::ParseError(string) => string,
423            _ => panic!(),
424        };
425        assert_eq!(message, "Unknown child in data form element.");
426    }
427
428    #[test]
429    fn option() {
430        let elem: Element =
431            "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value></option>"
432                .parse()
433                .unwrap();
434        let option = Option_::try_from(elem).unwrap();
435        assert_eq!(&option.label.unwrap(), "Coucou !");
436        assert_eq!(&option.value, "coucou");
437
438        let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'/>"
439            .parse()
440            .unwrap();
441        let error = Option_::try_from(elem).unwrap_err();
442        let message = match error {
443            Error::ParseError(string) => string,
444            _ => panic!(),
445        };
446        assert_eq!(message, "Missing child value in option element.");
447
448        let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value><value>error</value></option>".parse().unwrap();
449        let error = Option_::try_from(elem).unwrap_err();
450        let message = match error {
451            Error::ParseError(string) => string,
452            _ => panic!(),
453        };
454        assert_eq!(
455            message,
456            "Element option must not have more than one value child."
457        );
458    }
459
460    #[test]
461    fn test_ignore_form_type_field_if_field_type_mismatches_in_form_typed_forms() {
462        // https://xmpp.org/extensions/xep-0068.html#usecases-incorrect
463        // […] it MUST be ignored as a context indicator
464        let elem: Element = "<x xmlns='jabber:x:data' type='form'><field var='FORM_TYPE' type='text-single'><value>foo</value></field></x>".parse().unwrap();
465        match DataForm::try_from(elem) {
466            Ok(form) => {
467                match form.form_type {
468                    None => (),
469                    other => panic!("unexpected extracted form type: {:?}", other),
470                };
471            }
472            other => panic!("unexpected result: {:?}", other),
473        }
474    }
475
476    #[test]
477    fn test_ignore_form_type_field_if_field_type_mismatches_in_result_typed_forms() {
478        // https://xmpp.org/extensions/xep-0068.html#usecases-incorrect
479        // […] it MUST be ignored as a context indicator
480        let elem: Element = "<x xmlns='jabber:x:data' type='result'><field var='FORM_TYPE' type='text-single'><value>foo</value></field></x>".parse().unwrap();
481        match DataForm::try_from(elem) {
482            Ok(form) => {
483                match form.form_type {
484                    None => (),
485                    other => panic!("unexpected extracted form type: {:?}", other),
486                };
487            }
488            other => panic!("unexpected result: {:?}", other),
489        }
490    }
491
492    #[test]
493    fn test_accept_form_type_field_without_type_attribute_in_submit_typed_forms() {
494        let elem: Element = "<x xmlns='jabber:x:data' type='submit'><field var='FORM_TYPE'><value>foo</value></field></x>".parse().unwrap();
495        match DataForm::try_from(elem) {
496            Ok(form) => {
497                match form.form_type {
498                    Some(ty) => assert_eq!(ty, "foo"),
499                    other => panic!("unexpected extracted form type: {:?}", other),
500                };
501            }
502            other => panic!("unexpected result: {:?}", other),
503        }
504    }
505
506    #[test]
507    fn test_accept_form_type_field_with_type_hidden_in_submit_typed_forms() {
508        let elem: Element = "<x xmlns='jabber:x:data' type='submit'><field var='FORM_TYPE' type='hidden'><value>foo</value></field></x>".parse().unwrap();
509        match DataForm::try_from(elem) {
510            Ok(form) => {
511                match form.form_type {
512                    Some(ty) => assert_eq!(ty, "foo"),
513                    other => panic!("unexpected extracted form type: {:?}", other),
514                };
515            }
516            other => panic!("unexpected result: {:?}", other),
517        }
518    }
519
520    #[test]
521    fn test_accept_form_type_field_with_type_hidden_in_result_typed_forms() {
522        let elem: Element = "<x xmlns='jabber:x:data' type='result'><field var='FORM_TYPE' type='hidden'><value>foo</value></field></x>".parse().unwrap();
523        match DataForm::try_from(elem) {
524            Ok(form) => {
525                match form.form_type {
526                    Some(ty) => assert_eq!(ty, "foo"),
527                    other => panic!("unexpected extracted form type: {:?}", other),
528                };
529            }
530            other => panic!("unexpected result: {:?}", other),
531        }
532    }
533
534    #[test]
535    fn test_accept_form_type_field_with_type_hidden_in_form_typed_forms() {
536        let elem: Element = "<x xmlns='jabber:x:data' type='form'><field var='FORM_TYPE' type='hidden'><value>foo</value></field></x>".parse().unwrap();
537        match DataForm::try_from(elem) {
538            Ok(form) => {
539                match form.form_type {
540                    Some(ty) => assert_eq!(ty, "foo"),
541                    other => panic!("unexpected extracted form type: {:?}", other),
542                };
543            }
544            other => panic!("unexpected result: {:?}", other),
545        }
546    }
547}