From 7649ad84a14aaf920f6ac9facbbdbb5787f41a25 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Dec 2023 17:14:49 -0600 Subject: [PATCH] allow asset handlers to read the whole request --- packages/desktop/src/lib.rs | 2 +- packages/desktop/src/protocol.rs | 76 +++++++++++++++++++++++++------- packages/desktop/src/webview.rs | 2 +- 3 files changed, 61 insertions(+), 19 deletions(-) diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 515c26009..18739aeda 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -32,7 +32,7 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; -pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetResponse}; +pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetRequest, AssetResponse}; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index cb21245f8..31930da50 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -3,8 +3,8 @@ use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS}; use slab::Slab; use std::{ borrow::Cow, - collections::HashMap, future::Future, + ops::{Deref, DerefMut}, path::{Path, PathBuf}, pin::Pin, rc::Rc, @@ -72,13 +72,57 @@ pub type AssetResponse = Response>; pub trait AssetFuture: Future> + Send + Sync + 'static {} impl> + Send + Sync + 'static> AssetFuture for T {} -/// A handler that takes an asset [`Path`] and returns a future that loads the path. +/// A request for an asset. This is a wrapper around [`Request>`] that provides methods specific to asset requests. +pub struct AssetRequest { + path: PathBuf, + request: Request>, +} + +impl AssetRequest { + /// Get the path the asset request is for + pub fn path(&self) -> &Path { + &self.path + } +} + +impl From>> for AssetRequest { + fn from(request: Request>) -> Self { + let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/')) + .expect("expected URL to be UTF-8 encoded"); + let path = PathBuf::from(&*decoded); + Self { request, path } + } +} + +impl Deref for AssetRequest { + type Target = Request>; + + fn deref(&self) -> &Self::Target { + &self.request + } +} + +impl DerefMut for AssetRequest { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.request + } +} + +/// A handler that takes an [`AssetRequest`] and returns a future that either loads the asset, or returns `None`. /// This handler is stashed indefinitely in a context object, so it must be `'static`. -pub trait AssetHandler: Fn(&Path) -> F + Send + Sync + 'static {} -impl F + Send + Sync + 'static> AssetHandler for T {} +pub trait AssetHandler: Send + Sync + 'static { + /// Handle an asset request, returning a future that either loads the asset, or returns `None` + fn handle_request(&self, request: &AssetRequest) -> F; +} + +impl F + Send + Sync + 'static> AssetHandler for T { + fn handle_request(&self, request: &AssetRequest) -> F { + self(request) + } +} type AssetHandlerRegistryInner = - Slab Pin> + Send + Sync + 'static>>; + Slab Pin> + Send + Sync + 'static>>; #[derive(Clone)] pub struct AssetHandlerRegistry(Arc>); @@ -90,7 +134,7 @@ impl AssetHandlerRegistry { pub async fn register_handler(&self, f: impl AssetHandler) -> usize { let mut registry = self.0.write().await; - registry.insert(Box::new(move |path| Box::pin(f(path)))) + registry.insert(Box::new(move |req| Box::pin(f.handle_request(req)))) } pub async fn remove_handler(&self, id: usize) -> Option<()> { @@ -98,10 +142,10 @@ impl AssetHandlerRegistry { registry.try_remove(id).map(|_| ()) } - pub async fn try_handlers(&self, path: &Path) -> Option { + pub async fn try_handlers(&self, req: &AssetRequest) -> Option { let registry = self.0.read().await; for (_, handler) in registry.iter() { - if let Some(response) = handler(path).await { + if let Some(response) = handler(req).await { return Some(response); } } @@ -164,12 +208,14 @@ pub fn use_asset_handler( } pub(super) async fn desktop_handler( - request: &Request>, + request: Request>, custom_head: Option, custom_index: Option, root_name: &str, asset_handlers: &AssetHandlerRegistry, ) -> Result { + let request = AssetRequest::from(request); + // If the request is for the root, we'll serve the index.html file. if request.uri().path() == "/" { // If a custom index is provided, just defer to that, expecting the user to know what they're doing. @@ -204,25 +250,21 @@ pub(super) async fn desktop_handler( .map_err(From::from); } - // Else, try to serve a file from the filesystem. - let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/')) - .expect("expected URL to be UTF-8 encoded"); - let path = PathBuf::from(&*decoded); - // If the user provided a custom asset handler, then call it and return the response // if the request was handled. - if let Some(response) = asset_handlers.try_handlers(&path).await { + if let Some(response) = asset_handlers.try_handlers(&request).await { return Ok(response); } // Else, try to serve a file from the filesystem. + // If the path is relative, we'll try to serve it from the assets directory. let mut asset = get_asset_root() .unwrap_or_else(|| Path::new(".").to_path_buf()) - .join(&path); + .join(&request.path); if !asset.exists() { - asset = PathBuf::from("/").join(path); + asset = PathBuf::from("/").join(request.path); } if asset.exists() { diff --git a/packages/desktop/src/webview.rs b/packages/desktop/src/webview.rs index 1b13216c7..0294d3460 100644 --- a/packages/desktop/src/webview.rs +++ b/packages/desktop/src/webview.rs @@ -54,7 +54,7 @@ pub fn build( let asset_handlers_ref = asset_handlers_ref.clone(); tokio::spawn(async move { let response_res = protocol::desktop_handler( - &request, + request, custom_head.clone(), index_file.clone(), &root_name,