async_wsocket/
lib.rs

1// Copyright (c) 2022-2024 Yuki Kishimoto
2// Distributed under the MIT software license
3
4//! Async WebSocket
5
6#![forbid(unsafe_code)]
7#![warn(clippy::large_futures)]
8#![cfg_attr(feature = "default", doc = include_str!("../README.md"))]
9
10#[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
11use std::net::SocketAddr;
12#[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16pub use futures_util;
17pub use url::{self, Url};
18
19pub mod message;
20#[cfg(not(target_arch = "wasm32"))]
21pub mod native;
22pub mod prelude;
23mod socket;
24#[cfg(target_arch = "wasm32")]
25pub mod wasm;
26
27pub use self::message::Message;
28#[cfg(not(target_arch = "wasm32"))]
29pub use self::native::Error;
30pub use self::socket::WebSocket;
31#[cfg(target_arch = "wasm32")]
32pub use self::wasm::Error;
33
34#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub enum ConnectionMode {
36    /// Direct
37    #[default]
38    Direct,
39    /// Custom proxy
40    #[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
41    Proxy(SocketAddr),
42    /// Embedded tor client
43    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
44    Tor {
45        /// Path for cache and state data
46        ///
47        /// Mandatory for `android` and `ios` targets!
48        custom_path: Option<PathBuf>,
49    },
50}
51
52impl ConnectionMode {
53    /// Direct connection
54    #[inline]
55    pub fn direct() -> Self {
56        Self::Direct
57    }
58
59    /// Proxy
60    #[inline]
61    #[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
62    pub fn proxy(addr: SocketAddr) -> Self {
63        Self::Proxy(addr)
64    }
65
66    /// Embedded tor client
67    ///
68    /// This not work on `android` and/or `ios` targets.
69    /// Use [`Connection::tor_with_path`] instead.
70    #[inline]
71    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
72    pub fn tor() -> Self {
73        Self::Tor { custom_path: None }
74    }
75
76    /// Embedded tor client
77    ///
78    /// Specify a path where to store data
79    #[inline]
80    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
81    pub fn tor_with_path<P>(data_path: P) -> Self
82    where
83        P: AsRef<Path>,
84    {
85        Self::Tor {
86            custom_path: Some(data_path.as_ref().to_path_buf()),
87        }
88    }
89}
90
91/// Connect
92#[inline]
93pub async fn connect(
94    url: &Url,
95    mode: &ConnectionMode,
96    timeout: Duration,
97) -> Result<WebSocket, Error> {
98    WebSocket::connect(url, mode, timeout).await
99}