tauri_plugin_android_fs/models/
file_uri.rs1use serde::{Deserialize, Serialize};
2use crate::*;
3
4
5#[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize, Serialize)]
28#[serde(rename_all = "camelCase")]
29pub struct FileUri {
30 pub uri: String,
31 pub document_top_tree_uri: Option<String>,
32}
33
34#[allow(unused)]
35impl FileUri {
36
37 pub fn to_json_string(&self) -> Result<String> {
39 serde_json::to_string(self).map_err(Into::into)
40 }
41
42 pub fn from_json_str(json: impl AsRef<str>) -> Result<Self> {
44 serde_json::from_str(json.as_ref()).map_err(Into::into)
45 }
46
47 pub fn from_path(path: impl AsRef<std::path::Path>) -> Self {
55 Self { uri: format!("file://{}", path.as_ref().to_string_lossy()), document_top_tree_uri: None }
56 }
57
58 pub(crate) fn as_path(&self) -> Option<&std::path::Path> {
59 if self.uri.starts_with("file://") {
60 return Some(std::path::Path::new(self.uri.trim_start_matches("file://")))
61 }
62 None
63 }
64
65 pub(crate) fn is_content_scheme(&self) -> bool {
66 self.uri.starts_with("content://")
67 }
68
69 pub(crate) fn require_content_scheme(&self) -> Result<()> {
70 if self.is_content_scheme() {
71 Ok(())
72 }
73 else {
74 Err(Error::with(format!("invalid URI scheme: {}", self.uri)))
75 }
76 }
77}
78
79impl From<&std::path::Path> for FileUri {
80
81 fn from(path: &std::path::Path) -> Self {
82 Self::from_path(path)
83 }
84}
85
86impl From<&std::path::PathBuf> for FileUri {
87
88 fn from(path: &std::path::PathBuf) -> Self {
89 Self::from_path(path)
90 }
91}
92
93impl From<std::path::PathBuf> for FileUri {
94
95 fn from(path: std::path::PathBuf) -> Self {
96 Self::from_path(path)
97 }
98}
99
100impl From<tauri_plugin_fs::FilePath> for FileUri {
101
102 fn from(value: tauri_plugin_fs::FilePath) -> Self {
103 match value {
104 tauri_plugin_fs::FilePath::Url(url) => Self { uri: url.to_string(), document_top_tree_uri: None },
105 tauri_plugin_fs::FilePath::Path(path_buf) => path_buf.into(),
106 }
107 }
108}
109
110impl From<FileUri> for tauri_plugin_fs::FilePath {
111
112 fn from(value: FileUri) -> Self {
113 type NeverErr<T> = std::result::Result::<T, std::convert::Infallible>;
114 NeverErr::unwrap(value.uri.parse())
115 }
116}