feat(core): add asset_resolver API (#2879)

This commit is contained in:
Lucas Fernandes Nogueira 2021-11-12 22:23:54 -03:00 committed by GitHub
parent d13c48f02f
commit 7c6c7adcc4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 100 additions and 59 deletions

View File

@ -0,0 +1,5 @@
---
"tauri": patch
---
Expose the `asset_resolver` API on the `App` and `AppHandle` structs.

View File

@ -8,7 +8,7 @@ pub(crate) mod tray;
use crate::{
command::{CommandArg, CommandItem},
hooks::{InvokeHandler, OnPageLoad, PageLoadPayload, SetupHook},
manager::{CustomProtocol, WindowManager},
manager::{Asset, CustomProtocol, WindowManager},
plugin::{Plugin, PluginStore},
runtime::{
http::{Request as HttpRequest, Response as HttpResponse},
@ -169,6 +169,19 @@ impl PathResolver {
}
}
/// The asset resolver is a helper to access the [`tauri_utils::assets::Assets`] interface.
#[derive(Debug, Clone)]
pub struct AssetResolver<R: Runtime> {
manager: WindowManager<R>,
}
impl<R: Runtime> AssetResolver<R> {
/// Gets the app asset associated with the given path.
pub fn get(&self, path: String) -> Option<Asset> {
self.manager.get_asset(path).ok()
}
}
/// A handle to the currently running application.
///
/// This type implements [`Manager`] which allows for manipulation of global application items.
@ -400,6 +413,13 @@ macro_rules! shared_app_impl {
pub fn package_info(&self) -> &PackageInfo {
self.manager.package_info()
}
/// The application's asset resolver.
pub fn asset_resolver(&self) -> AssetResolver<R> {
AssetResolver {
manager: self.manager.clone(),
}
}
}
};
}

View File

@ -86,11 +86,14 @@ pub use {
self::window::menu::MenuEvent,
};
pub use {
self::app::{App, AppHandle, Builder, CloseRequestApi, Event, GlobalWindowEvent, PathResolver},
self::app::{
App, AppHandle, AssetResolver, Builder, CloseRequestApi, Event, GlobalWindowEvent, PathResolver,
},
self::hooks::{
Invoke, InvokeError, InvokeHandler, InvokeMessage, InvokeResolver, InvokeResponse, OnPageLoad,
PageLoadPayload, SetupHook,
},
self::manager::Asset,
self::runtime::{
webview::{WebviewAttributes, WindowBuilder},
window::{

View File

@ -95,6 +95,14 @@ impl<R: Runtime> fmt::Debug for InnerWindowManager<R> {
}
}
/// A resolved asset.
pub struct Asset {
/// The asset bytes.
pub bytes: Vec<u8>,
/// The asset's mime type.
pub mime_type: String,
}
/// Uses a custom URI scheme handler to resolve file requests
pub struct CustomProtocol<R: Runtime> {
/// Handler for protocol
@ -371,22 +379,8 @@ impl<R: Runtime> WindowManager<R> {
})
}
#[allow(clippy::type_complexity)]
fn prepare_uri_scheme_protocol(
&self,
) -> Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync>
{
let assets = self.inner.assets.clone();
let manager = self.clone();
Box::new(move |request| {
let mut path = request
.uri()
.split(&['?', '#'][..])
// ignore query string
.next()
.unwrap()
.to_string()
.replace("tauri://localhost", "");
pub fn get_asset(&self, mut path: String) -> Result<Asset, Box<dyn std::error::Error>> {
let assets = &self.inner.assets;
if path.ends_with('/') {
path.pop();
}
@ -421,20 +415,18 @@ impl<R: Runtime> WindowManager<R> {
.into_owned()
.replacen(
"__TAURI__INVOKE_KEY_TOKEN__",
&manager.generate_invoke_key().to_string(),
&self.generate_invoke_key().to_string(),
1,
)
.as_bytes()
.to_vec(),
false => asset,
};
let mime_type = MimeType::parse(&final_data, &path);
Ok(
HttpResponseBuilder::new()
.mimetype(&mime_type)
.body(final_data)?,
)
Ok(Asset {
bytes: final_data,
mime_type,
})
}
Err(e) => {
#[cfg(debug_assertions)]
@ -442,6 +434,27 @@ impl<R: Runtime> WindowManager<R> {
Err(Box::new(e))
}
}
}
#[allow(clippy::type_complexity)]
fn prepare_uri_scheme_protocol(
&self,
) -> Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync>
{
let manager = self.clone();
Box::new(move |request| {
let path = request
.uri()
.split(&['?', '#'][..])
// ignore query string
.next()
.unwrap()
.to_string()
.replace("tauri://localhost", "");
let asset = manager.get_asset(path)?;
HttpResponseBuilder::new()
.mimetype(&asset.mime_type)
.body(asset.bytes)
})
}