Skip to content

An open-source cross-platform alternative to AirDrop

fix: create sub folders correctly in Android SAF (#1560)

Tien Do Nam75ba226cd068
diff --git a/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt b/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt
index 865b53a8..97439bda 100644
--- a/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt
+++ b/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt
@@ -3,11 +3,15 @@ package org.localsend.localsend_app
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
+import android.database.Cursor
import android.net.Uri
+import android.provider.DocumentsContract
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
+
private const val CHANNEL = "org.localsend.localsend_app/localsend"
private const val REQUEST_CODE_PICK_DIRECTORY = 1
private const val REQUEST_CODE_PICK_DIRECTORY_PATH = 2
@@ -27,14 +31,19 @@ class MainActivity : FlutterActivity() {
pendingResult = result
openDirectoryPicker(onlyPath = false)
}
+
"pickFiles" -> {
pendingResult = result
openFilePicker()
}
+
"pickDirectoryPath" -> {
pendingResult = result
openDirectoryPicker(onlyPath = true)
}
+
+ "createDirectory" -> handleCreateDirectory(call, result)
+
else -> result.notImplemented()
}
}
@@ -43,7 +52,10 @@ class MainActivity : FlutterActivity() {
private fun openDirectoryPicker(onlyPath: Boolean) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
- startActivityForResult(intent, if (onlyPath) REQUEST_CODE_PICK_DIRECTORY_PATH else REQUEST_CODE_PICK_DIRECTORY)
+ startActivityForResult(
+ intent,
+ if (onlyPath) REQUEST_CODE_PICK_DIRECTORY_PATH else REQUEST_CODE_PICK_DIRECTORY
+ )
}
private fun openFilePicker() {
@@ -91,6 +103,7 @@ class MainActivity : FlutterActivity() {
pendingResult = null
}
}
+
REQUEST_CODE_PICK_DIRECTORY_PATH -> {
val uri: Uri? = data.data
val takeFlags: Int =
@@ -104,6 +117,7 @@ class MainActivity : FlutterActivity() {
pendingResult = null
}
}
+
REQUEST_CODE_PICK_FILE -> {
val uriList: List<Uri> = when {
data.clipData != null -> {
@@ -114,6 +128,7 @@ class MainActivity : FlutterActivity() {
}
uris
}
+
data.data != null -> listOf(data.data!!)
else -> {
pendingResult?.error("Error", "Failed to access file", null)
@@ -167,6 +182,54 @@ class MainActivity : FlutterActivity() {
}
}
}
+
+ @SuppressLint("WrongConstant")
+ private fun handleCreateDirectory(call: MethodCall, result: MethodChannel.Result) {
+ val documentUri = Uri.parse(call.argument<String>("documentUri")!!)
+ val directoryName = call.argument<String>("directoryName")!!
+
+ if (folderExists(documentUri, directoryName)) {
+ result.success(null)
+ return
+ }
+
+ DocumentsContract.createDocument(
+ context.contentResolver, documentUri, DocumentsContract.Document.MIME_TYPE_DIR,
+ directoryName
+ )
+
+ result.success(null)
+ }
+
+ private fun folderExists(documentUri: Uri, folderName: String): Boolean {
+ var cursor: Cursor? = null
+ try {
+ cursor = contentResolver.query(
+ documentUri,
+ arrayOf(
+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,
+ DocumentsContract.Document.COLUMN_MIME_TYPE
+ ),
+ null,
+ null,
+ null,
+ )
+
+ if (cursor != null) {
+ while (cursor.moveToNext()) {
+ val displayName = cursor.getString(0)
+ val mimeType = cursor.getString(1)
+
+ if (folderName == displayName && DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
+ return true
+ }
+ }
+ }
+ } finally {
+ cursor?.close()
+ }
+ return false
+ }
}
data class PickDirectoryResult(
diff --git a/app/lib/model/state/server/receive_session_state.dart b/app/lib/model/state/server/receive_session_state.dart
index fc6778ba..a8335f6c 100644
--- a/app/lib/model/state/server/receive_session_state.dart
+++ b/app/lib/model/state/server/receive_session_state.dart
@@ -23,6 +23,12 @@ class ReceiveSessionState with ReceiveSessionStateMappable {
final String destinationDirectory;
final String cacheDirectory;
final bool saveToGallery;
+
+ /// On Android, we need to manually create missing directories.
+ /// To improve performance, we cache the created directories so we don't need to check them again.
+ /// WARNING: This list is modified in-place!
+ final Set<String> createdDirectories;
+
final StreamController<Map<String, String>?>? responseHandler;
const ReceiveSessionState({
@@ -36,6 +42,7 @@ class ReceiveSessionState with ReceiveSessionStateMappable {
required this.destinationDirectory,
required this.cacheDirectory,
required this.saveToGallery,
+ required this.createdDirectories,
required this.responseHandler,
});
diff --git a/app/lib/model/state/server/receive_session_state.mapper.dart b/app/lib/model/state/server/receive_session_state.mapper.dart
index ff833d05..a421144f 100644
--- a/app/lib/model/state/server/receive_session_state.mapper.dart
+++ b/app/lib/model/state/server/receive_session_state.mapper.dart
@@ -42,6 +42,8 @@ class ReceiveSessionStateMapper extends ClassMapperBase<ReceiveSessionState> {
static const Field<ReceiveSessionState, String> _f$cacheDirectory = Field('cacheDirectory', _$cacheDirectory);
static bool _$saveToGallery(ReceiveSessionState v) => v.saveToGallery;
static const Field<ReceiveSessionState, bool> _f$saveToGallery = Field('saveToGallery', _$saveToGallery);
+ static Set<String> _$createdDirectories(ReceiveSessionState v) => v.createdDirectories;
+ static const Field<ReceiveSessionState, Set<String>> _f$createdDirectories = Field('createdDirectories', _$createdDirectories);
static StreamController<Map<String, String>?>? _$responseHandler(ReceiveSessionState v) => v.responseHandler;
static const Field<ReceiveSessionState, StreamController<Map<String, String>?>> _f$responseHandler = Field('responseHandler', _$responseHandler);
@@ -57,6 +59,7 @@ class ReceiveSessionStateMapper extends ClassMapperBase<ReceiveSessionState> {
#destinationDirectory: _f$destinationDirectory,
#cacheDirectory: _f$cacheDirectory,
#saveToGallery: _f$saveToGallery,
+ #createdDirectories: _f$createdDirectories,
#responseHandler: _f$responseHandler,
};
@@ -72,6 +75,7 @@ class ReceiveSessionStateMapper extends ClassMapperBase<ReceiveSessionState> {
destinationDirectory: data.dec(_f$destinationDirectory),
cacheDirectory: data.dec(_f$cacheDirectory),
saveToGallery: data.dec(_f$saveToGallery),
+ createdDirectories: data.dec(_f$createdDirectories),
responseHandler: data.dec(_f$responseHandler));
}
@@ -133,6 +137,7 @@ abstract class ReceiveSessionStateCopyWith<$R, $In extends ReceiveSessionState,
String? destinationDirectory,
String? cacheDirectory,
bool? saveToGallery,
+ Set<String>? createdDirectories,
StreamController<Map<String, String>?>? responseHandler});
ReceiveSessionStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
@@ -160,6 +165,7 @@ class _ReceiveSessionStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, R
String? destinationDirectory,
String? cacheDirectory,
bool? saveToGallery,
+ Set<String>? createdDirectories,
Object? responseHandler = $none}) =>
$apply(FieldCopyWithData({
if (sessionId != null) #sessionId: sessionId,
@@ -172,6 +178,7 @@ class _ReceiveSessionStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, R
if (destinationDirectory != null) #destinationDirectory: destinationDirectory,
if (cacheDirectory != null) #cacheDirectory: cacheDirectory,
if (saveToGallery != null) #saveToGallery: saveToGallery,
+ if (createdDirectories != null) #createdDirectories: createdDirectories,
if (responseHandler != $none) #responseHandler: responseHandler
}));
@override
@@ -186,6 +193,7 @@ class _ReceiveSessionStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, R
destinationDirectory: data.get(#destinationDirectory, or: $value.destinationDirectory),
cacheDirectory: data.get(#cacheDirectory, or: $value.cacheDirectory),
saveToGallery: data.get(#saveToGallery, or: $value.saveToGallery),
+ createdDirectories: data.get(#createdDirectories, or: $value.createdDirectories),
responseHandler: data.get(#responseHandler, or: $value.responseHandler));
@override
diff --git a/app/lib/pages/tabs/settings_tab.dart b/app/lib/pages/tabs/settings_tab.dart
index fcb250e7..4ea642a2 100644
--- a/app/lib/pages/tabs/settings_tab.dart
+++ b/app/lib/pages/tabs/settings_tab.dart
@@ -16,7 +16,7 @@ import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/provider/version_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/util/device_type_ext.dart';
-import 'package:localsend_app/util/native/file_picker_android.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/pick_directory_path.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/custom_dropdown_button.dart';
diff --git a/app/lib/provider/network/server/controller/receive_controller.dart b/app/lib/provider/network/server/controller/receive_controller.dart
index a715e23e..b2929b58 100644
--- a/app/lib/provider/network/server/controller/receive_controller.dart
+++ b/app/lib/provider/network/server/controller/receive_controller.dart
@@ -39,7 +39,6 @@ import 'package:localsend_app/util/native/file_saver.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/native/tray_helper.dart';
import 'package:logging/logging.dart';
-import 'package:path/path.dart' as p;
import 'package:permission_handler/permission_handler.dart';
import 'package:routerino/routerino.dart';
import 'package:shelf/shelf.dart';
@@ -246,6 +245,7 @@ class ReceiveController {
destinationDirectory: destinationDir,
cacheDirectory: cacheDir,
saveToGallery: checkPlatformWithGallery() && settings.saveToGallery && dto.files.values.every((f) => !f.fileName.contains('/')),
+ createdDirectories: {},
responseHandler: streamController,
),
),
@@ -437,13 +437,12 @@ class ReceiveController {
final fileType = receivingFile.file.fileType;
final saveToGallery = receiveState.saveToGallery && (fileType == FileType.image || fileType == FileType.video);
- final destinationPath = await digestFilePathAndPrepareDirectory(
+ final (destinationPath, finalName) = await digestFilePathAndPrepareDirectory(
parentDirectory: saveToGallery ? receiveState.cacheDirectory : receiveState.destinationDirectory,
fileName: receivingFile.desiredName!,
+ createdDirectories: receiveState.createdDirectories,
);
- final finalName = p.basename(destinationPath);
-
_logger.info('Saving ${receivingFile.file.fileName} to $destinationPath');
await saveFile(
diff --git a/app/lib/provider/selection/selected_sending_files_provider.dart b/app/lib/provider/selection/selected_sending_files_provider.dart
index 4e90f4ba..e678d4aa 100644
--- a/app/lib/provider/selection/selected_sending_files_provider.dart
+++ b/app/lib/provider/selection/selected_sending_files_provider.dart
@@ -5,10 +5,10 @@ import 'dart:typed_data';
import 'package:common/model/file_type.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/util/file_path_helper.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/cache_helper.dart';
import 'package:localsend_app/util/native/content_uri_helper.dart';
import 'package:localsend_app/util/native/cross_file_converters.dart';
-import 'package:localsend_app/util/native/file_picker_android.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:refena_flutter/refena_flutter.dart';
@@ -193,7 +193,7 @@ class AddAndroidDirectoryAction extends AsyncReduxAction<SelectedSendingFilesNot
final newFiles = <CrossFile>[];
_logger.info('Reading files in ${result.directoryUri}');
- final basePath = ContentUriHelper.getFolderPathFromContentUri(result.directoryUri);
+ final basePath = ContentUriHelper.getPathFromTreeUri(result.directoryUri);
if (basePath == null) {
_logger.warning('Could not get base path from ${result.directoryUri}');
return state;
diff --git a/app/lib/util/native/file_picker_android.dart b/app/lib/util/native/android_saf.dart
similarity index 60%
rename from app/lib/util/native/file_picker_android.dart
rename to app/lib/util/native/android_saf.dart
index 84b17e7f..06cff629 100644
--- a/app/lib/util/native/file_picker_android.dart
+++ b/app/lib/util/native/android_saf.dart
@@ -1,9 +1,12 @@
import 'package:dart_mappable/dart_mappable.dart';
import 'package:flutter/services.dart';
+import 'package:localsend_app/util/native/content_uri_helper.dart';
+import 'package:logging/logging.dart';
-part 'file_picker_android.mapper.dart';
+part 'android_saf.mapper.dart';
const _methodChannel = MethodChannel('org.localsend.localsend_app/localsend');
+final _logger = Logger('AndroidSaf');
/// From Android 9 (Pie) and above, we need to use the Storage Access Framework (SAF) to access files.
/// Older versions might also work but the encoded content URI is not guaranteed to work with our algorithm.
@@ -35,6 +38,40 @@ Future<List<FileInfo>?> pickFilesAndroid() async {
return result.map((e) => FileInfoMapper.fromJson((e as Map).cast<String, dynamic>())).toList();
}
+Future<void> createDirectory({
+ required String documentUri,
+ required String directoryName,
+}) async {
+ _logger.info('Creating directory "$directoryName" in $documentUri');
+ await _methodChannel.invokeMethod('createDirectory', {
+ 'documentUri': documentUri,
+ 'directoryName': directoryName,
+ });
+}
+
+Future<void> createMissingDirectoriesAndroid({
+ required String parentUri,
+ required String fileName,
+ required Set<String> createdDirectories,
+}) async {
+ final parts = fileName.split('/');
+ for (int i = 0; i < parts.length - 1; i++) {
+ final subDirPath = parts.sublist(0, i + 1).join('/');
+ if (createdDirectories.contains(subDirPath)) {
+ continue;
+ }
+
+ await createDirectory(
+ documentUri: ContentUriHelper.convertTreeUriToDocumentUri(
+ treeUri: parentUri,
+ suffix: i == 0 ? null : parts.sublist(0, i).join('/'),
+ ),
+ directoryName: parts[i],
+ );
+ createdDirectories.add(subDirPath);
+ }
+}
+
@MappableClass()
class PickDirectoryResult with PickDirectoryResultMappable {
final String directoryUri;
diff --git a/app/lib/util/native/file_picker_android.mapper.dart b/app/lib/util/native/android_saf.mapper.dart
similarity index 99%
rename from app/lib/util/native/file_picker_android.mapper.dart
rename to app/lib/util/native/android_saf.mapper.dart
index 68fe2c6b..b3490540 100644
--- a/app/lib/util/native/file_picker_android.mapper.dart
+++ b/app/lib/util/native/android_saf.mapper.dart
@@ -4,7 +4,7 @@
// ignore_for_file: unused_element, unnecessary_cast, override_on_non_overriding_member
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
-part of 'file_picker_android.dart';
+part of 'android_saf.dart';
class PickDirectoryResultMapper extends ClassMapperBase<PickDirectoryResult> {
PickDirectoryResultMapper._();
diff --git a/app/lib/util/native/content_uri_helper.dart b/app/lib/util/native/content_uri_helper.dart
index 8baaf981..ed8b2b8b 100644
--- a/app/lib/util/native/content_uri_helper.dart
+++ b/app/lib/util/native/content_uri_helper.dart
@@ -2,7 +2,7 @@ class ContentUriHelper {
/// Converts
/// content://com.android.externalstorage.documents/tree/primary%3ADocuments
/// to primary:Documents
- static String? getFolderPathFromContentUri(String uri) {
+ static String? getPathFromTreeUri(String uri) {
final index = uri.indexOf('/tree/');
if (index == -1) {
return null;
@@ -50,6 +50,26 @@ class ContentUriHelper {
}
}
+ /// Converts
+ /// content://com.android.externalstorage.documents/tree/primary%3ALocalSend
+ /// to
+ /// content://com.android.externalstorage.documents/tree/primary%3ALocalSend/document/primary%3ALocalSend
+ /// or
+ /// content://com.android.externalstorage.documents/tree/primary%3ALocalSend/document/primary%3ALocalSend%2FsubFolder
+ static String convertTreeUriToDocumentUri({
+ required String treeUri,
+ String? suffix,
+ }) {
+ final index = treeUri.indexOf('/tree/');
+ final treePath = treeUri.substring(index + 6);
+
+ if (suffix == null) {
+ return '$treeUri/document/$treePath';
+ } else {
+ return '$treeUri/document/$treePath%2F${Uri.encodeComponent(suffix)}';
+ }
+ }
+
/// Converts
/// content://com.android.externalstorage.documents/tree/primary%3ALocalSend/subFolder
/// to
diff --git a/app/lib/util/native/cross_file_converters.dart b/app/lib/util/native/cross_file_converters.dart
index d40630cc..4807132c 100644
--- a/app/lib/util/native/cross_file_converters.dart
+++ b/app/lib/util/native/cross_file_converters.dart
@@ -6,7 +6,7 @@ import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/util/file_path_helper.dart';
-import 'package:localsend_app/util/native/file_picker_android.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:share_handler/share_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
diff --git a/app/lib/util/native/file_picker.dart b/app/lib/util/native/file_picker.dart
index 07b730c5..a667c088 100644
--- a/app/lib/util/native/file_picker.dart
+++ b/app/lib/util/native/file_picker.dart
@@ -13,8 +13,8 @@ import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/util/determine_image_type.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/cross_file_converters.dart';
-import 'package:localsend_app/util/native/file_picker_android.dart';
import 'package:localsend_app/util/native/pick_directory_path.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/ui/asset_picker_translated_text_delegate.dart';
diff --git a/app/lib/util/native/file_saver.dart b/app/lib/util/native/file_saver.dart
index ed073f8b..b570b719 100644
--- a/app/lib/util/native/file_saver.dart
+++ b/app/lib/util/native/file_saver.dart
@@ -4,6 +4,7 @@ import 'dart:typed_data';
import 'package:gal/gal.dart';
import 'package:legalize/legalize.dart';
import 'package:localsend_app/util/file_path_helper.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/content_uri_helper.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
@@ -27,14 +28,15 @@ Future<void> saveFile({
required DateTime? lastAccessed,
required void Function(int savedBytes) onProgress,
}) async {
- if (androidSdkInt != null) {
+ if (!saveToGallery && androidSdkInt != null) {
+ // Use SAF to save the file
+ // When saveToGallery is enabled, the destination is always the app's cache directory so we don't need to use SAF
SafWriteStreamInfo? safInfo;
if (destinationPath.startsWith('content://')) {
- final uriString = ContentUriHelper.encodeTreeUri(destinationPath.withoutFileName());
- _logger.info('Using SAF to save file to $uriString');
+ _logger.info('Using SAF to save file to $destinationPath as $name');
safInfo = await _saf.startWriteStream(
- Uri.parse(uriString),
+ Uri.parse(destinationPath),
name,
isImage ? 'image/*' : '*/*',
);
@@ -156,17 +158,31 @@ Future<void> _saveFile({
}
/// If there is a file with the same name, then it appends a number to its file name
-Future<String> digestFilePathAndPrepareDirectory({required String parentDirectory, required String fileName}) async {
+Future<(String, String)> digestFilePathAndPrepareDirectory({
+ required String parentDirectory,
+ required String fileName,
+ required Set<String> createdDirectories,
+}) async {
+ if (parentDirectory.startsWith('content://')) {
+ if (fileName.contains('/')) {
+ try {
+ await createMissingDirectoriesAndroid(parentUri: parentDirectory, fileName: fileName, createdDirectories: createdDirectories);
+ } catch (e) {
+ _logger.warning('Could not create missing directories', e);
+ }
+ return (ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: fileName.withoutFileName()), p.basename(fileName));
+ }
+ return (ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: null), p.basename(fileName));
+ }
+
final actualFileName = legalizeFilename(p.basename(fileName), os: Platform.operatingSystem);
final fileNameParts = p.split(fileName);
final dir = p.joinAll([parentDirectory, ...fileNameParts.take(fileNameParts.length - 1)]);
- if (!dir.startsWith('content://')) {
- try {
- Directory(dir).createSync(recursive: true);
- } catch (e) {
- _logger.warning('Could not create directory', e);
- }
+ try {
+ Directory(dir).createSync(recursive: true);
+ } catch (e) {
+ _logger.warning('Could not create directory', e);
}
String destinationPath;
@@ -175,7 +191,7 @@ Future<String> digestFilePathAndPrepareDirectory({required String parentDirector
destinationPath = counter == 1 ? p.join(dir, actualFileName) : p.join(dir, actualFileName.withCount(counter));
counter++;
} while (await File(destinationPath).exists());
- return destinationPath;
+ return (destinationPath, p.basename(destinationPath));
}
final _sdCardPathRegex = RegExp(r'^/storage/([A-Fa-f0-9]{4}-[A-Fa-f0-9]{4})/(.*)$');
diff --git a/app/test/unit/util/native/content_uri_helper_test.dart b/app/test/unit/util/native/content_uri_helper_test.dart
index d28f3dcd..1e0e3093 100644
--- a/app/test/unit/util/native/content_uri_helper_test.dart
+++ b/app/test/unit/util/native/content_uri_helper_test.dart
@@ -2,24 +2,24 @@ import 'package:localsend_app/util/native/content_uri_helper.dart';
import 'package:test/test.dart';
void main() {
- group('getFolderPathFromContentUri', () {
+ group('getPathFromTreeUri', () {
test('should return the root folder path from the content uri', () {
expect(
- ContentUriHelper.getFolderPathFromContentUri('content://com.android.externalstorage.documents/tree/primary%3ADocuments'),
+ ContentUriHelper.getPathFromTreeUri('content://com.android.externalstorage.documents/tree/primary%3ADocuments'),
'primary:Documents',
);
});
test('should return the folder path from the content uri', () {
expect(
- ContentUriHelper.getFolderPathFromContentUri('content://com.android.externalstorage.documents/tree/primary%3ADocuments%2FOffice%20Lens'),
+ ContentUriHelper.getPathFromTreeUri('content://com.android.externalstorage.documents/tree/primary%3ADocuments%2FOffice%20Lens'),
'primary:Documents/Office Lens',
);
});
test('should return folder path from content uri in SD card', () {
expect(
- ContentUriHelper.getFolderPathFromContentUri('content://com.android.externalstorage.documents/tree/1234-5678:Documents'),
+ ContentUriHelper.getPathFromTreeUri('content://com.android.externalstorage.documents/tree/1234-5678:Documents'),
'1234-5678:Documents',
);
});
@@ -99,11 +99,27 @@ void main() {
});
});
+ group('convertTreeUriToDocumentUri', () {
+ test('should return the document uri from the tree uri', () {
+ expect(
+ ContentUriHelper.convertTreeUriToDocumentUri(treeUri: 'content://com.android.externalstorage.documents/tree/primary%3ALocalSend'),
+ 'content://com.android.externalstorage.documents/tree/primary%3ALocalSend/document/primary%3ALocalSend',
+ );
+ });
+
+ test('should return the document uri from the tree uri with a folder', () {
+ expect(
+ ContentUriHelper.convertTreeUriToDocumentUri(
+ treeUri: 'content://com.android.externalstorage.documents/tree/primary%3ALocalSend', suffix: 'subFolder'),
+ 'content://com.android.externalstorage.documents/tree/primary%3ALocalSend/document/primary%3ALocalSend%2FsubFolder',
+ );
+ });
+ });
+
group('encodeTreeUri', () {
test('should return the encoded tree uri', () {
expect(
- ContentUriHelper.encodeTreeUri(
- 'content://com.android.externalstorage.documents/tree/primary%3ALocalSend/subFolder'),
+ ContentUriHelper.encodeTreeUri('content://com.android.externalstorage.documents/tree/primary%3ALocalSend/subFolder'),
'content://com.android.externalstorage.documents/tree/primary%3ALocalSend%2FsubFolder',
);
});