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
125impl TryFrom<Element> for Field {
126 type Error = Error;
127
128 fn try_from(elem: Element) -> Result<Field, Error> {
129 check_self!(elem, "field", DATA_FORMS);
130 check_no_unknown_attributes!(elem, "field", ["label", "type", "var"]);
131 let mut field = Field {
132 var: get_attr!(elem, "var", Required),
133 type_: get_attr!(elem, "type", Default),
134 label: get_attr!(elem, "label", Option),
135 required: false,
136 options: vec![],
137 values: vec![],
138 media: vec![],
139 };
140 for element in elem.children() {
141 if element.is("value", ns::DATA_FORMS) {
142 check_no_children!(element, "value");
143 check_no_attributes!(element, "value");
144 field.values.push(element.text());
145 } else if element.is("required", ns::DATA_FORMS) {
146 if field.required {
147 return Err(Error::ParseError("More than one required element."));
148 }
149 check_no_children!(element, "required");
150 check_no_attributes!(element, "required");
151 field.required = true;
152 } else if element.is("option", ns::DATA_FORMS) {
153 if !field.is_list() {
154 return Err(Error::ParseError("Option element found in non-list field."));
155 }
156 let option = Option_::try_from(element.clone())?;
157 field.options.push(option);
158 } else if element.is("media", ns::MEDIA_ELEMENT) {
159 let media_element = MediaElement::try_from(element.clone())?;
160 field.media.push(media_element);
161 } else {
162 return Err(Error::ParseError(
163 "Field child isn’t a value, option or media element.",
164 ));
165 }
166 }
167 Ok(field)
168 }
169}
170
171impl From<Field> for Element {
172 fn from(field: Field) -> Element {
173 Element::builder("field", ns::DATA_FORMS)
174 .attr("var", field.var)
175 .attr("type", field.type_)
176 .attr("label", field.label)
177 .append_all(if field.required {
178 Some(Element::builder("required", ns::DATA_FORMS))
179 } else {
180 None
181 })
182 .append_all(field.options.iter().cloned().map(Element::from))
183 .append_all(
184 field
185 .values
186 .into_iter()
187 .map(|value| Element::builder("value", ns::DATA_FORMS).append(value)),
188 )
189 .append_all(field.media.iter().cloned().map(Element::from))
190 .build()
191 }
192}
193
194generate_attribute!(
195 /// Represents the type of a [data form](struct.DataForm.html).
196 DataFormType, "type", {
197 /// This is a cancel request for a prior type="form" data form.
198 Cancel => "cancel",
199
200 /// This is a request for the recipient to fill this form and send it
201 /// back as type="submit".
202 Form => "form",
203
204 /// This is a result form, which contains what the requester asked for.
205 Result_ => "result",
206
207 /// This is a complete response to a form received before.
208 Submit => "submit",
209 }
210);
211
212/// This is a form to be sent to another entity for filling.
213#[derive(Debug, Clone, PartialEq)]
214pub struct DataForm {
215 /// The type of this form, telling the other party which action to execute.
216 pub type_: DataFormType,
217
218 /// An easy accessor for the FORM_TYPE of this form, see
219 /// [XEP-0068](https://xmpp.org/extensions/xep-0068.html) for more
220 /// information.
221 pub form_type: Option<String>,
222
223 /// The title of this form.
224 pub title: Option<String>,
225
226 /// The instructions given with this form.
227 pub instructions: Option<String>,
228
229 /// A list of fields comprising this form.
230 pub fields: Vec<Field>,
231}
232
233impl DataForm {
234 /// Create a new DataForm.
235 pub fn new(type_: DataFormType, form_type: &str, fields: Vec<Field>) -> DataForm {
236 DataForm {
237 type_,
238 form_type: Some(String::from(form_type)),
239 title: None,
240 instructions: None,
241 fields,
242 }
243 }
244}
245
246impl TryFrom<Element> for DataForm {
247 type Error = Error;
248
249 fn try_from(elem: Element) -> Result<DataForm, Error> {
250 check_self!(elem, "x", DATA_FORMS);
251 check_no_unknown_attributes!(elem, "x", ["type"]);
252 let type_ = get_attr!(elem, "type", Required);
253 let mut form = DataForm {
254 type_,
255 form_type: None,
256 title: None,
257 instructions: None,
258 fields: vec![],
259 };
260 for child in elem.children() {
261 if child.is("title", ns::DATA_FORMS) {
262 if form.title.is_some() {
263 return Err(Error::ParseError("More than one title in form element."));
264 }
265 check_no_children!(child, "title");
266 check_no_attributes!(child, "title");
267 form.title = Some(child.text());
268 } else if child.is("instructions", ns::DATA_FORMS) {
269 if form.instructions.is_some() {
270 return Err(Error::ParseError(
271 "More than one instructions in form element.",
272 ));
273 }
274 check_no_children!(child, "instructions");
275 check_no_attributes!(child, "instructions");
276 form.instructions = Some(child.text());
277 } else if child.is("field", ns::DATA_FORMS) {
278 let field = Field::try_from(child.clone())?;
279 if field.var == "FORM_TYPE" {
280 let mut field = field;
281 if form.form_type.is_some() {
282 return Err(Error::ParseError("More than one FORM_TYPE in a data form."));
283 }
284 if field.type_ != FieldType::Hidden {
285 return Err(Error::ParseError("Invalid field type for FORM_TYPE."));
286 }
287 if field.values.len() != 1 {
288 return Err(Error::ParseError("Wrong number of values in FORM_TYPE."));
289 }
290 form.form_type = field.values.pop();
291 } else {
292 form.fields.push(field);
293 }
294 } else {
295 return Err(Error::ParseError("Unknown child in data form element."));
296 }
297 }
298 Ok(form)
299 }
300}
301
302impl From<DataForm> for Element {
303 fn from(form: DataForm) -> Element {
304 Element::builder("x", ns::DATA_FORMS)
305 .attr("type", form.type_)
306 .append_all(
307 form.title
308 .map(|title| Element::builder("title", ns::DATA_FORMS).append(title)),
309 )
310 .append_all(
311 form.instructions
312 .map(|text| Element::builder("instructions", ns::DATA_FORMS).append(text)),
313 )
314 .append_all(form.form_type.map(|form_type| {
315 Element::builder("field", ns::DATA_FORMS)
316 .attr("var", "FORM_TYPE")
317 .attr("type", "hidden")
318 .append(Element::builder("value", ns::DATA_FORMS).append(form_type))
319 }))
320 .append_all(form.fields.iter().cloned().map(Element::from))
321 .build()
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[cfg(target_pointer_width = "32")]
330 #[test]
331 fn test_size() {
332 assert_size!(Option_, 24);
333 assert_size!(FieldType, 1);
334 assert_size!(Field, 64);
335 assert_size!(DataFormType, 1);
336 assert_size!(DataForm, 52);
337 }
338
339 #[cfg(target_pointer_width = "64")]
340 #[test]
341 fn test_size() {
342 assert_size!(Option_, 48);
343 assert_size!(FieldType, 1);
344 assert_size!(Field, 128);
345 assert_size!(DataFormType, 1);
346 assert_size!(DataForm, 104);
347 }
348
349 #[test]
350 fn test_simple() {
351 let elem: Element = "<x xmlns='jabber:x:data' type='result'/>".parse().unwrap();
352 let form = DataForm::try_from(elem).unwrap();
353 assert_eq!(form.type_, DataFormType::Result_);
354 assert!(form.form_type.is_none());
355 assert!(form.fields.is_empty());
356 }
357
358 #[test]
359 fn test_invalid() {
360 let elem: Element = "<x xmlns='jabber:x:data'/>".parse().unwrap();
361 let error = DataForm::try_from(elem).unwrap_err();
362 let message = match error {
363 Error::ParseError(string) => string,
364 _ => panic!(),
365 };
366 assert_eq!(message, "Required attribute 'type' missing.");
367
368 let elem: Element = "<x xmlns='jabber:x:data' type='coucou'/>".parse().unwrap();
369 let error = DataForm::try_from(elem).unwrap_err();
370 let message = match error {
371 Error::ParseError(string) => string,
372 _ => panic!(),
373 };
374 assert_eq!(message, "Unknown value for 'type' attribute.");
375 }
376
377 #[test]
378 fn test_wrong_child() {
379 let elem: Element = "<x xmlns='jabber:x:data' type='cancel'><coucou/></x>"
380 .parse()
381 .unwrap();
382 let error = DataForm::try_from(elem).unwrap_err();
383 let message = match error {
384 Error::ParseError(string) => string,
385 _ => panic!(),
386 };
387 assert_eq!(message, "Unknown child in data form element.");
388 }
389
390 #[test]
391 fn option() {
392 let elem: Element =
393 "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value></option>"
394 .parse()
395 .unwrap();
396 let option = Option_::try_from(elem).unwrap();
397 assert_eq!(&option.label.unwrap(), "Coucou !");
398 assert_eq!(&option.value, "coucou");
399
400 let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'/>"
401 .parse()
402 .unwrap();
403 let error = Option_::try_from(elem).unwrap_err();
404 let message = match error {
405 Error::ParseError(string) => string,
406 _ => panic!(),
407 };
408 assert_eq!(message, "Missing child value in option element.");
409
410 let elem: Element = "<option xmlns='jabber:x:data' label='Coucou !'><value>coucou</value><value>error</value></option>".parse().unwrap();
411 let error = Option_::try_from(elem).unwrap_err();
412 let message = match error {
413 Error::ParseError(string) => string,
414 _ => panic!(),
415 };
416 assert_eq!(
417 message,
418 "Element option must not have more than one value child."
419 );
420 }
421}