#![cfg_attr(docsrs, feature(doc_cfg))]
use tauri::plugin::TauriPlugin;
use tauri::webview::PageLoadEvent;
use tauri::{AppHandle, Manager, RunEvent, Runtime, Webview, WindowEvent};
mod commands;
mod error;
mod models;
mod registry;
pub use error::{Error, ErrorPayload, Result};
pub use models::{Access, Args, ClientInfo, Link, Message, State};
pub use registry::{
ACK_TTL, MAX_CLIENTS_PER_WEBVIEW, MAX_PENDING_ACKS_PER_WEBVIEW, MAX_SUBSCRIPTIONS_PER_WEBVIEW,
SocketIo, SubscriptionId,
};
pub use socketio_next;
pub trait SocketIoExt<R: Runtime> {
fn socketio(&self) -> &SocketIo;
}
impl<R: Runtime, T: Manager<R>> SocketIoExt<R> for T {
fn socketio(&self) -> &SocketIo {
self.state::<SocketIo>().inner()
}
}
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new().build()
}
#[derive(Debug, Default)]
pub struct Builder {
allowed: Vec<url::Url>,
}
impl Builder {
pub fn new() -> Self {
Builder::default()
}
pub fn allow_url_prefix(mut self, prefix: impl AsRef<str>) -> Self {
let prefix = prefix.as_ref();
let url = url::Url::parse(prefix)
.unwrap_or_else(|e| panic!("tauri-plugin-socketio: bad URL prefix: {e}"));
self.allowed.push(url);
self
}
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
let allowed = self.allowed;
tauri::plugin::Builder::new("socketio")
.invoke_handler(tauri::generate_handler![
commands::connect,
commands::disconnect,
commands::emit,
commands::emit_with_ack,
commands::ack,
commands::subscribe,
commands::unsubscribe,
commands::list,
commands::state,
commands::link_info,
commands::set_auth,
commands::set_headers,
commands::set_query,
commands::reconnect,
])
.setup(move |app, _api| {
app.manage(SocketIo::with_allowed(allowed));
Ok(())
})
.on_page_load(|webview, payload| page_load(webview, payload.event()))
.on_event(run_event)
.build()
}
}
fn page_load<R: Runtime>(webview: &Webview<R>, event: PageLoadEvent) {
if event == PageLoadEvent::Started {
if let Some(io) = webview.try_state::<SocketIo>() {
io.drop_webview(webview.label());
}
}
}
fn run_event<R: Runtime>(app: &AppHandle<R>, event: &RunEvent) {
if let RunEvent::WindowEvent {
label,
event: WindowEvent::Destroyed,
..
} = event
{
window_destroyed(app, label);
}
}
fn window_destroyed<R: Runtime>(app: &AppHandle<R>, label: &str) {
if let Some(io) = app.try_state::<SocketIo>() {
io.drop_webview(label);
let io = SocketIo::clone(&io);
let label = label.to_owned();
tauri::async_runtime::spawn(async move { io.disconnect_owned(&label).await });
}
}
#[cfg(test)]
mod tests {
use super::*;
use tauri::ipc::{Channel, InvokeResponseBody};
use tauri::test::{mock_builder, mock_context, noop_assets};
#[test]
fn the_hooks_end_the_webview_subscriptions() {
let app = mock_builder()
.plugin(init())
.build(mock_context(noop_assets()))
.unwrap();
let webview = tauri::WebviewWindowBuilder::new(&app, "w", Default::default())
.build()
.unwrap();
let io = app.socketio().clone();
let client = tauri::async_runtime::block_on(io.connect(
"c",
socketio_next::ClientBuilder::new(socketio_next_testing::conformance_server()),
))
.unwrap();
let sub = || {
io.subscribe_with(
"c",
registry::SubscribeArgs {
events: None,
channel: Channel::new(|_: InvokeResponseBody| Ok(())),
webview: Some("w".into()),
},
)
.unwrap()
.0
};
let s = sub();
page_load(webview.as_ref(), PageLoadEvent::Finished);
assert!(io.unsubscribe("c", s), "a finished load keeps it");
let s = sub();
page_load(webview.as_ref(), PageLoadEvent::Started);
assert!(!io.unsubscribe("c", s), "a new page ends it");
let s = sub();
window_destroyed(app.handle(), "w");
assert!(!io.unsubscribe("c", s), "a destroyed window ends it");
tauri::async_runtime::block_on(client.disconnect()).unwrap();
}
}