tauri_plugin_android_fs/api/android_fs.rs
1use sync_async::sync_async;
2use crate::*;
3use super::*;
4
5
6/// ***Root API***
7///
8/// # Examples
9/// ```no_run
10/// fn example(app: &tauri::AppHandle) {
11/// use tauri_plugin_android_fs::AndroidFsExt as _;
12///
13/// let api = app.android_fs();
14/// }
15/// ```
16
17#[sync_async]
18pub struct AndroidFs<R: tauri::Runtime> {
19 #[cfg(target_os = "android")]
20 pub(crate) handle: tauri::plugin::PluginHandle<R>,
21
22 #[cfg(not(target_os = "android"))]
23 #[allow(unused)]
24 pub(crate) handle: std::marker::PhantomData<fn() -> R>
25}
26
27#[cfg(target_os = "android")]
28#[sync_async(
29 use(if_sync) impls::SyncImpls as Impls;
30 use(if_async) impls::AsyncImpls as Impls;
31)]
32impl<R: tauri::Runtime> AndroidFs<R> {
33
34 #[always_sync]
35 pub(crate) fn impls(&self) -> Impls<'_, R> {
36 Impls { handle: &self.handle }
37 }
38}
39
40#[sync_async(
41 use(if_async) api_async::{FileOpener, FilePicker, PrivateStorage, PublicStorage, WritableStream};
42 use(if_sync) api_sync::{FileOpener, FilePicker, PrivateStorage, PublicStorage, WritableStream};
43)]
44impl<R: tauri::Runtime> AndroidFs<R> {
45
46 /// API of file storage intended for the app's use only.
47 #[always_sync]
48 pub fn private_storage(&self) -> PrivateStorage<'_, R> {
49 PrivateStorage { handle: &self.handle }
50 }
51
52 /// API of file storage that is available to other applications and users.
53 #[always_sync]
54 pub fn public_storage(&self) -> PublicStorage<'_, R> {
55 PublicStorage { handle: &self.handle }
56 }
57
58 /// API of file/dir picker.
59 #[always_sync]
60 pub fn file_picker(&self) -> FilePicker<'_, R> {
61 FilePicker { handle: &self.handle }
62 }
63
64 /// API of opening file/dir with other apps.
65 #[always_sync]
66 pub fn file_opener(&self) -> FileOpener<'_, R> {
67 FileOpener { handle: &self.handle }
68 }
69
70 /// Get the file or directory name.
71 ///
72 /// # Args
73 /// - ***uri*** :
74 /// Target URI.
75 /// Must be **readable**.
76 ///
77 /// # Support
78 /// All Android version.
79 #[maybe_async]
80 pub fn get_name(&self, uri: &FileUri) -> Result<String> {
81 #[cfg(not(target_os = "android"))] {
82 Err(Error::NOT_ANDROID)
83 }
84 #[cfg(target_os = "android")] {
85 self.impls().get_entry_name(uri).await
86 }
87 }
88
89 /// Queries the provider to get the MIME type.
90 ///
91 /// For file URIs via [`FileUri::from_path`], the MIME type is determined from the file extension.
92 /// In most other cases, it uses the MIME type that was associated with the file when it was created.
93 /// If the MIME type is unknown or unset, it falls back to `"application/octet-stream"`.
94 ///
95 /// If the target is a directory, an error will occur.
96 /// To check whether the target is a file or a directory, use [`AndroidFs::get_type`].
97 ///
98 /// # Args
99 /// - ***uri*** :
100 /// Target file URI.
101 /// Must be **readable**.
102 ///
103 /// # Support
104 /// All Android version.
105 #[maybe_async]
106 pub fn get_mime_type(&self, uri: &FileUri) -> Result<String> {
107 #[cfg(not(target_os = "android"))] {
108 Err(Error::NOT_ANDROID)
109 }
110 #[cfg(target_os = "android")] {
111 self.impls().get_file_mime_type(uri).await
112 }
113 }
114
115 /// Gets the entry type.
116 ///
117 /// If the target is a directory, returns [`EntryType::Dir`].
118 ///
119 /// If the target is a file, returns [`EntryType::File { mime_type }`](EntryType::File).
120 /// For file URIs via [`FileUri::from_path`], the MIME type is determined from the file extension.
121 /// In most other cases, it uses the MIME type that was associated with the file when it was created.
122 /// If the MIME type is unknown or unset, it falls back to `"application/octet-stream"`.
123 ///
124 /// # Args
125 /// - ***uri*** :
126 /// Target URI.
127 /// Must be **readable**.
128 ///
129 /// # Support
130 /// All Android version.
131 #[maybe_async]
132 pub fn get_type(&self, uri: &FileUri) -> Result<EntryType> {
133 #[cfg(not(target_os = "android"))] {
134 Err(Error::NOT_ANDROID)
135 }
136 #[cfg(target_os = "android")] {
137 self.impls().get_entry_type(uri).await
138 }
139 }
140
141 /// Queries the file system to get information about a file, directory.
142 ///
143 /// # Args
144 /// - ***uri*** :
145 /// Target URI.
146 /// Must be **readable**.
147 ///
148 /// # Note
149 /// This uses [`AndroidFs::open_file`] internally.
150 ///
151 /// # Support
152 /// All Android version.
153 #[maybe_async]
154 pub fn get_metadata(&self, uri: &FileUri) -> Result<std::fs::Metadata> {
155 #[cfg(not(target_os = "android"))] {
156 Err(Error::NOT_ANDROID)
157 }
158 #[cfg(target_os = "android")] {
159 self.impls().get_entry_metadata(uri).await
160 }
161 }
162
163 /// Open the file in **readable** mode.
164 ///
165 /// # Note
166 /// If the target is a file on cloud storage or otherwise not physically present on the device,
167 /// the file provider may downloads the entire contents, and then opens it.
168 /// As a result, this processing may take longer than with regular local files.
169 /// And files might be a pair of pipe or socket for streaming data.
170 ///
171 /// # Args
172 /// - ***uri*** :
173 /// Target file URI.
174 /// This need to be **readable**.
175 ///
176 /// # Support
177 /// All Android version.
178 #[maybe_async]
179 pub fn open_file_readable(&self, uri: &FileUri) -> Result<std::fs::File> {
180 #[cfg(not(target_os = "android"))] {
181 Err(Error::NOT_ANDROID)
182 }
183 #[cfg(target_os = "android")] {
184 self.impls().open_file_readable(uri).await
185 }
186 }
187
188 /// Open the file in **writable** mode.
189 /// This truncates the existing contents.
190 ///
191 /// # Note
192 /// For file provider of some cloud storage,
193 /// writing by file descriptor like std::fs may not correctoly notify and reflect changes.
194 /// If you need to write to such files, use [`AndroidFs::open_writable_stream`].
195 /// It will fall back to Kotlin API as needed.
196 /// And you can check by [`AndroidFs::need_write_via_kotlin`].
197 ///
198 /// # Args
199 /// - ***uri*** :
200 /// Target file URI.
201 /// This need to be **writable**.
202 ///
203 /// # Support
204 /// All Android version.
205 #[maybe_async]
206 pub fn open_file_writable(
207 &self,
208 uri: &FileUri,
209 ) -> Result<std::fs::File> {
210
211 #[cfg(not(target_os = "android"))] {
212 Err(Error::NOT_ANDROID)
213 }
214 #[cfg(target_os = "android")] {
215 self.impls().open_file_writable(uri).await
216 }
217 }
218
219 /// Open the file in the specified mode.
220 ///
221 /// # Note
222 /// If the target is a file on cloud storage or otherwise not physically present on the device,
223 /// the file provider may downloads the entire contents, and then opens it.
224 /// As a result, this processing may take longer than with regular local files.
225 /// And files might be a pair of pipe or socket for streaming data.
226 ///
227 /// When writing to a file with this function,
228 /// pay attention to the following points:
229 ///
230 /// 1. **File reflection**:
231 /// For file provider of some cloud storage,
232 /// writing by file descriptor like std::fs may not correctoly notify and reflect changes.
233 /// If you need to write to such files, use [`AndroidFs::open_writable_stream`].
234 /// It will fall back to Kotlin API as needed.
235 /// And you can check by [`AndroidFs::need_write_via_kotlin`].
236 ///
237 /// 2. **File mode restrictions**:
238 /// Files provided by third-party apps may not support writable modes other than
239 /// [`FileAccessMode::Write`]. However, [`FileAccessMode::Write`] does not guarantee
240 /// that existing contents will always be truncated.
241 /// As a result, if the new contents are shorter than the original, the file may
242 /// become corrupted. To avoid this, consider using
243 /// [`AndroidFs::open_file_writable`] or [`AndroidFs::open_writable_stream`], which
244 /// ensure that existing contents are truncated and also automatically apply the
245 /// maximum possible fallbacks.
246 /// <https://issuetracker.google.com/issues/180526528>
247 ///
248 /// # Args
249 /// - ***uri*** :
250 /// Target file URI.
251 /// This must have corresponding permissions (read, write, or both) for the specified ***mode***.
252 ///
253 /// - ***mode*** :
254 /// Indicates how the file is opened and the permissions granted.
255 /// The only ones that can be expected to work in all cases are [`FileAccessMode::Write`] and [`FileAccessMode::Read`].
256 /// Because files hosted by third-party apps may not support others.
257 ///
258 /// # Support
259 /// All Android version.
260 #[maybe_async]
261 pub fn open_file(&self, uri: &FileUri, mode: FileAccessMode) -> Result<std::fs::File> {
262 #[cfg(not(target_os = "android"))] {
263 Err(Error::NOT_ANDROID)
264 }
265 #[cfg(target_os = "android")] {
266 self.impls().open_file(uri, mode).await
267 }
268 }
269
270 /// For detailed documentation and notes, see [`AndroidFs::open_file`].
271 ///
272 /// The modes specified in ***candidate_modes*** are tried in order.
273 /// If the file can be opened, this returns the file along with the mode used.
274 /// If all attempts fail, an error is returned.
275 #[maybe_async]
276 pub fn open_file_with_fallback(
277 &self,
278 uri: &FileUri,
279 candidate_modes: impl IntoIterator<Item = FileAccessMode>
280 ) -> Result<(std::fs::File, FileAccessMode)> {
281
282 #[cfg(not(target_os = "android"))] {
283 Err(Error::NOT_ANDROID)
284 }
285 #[cfg(target_os = "android")] {
286 self.impls().open_file_with_fallback(uri, candidate_modes).await
287 }
288 }
289
290 /// Opens a stream for writing to the specified file.
291 /// This truncates the existing contents.
292 ///
293 /// # Usage
294 /// [`WritableStream`] implements [`std::io::Write`], so it can be used for writing.
295 /// As with [`std::fs::File`], wrap it with [`std::io::BufWriter`] if buffering is needed.
296 ///
297 /// After writing, call [`WritableStream::reflect`].
298 ///
299 /// # Note
300 /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].
301 /// If it is `false`, this behaves like [`AndroidFs::open_file_writable`].
302 /// If it is `true`, this behaves like [`AndroidFs::open_writable_stream_via_kotlin`].
303 ///
304 /// # Args
305 /// - ***uri*** :
306 /// Target file URI.
307 /// This need to be **writable**.
308 ///
309 /// # Support
310 /// All Android version.
311 #[maybe_async]
312 pub fn open_writable_stream(
313 &self,
314 uri: &FileUri
315 ) -> Result<WritableStream<R>> {
316
317 #[cfg(not(target_os = "android"))] {
318 Err(Error::NOT_ANDROID)
319 }
320 #[cfg(target_os = "android")] {
321 let impls = self.impls().create_writable_stream_auto(uri).await?;
322 Ok(WritableStream { impls })
323 }
324 }
325
326 /// Opens a writable stream to the specified file.
327 /// This truncates the existing contents.
328 ///
329 /// This function always writes content via the Kotlin API.
330 /// But this takes several times longer compared.
331 /// [`AndroidFs::open_writable_stream`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].
332 ///
333 /// # Usage
334 /// [`WritableStream`] implements [`std::io::Write`], so it can be used for writing.
335 /// As with [`std::fs::File`], wrap it with [`std::io::BufWriter`] if buffering is needed.
336 ///
337 /// After writing, call [`WritableStream::reflect`].
338 ///
339 /// # Args
340 /// - ***uri*** :
341 /// Target file URI.
342 /// This need to be **writable**.
343 ///
344 /// # Support
345 /// All Android version.
346 #[maybe_async]
347 pub fn open_writable_stream_via_kotlin(
348 &self,
349 uri: &FileUri
350 ) -> Result<WritableStream<R>> {
351
352 #[cfg(not(target_os = "android"))] {
353 Err(Error::NOT_ANDROID)
354 }
355 #[cfg(target_os = "android")] {
356 let impls = self.impls().create_writable_stream_via_kotlin(uri).await?;
357 Ok(WritableStream { impls })
358 }
359 }
360
361 /// Reads the entire contents of a file into a bytes vector.
362 ///
363 /// # Args
364 /// - ***uri*** :
365 /// Target file URI.
366 /// Must be **readable**.
367 ///
368 /// # Support
369 /// All Android version.
370 #[maybe_async]
371 pub fn read(&self, uri: &FileUri) -> Result<Vec<u8>> {
372 #[cfg(not(target_os = "android"))] {
373 Err(Error::NOT_ANDROID)
374 }
375 #[cfg(target_os = "android")] {
376 self.impls().read_file(uri).await
377 }
378 }
379
380 /// Reads the entire contents of a file into a string.
381 ///
382 /// # Args
383 /// - ***uri*** :
384 /// Target file URI.
385 /// Must be **readable**.
386 ///
387 /// # Support
388 /// All Android version.
389 #[maybe_async]
390 pub fn read_to_string(&self, uri: &FileUri) -> Result<String> {
391 #[cfg(not(target_os = "android"))] {
392 Err(Error::NOT_ANDROID)
393 }
394 #[cfg(target_os = "android")] {
395 self.impls().read_file_to_string(uri).await
396 }
397 }
398
399 /// Writes a slice as the entire contents of a file.
400 /// This function will entirely replace its contents if it does exist.
401 ///
402 /// # Note
403 /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].
404 /// If it is `false`, this uses [`std::fs::File`].
405 /// If it is `true`, this uses [`AndroidFs::write_via_kotlin`].
406 ///
407 /// # Args
408 /// - ***uri*** :
409 /// Target file URI.
410 /// Must be **writable**.
411 ///
412 /// # Support
413 /// All Android version.
414 #[maybe_async]
415 pub fn write(&self, uri: &FileUri, contents: impl AsRef<[u8]>) -> Result<()> {
416 #[cfg(not(target_os = "android"))] {
417 Err(Error::NOT_ANDROID)
418 }
419 #[cfg(target_os = "android")] {
420 self.impls().write_file_auto(uri, contents).await
421 }
422 }
423
424 /// Writes a slice as the entire contents of a file.
425 /// This function will entirely replace its contents if it does exist.
426 ///
427 /// This function always writes content via the Kotlin API.
428 /// But this takes several times longer compared.
429 /// [`AndroidFs::write`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].
430 ///
431 /// # Support
432 /// All Android version.
433 #[maybe_async]
434 pub fn write_via_kotlin(
435 &self,
436 uri: &FileUri,
437 contents: impl AsRef<[u8]>
438 ) -> Result<()> {
439
440 #[cfg(not(target_os = "android"))] {
441 Err(Error::NOT_ANDROID)
442 }
443 #[cfg(target_os = "android")] {
444 self.impls().write_file_via_kotlin(uri, contents).await
445 }
446 }
447
448 /// Copies the contents of the source file to the destination.
449 /// If the destination already has contents, they are truncated before writing the source contents.
450 ///
451 /// # Note
452 /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].
453 /// If it is `false`, this uses [`std::io::copy`] with [`std::fs::File`].
454 /// If it is `true`, this uses [`AndroidFs::copy_via_kotlin`].
455 ///
456 /// # Args
457 /// - ***src*** :
458 /// The URI of source file.
459 /// Must be **readable**.
460 ///
461 /// - ***dest*** :
462 /// The URI of destination file.
463 /// Must be **writable**.
464 ///
465 /// # Support
466 /// All Android version.
467 #[maybe_async]
468 pub fn copy(&self, src: &FileUri, dest: &FileUri) -> Result<()> {
469 #[cfg(not(target_os = "android"))] {
470 Err(Error::NOT_ANDROID)
471 }
472 #[cfg(target_os = "android")] {
473 self.impls().copy_file(src, dest).await
474 }
475 }
476
477 /// Copies the contents of src file to dest.
478 /// If dest already has contents, it is truncated before write src contents.
479 ///
480 /// This function always writes content via the Kotlin API.
481 /// [`AndroidFs::copy`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].
482 ///
483 /// # Args
484 /// - ***src*** :
485 /// The URI of source file.
486 /// Must be **readable**.
487 ///
488 /// - ***dest*** :
489 /// The URI of destination file.
490 /// Must be **writable**.
491 ///
492 /// - ***buffer_size***:
493 /// The size of the buffer, in bytes, to use during the copy process on Kotlin.
494 /// If `None`, [`DEFAULT_BUFFER_SIZE`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.io/-d-e-f-a-u-l-t_-b-u-f-f-e-r_-s-i-z-e.html) is used.
495 /// At least, when I checked, it was 8 KB.
496 /// If zero, this causes error.
497 ///
498 /// # Support
499 /// All Android version.
500 #[maybe_async]
501 pub fn copy_via_kotlin(
502 &self,
503 src: &FileUri,
504 dest: &FileUri,
505 buffer_size: Option<u32>,
506 ) -> Result<()> {
507
508 #[cfg(not(target_os = "android"))] {
509 Err(Error::NOT_ANDROID)
510 }
511 #[cfg(target_os = "android")] {
512 self.impls().copy_file_via_kotlin(src, dest, buffer_size).await
513 }
514 }
515
516 /// Determines whether the file must be written via the Kotlin API rather than through a file descriptor.
517 ///
518 /// In the case of a file that physically exists on the device, this will always return false.
519 /// This is intended for special cases, such as some cloud storage.
520 ///
521 /// # Support
522 /// All Android version.
523 #[maybe_async]
524 pub fn need_write_via_kotlin(&self, uri: &FileUri) -> Result<bool> {
525 #[cfg(not(target_os = "android"))] {
526 Err(Error::NOT_ANDROID)
527 }
528 #[cfg(target_os = "android")] {
529 self.impls().need_write_file_via_kotlin(uri).await
530 }
531 }
532
533 /// Renames a file or directory to a new name, and return new URI.
534 /// Even if the names conflict, the existing file will not be overwritten.
535 ///
536 /// Note that when files or folders (and their descendants) are renamed, their URIs will change, and any previously granted permissions will be lost.
537 /// In other words, this function returns a new URI without any permissions.
538 /// However, for files created in PublicStorage, the URI remains unchanged even after such operations, and all permissions are retained.
539 /// In this, this function returns the same URI as original URI.
540 ///
541 /// # Args
542 /// - ***uri*** :
543 /// URI of target entry.
544 ///
545 /// - ***new_name*** :
546 /// New name of target entry.
547 /// This include extension if use.
548 /// The behaviour in the same name already exists depends on the file provider.
549 /// In the case of e.g. [`PublicStorage`], the suffix (e.g. `(1)`) is added to this name.
550 /// In the case of files hosted by other applications, errors may occur.
551 /// But at least, the existing file will not be overwritten.
552 /// The system may sanitize these strings as needed, so those strings may not be used as it is.
553 ///
554 /// # Support
555 /// All Android version.
556 #[maybe_async]
557 pub fn rename(&self, uri: &FileUri, new_name: impl AsRef<str>) -> Result<FileUri> {
558 #[cfg(not(target_os = "android"))] {
559 Err(Error::NOT_ANDROID)
560 }
561 #[cfg(target_os = "android")] {
562 self.impls().rename_entry(uri, new_name).await
563 }
564 }
565
566 /// Remove the file.
567 ///
568 /// # Args
569 /// - ***uri*** :
570 /// Target file URI.
571 /// Must be **read-writable**.
572 /// If not file, an error will occur.
573 ///
574 /// # Support
575 /// All Android version.
576 #[maybe_async]
577 pub fn remove_file(&self, uri: &FileUri) -> Result<()> {
578 #[cfg(not(target_os = "android"))] {
579 Err(Error::NOT_ANDROID)
580 }
581 #[cfg(target_os = "android")] {
582 self.impls().remove_file(uri).await
583 }
584 }
585
586 /// Remove the **empty** directory.
587 ///
588 /// # Args
589 /// - ***uri*** :
590 /// Target directory URI.
591 /// Must be **read-writable**.
592 /// If not empty directory, an error will occur.
593 ///
594 /// # Support
595 /// All Android version.
596 #[maybe_async]
597 pub fn remove_dir(&self, uri: &FileUri) -> Result<()> {
598 #[cfg(not(target_os = "android"))] {
599 Err(Error::NOT_ANDROID)
600 }
601 #[cfg(target_os = "android")] {
602 self.impls().remove_dir_if_empty(uri).await
603 }
604 }
605
606 /// Removes a directory and all its contents. Use carefully!
607 ///
608 /// # Args
609 /// - ***uri*** :
610 /// Target directory URI.
611 /// Must be **read-writable**.
612 /// If not directory, an error will occur.
613 ///
614 /// # Support
615 /// All Android version.
616 #[maybe_async]
617 pub fn remove_dir_all(&self, uri: &FileUri) -> Result<()> {
618 #[cfg(not(target_os = "android"))] {
619 Err(Error::NOT_ANDROID)
620 }
621 #[cfg(target_os = "android")] {
622 self.impls().remove_dir_all(uri).await
623 }
624 }
625
626 /// Build a URI of an **existing** file located at the relative path from the specified directory.
627 /// Error occurs, if the file does not exist.
628 ///
629 /// The permissions and validity period of the returned URI depend on the origin directory
630 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
631 ///
632 /// # Note
633 /// For [`AndroidFs::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
634 /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
635 ///
636 /// # Args
637 /// - ***uri*** :
638 /// Base directory URI.
639 /// Must be **readable**.
640 ///
641 /// - ***relative_path*** :
642 /// Relative path from base directory.
643 ///
644 /// # Support
645 /// All Android version.
646 #[maybe_async]
647 pub fn try_resolve_file_uri(
648 &self,
649 dir: &FileUri,
650 relative_path: impl AsRef<std::path::Path>
651 ) -> Result<FileUri> {
652
653 #[cfg(not(target_os = "android"))] {
654 Err(Error::NOT_ANDROID)
655 }
656 #[cfg(target_os = "android")] {
657 self.impls().try_resolve_file_uri(dir, relative_path).await
658 }
659 }
660
661 /// Build a URI of an **existing** directory located at the relative path from the specified directory.
662 /// Error occurs, if the directory does not exist.
663 ///
664 /// The permissions and validity period of the returned URI depend on the origin directory
665 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
666 ///
667 /// # Note
668 /// For [`AndroidFs::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
669 /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
670 ///
671 /// # Args
672 /// - ***uri*** :
673 /// Base directory URI.
674 /// Must be **readable**.
675 ///
676 /// - ***relative_path*** :
677 /// Relative path from base directory.
678 ///
679 /// # Support
680 /// All Android version.
681 #[maybe_async]
682 pub fn try_resolve_dir_uri(
683 &self,
684 dir: &FileUri,
685 relative_path: impl AsRef<std::path::Path>
686 ) -> Result<FileUri> {
687
688 #[cfg(not(target_os = "android"))] {
689 Err(Error::NOT_ANDROID)
690 }
691 #[cfg(target_os = "android")] {
692 self.impls().try_resolve_dir_uri(dir, relative_path).await
693 }
694 }
695
696 /// Build a URI of an entry located at the relative path from the specified directory.
697 ///
698 /// This function does **not** create any entries; it only constructs the URI.
699 ///
700 /// This function does not perform checks on the arguments or the returned URI.
701 /// Even if the dir argument refers to a file, no error occurs (and no panic either).
702 /// Instead, it simply returns an invalid URI that will cause errors if used with other functions.
703 ///
704 /// If you need check, consider using [`AndroidFs::try_resolve_file_uri`] or [`AndroidFs::try_resolve_dir_uri`] instead.
705 /// Or use this with [`AndroidFs::get_type`].
706 ///
707 /// The permissions and validity period of the returned URI depend on the origin directory
708 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
709 ///
710 /// # Note
711 /// For [`PublicStorage::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
712 /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
713 ///
714 /// # Args
715 /// - ***uri*** :
716 /// Base directory URI.
717 /// Must be **readable**.
718 ///
719 /// - ***relative_path*** :
720 /// Relative path from base directory.
721 ///
722 /// # Support
723 /// All Android version.
724 #[maybe_async]
725 pub fn resolve_uri_unvalidated(
726 &self,
727 dir: &FileUri,
728 relative_path: impl AsRef<std::path::Path>
729 ) -> Result<FileUri> {
730
731 #[cfg(not(target_os = "android"))] {
732 Err(Error::NOT_ANDROID)
733 }
734 #[cfg(target_os = "android")] {
735 self.impls().resolve_entry_uri_unvalidated(dir, relative_path).await
736 }
737 }
738
739 /// See [`AndroidFs::get_thumbnail_to`] for descriptions.
740 ///
741 /// If thumbnail does not wrote to dest, return false.
742 #[maybe_async]
743 pub fn get_thumbnail_to(
744 &self,
745 src: &FileUri,
746 dest: &FileUri,
747 preferred_size: Size,
748 format: ImageFormat,
749 ) -> Result<bool> {
750
751 #[cfg(not(target_os = "android"))] {
752 Err(Error::NOT_ANDROID)
753 }
754 #[cfg(target_os = "android")] {
755 self.impls().get_file_thumbnail_to_file(src, dest, preferred_size, format).await
756 }
757 }
758
759 /// Get a file thumbnail.
760 /// If thumbnail does not exist it, return None.
761 ///
762 /// Note this does not cache. Please do it in your part if need.
763 ///
764 /// # Args
765 /// - ***uri*** :
766 /// Targe file uri.
767 /// Thumbnail availablty depends on the file provider.
768 /// In general, images and videos are available.
769 /// For file URIs via [`FileUri::from_path`],
770 /// the file type must match the filename extension.
771 /// In this case, the type is determined by the extension and generate thumbnails.
772 /// Otherwise, thumbnails are provided through MediaStore, file provider, and etc.
773 ///
774 /// - ***preferred_size*** :
775 /// Optimal thumbnail size desired.
776 /// This may return a thumbnail of a different size,
777 /// but never more than double the requested size.
778 /// In any case, the aspect ratio is maintained.
779 ///
780 /// - ***format*** :
781 /// Thumbnail image format.
782 /// [`ImageFormat::Jpeg`] is recommended.
783 /// If you need transparency, use others.
784 ///
785 /// # Support
786 /// All Android version.
787 #[maybe_async]
788 pub fn get_thumbnail(
789 &self,
790 uri: &FileUri,
791 preferred_size: Size,
792 format: ImageFormat,
793 ) -> Result<Option<Vec<u8>>> {
794
795 #[cfg(not(target_os = "android"))] {
796 Err(Error::NOT_ANDROID)
797 }
798 #[cfg(target_os = "android")] {
799 self.impls().get_file_thumbnail_in_memory(uri, preferred_size, format).await
800 }
801 }
802
803 /// Creates a new empty file in the specified location and returns a URI.
804 ///
805 /// The permissions and validity period of the returned URIs depend on the origin directory
806 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
807 ///
808 /// # Args
809 /// - ***dir*** :
810 /// The URI of the base directory.
811 /// Must be **read-write**.
812 ///
813 /// - ***relative_path*** :
814 /// The file path relative to the base directory.
815 /// Any missing parent directories will be created recursively.
816 /// If a file with the same name already exists,
817 /// the system append a sequential number to ensure uniqueness.
818 /// If no extension is present,
819 /// the system may infer one from ***mime_type*** and may append it to the file name.
820 /// But this append-extension operation depends on the model and version.
821 /// The system may sanitize these strings as needed, so those strings may not be used as it is.
822 ///
823 /// - ***mime_type*** :
824 /// The MIME type of the file to be created.
825 /// If this is None, MIME type is inferred from the extension of ***relative_path***
826 /// and if that fails, `application/octet-stream` is used.
827 ///
828 /// # Support
829 /// All Android version.
830 #[maybe_async]
831 pub fn create_new_file(
832 &self,
833 dir: &FileUri,
834 relative_path: impl AsRef<std::path::Path>,
835 mime_type: Option<&str>
836 ) -> Result<FileUri> {
837
838 #[cfg(not(target_os = "android"))] {
839 Err(Error::NOT_ANDROID)
840 }
841 #[cfg(target_os = "android")] {
842 self.impls().create_new_file(dir, relative_path, mime_type).await
843 }
844 }
845
846 /// Recursively create a directory and all of its parent components if they are missing,
847 /// then return the URI.
848 /// If it already exists, do nothing and just return the direcotry uri.
849 ///
850 /// [`AndroidFs::create_new_file`] does this automatically, so there is no need to use it together.
851 ///
852 /// # Args
853 /// - ***dir*** :
854 /// The URI of the base directory.
855 /// Must be **read-write**.
856 ///
857 /// - ***relative_path*** :
858 /// The directory path relative to the base directory.
859 /// The system may sanitize these strings as needed, so those strings may not be used as it is.
860 ///
861 /// # Support
862 /// All Android version.
863 #[maybe_async]
864 pub fn create_dir_all(
865 &self,
866 dir: &FileUri,
867 relative_path: impl AsRef<std::path::Path>,
868 ) -> Result<FileUri> {
869
870 #[cfg(not(target_os = "android"))] {
871 Err(Error::NOT_ANDROID)
872 }
873 #[cfg(target_os = "android")] {
874 self.impls().create_dir_all(dir, relative_path).await
875 }
876 }
877
878 /// Returns the child files and directories of the specified directory.
879 /// The order of the entries is not guaranteed.
880 ///
881 /// The permissions and validity period of the returned URIs depend on the origin directory
882 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
883 ///
884 /// This retrieves all metadata including `uri`, `name`, `last_modified`, `len`, and `mime_type`.
885 /// If only specific information is needed,
886 /// using [`AndroidFs::read_dir_with_options`] will improve performance.
887 ///
888 /// # Note
889 /// The returned type is an iterator, but the file system call is not executed lazily.
890 /// Instead, all data is retrieved at once.
891 /// For directories containing thousands or even tens of thousands of entries,
892 /// this function may take several seconds to complete.
893 /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
894 ///
895 /// # Args
896 /// - ***uri*** :
897 /// Target directory URI.
898 /// Must be **readable**.
899 ///
900 /// # Support
901 /// All Android version.
902 #[maybe_async]
903 pub fn read_dir(&self, uri: &FileUri) -> Result<impl Iterator<Item = Entry>> {
904 let entries = self.read_dir_with_options(uri, EntryOptions::ALL).await?
905 .map(Entry::try_from)
906 .filter_map(Result::ok);
907
908 Ok(entries)
909 }
910
911 /// Returns the child files and directories of the specified directory.
912 /// The order of the entries is not guaranteed.
913 ///
914 /// The permissions and validity period of the returned URIs depend on the origin directory
915 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
916 ///
917 /// # Note
918 /// The returned type is an iterator, but the file system call is not executed lazily.
919 /// Instead, all data is retrieved at once.
920 /// For directories containing thousands or even tens of thousands of entries,
921 /// this function may take several seconds to complete.
922 /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
923 ///
924 /// # Args
925 /// - ***uri*** :
926 /// Target directory URI.
927 /// Must be **readable**.
928 ///
929 /// # Support
930 /// All Android version.
931 #[maybe_async]
932 pub fn read_dir_with_options(
933 &self,
934 uri: &FileUri,
935 options: EntryOptions
936 ) -> Result<impl Iterator<Item = OptionalEntry>> {
937
938 #[cfg(not(target_os = "android"))] {
939 Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
940 }
941 #[cfg(target_os = "android")] {
942 self.impls().read_dir_with_options(uri, options).await
943 }
944 }
945
946 /// Take persistent permission to access the file, directory and its descendants.
947 /// This is a prolongation of an already acquired permission, not the acquisition of a new one.
948 ///
949 /// This works by just calling, without displaying any confirmation to the user.
950 ///
951 /// Note that [there is a limit to the total number of URI that can be made persistent by this function.](https://stackoverflow.com/questions/71099575/should-i-release-persistableuripermission-when-a-new-storage-location-is-chosen/71100621#71100621)
952 /// Therefore, it is recommended to relinquish the unnecessary persisted URI by [`AndroidFs::release_persisted_uri_permission`] or [`AndroidFs::release_all_persisted_uri_permissions`].
953 /// Persisted permissions may be relinquished by other apps, user, or by moving/removing entries.
954 /// So check by [`AndroidFs::check_persisted_uri_permission`].
955 /// And you can retrieve the list of persisted uris using [`AndroidFs::get_all_persisted_uri_permissions`].
956 ///
957 /// # Args
958 /// - **uri** :
959 /// URI of the target file or directory.
960 /// This must be a URI taken from following :
961 /// - [`FilePicker::pick_files`]
962 /// - [`FilePicker::pick_file`]
963 /// - [`FilePicker::pick_visual_medias`]
964 /// - [`FilePicker::pick_visual_media`]
965 /// - [`FilePicker::pick_dir`]
966 /// - [`FilePicker::save_file`]
967 /// - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :
968 /// If use URI from thoese fucntions, the permissions of the origin directory URI is persisted, not a entry iteself by this function.
969 /// Because the permissions and validity period of the descendant entry URIs depend on the origin directory.
970 ///
971 /// # Support
972 /// All Android version.
973 #[maybe_async]
974 pub fn take_persistable_uri_permission(&self, uri: &FileUri) -> Result<()> {
975 #[cfg(not(target_os = "android"))] {
976 Err(Error::NOT_ANDROID)
977 }
978 #[cfg(target_os = "android")] {
979 self.impls().take_persistable_uri_permission(uri).await
980 }
981 }
982
983 /// Check a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].
984 /// Returns false if there are only non-persistent permissions or no permissions.
985 ///
986 /// # Args
987 /// - **uri** :
988 /// URI of the target file or directory.
989 /// This must be a URI taken from following :
990 /// - [`FilePicker::pick_files`]
991 /// - [`FilePicker::pick_file`]
992 /// - [`FilePicker::pick_visual_medias`]
993 /// - [`FilePicker::pick_visual_media`]
994 /// - [`FilePicker::pick_dir`]
995 /// - [`FilePicker::save_file`]
996 /// - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :
997 /// If use URI from thoese fucntions, the permissions of the origin directory URI is checked, not a entry iteself by this function.
998 /// Because the permissions and validity period of the descendant entry URIs depend on the origin directory.
999 ///
1000 /// - **mode** :
1001 /// The mode of permission you want to check.
1002 ///
1003 /// # Support
1004 /// All Android version.
1005 #[maybe_async]
1006 pub fn check_persisted_uri_permission(
1007 &self,
1008 uri: &FileUri,
1009 mode: PersistableAccessMode
1010 ) -> Result<bool> {
1011
1012 #[cfg(not(target_os = "android"))] {
1013 Err(Error::NOT_ANDROID)
1014 }
1015 #[cfg(target_os = "android")] {
1016 self.impls().check_persisted_uri_permission(uri, mode).await
1017 }
1018 }
1019
1020 /// Return list of all persisted URIs that have been persisted by [`AndroidFs::take_persistable_uri_permission`] and currently valid.
1021 ///
1022 /// # Support
1023 /// All Android version.
1024 #[maybe_async]
1025 pub fn get_all_persisted_uri_permissions(&self) -> Result<impl Iterator<Item = PersistedUriPermission>> {
1026 #[cfg(not(target_os = "android"))] {
1027 Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
1028 }
1029 #[cfg(target_os = "android")] {
1030 self.impls().get_all_persisted_uri_permissions().await
1031 }
1032 }
1033
1034 /// Relinquish a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].
1035 ///
1036 /// # Args
1037 /// - ***uri*** :
1038 /// URI of the target file or directory.
1039 ///
1040 /// # Support
1041 /// All Android version.
1042 #[maybe_async]
1043 pub fn release_persisted_uri_permission(&self, uri: &FileUri) -> Result<()> {
1044 #[cfg(not(target_os = "android"))] {
1045 Err(Error::NOT_ANDROID)
1046 }
1047 #[cfg(target_os = "android")] {
1048 self.impls().release_persisted_uri_permission(uri).await
1049 }
1050 }
1051
1052 /// Relinquish a all persisted uri permission grants by [`AndroidFs::take_persistable_uri_permission`].
1053 ///
1054 /// # Support
1055 /// All Android version.
1056 #[maybe_async]
1057 pub fn release_all_persisted_uri_permissions(&self) -> Result<()> {
1058 #[cfg(not(target_os = "android"))] {
1059 Err(Error::NOT_ANDROID)
1060 }
1061 #[cfg(target_os = "android")] {
1062 self.impls().release_all_persisted_uri_permissions().await
1063 }
1064 }
1065
1066 /// See [`PublicStorage::get_volumes`] or [`PrivateStorage::get_volumes`] for details.
1067 ///
1068 /// The difference is that this does not perform any filtering.
1069 /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1070 #[maybe_async]
1071 pub fn get_volumes(&self) -> Result<Vec<StorageVolume>> {
1072 #[cfg(not(target_os = "android"))] {
1073 Err(Error::NOT_ANDROID)
1074 }
1075 #[cfg(target_os = "android")] {
1076 self.impls().get_available_storage_volumes().await
1077 }
1078 }
1079
1080 /// See [`PublicStorage::get_primary_volume`] or [`PrivateStorage::get_primary_volume`] for details.
1081 ///
1082 /// The difference is that this does not perform any filtering.
1083 /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1084 #[maybe_async]
1085 pub fn get_primary_volume(&self) -> Result<Option<StorageVolume>> {
1086 #[cfg(not(target_os = "android"))] {
1087 Err(Error::NOT_ANDROID)
1088 }
1089 #[cfg(target_os = "android")] {
1090 self.impls().get_primary_storage_volume_if_available().await
1091 }
1092 }
1093
1094 /// Verify whether this plugin is available.
1095 ///
1096 /// On Android, this returns true.
1097 /// On other platforms, this returns false.
1098 #[always_sync]
1099 pub fn is_available(&self) -> bool {
1100 cfg!(target_os = "android")
1101 }
1102
1103 /// Get the api level of this Android device.
1104 ///
1105 /// The correspondence table between API levels and Android versions can be found following.
1106 /// <https://developer.android.com/guide/topics/manifest/uses-sdk-element#api-level-table>
1107 ///
1108 /// If you want the constant value of the API level from an Android version, there is the [`api_level`] module.
1109 ///
1110 /// # Table
1111 /// | Android version | API Level |
1112 /// |------------------|-----------|
1113 /// | 16.0 | 36 |
1114 /// | 15.0 | 35 |
1115 /// | 14.0 | 34 |
1116 /// | 13.0 | 33 |
1117 /// | 12L | 32 |
1118 /// | 12.0 | 31 |
1119 /// | 11.0 | 30 |
1120 /// | 10.0 | 29 |
1121 /// | 9.0 | 28 |
1122 /// | 8.1 | 27 |
1123 /// | 8.0 | 26 |
1124 /// | 7.1 - 7.1.2 | 25 |
1125 /// | 7.0 | 24 |
1126 ///
1127 /// Tauri does not support Android versions below 7.
1128 #[always_sync]
1129 pub fn api_level(&self) -> Result<i32> {
1130 #[cfg(not(target_os = "android"))] {
1131 Err(Error::NOT_ANDROID)
1132 }
1133 #[cfg(target_os = "android")] {
1134 self.impls().api_level()
1135 }
1136 }
1137
1138
1139 #[deprecated = "use `AndroidFs::resolve_uri_unvalidated`"]
1140 #[maybe_async]
1141 pub fn resolve_uri(
1142 &self,
1143 dir: &FileUri,
1144 relative_path: impl AsRef<std::path::Path>
1145 ) -> Result<FileUri> {
1146
1147 self.resolve_uri_unvalidated(dir, relative_path).await
1148 }
1149}