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