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