1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
|
// use quick_xml::events::BytesDecl;
pub mod bind;
pub mod iq;
pub mod sasl;
pub mod stream;
use std::collections::BTreeMap;
use std::str;
// const DECLARATION: BytesDecl<'_> = BytesDecl::new("1.0", None, None);
use async_recursion::async_recursion;
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::{Reader, Writer};
use tokio::io::{AsyncBufRead, AsyncWrite};
use crate::{JabberError, Result};
// #[derive(Clone, Debug)]
// pub struct EventTree<'e> {
// pub event: Event<'e>,
// pub children: Option<Vec<Element<'e>>>,
// }
pub type Prefix<'s> = Option<&'s str>;
#[derive(Clone, Debug)]
/// represents an xml element as a tree of nodes
pub struct Element<'s> {
/// element prefix
/// e.g. `foo` in `<foo:bar />`.
prefix: Option<&'s str>,
/// element name
/// e.g. `bar` in `<foo:bar />`.
localname: &'s str,
/// qualifying namespace
/// an element must be qualified by a namespace
/// e.g. for `<stream:features>` in
/// ```
/// <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>
/// <stream:features>
/// <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>
/// <compression xmlns='http://jabber.org/features/compress'>
/// <method>zlib</method>
/// <method>lzw</method>
/// </compression>
/// </stream:features>
/// </stream:stream>
/// ```
/// would be `"http://etherx.jabber.org/streams"` but for
/// ```
/// <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>
/// <features>
/// <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>
/// <compression xmlns='http://jabber.org/features/compress'>
/// <method>zlib</method>
/// <method>lzw</method>
/// </compression>
/// </features>
/// </stream:stream>
/// ```
/// would be `"jabber:client"`
namespace: &'s str,
/// all namespaces applied to element
/// e.g. for `<bind>` in
/// ```
/// <stream:features xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>
/// <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>
/// <compression xmlns='http://jabber.org/features/compress'>
/// <method>zlib</method>
/// <method>lzw</method>
/// </compression>
/// </stream:features>
/// ```
/// would be `[(None, "urn:ietf:params:xml:ns:xmpp-bind")]` despite
/// `(Some("stream"), "http://etherx.jabber.org/streams")` also being available
namespace_declarations: Box<BTreeMap<Option<&'s str>, &'s str>>,
/// element attributes
attributes: Box<BTreeMap<&'s str, &'s str>>,
// children elements namespaces contain their parents' namespaces
children: Box<Vec<Node<'s>>>,
}
#[derive(Clone, Debug)]
pub enum Node<'s> {
Element(Element<'s>),
Text(&'s str),
}
impl<'s> From<&Node<'s>> for Vec<Event<'s>> {
fn from(node: &Node<'s>) -> Self {
match node {
Node::Element(e) => e.into(),
Node::Text(t) => vec![Event::Text(BytesText::new(t))],
}
}
}
impl<'s> Element<'s> {
/// returns the fully qualified name
/// e.g. `foo:bar` in
/// `<foo:bar>`.
pub fn name(&self) -> &str {
if let Some(prefix) = self.prefix {
format!("{}:{}", prefix, self.localname).as_str()
} else {
self.localname
}
}
/// returns the localname.
/// e.g. `bar` in `<foo:bar>`
pub fn localname(&self) -> &str {
self.localname
}
/// returns the prefix.
/// e.g. `foo` in `<foo:bar>`. returns None if there is
/// no prefix.
pub fn prefix(&self) -> Option<&str> {
self.prefix
}
/// returns the namespace which applies to the current element, e.g. for
/// `<element xmlns='foo' xmlns:bar='bar'>`
/// it will be `foo` but for
/// `<bar:element xmlns='foo' xmlns:bar='bar'>`
/// it will be `bar`.
pub fn namespace(&self) -> &str {
self.namespace
}
}
impl<'s> From<&Element<'s>> for Vec<Event<'s>> {
fn from(element: &Element<'s>) -> Self {
let name = element.name();
let event = BytesStart::new(name);
// namespace declarations
let namespace_declarations = element.namespace_declarations.iter().map(|declaration| {
let (prefix, namespace) = declaration;
match prefix {
Some(prefix) => return (format!("xmlns:{}", prefix).as_str(), *namespace),
None => return ("xmlns", *namespace),
}
});
let event = event.with_attributes(namespace_declarations);
// attributes
let event = event.with_attributes(element.attributes.into_iter());
match element.children.is_empty() {
true => return vec![Event::Empty(event)],
false => {
return {
let start: Vec<Event<'s>> = vec![Event::Start(event)];
let start_and_content: Vec<Event<'s>> = start
.into_iter()
.chain({
let u = element.children.iter().fold(
Vec::new(),
|acc: Vec<Event<'s>>, child: &Node<'s>| {
acc.into_iter()
.chain(Into::<Vec<Event<'s>>>::into(child).into_iter())
.collect()
},
);
u
})
.collect();
let full: Vec<Event<'s>> = start_and_content
.into_iter()
.chain(vec![Event::End(BytesEnd::new(name))])
.collect();
full
}
}
}
}
}
impl<'s> Element<'s> {
/// if there is only one child in the vec of children, will return that element
pub fn child(&self) -> Result<&Element<'s>> {
if self.children.len() == 1 {
Ok(&self.children[0])
} else {
Err(ElementError::NoChildren.into())
}
}
/// returns reference to children
pub fn children(&self) -> Result<&Vec<Element<'s>>> {
if !self.children.is_empty() {
Ok(&self.children)
} else {
Err(ElementError::NoChildren.into())
}
}
/// returns text content, error if there is none
pub fn content(&self) -> Result<&str> {
for node in *self.children {
match node {
Node::Text(t) => return Ok(t),
_ => {}
}
}
Err(ElementError::NotText)
}
pub async fn write<W: AsyncWrite + Unpin + Send>(&self, writer: &mut Writer<W>) -> Result<()> {
let events: Vec<Event> = self.into();
for event in events {
writer.write_event_async(event).await?
}
Ok(())
}
pub async fn write_start<W: AsyncWrite + Unpin + Send>(
&self,
writer: &mut Writer<W>,
) -> Result<()> {
let mut event = BytesStart::new(self.name());
// namespace declarations
self.namespace_declarations.iter().for_each(|declaration| {
let (prefix, namespace) = declaration;
match prefix {
Some(prefix) => {
event.push_attribute((format!("xmlns:{}", prefix).as_str(), *namespace))
}
None => event.push_attribute(("xmlns", *namespace)),
}
});
// attributes
let event =
event.with_attributes(self.attributes.iter().map(|(attr, value)| (*attr, *value)));
writer.write_event_async(Event::Start(event)).await?;
Ok(())
}
pub async fn write_end<W: AsyncWrite + Unpin + Send>(
&self,
writer: &mut Writer<W>,
) -> Result<()> {
let event = BytesEnd::new(self.name());
writer.write_event_async(Event::End(event)).await?;
Ok(())
}
// pub async fn write_start<W: AsyncWrite + Unpin + Send>(
// &self,
// writer: &mut Writer<W>,
// ) -> Result<(), JabberError> {
// match self.event.as_ref() {
// Event::Start(e) => Ok(writer.write_event_async(Event::Start(e.clone())).await?),
// e => Err(ElementError::NotAStart(e.clone().into_owned()).into()),
// }
// }
// pub async fn write_end<W: AsyncWrite + Unpin + Send>(
// &self,
// writer: &mut Writer<W>,
// ) -> Result<(), JabberError> {
// match self.event.as_ref() {
// Event::Start(e) => Ok(writer
// .write_event_async(Event::End(e.clone().to_end()))
// .await?),
// e => Err(ElementError::NotAStart(e.clone().into_owned()).into()),
// }
// }
#[async_recursion]
pub async fn read<R: AsyncBufRead + Unpin + Send>(
reader: &mut Reader<R>,
local_namespaces: BTreeMap<Option<&str>, &str>,
) -> Result<Self> {
let node = Node::read_recursive(reader, local_namespaces)
.await?
.ok_or(JabberError::UnexpectedEnd)?;
match node {
Node::Element(e) => Ok(e),
Node::Text(_) => Err(JabberError::UnexpectedText),
}
}
}
impl<'s> Node<'s> {
#[async_recursion]
async fn read_recursive<R: AsyncBufRead + Unpin + Send>(
reader: &mut Reader<R>,
local_namespaces: BTreeMap<Option<&str>, &str>,
) -> Result<Option<Node<'s>>> {
let mut buf = Vec::new();
let event = reader.read_event_into_async(&mut buf).await?;
match event {
Event::Start(e) => {
let prefix = e
.name()
.prefix()
.map(|prefix| str::from_utf8(prefix.into_inner())?);
let mut children_vec: Vec = Vec::new();
while let Some(sub_element) = Element::read_recursive(reader).await? {
children_vec.push(sub_element)
}
Ok(Some(Self::Element(Element {
prefix,
localname: e.local_name().into_inner(),
namespace: todo!(),
namespace_declarations: todo!(),
attributes: todo!(),
children: todo!(),
})))
}
Event::End(_) => Ok(None),
Event::Text(e) => Ok(Some(Self::Text(e.unescape()?.as_ref()))),
e => Ok(Some(Self {
event: e.into_owned(),
children: None,
})),
}
}
}
// #[async_recursion]
// pub async fn read_start<R: AsyncBufRead + Unpin + Send>(
// reader: &mut Reader<R>,
// ) -> Result<Self, JabberError> {
// let mut buf = Vec::new();
// let event = reader.read_event_into_async(&mut buf).await?;
// match event {
// Event::Start(e) => {
// return Ok(Self {
// event: Event::Start(e.into_owned()),
// children: None,
// })
// }
// e => Err(ElementError::NotAStart(e.into_owned()).into()),
// }
// }
// pub trait IntoElement<'e> {
// fn event(&self) -> Event<'e>;
// fn children(&self) -> Option<Vec<Element<'e>>>;
// }
// impl<'e, T: IntoElement<'e>> From<T> for Element<'e> {
// fn from(value: T) -> Self {
// Element {
// event: value.event(),
// children: value.children(),
// }
// }
// }
#[derive(Debug)]
pub enum ElementError<'e> {
NotAStart(Event<'e>),
NotText,
NoChildren,
MultipleChildren,
}
|