xmpp_stream.rs

 1//! `XMPPStream` is the common container for all XMPP network connections
 2
 3use futures::sink::Send;
 4use futures::{Poll, Sink, StartSend, Stream};
 5use xmpp_parsers::{Jid, Element};
 6use tokio_codec::Framed;
 7use tokio_io::{AsyncRead, AsyncWrite};
 8
 9use crate::stream_start::StreamStart;
10use crate::xmpp_codec::{Packet, XMPPCodec};
11
12/// <stream:stream> namespace
13pub const NS_XMPP_STREAM: &str = "http://etherx.jabber.org/streams";
14
15/// Wraps a `stream`
16pub struct XMPPStream<S> {
17    /// The local Jabber-Id
18    pub jid: Jid,
19    /// Codec instance
20    pub stream: Framed<S, XMPPCodec>,
21    /// `<stream:features/>` for XMPP version 1.0
22    pub stream_features: Element,
23    /// Root namespace
24    ///
25    /// This is different for either c2s, s2s, or component
26    /// connections.
27    pub ns: String,
28}
29
30impl<S: AsyncRead + AsyncWrite> XMPPStream<S> {
31    /// Constructor
32    pub fn new(
33        jid: Jid,
34        stream: Framed<S, XMPPCodec>,
35        ns: String,
36        stream_features: Element,
37    ) -> Self {
38        XMPPStream {
39            jid,
40            stream,
41            stream_features,
42            ns,
43        }
44    }
45
46    /// Send a `<stream:stream>` start tag
47    pub fn start(stream: S, jid: Jid, ns: String) -> StreamStart<S> {
48        let xmpp_stream = Framed::new(stream, XMPPCodec::new());
49        StreamStart::from_stream(xmpp_stream, jid, ns)
50    }
51
52    /// Unwraps the inner stream
53    pub fn into_inner(self) -> S {
54        self.stream.into_inner()
55    }
56
57    /// Re-run `start()`
58    pub fn restart(self) -> StreamStart<S> {
59        Self::start(self.stream.into_inner(), self.jid, self.ns)
60    }
61}
62
63impl<S: AsyncWrite> XMPPStream<S> {
64    /// Convenience method
65    pub fn send_stanza<E: Into<Element>>(self, e: E) -> Send<Self> {
66        self.send(Packet::Stanza(e.into()))
67    }
68}
69
70/// Proxy to self.stream
71impl<S: AsyncWrite> Sink for XMPPStream<S> {
72    type SinkItem = <Framed<S, XMPPCodec> as Sink>::SinkItem;
73    type SinkError = <Framed<S, XMPPCodec> as Sink>::SinkError;
74
75    fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
76        self.stream.start_send(item)
77    }
78
79    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
80        self.stream.poll_complete()
81    }
82}
83
84/// Proxy to self.stream
85impl<S: AsyncRead> Stream for XMPPStream<S> {
86    type Item = <Framed<S, XMPPCodec> as Stream>::Item;
87    type Error = <Framed<S, XMPPCodec> as Stream>::Error;
88
89    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
90        self.stream.poll()
91    }
92}