Skip to content

An open-source cross-platform alternative to AirDrop

feat: improve Android SAF

Tien Do Namf6aec77ad025
diff --git a/app/android/app/src/main/kotlin/org/localsend/localsend_app/FileOpener.kt b/app/android/app/src/main/kotlin/org/localsend/localsend_app/FileOpener.kt
new file mode 100644
index 00000000..d40b974e
--- /dev/null
+++ b/app/android/app/src/main/kotlin/org/localsend/localsend_app/FileOpener.kt
@@ -0,0 +1,93 @@
+package org.localsend.localsend_app
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.provider.DocumentsContract
+import java.util.Locale
+
+fun openUri(context: Context, uriStr: String) {
+ val uri = Uri.parse(uriStr)
+ val intent = Intent(Intent.ACTION_VIEW, uri)
+ val type = getFileType(uriStr)
+
+ println("Inferred type: $type")
+
+ intent.setDataAndType(uri, type)
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ context.startActivity(intent)
+}
+
+private fun getFileType(filePath: String): String {
+ val fileExt = filePath.substring(filePath.lastIndexOf(".") + 1).lowercase(Locale.ROOT)
+ println("File extension: $fileExt")
+ return when (fileExt) {
+ "3gp" -> "video/3gpp"
+ "torrent" -> "application/x-bittorrent"
+ "kml" -> "application/vnd.google-earth.kml+xml"
+ "gpx" -> "application/gpx+xml"
+ "apk" -> "application/vnd.android.package-archive"
+ "asf" -> "video/x-ms-asf"
+ "avi" -> "video/x-msvideo"
+ "bin", "class", "exe" -> "application/octet-stream"
+ "bmp" -> "image/bmp"
+ "c" -> "text/plain"
+ "conf" -> "text/plain"
+ "cpp" -> "text/plain"
+ "doc" -> "application/msword"
+ "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ "xls", "csv" -> "application/vnd.ms-excel"
+ "xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+ "gif" -> "image/gif"
+ "gtar" -> "application/x-gtar"
+ "gz" -> "application/x-gzip"
+ "h" -> "text/plain"
+ "htm" -> "text/html"
+ "html" -> "text/html"
+ "jar" -> "application/java-archive"
+ "java" -> "text/plain"
+ "jpeg" -> "image/jpeg"
+ "jpg" -> "image/jpeg"
+ "js" -> "application/x-javascript"
+ "log" -> "text/plain"
+ "m3u" -> "audio/x-mpegurl"
+ "m4a" -> "audio/mp4a-latm"
+ "m4b" -> "audio/mp4a-latm"
+ "m4p" -> "audio/mp4a-latm"
+ "m4u" -> "video/vnd.mpegurl"
+ "m4v" -> "video/x-m4v"
+ "mov" -> "video/quicktime"
+ "mp2" -> "audio/x-mpeg"
+ "mp3" -> "audio/x-mpeg"
+ "mp4" -> "video/mp4"
+ "mpc" -> "application/vnd.mpohun.certificate"
+ "mpe" -> "video/mpeg"
+ "mpeg" -> "video/mpeg"
+ "mpg" -> "video/mpeg"
+ "mpg4" -> "video/mp4"
+ "mpga" -> "audio/mpeg"
+ "msg" -> "application/vnd.ms-outlook"
+ "ogg" -> "audio/ogg"
+ "pdf" -> "application/pdf"
+ "png" -> "image/png"
+ "pps" -> "application/vnd.ms-powerpoint"
+ "ppt" -> "application/vnd.ms-powerpoint"
+ "pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation"
+ "prop" -> "text/plain"
+ "rc" -> "text/plain"
+ "rmvb" -> "audio/x-pn-realaudio"
+ "rtf" -> "application/rtf"
+ "sh" -> "text/plain"
+ "tar" -> "application/x-tar"
+ "tgz" -> "application/x-compressed"
+ "txt" -> "text/plain"
+ "wav" -> "audio/x-wav"
+ "wma" -> "audio/x-ms-wma"
+ "wmv" -> "audio/x-ms-wmv"
+ "wps" -> "application/vnd.ms-works"
+ "xml" -> "text/plain"
+ "z" -> "application/x-compress"
+ "zip" -> "application/x-zip-compressed"
+ else -> DocumentsContract.Document.MIME_TYPE_DIR
+ }
+}
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 97439bda..b7ee1d40 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
@@ -44,6 +44,11 @@ class MainActivity : FlutterActivity() {
"createDirectory" -> handleCreateDirectory(call, result)
+ "openContentUri" -> {
+ openUri(context, call.argument<String>("uri")!!)
+ result.success(null)
+ }
+
else -> result.notImplemented()
}
}
diff --git a/app/lib/pages/tabs/settings_tab.dart b/app/lib/pages/tabs/settings_tab.dart
index 4ea642a2..fc330e63 100644
--- a/app/lib/pages/tabs/settings_tab.dart
+++ b/app/lib/pages/tabs/settings_tab.dart
@@ -11,12 +11,10 @@ import 'package:localsend_app/pages/changelog_page.dart';
import 'package:localsend_app/pages/donation/donation_page.dart';
import 'package:localsend_app/pages/language_page.dart';
import 'package:localsend_app/pages/tabs/settings_tab_controller.dart';
-import 'package:localsend_app/provider/device_info_provider.dart';
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/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';
@@ -194,13 +192,7 @@ class SettingsTab extends StatelessWidget {
return;
}
- final String? directory;
- if (defaultTargetPlatform == TargetPlatform.android &&
- (ref.read(deviceRawInfoProvider).androidSdkInt ?? 0) >= contentUriMinSdk) {
- directory = await pickDirectoryPathAndroid();
- } else {
- directory = await pickDirectoryPath();
- }
+ final directory = await pickDirectoryPath();
if (directory != null) {
await ref.notifier(settingsProvider).setDestination(directory);
}
diff --git a/app/lib/provider/network/server/controller/receive_controller.dart b/app/lib/provider/network/server/controller/receive_controller.dart
index b2929b58..fcc23039 100644
--- a/app/lib/provider/network/server/controller/receive_controller.dart
+++ b/app/lib/provider/network/server/controller/receive_controller.dart
@@ -437,7 +437,7 @@ class ReceiveController {
final fileType = receivingFile.file.fileType;
final saveToGallery = receiveState.saveToGallery && (fileType == FileType.image || fileType == FileType.video);
- final (destinationPath, finalName) = await digestFilePathAndPrepareDirectory(
+ final (destinationPath, documentUri, finalName) = await digestFilePathAndPrepareDirectory(
parentDirectory: saveToGallery ? receiveState.cacheDirectory : receiveState.destinationDirectory,
fileName: receivingFile.desiredName!,
createdDirectories: receiveState.createdDirectories,
@@ -447,6 +447,7 @@ class ReceiveController {
await saveFile(
destinationPath: destinationPath,
+ documentUri: documentUri,
name: finalName,
saveToGallery: saveToGallery,
isImage: fileType == FileType.image,
diff --git a/app/lib/util/file_path_helper.dart b/app/lib/util/file_path_helper.dart
index d019f6fe..a3387d12 100644
--- a/app/lib/util/file_path_helper.dart
+++ b/app/lib/util/file_path_helper.dart
@@ -49,7 +49,7 @@ extension FilePathStringExt on String {
}
}
- String withoutFileName() {
+ String parentPath() {
final parts = replaceAll('\\', '/').split('/');
return parts.take(parts.length - 1).join('/');
}
diff --git a/app/lib/util/native/android_saf.dart b/app/lib/util/native/android_saf.dart
index f6bd7577..2ba31aff 100644
--- a/app/lib/util/native/android_saf.dart
+++ b/app/lib/util/native/android_saf.dart
@@ -74,6 +74,15 @@ Future<void> createMissingDirectoriesAndroid({
}
}
+Future<void> openContentUri({
+ required String uri,
+}) async {
+ _logger.info('Opening content URI: $uri');
+ await _methodChannel.invokeMethod('openContentUri', {
+ 'uri': uri,
+ });
+}
+
@MappableClass()
class PickDirectoryResult with PickDirectoryResultMappable {
final String directoryUri;
diff --git a/app/lib/util/native/file_saver.dart b/app/lib/util/native/file_saver.dart
index b570b719..f8ac2e16 100644
--- a/app/lib/util/native/file_saver.dart
+++ b/app/lib/util/native/file_saver.dart
@@ -19,6 +19,7 @@ final _saf = SafStream();
/// [onProgress] will be called on every 100 ms.
Future<void> saveFile({
required String destinationPath,
+ required String? documentUri,
required String name,
required bool saveToGallery,
required bool isImage,
@@ -33,10 +34,10 @@ Future<void> saveFile({
// 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://')) {
- _logger.info('Using SAF to save file to $destinationPath as $name');
+ if (documentUri != null || destinationPath.startsWith('content://')) {
+ _logger.info('Using SAF to save file to ${documentUri ?? destinationPath} as $name');
safInfo = await _saf.startWriteStream(
- Uri.parse(destinationPath),
+ Uri.parse(documentUri ?? destinationPath),
name,
isImage ? 'image/*' : '*/*',
);
@@ -44,7 +45,7 @@ Future<void> saveFile({
final sdCardPath = getSdCardPath(destinationPath);
if (sdCardPath != null) {
// Use Android SAF to save the file to the SD card
- final uriString = ContentUriHelper.encodeTreeUri(sdCardPath.path.withoutFileName());
+ final uriString = ContentUriHelper.encodeTreeUri(sdCardPath.path.parentPath());
_logger.info('Using SAF to save file to $uriString');
safInfo = await _saf.startWriteStream(
Uri.parse('content://com.android.externalstorage.documents/tree/${sdCardPath.sdCardId}:$uriString'),
@@ -158,21 +159,29 @@ Future<void> _saveFile({
}
/// If there is a file with the same name, then it appends a number to its file name
-Future<(String, String)> digestFilePathAndPrepareDirectory({
+Future<(String, String?, String)> digestFilePathAndPrepareDirectory({
required String parentDirectory,
required String fileName,
required Set<String> createdDirectories,
}) async {
if (parentDirectory.startsWith('content://')) {
+ final String documentUri;
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));
+ documentUri = ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: fileName.parentPath());
+ } else {
+ // root directory
+ documentUri = ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: null);
}
- return (ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: null), p.basename(fileName));
+
+ // destinationUri is for the history
+ // documentUri is for SAF to save the file, it should point to the parent directory
+ final destinationUri = ContentUriHelper.convertTreeUriToDocumentUri(treeUri: parentDirectory, suffix: fileName);
+ return (destinationUri, documentUri, p.basename(fileName));
}
final actualFileName = legalizeFilename(p.basename(fileName), os: Platform.operatingSystem);
@@ -191,7 +200,7 @@ Future<(String, String)> digestFilePathAndPrepareDirectory({
destinationPath = counter == 1 ? p.join(dir, actualFileName) : p.join(dir, actualFileName.withCount(counter));
counter++;
} while (await File(destinationPath).exists());
- return (destinationPath, p.basename(destinationPath));
+ return (destinationPath, null, p.basename(destinationPath));
}
final _sdCardPathRegex = RegExp(r'^/storage/([A-Fa-f0-9]{4}-[A-Fa-f0-9]{4})/(.*)$');
diff --git a/app/lib/util/native/open_file.dart b/app/lib/util/native/open_file.dart
index 1e762848..e5dd18bf 100644
--- a/app/lib/util/native/open_file.dart
+++ b/app/lib/util/native/open_file.dart
@@ -1,5 +1,6 @@
import 'package:common/model/file_type.dart';
import 'package:flutter/material.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/dialogs/cannot_open_file_dialog.dart';
import 'package:open_filex/open_filex.dart';
@@ -15,6 +16,12 @@ Future<void> openFile(
if ((fileType == FileType.apk || filePath.toLowerCase().endsWith('.apk')) && checkPlatform([TargetPlatform.android])) {
await Permission.requestInstallPackages.request();
}
+
+ if (filePath.startsWith('content://')) {
+ await openContentUri(uri: filePath);
+ return;
+ }
+
final fileOpenResult = await OpenFilex.open(filePath);
if (fileOpenResult.type != ResultType.done && context.mounted) {
await CannotOpenFileDialog.open(context, filePath, onDeleteTap);
diff --git a/app/lib/util/native/open_folder.dart b/app/lib/util/native/open_folder.dart
index cc6eef35..e66b6e58 100644
--- a/app/lib/util/native/open_folder.dart
+++ b/app/lib/util/native/open_folder.dart
@@ -1,3 +1,4 @@
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:logging/logging.dart';
import 'package:open_filex/open_filex.dart';
@@ -5,6 +6,11 @@ final _logger = Logger('OpenFolder');
/// Opens the selected file which is stored on the device.
Future<void> openFolder(String path) async {
+ if (path.startsWith('content://')) {
+ await openContentUri(uri: path);
+ return;
+ }
+
if (!path.endsWith('/')) {
path = '$path/';
}
diff --git a/app/lib/util/native/pick_directory_path.dart b/app/lib/util/native/pick_directory_path.dart
index d0f78171..2805fcb8 100644
--- a/app/lib/util/native/pick_directory_path.dart
+++ b/app/lib/util/native/pick_directory_path.dart
@@ -1,13 +1,19 @@
import 'package:file_picker/file_picker.dart';
import 'package:file_selector/file_selector.dart' as file_selector;
-import 'package:flutter/services.dart';
+import 'package:flutter/foundation.dart';
+import 'package:localsend_app/provider/device_info_provider.dart';
+import 'package:localsend_app/util/native/android_saf.dart';
import 'package:localsend_app/util/native/platform_check.dart';
-
-const _methodChannel = MethodChannel('org.localsend.localsend_app/localsend');
+import 'package:refena_flutter/refena_flutter.dart';
/// Opens a file picker to select a directory.
/// Returns null if the user cancels the selection.
Future<String?> pickDirectoryPath() async {
+ if (defaultTargetPlatform == TargetPlatform.android &&
+ (RefenaScope.defaultRef.read(deviceRawInfoProvider).androidSdkInt ?? 0) >= contentUriMinSdk) {
+ return await pickDirectoryPathAndroid();
+ }
+
if (checkPlatform([TargetPlatform.android, TargetPlatform.iOS])) {
/// We need to use the file_picker package because file_selector does not expose the raw path.
/// We need the raw path to properly manipulate the path to save new files, or
@@ -18,7 +24,3 @@ Future<String?> pickDirectoryPath() async {
return await file_selector.getDirectoryPath();
}
}
-
-Future<void> pickDirectoryNew() async {
- await _methodChannel.invokeMethod<void>('pickDirectory');
-}