Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Custom protcol request/response #387

Merged
merged 18 commits into from
Aug 22, 2021
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changes/custom-protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"wry": patch
---

The custom protocol now return a `Request` and expect a `Response`.

- This allow us to get the complete request from the Webview. (Method, GET, POST, PUT etc..)
Read the complete header.

- And allow us to be more flexible in the future without bringing breaking changes.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ target
Cargo.lock
gh-pages
.DS_Store
examples/test_video.mp4
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ serde_json = "1.0"
thiserror = "1.0"
url = "2.2"
tao = { version = "0.5.2", default-features = false, features = [ "serde" ] }
http = "0.2.4"

[dev-dependencies]
anyhow = "1.0.43"
chrono = "0.4.19"
tempfile = "3.2.0"
http-range = "0.1.4"

[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
webkit2gtk = { version = "0.14", features = [ "v2_18" ] }
Expand Down
17 changes: 10 additions & 7 deletions examples/custom_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fn main() -> wry::Result<()> {
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
},
http::ResponseBuilder,
webview::WebViewBuilder,
};

Expand All @@ -22,24 +23,26 @@ fn main() -> wry::Result<()> {

let _webview = WebViewBuilder::new(window)
.unwrap()
.with_custom_protocol("wry".into(), move |requested_asset_path| {
.with_custom_protocol("wry".into(), move |request| {
// Remove url scheme
let path = requested_asset_path.replace("wry://", "");
let path = request.uri().to_string().replace("wry://", "");
// Read the file content from file path
let content = read(canonicalize(&path)?)?;

// Return asset contents and mime types based on file extentions
// If you don't want to do this manually, there are some crates for you.
// Such as `infer` and `mime_guess`.
if path.ends_with(".html") {
Ok((content, String::from("text/html")))
let (data, meta) = if path.ends_with(".html") {
(content, "text/html")
} else if path.ends_with(".js") {
Ok((content, String::from("text/javascript")))
(content, "text/javascript")
} else if path.ends_with(".png") {
Ok((content, String::from("image/png")))
(content, "image/png")
} else {
unimplemented!();
}
};

ResponseBuilder::new(meta).body(data)
})
// tell the webview to load the custom protocol
.with_url("wry://examples/index.html")?
Expand Down
17 changes: 10 additions & 7 deletions examples/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fn main() -> wry::Result<()> {
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
},
http::ResponseBuilder,
webview::WebViewBuilder,
};

Expand All @@ -24,24 +25,26 @@ fn main() -> wry::Result<()> {
.unwrap()
// We still register custom protocol here to show that how the page with http:// origin can
// load them.
.with_custom_protocol("wry".into(), move |requested_asset_path| {
.with_custom_protocol("wry".into(), move |request| {
// Remove url scheme
let path = requested_asset_path.replace("wry://", "");
let path = request.uri().to_string().replace("wry://", "");
// Read the file content from file path
let content = read(canonicalize(&path)?)?;

// Return asset contents and mime types based on file extentions
// If you don't want to do this manually, there are some crates for you.
// Such as `infer` and `mime_guess`.
if path.ends_with(".html") {
Ok((content, String::from("text/html")))
let (data, meta) = if path.ends_with(".html") {
(content, "text/html")
} else if path.ends_with(".js") {
Ok((content, String::from("text/javascript")))
(content, "text/javascript")
} else if path.ends_with(".png") {
Ok((content, String::from("image/png")))
(content, "image/png")
} else {
unimplemented!();
}
};

ResponseBuilder::new(meta).body(data)
})
// tell the webview to load the html string
.with_html(
Expand Down
30 changes: 30 additions & 0 deletions examples/stream.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<video
id="video_source"
style="width: 90vw; height: 90vh"
controls=""
autoplay=""
name="media"
>
<source src="wry://examples/test_video.mp4" type="video/mp4" />
</video>

<script>
(function () {
if (navigator.userAgent.includes("Windows")) {
const video = document.getElementById("video_source");
const sources = video.getElementsByTagName("source");
sources[0].src = "https://wry.examples/test_video.mp4";
video.load();
}
})();
</script>
</body>
</html>
146 changes: 146 additions & 0 deletions examples/stream_file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
use std::process::Stdio;

// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

fn main() -> wry::Result<()> {
use http_range::HttpRange;
use std::{
fs::{canonicalize, File},
io::{Read, Seek, SeekFrom},
path::PathBuf,
process::Command,
};
use wry::{
application::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
},
http::ResponseBuilder,
webview::WebViewBuilder,
};

let video_file = PathBuf::from("examples/test_video.mp4");
let video_url =
"http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4";

if !video_file.exists() {
// Downloading with curl this saves us from adding
// a Rust HTTP client dependency.
println!("Downloading {}", video_url);
let status = Command::new("curl")
.arg("-L")
.arg("-o")
.arg(&video_file)
.arg(video_url)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()
.unwrap();

assert!(status.status.success());
assert!(video_file.exists());
}

let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Hello World")
.build(&event_loop)
.unwrap();

let _webview = WebViewBuilder::new(window)
.unwrap()
.with_custom_protocol("wry".into(), move |request| {
// Remove url scheme
let path = request.uri().to_string().replace("wry://", "");
// Read the file content from file path
let mut content = File::open(canonicalize(&path)?)?;

// Return asset contents and mime types based on file extentions
// If you don't want to do this manually, there are some crates for you.
// Such as `infer` and `mime_guess`.
let mut status_code = 200;
let mut buf = Vec::new();

// guess our mimetype from the path
let mimetype = if path.ends_with(".html") {
"text/html"
} else if path.ends_with(".mp4") {
"video/mp4"
} else {
unimplemented!();
};

// prepare our http response
let mut response = ResponseBuilder::new(mimetype);

// read our range header if it exist, so we can return partial content
if let Some(range) = request.headers().get("range") {
// Get the file size
let file_size = content.metadata().unwrap().len();

// we parse the range header
let range = HttpRange::parse(range.to_str().unwrap(), file_size).unwrap();

// let support only 1 range for now
let first_range = range.first();
if let Some(range) = first_range {
let mut real_length = range.length;

// prevent max_length;
// specially on webview2
if range.length > file_size / 3 {
// max size sent (400ko / request)
// as it's local file system we can afford to read more often
real_length = 1024 * 400;
}

// last byte we are reading, the length of the range include the last byte
// who should be skipped on the header
let last_byte = range.start + real_length - 1;
// partial content
status_code = 206;

response = response.header("Connection", "Keep-Alive");
response = response.header("Accept-Ranges", "bytes");
// we need to overwrite our content length
response = response.header("Content-Length", real_length);
response = response.header(
"Content-Range",
format!("bytes {}-{}/{}", range.start, last_byte, file_size),
);

// seek our file bytes
content.seek(SeekFrom::Start(range.start))?;
content.take(real_length).read_to_end(&mut buf)?;
} else {
content.read_to_end(&mut buf)?;
}
} else {
content.read_to_end(&mut buf)?;
}

response.status(status_code).body(buf)
})
// tell the webview to load the custom protocol
.with_url("wry://examples/stream.html")?
.build()?;

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::NewEvents(StartCause::Init) => println!("Wry application started!"),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => {
#[cfg(target_os = "windows")]
let _ = _webview.resize();
}
}
});
}
5 changes: 3 additions & 2 deletions examples/system_tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ fn main() -> wry::Result<()> {
system_tray::SystemTrayBuilder,
window::{WindowBuilder, WindowId},
},
http::ResponseBuilder,
webview::{WebView, WebViewBuilder},
};

Expand Down Expand Up @@ -129,8 +130,8 @@ fn main() -> wry::Result<()> {

let webview = WebViewBuilder::new(window)
.unwrap()
.with_custom_protocol("wry.dev".into(), move |_uri| {
Ok((index_html.as_bytes().into(), "text/html".into()))
.with_custom_protocol("wry.dev".into(), move |_request| {
ResponseBuilder::new("text/html").body(index_html.as_bytes().into())
})
.with_url("wry.dev://")
.unwrap()
Expand Down
3 changes: 2 additions & 1 deletion examples/system_tray_no_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ fn main() -> wry::Result<()> {
system_tray::SystemTrayBuilder,
window::{WindowBuilder, WindowId},
},
http::ResponseBuilder,
webview::{WebView, WebViewBuilder},
};

Expand Down Expand Up @@ -135,7 +136,7 @@ fn main() -> wry::Result<()> {
let webview = WebViewBuilder::new(window)
.unwrap()
.with_custom_protocol("wry.dev".into(), move |_uri| {
Ok((index_html.as_bytes().into(), "text/html".into()))
ResponseBuilder::new("text/html").body(index_html.as_bytes().into())
})
.with_url("wry.dev://")
.unwrap()
Expand Down
25 changes: 24 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,24 @@ extern crate objc;

use std::sync::mpsc::{RecvError, SendError};

use crate::application::window::BadIcon;
use crate::{
application::window::BadIcon,
shared::http::{
header::{InvalidHeaderName, InvalidHeaderValue},
method::InvalidMethod,
status::InvalidStatusCode,
InvalidUri,
},
};
pub use serde_json::Value;
use url::ParseError;

pub mod application;
pub mod webview;

mod shared;
pub use shared::*;

/// Convenient type alias of Result type for wry.
pub type Result<T> = std::result::Result<T, Error>;

Expand Down Expand Up @@ -155,4 +166,16 @@ pub enum Error {
WebView2Error(#[from] webview2::Error),
#[error("Duplicate custom protocol registered: {0}")]
DuplicateCustomProtocol(String),
#[error("Invalid header name: {0}")]
InvalidHeaderName(#[from] InvalidHeaderName),
#[error("Invalid header value: {0}")]
InvalidHeaderValue(#[from] InvalidHeaderValue),
#[error("Invalid uri: {0}")]
InvalidUri(#[from] InvalidUri),
#[error("Invalid status code: {0}")]
InvalidStatusCode(#[from] InvalidStatusCode),
#[error("Invalid method: {0}")]
InvalidMethod(#[from] InvalidMethod),
#[error("Infallible error, something went really wrong: {0}")]
Infallible(#[from] std::convert::Infallible),
}
11 changes: 11 additions & 0 deletions src/shared/http/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// custom wry types
mod request;
mod response;

// re-expose default http types
pub use http::{header, method, status, uri::InvalidUri, version, Extensions, Uri};

pub use self::{
request::{Builder as RequestBuilder, Request},
response::{Builder as ResponseBuilder, Response},
};
Loading