pub struct Response(_, _, _);
Available on crate feature
http-api
only.Expand description
The HTTP response.
Implementations§
source§impl Response
impl Response
sourcepub fn status(&self) -> StatusCode
pub fn status(&self) -> StatusCode
Get the StatusCode
of this Response.
Examples found in repository?
More examples
src/updater/core.rs (line 550)
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
pub(crate) async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
&self,
pub_key: String,
on_chunk: C,
on_download_finish: D,
) -> Result {
// make sure we can install the update on linux
// We fail here because later we can add more linux support
// actually if we use APPIMAGE, our extract path should already
// be set with our APPIMAGE env variable, we don't need to do
// anything with it yet
#[cfg(target_os = "linux")]
if self.app.state::<Env>().appimage.is_none() {
return Err(Error::UnsupportedLinuxPackage);
}
// set our headers
let mut headers = self.headers.clone();
headers.insert(
"Accept",
HeaderValue::from_str("application/octet-stream").unwrap(),
);
headers.insert(
"User-Agent",
HeaderValue::from_str("tauri/updater").unwrap(),
);
let client = ClientBuilder::new().build()?;
// Create our request
let mut req = HttpRequestBuilder::new("GET", self.download_url.as_str())?.headers(headers);
if let Some(timeout) = self.timeout {
req = req.timeout(timeout);
}
let response = client.send(req).await?;
// make sure it's success
if !response.status().is_success() {
return Err(Error::Network(format!(
"Download request failed with status: {}",
response.status()
)));
}
let content_length: Option<u64> = response
.headers()
.get("Content-Length")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
let mut buffer = Vec::new();
#[cfg(feature = "reqwest-client")]
{
use futures_util::StreamExt;
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
let bytes = chunk.as_ref().to_vec();
on_chunk(bytes.len(), content_length);
buffer.extend(bytes);
}
}
#[cfg(not(feature = "reqwest-client"))]
{
let mut reader = response.reader();
let mut buf = [0; 16384];
loop {
match reader.read(&mut buf) {
Ok(b) => {
if b == 0 {
break;
} else {
let bytes = buf[0..b].to_vec();
on_chunk(bytes.len(), content_length);
buffer.extend(bytes);
}
}
Err(e) => return Err(e.into()),
}
}
}
on_download_finish();
// create memory buffer from our archive (Seek + Read)
let mut archive_buffer = Cursor::new(buffer);
// We need an announced signature by the server
// if there is no signature, bail out.
verify_signature(&mut archive_buffer, &self.signature, &pub_key)?;
// TODO: implement updater in mobile
#[cfg(desktop)]
{
// we copy the files depending of the operating system
// we run the setup, appimage re-install or overwrite the
// macos .app
#[cfg(target_os = "windows")]
copy_files_and_run(
archive_buffer,
&self.extract_path,
self.with_elevated_task,
self
.app
.config()
.tauri
.updater
.windows
.install_mode
.clone()
.msiexec_args(),
)?;
#[cfg(not(target_os = "windows"))]
copy_files_and_run(archive_buffer, &self.extract_path)?;
}
// We are done!
Ok(())
}
sourcepub fn headers(&self) -> &HeaderMap
pub fn headers(&self) -> &HeaderMap
Get the headers of this Response.
Examples found in repository?
src/updater/core.rs (line 558)
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
pub(crate) async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
&self,
pub_key: String,
on_chunk: C,
on_download_finish: D,
) -> Result {
// make sure we can install the update on linux
// We fail here because later we can add more linux support
// actually if we use APPIMAGE, our extract path should already
// be set with our APPIMAGE env variable, we don't need to do
// anything with it yet
#[cfg(target_os = "linux")]
if self.app.state::<Env>().appimage.is_none() {
return Err(Error::UnsupportedLinuxPackage);
}
// set our headers
let mut headers = self.headers.clone();
headers.insert(
"Accept",
HeaderValue::from_str("application/octet-stream").unwrap(),
);
headers.insert(
"User-Agent",
HeaderValue::from_str("tauri/updater").unwrap(),
);
let client = ClientBuilder::new().build()?;
// Create our request
let mut req = HttpRequestBuilder::new("GET", self.download_url.as_str())?.headers(headers);
if let Some(timeout) = self.timeout {
req = req.timeout(timeout);
}
let response = client.send(req).await?;
// make sure it's success
if !response.status().is_success() {
return Err(Error::Network(format!(
"Download request failed with status: {}",
response.status()
)));
}
let content_length: Option<u64> = response
.headers()
.get("Content-Length")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
let mut buffer = Vec::new();
#[cfg(feature = "reqwest-client")]
{
use futures_util::StreamExt;
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
let bytes = chunk.as_ref().to_vec();
on_chunk(bytes.len(), content_length);
buffer.extend(bytes);
}
}
#[cfg(not(feature = "reqwest-client"))]
{
let mut reader = response.reader();
let mut buf = [0; 16384];
loop {
match reader.read(&mut buf) {
Ok(b) => {
if b == 0 {
break;
} else {
let bytes = buf[0..b].to_vec();
on_chunk(bytes.len(), content_length);
buffer.extend(bytes);
}
}
Err(e) => return Err(e.into()),
}
}
}
on_download_finish();
// create memory buffer from our archive (Seek + Read)
let mut archive_buffer = Cursor::new(buffer);
// We need an announced signature by the server
// if there is no signature, bail out.
verify_signature(&mut archive_buffer, &self.signature, &pub_key)?;
// TODO: implement updater in mobile
#[cfg(desktop)]
{
// we copy the files depending of the operating system
// we run the setup, appimage re-install or overwrite the
// macos .app
#[cfg(target_os = "windows")]
copy_files_and_run(
archive_buffer,
&self.extract_path,
self.with_elevated_task,
self
.app
.config()
.tauri
.updater
.windows
.install_mode
.clone()
.msiexec_args(),
)?;
#[cfg(not(target_os = "windows"))]
copy_files_and_run(archive_buffer, &self.extract_path)?;
}
// We are done!
Ok(())
}
sourcepub async fn bytes(self) -> Result<RawResponse>
pub async fn bytes(self) -> Result<RawResponse>
Reads the response as raw bytes.
sourcepub async fn read(self) -> Result<ResponseData>
pub async fn read(self) -> Result<ResponseData>
Reads the response.
Note that the body is serialized to a Value
.
Examples found in repository?
src/endpoints/http.rs (line 114)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
async fn http_request<R: Runtime>(
context: InvokeContext<R>,
client_id: ClientId,
options: Box<HttpRequestBuilder>,
) -> super::Result<ResponseData> {
use crate::Manager;
let scopes = context.window.state::<crate::Scopes>();
if scopes.http.is_allowed(&options.url) {
let client = clients()
.lock()
.unwrap()
.get(&client_id)
.ok_or_else(|| crate::Error::HttpClientNotInitialized.into_anyhow())?
.clone();
let options = *options;
if let Some(crate::api::http::Body::Form(form)) = &options.body {
for value in form.0.values() {
if let crate::api::http::FormPart::File {
file: crate::api::http::FilePart::Path(path),
..
} = value
{
if crate::api::file::SafePathBuf::new(path.clone()).is_err()
|| !scopes.fs.is_allowed(&path)
{
return Err(crate::Error::PathNotAllowed(path.clone()).into_anyhow());
}
}
}
}
let response = client.send(options).await?;
Ok(response.read().await?)
} else {
Err(crate::Error::UrlNotAllowed(options.url).into_anyhow())
}
}
More examples
src/updater/core.rs (line 386)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub async fn build(mut self) -> Result<Update<R>> {
let mut remote_release: Option<RemoteRelease> = None;
// make sure we have at least one url
if self.urls.is_empty() {
return Err(Error::Builder(
"Unable to check update, `url` is required.".into(),
));
};
// If no executable path provided, we use current_exe from tauri_utils
let executable_path = self.executable_path.unwrap_or(current_exe()?);
let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?;
// `target` is the `{{target}}` variable we replace in the endpoint
// `json_target` is the value we search if the updater server returns a JSON with the `platforms` object
let (target, json_target) = if let Some(target) = self.target {
(target.clone(), target)
} else {
let target = get_updater_target().ok_or(Error::UnsupportedOs)?;
(target.to_string(), format!("{}-{}", target, arch))
};
// Get the extract_path from the provided executable_path
let extract_path = extract_path_from_executable(&self.app.state::<Env>(), &executable_path);
// Set SSL certs for linux if they aren't available.
// We do not require to recheck in the download_and_install as we use
// ENV variables, we can expect them to be set for the second call.
#[cfg(target_os = "linux")]
{
if env::var_os("SSL_CERT_FILE").is_none() {
env::set_var("SSL_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt");
}
if env::var_os("SSL_CERT_DIR").is_none() {
env::set_var("SSL_CERT_DIR", "/etc/ssl/certs");
}
}
// we want JSON only
let mut headers = self.headers;
headers.insert("Accept", HeaderValue::from_str("application/json").unwrap());
// Allow fallback if more than 1 urls is provided
let mut last_error: Option<Error> = None;
for url in &self.urls {
// replace {{current_version}}, {{target}} and {{arch}} in the provided URL
// this is useful if we need to query example
// https://releases.myapp.com/update/{{target}}/{{arch}}/{{current_version}}
// will be translated into ->
// https://releases.myapp.com/update/darwin/aarch64/1.0.0
// The main objective is if the update URL is defined via the Cargo.toml
// the URL will be generated dynamically
let fixed_link = url
.replace("{{current_version}}", &self.current_version.to_string())
.replace("{{target}}", &target)
.replace("{{arch}}", arch);
let mut request = HttpRequestBuilder::new("GET", &fixed_link)?.headers(headers.clone());
if let Some(timeout) = self.timeout {
request = request.timeout(timeout);
}
let resp = ClientBuilder::new().build()?.send(request).await;
// If we got a success, we stop the loop
// and we set our remote_release variable
if let Ok(res) = resp {
let res = res.read().await?;
// got status code 2XX
if StatusCode::from_u16(res.status)
.map_err(|e| Error::Builder(e.to_string()))?
.is_success()
{
// if we got 204
if StatusCode::NO_CONTENT.as_u16() == res.status {
// return with `UpToDate` error
// we should catch on the client
return Err(Error::UpToDate);
};
// Convert the remote result to our local struct
let built_release = serde_json::from_value(res.data).map_err(Into::into);
// make sure all went well and the remote data is compatible
// with what we need locally
match built_release {
Ok(release) => {
last_error = None;
remote_release = Some(release);
break;
}
Err(err) => last_error = Some(err),
}
} // if status code is not 2XX we keep loopin' our urls
}
}
// Last error is cleaned on success -- shouldn't be triggered if
// we have a successful call
if let Some(error) = last_error {
return Err(error);
}
// Extracted remote metadata
let final_release = remote_release.ok_or(Error::ReleaseNotFound)?;
// is the announced version greater than our current one?
let should_update = if let Some(comparator) = self.should_install.take() {
comparator(&self.current_version, &final_release)
} else {
final_release.version() > &self.current_version
};
headers.remove("Accept");
// create our new updater
Ok(Update {
app: self.app,
target,
extract_path,
should_update,
version: final_release.version().to_string(),
date: final_release.pub_date().cloned(),
current_version: self.current_version,
download_url: final_release.download_url(&json_target)?.to_owned(),
body: final_release.notes().cloned(),
signature: final_release.signature(&json_target)?.to_owned(),
#[cfg(target_os = "windows")]
with_elevated_task: final_release.with_elevated_task(&json_target)?,
timeout: self.timeout,
headers,
})
}