summaryrefslogtreecommitdiffstats
path: root/src/client/encrypted.rs
blob: 898dc23a9e049f955ff77fc7f3e0aca779e3bf0b (plain) (blame)
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
use quick_xml::{
    events::{BytesDecl, Event},
    Reader, Writer,
};
use tokio::io::{BufReader, ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio_native_tls::TlsStream;

use crate::stanza::stream::{Stream, StreamFeature};
use crate::stanza::Element;
use crate::Jabber;
use crate::Result;

pub struct JabberClient<'j> {
    reader: Reader<BufReader<ReadHalf<TlsStream<TcpStream>>>>,
    writer: Writer<WriteHalf<TlsStream<TcpStream>>>,
    jabber: &'j mut Jabber<'j>,
}

impl<'j> JabberClient<'j> {
    pub fn new(
        reader: Reader<BufReader<ReadHalf<TlsStream<TcpStream>>>>,
        writer: Writer<WriteHalf<TlsStream<TcpStream>>>,
        jabber: &'j mut Jabber<'j>,
    ) -> Self {
        Self {
            reader,
            writer,
            jabber,
        }
    }

    pub async fn start_stream(&mut self) -> Result<()> {
        // client to server
        let declaration = BytesDecl::new("1.0", None, None);
        let server = &self.jabber.server.to_owned().try_into()?;
        let stream_element =
            Stream::new_client(&self.jabber.jid, server, None, Some("en".to_string()));
        self.writer
            .write_event_async(Event::Decl(declaration))
            .await;
        let stream_element: Element<'_> = stream_element.into();
        stream_element.write_start(&mut self.writer).await?;
        // server to client
        let mut buf = Vec::new();
        self.reader.read_event_into_async(&mut buf).await?;
        let _stream_response = Element::read_start(&mut self.reader).await?;
        Ok(())
    }

    pub async fn get_features(&mut self) -> Result<Option<Vec<StreamFeature>>> {
        if let Some(features) = Element::read(&mut self.reader).await? {
            Ok(Some(features.try_into()?))
        } else {
            Ok(None)
        }
    }

    pub async fn negotiate(&mut self) -> Result<()> {
        loop {
            println!("loop");
            let features = &self.get_features().await?;
            println!("{:?}", features);
            // match &features[0] {
            //     StreamFeature::Sasl(sasl) => {
            //         println!("{:?}", sasl);
            //         todo!()
            //     }
            //     StreamFeature::Bind => todo!(),
            //     x => println!("{:?}", x),
            // }
        }
    }
}