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::util::error::Error;
8use crate::media_element::MediaElement;
9use crate::ns;
10use minidom::{Element, Node};
11use std::convert::TryFrom;
12
13generate_element!(
14 /// Represents one of the possible values for a list- field.
15 Option_, "option", DATA_FORMS,
16 attributes: [
17 /// The optional label to be displayed to the user for this option.
18 label: Option<String> = "label"
19 ],
20 children: [
21 /// The value returned to the server when selecting this option.
22 value: Required<String> = ("value", DATA_FORMS) => String
23 ]
24);
25
26generate_attribute!(
27 /// The type of a [field](struct.Field.html) element.
28 FieldType, "type", {
29 /// This field can only take the values "0" or "false" for a false
30 /// value, and "1" or "true" for a true value.
31 Boolean => "boolean",
32
33 /// This field describes data, it must not be sent back to the
34 /// requester.
35 Fixed => "fixed",
36
37 /// This field is hidden, it should not be displayed to the user but
38 /// should be sent back to the requester.
39 Hidden => "hidden",
40
41 /// This field accepts one or more [JIDs](../../jid/struct.Jid.html).
42 /// A client may want to let the user autocomplete them based on their
43 /// contacts list for instance.
44 JidMulti => "jid-multi",
45
46 /// This field accepts one [JID](../../jid/struct.Jid.html). A client
47 /// may want to let the user autocomplete it based on their contacts
48 /// list for instance.
49 JidSingle => "jid-single",
50
51 /// This field accepts one or more values from the list provided as
52 /// [options](struct.Option_.html).
53 ListMulti => "list-multi",
54
55 /// This field accepts one value from the list provided as
56 /// [options](struct.Option_.html).
57 ListSingle => "list-single",
58
59 /// This field accepts one or more free form text lines.
60 TextMulti => "text-multi",
61
62 /// This field accepts one free form password, a client should hide it
63 /// in its user interface.
64 TextPrivate => "text-private",
65
66 /// This field accepts one free form text line.
67 TextSingle => "text-single",
68 }, Default = TextSingle
69);
70
71/// Represents a field in a [data form](struct.DataForm.html).
72#[derive(Debug, Clone)]
73pub struct Field {
74 /// The unique identifier for this field, in the form.
75 pub var: String,
76
77 /// The type of this field.
78 pub type_: FieldType,
79
80 /// The label to be possibly displayed to the user for this field.
81 pub label: Option<String>,
82
83 /// The form will be rejected if this field isn’t present.
84 pub required: bool,
85
86 /// A list of allowed values.
87 pub options: Vec<Option_>,
88
89 /// The values provided for this field.
90 pub values: Vec<String>,
91
92 /// A list of media related to this field.
93 pub media: Vec<MediaElement>,
94}
95
96impl Field {
97 fn is_list(&self) -> bool {
98 self.type_ == FieldType::ListSingle || self.type_ == FieldType::ListMulti
99 }
100}
101
102impl TryFrom<Element> for Field {
103 type Error = Error;
104
105 fn try_from(elem: Element) -> Result<Field, Error> {
106 check_self!(elem, "field", DATA_FORMS);
107 check_no_unknown_attributes!(elem, "field", ["label", "type", "var"]);
108 let mut field = Field {
109 var: get_attr!(elem, "var", Required),
110 type_: get_attr!(elem, "type", Default),
111 label: get_attr!(elem, "label", Option),
112 required: false,
113 options: vec![],
114 values: vec![],
115 media: vec![],
116 };
117 for element in elem.children() {
118 if element.is("value", ns::DATA_FORMS) {
119 check_no_children!(element, "value");
120 check_no_attributes!(element, "value");
121 field.values.push(element.text());
122 } else if element.is("required", ns::DATA_FORMS) {
123 if field.required {
124 return Err(Error::ParseError("More than one required element."));
125 }
126 check_no_children!(element, "required");
127 check_no_attributes!(element, "required");
128 field.required = true;
129 } else if element.is("option", ns::DATA_FORMS) {
130 if !field.is_list() {
131 return Err(Error::ParseError("Option element found in non-list field."));
132 }
133 let option = Option_::try_from(element.clone())?;
134 field.options.push(option);
135 } else if element.is("media", ns::MEDIA_ELEMENT) {
136 let media_element = MediaElement::try_from(element.clone())?;
137 field.media.push(media_element);
138 } else {
139 return Err(Error::ParseError(
140 "Field child isn’t a value, option or media element.",
141 ));
142 }
143 }
144 Ok(field)
145 }
146}
147
148impl From<Field> for Element {
149 fn from(field: Field) -> Element {
150 Element::builder("field")
151 .ns(ns::DATA_FORMS)
152 .attr("var", field.var)
153 .attr("type", field.type_)
154 .attr("label", field.label)
155 .append_all((if field.required {
156 Some(Element::builder("required").ns(ns::DATA_FORMS).build())
157 } else {
158 None
159 }).into_iter())
160 .append_all(field.options.iter().cloned().map(Element::from).map(Node::Element).into_iter())
161 .append_all(
162 field
163 .values
164 .into_iter()
165 .map(|value| {
166 Element::builder("value")
167 .ns(ns::DATA_FORMS)
168 .append(value)
169 .build()
170 })
171 )
172 .append_all(field.media.iter().cloned().map(Element::from).map(Node::Element))
173 .build()
174 }
175}
176
177generate_attribute!(
178 /// Represents the type of a [data form](struct.DataForm.html).
179 DataFormType, "type", {
180 /// This is a cancel request for a prior type="form" data form.
181 Cancel => "cancel",
182
183 /// This is a request for the recipient to fill this form and send it
184 /// back as type="submit".
185 Form => "form",
186
187 /// This is a result form, which contains what the requester asked for.
188 Result_ => "result",
189
190 /// This is a complete response to a form received before.
191 Submit => "submit",
192 }
193);
194
195/// This is a form to be sent to another entity for filling.
196#[derive(Debug, Clone)]
197pub struct DataForm {
198 /// The type of this form, telling the other party which action to execute.
199 pub type_: DataFormType,
200
201 /// An easy accessor for the FORM_TYPE of this form, see
202 /// [XEP-0068](https://xmpp.org/extensions/xep-0068.html) for more
203 /// information.
204 pub form_type: Option<String>,
205
206 /// The title of this form.
207 pub title: Option<String>,
208
209 /// The instructions given with this form.
210 pub instructions: Option<String>,
211
212 /// A list of fields comprising this form.
213 pub fields: Vec<Field>,
214}
215
216impl TryFrom<Element> for DataForm {
217 type Error = Error;
218
219 fn try_from(elem: Element) -> Result<DataForm, Error> {
220 check_self!(elem, "x", DATA_FORMS);
221 check_no_unknown_attributes!(elem, "x", ["type"]);
222 let type_ = get_attr!(elem, "type", Required);
223 let mut form = DataForm {
224 type_,
225 form_type: None,
226 title: None,
227 instructions: None,
228 fields: vec![],
229 };
230 for child in elem.children() {
231 if child.is("title", ns::DATA_FORMS) {
232 if form.title.is_some() {
233 return Err(Error::ParseError("More than one title in form element."));
234 }
235 check_no_children!(child, "title");
236 check_no_attributes!(child, "title");
237 form.title = Some(child.text());
238 } else if child.is("instructions", ns::DATA_FORMS) {
239 if form.instructions.is_some() {
240 return Err(Error::ParseError(
241 "More than one instructions in form element.",
242 ));
243 }
244 check_no_children!(child, "instructions");
245 check_no_attributes!(child, "instructions");
246 form.instructions = Some(child.text());
247 } else if child.is("field", ns::DATA_FORMS) {
248 let field = Field::try_from(child.clone())?;
249 if field.var == "FORM_TYPE" {
250 let mut field = field;
251 if form.form_type.is_some() {
252 return Err(Error::ParseError("More than one FORM_TYPE in a data form."));
253 }
254 if field.type_ != FieldType::Hidden {
255 return Err(Error::ParseError("Invalid field type for FORM_TYPE."));
256 }
257 if field.values.len() != 1 {
258 return Err(Error::ParseError("Wrong number of values in FORM_TYPE."));
259 }
260 form.form_type = field.values.pop();
261 } else {
262 form.fields.push(field);
263 }
264 } else {
265 return Err(Error::ParseError("Unknown child in data form element."));
266 }
267 }
268 Ok(form)
269 }
270}
271
272impl From<DataForm> for Element {
273 fn from(form: DataForm) -> Element {
274 Element::builder("x")
275 .ns(ns::DATA_FORMS)
276 .attr("type", form.type_)
277 .append_all(
278 form.title
279 .map(|title| Element::builder("title").ns(ns::DATA_FORMS).append(title)),
280 )
281 .append_all(form.instructions.map(|text| {
282 Element::builder("instructions")
283 .ns(ns::DATA_FORMS)
284 .append(text)
285 }))
286 .append_all((if let Some(form_type) = form.form_type {
287 vec![Element::builder("field").ns(ns::DATA_FORMS).attr("var", "FORM_TYPE").attr("type", "hidden").append(Element::builder("value").ns(ns::DATA_FORMS).append(form_type).build()).build()]
288 } else {
289 vec![]
290 }).into_iter())
291 .append_all(form.fields.iter().cloned().map(Element::from).map(Node::Element))
292 .build()
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[cfg(target_pointer_width = "32")]
301 #[test]
302 fn test_size() {
303 assert_size!(Option_, 24);
304 assert_size!(FieldType, 1);
305 assert_size!(Field, 64);
306 assert_size!(DataFormType, 1);
307 assert_size!(DataForm, 52);
308 }
309
310 #[cfg(target_pointer_width = "64")]
311 #[test]
312 fn test_size() {
313 assert_size!(Option_, 48);
314 assert_size!(FieldType, 1);
315 assert_size!(Field, 128);
316 assert_size!(DataFormType, 1);
317 assert_size!(DataForm, 104);
318 }
319
320 #[test]
321 fn test_simple() {
322 let elem: Element = "<x xmlns='jabber:x:data' type='result'/>".parse().unwrap();
323 let form = DataForm::try_from(elem).unwrap();
324 assert_eq!(form.type_, DataFormType::Result_);
325 assert!(form.form_type.is_none());
326 assert!(form.fields.is_empty());
327 }
328
329 #[test]
330 fn test_invalid() {
331 let elem: Element = "<x xmlns='jabber:x:data'/>".parse().unwrap();
332 let error = DataForm::try_from(elem).unwrap_err();
333 let message = match error {
334 Error::ParseError(string) => string,
335 _ => panic!(),
336 };
337 assert_eq!(message, "Required attribute 'type' missing.");
338
339 let elem: Element = "<x xmlns='jabber:x:data' type='coucou'/>".parse().unwrap();
340 let error = DataForm::try_from(elem).unwrap_err();
341 let message = match error {
342 Error::ParseError(string) => string,
343 _ => panic!(),
344 };
345 assert_eq!(message, "Unknown value for 'type' attribute.");
346 }
347
348 #[test]
349 fn test_wrong_child() {
350 let elem: Element = "<x xmlns='jabber:x:data' type='cancel'><coucou/></x>"
351 .parse()
352 .unwrap();
353 let error = DataForm::try_from(elem).unwrap_err();
354 let message = match error {
355 Error::ParseError(string) => string,
356 _ => panic!(),
357 };
358 assert_eq!(message, "Unknown child in data form element.");
359 }
360
361 #[test]
362 fn option() {
363 let elem: Element =
364 "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value></option>"
365 .parse()
366 .unwrap();
367 let option = Option_::try_from(elem).unwrap();
368 assert_eq!(&option.label.unwrap(), "Coucou !");
369 assert_eq!(&option.value, "coucou");
370
371 let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'/>"
372 .parse()
373 .unwrap();
374 let error = Option_::try_from(elem).unwrap_err();
375 let message = match error {
376 Error::ParseError(string) => string,
377 _ => panic!(),
378 };
379 assert_eq!(message, "Missing child value in option element.");
380
381 let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value><value>error</value></option>".parse().unwrap();
382 let error = Option_::try_from(elem).unwrap_err();
383 let message = match error {
384 Error::ParseError(string) => string,
385 _ => panic!(),
386 };
387 assert_eq!(
388 message,
389 "Element option must not have more than one value child."
390 );
391 }
392}