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),
// }
}
}
}