main.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![cfg_attr(
  5. all(not(debug_assertions), target_os = "windows"),
  6. windows_subsystem = "windows"
  7. )]
  8. fn main() {
  9. use std::{
  10. cmp::min,
  11. io::{Read, Seek, SeekFrom},
  12. path::PathBuf,
  13. process::{Command, Stdio},
  14. };
  15. use tauri::http::{HttpRange, ResponseBuilder};
  16. let video_file = PathBuf::from("test_video.mp4");
  17. let video_url =
  18. "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
  19. if !video_file.exists() {
  20. // Downloading with curl this saves us from adding
  21. // a Rust HTTP client dependency.
  22. println!("Downloading {}", video_url);
  23. let status = Command::new("curl")
  24. .arg("-L")
  25. .arg("-o")
  26. .arg(&video_file)
  27. .arg(video_url)
  28. .stdout(Stdio::inherit())
  29. .stderr(Stdio::inherit())
  30. .output()
  31. .unwrap();
  32. assert!(status.status.success());
  33. assert!(video_file.exists());
  34. }
  35. tauri::Builder::default()
  36. .invoke_handler(tauri::generate_handler![video_uri])
  37. .register_uri_scheme_protocol("stream", move |_app, request| {
  38. // prepare our response
  39. let mut response = ResponseBuilder::new();
  40. // get the wanted path
  41. #[cfg(target_os = "windows")]
  42. let path = request.uri().strip_prefix("stream://localhost/").unwrap();
  43. #[cfg(not(target_os = "windows"))]
  44. let path = request.uri().strip_prefix("stream://localhost/").unwrap();
  45. let path = percent_encoding::percent_decode(path.as_bytes())
  46. .decode_utf8_lossy()
  47. .to_string();
  48. if path != "example/test_video.mp4" {
  49. // return error 404 if it's not out video
  50. return response.mimetype("text/plain").status(404).body(Vec::new());
  51. }
  52. // read our file
  53. let mut content = std::fs::File::open(&video_file)?;
  54. let mut buf = Vec::new();
  55. // default status code
  56. let mut status_code = 200;
  57. // if the webview sent a range header, we need to send a 206 in return
  58. // Actually only macOS and Windows are supported. Linux will ALWAYS return empty headers.
  59. if let Some(range) = request.headers().get("range") {
  60. // Get the file size
  61. let file_size = content.metadata().unwrap().len();
  62. // we parse the range header with tauri helper
  63. let range = HttpRange::parse(range.to_str().unwrap(), file_size).unwrap();
  64. // let support only 1 range for now
  65. let first_range = range.first();
  66. if let Some(range) = first_range {
  67. let mut real_length = range.length;
  68. // prevent max_length;
  69. // specially on webview2
  70. if range.length > file_size / 3 {
  71. // max size sent (400ko / request)
  72. // as it's local file system we can afford to read more often
  73. real_length = min(file_size - range.start, 1024 * 400);
  74. }
  75. // last byte we are reading, the length of the range include the last byte
  76. // who should be skipped on the header
  77. let last_byte = range.start + real_length - 1;
  78. // partial content
  79. status_code = 206;
  80. // Only macOS and Windows are supported, if you set headers in linux they are ignored
  81. response = response
  82. .header("Connection", "Keep-Alive")
  83. .header("Accept-Ranges", "bytes")
  84. .header("Content-Length", real_length)
  85. .header(
  86. "Content-Range",
  87. format!("bytes {}-{}/{}", range.start, last_byte, file_size),
  88. );
  89. // FIXME: Add ETag support (caching on the webview)
  90. // seek our file bytes
  91. content.seek(SeekFrom::Start(range.start))?;
  92. content.take(real_length).read_to_end(&mut buf)?;
  93. } else {
  94. content.read_to_end(&mut buf)?;
  95. }
  96. }
  97. response.mimetype("video/mp4").status(status_code).body(buf)
  98. })
  99. .run(tauri::generate_context!(
  100. "../../examples/streaming/tauri.conf.json"
  101. ))
  102. .expect("error while running tauri application");
  103. }
  104. // returns the scheme and the path of the video file
  105. // we're using this just to allow using the custom `stream` protocol or tauri built-in `asset` protocol
  106. #[tauri::command]
  107. fn video_uri() -> (&'static str, std::path::PathBuf) {
  108. #[cfg(feature = "protocol-asset")]
  109. {
  110. let mut path = std::env::current_dir().unwrap();
  111. path.push("test_video.mp4");
  112. ("asset", path)
  113. }
  114. #[cfg(not(feature = "protocol-asset"))]
  115. ("stream", "example/test_video.mp4".into())
  116. }