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