From cd57dcdf049d759d06f5840b85e28f109f357f9a Mon Sep 17 00:00:00 2001 From: Ale Guzman <84918983+luis-cicada@users.noreply.github.com> Date: Mon, 13 May 2024 17:09:24 -0600 Subject: [PATCH] feat(dialog): set `len` and `modified_at` fields in `FileResponse` on desktop (#1295) --- .changes/dialog-metadata.md | 6 ++++++ plugins/dialog/src/lib.rs | 24 +++++++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 .changes/dialog-metadata.md diff --git a/.changes/dialog-metadata.md b/.changes/dialog-metadata.md new file mode 100644 index 00000000..1bb8bc7d --- /dev/null +++ b/.changes/dialog-metadata.md @@ -0,0 +1,6 @@ +--- +"dialog": "patch" +"dialog-js": "patch" +--- + +Fill file `len` and `modified_at` fields of `FileResponse` when using the open dialog. diff --git a/plugins/dialog/src/lib.rs b/plugins/dialog/src/lib.rs index d3eaaaa8..bb1b9882 100644 --- a/plugins/dialog/src/lib.rs +++ b/plugins/dialog/src/lib.rs @@ -18,6 +18,7 @@ use tauri::{ }; use std::{ + fs, path::{Path, PathBuf}, sync::mpsc::sync_channel, }; @@ -213,7 +214,7 @@ impl MessageDialogBuilder { } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Deserialize, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct FileResponse { pub base64_data: Option, @@ -230,16 +231,18 @@ pub struct FileResponse { impl FileResponse { #[cfg(desktop)] fn new(path: PathBuf) -> Self { + let metadata = fs::metadata(&path); + let metadata = metadata.as_ref(); Self { base64_data: None, duration: None, height: None, width: None, mime_type: None, - modified_at: None, + modified_at: metadata.ok().and_then(|m| to_msec(m.modified())), name: path.file_name().map(|f| f.to_string_lossy().into_owned()), path, - size: 0, + size: metadata.map(|m| m.len()).unwrap_or(0), } } } @@ -574,3 +577,18 @@ impl FileDialogBuilder { blocking_fn!(self, save_file) } } + +// taken from deno source code: https://github.com/denoland/deno/blob/ffffa2f7c44bd26aec5ae1957e0534487d099f48/runtime/ops/fs.rs#L913 +#[inline] +fn to_msec(maybe_time: std::result::Result) -> Option { + match maybe_time { + Ok(time) => { + let msec = time + .duration_since(std::time::UNIX_EPOCH) + .map(|t| t.as_millis() as u64) + .unwrap_or_else(|err| err.duration().as_millis() as u64); + Some(msec) + } + Err(_) => None, + } +}