diff --git a/CHANGELOG.md b/CHANGELOG.md index 466de5c..a3f4048 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ Procedure when bumping the version number: ## Unreleased +### Added +- `euphoxide::connect` + ## v0.1.0 - 2022-10-23 Initial release diff --git a/src/conn.rs b/src/conn.rs index 09a993d..0386be3 100644 --- a/src/conn.rs +++ b/src/conn.rs @@ -14,6 +14,8 @@ use futures::{SinkExt, StreamExt}; use tokio::net::TcpStream; use tokio::sync::mpsc; use tokio::{select, task, time}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::{header, HeaderValue}; use tokio_tungstenite::{tungstenite, MaybeTlsStream, WebSocketStream}; use crate::api::packet::{Command, Packet, ParsedPacket}; @@ -559,3 +561,27 @@ pub fn wrap(ws: WsStream, timeout: Duration) -> (ConnTx, ConnRx) { }; (tx, rx) } + +pub async fn connect( + domain: &str, + room: &str, + human: bool, + cookies: Option, + timeout: Duration, +) -> tungstenite::Result<(ConnTx, ConnRx, Vec)> { + let human = if human { "?h=1" } else { "" }; + let uri = format!("wss://{domain}/room/{room}/ws{human}"); + let mut request = uri.into_client_request().expect("valid request"); + if let Some(cookies) = cookies { + request.headers_mut().append(header::COOKIE, cookies); + } + + let (ws, response) = tokio_tungstenite::connect_async(request).await?; + let (mut parts, ()) = response.into_parts(); + let set_cookies = match parts.headers.entry(header::SET_COOKIE) { + header::Entry::Occupied(entry) => entry.remove_entry_mult().1.collect(), + header::Entry::Vacant(_) => vec![], + }; + let (tx, rx) = wrap(ws, timeout); + Ok((tx, rx, set_cookies)) +} diff --git a/src/lib.rs b/src/lib.rs index 13b417d..eedc91f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,5 +19,5 @@ pub mod conn; mod huehash; mod replies; -pub use conn::wrap; +pub use conn::{connect, wrap}; pub use huehash::nick_hue;