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