Skip to content

Commit

Permalink
[file_selector_android] Modifies getDirectoryPath, openFile, `ope…
Browse files Browse the repository at this point in the history
…nFiles` to return file/directory paths instead of URIs (#6438)

## Overview

Changes `getDirectoryPath`, `openFile`, and `openFiles` to return the directory path instead of the URI representing the directory or file.

Fixes flutter/flutter#141250.

## Technical Details

Technically, `getDirectoryPath` returns the path of the selected directory directly, whereas `openFile` and `openFiles` actually copy the content that the URI points to into another file and returns the path of the file. This is a direct result of the fact that Android **highly discourages** folks from accessing files through direct paths, so it's extremely difficult to do reliably without this approach (can confirm by how much effort it took to get this PR out...).

This approach [is also used in `image_picker_android`](https://github.com/flutter/packages/blob/main/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java) and this PR uses essentially the same logic.

I think we should move forward with this short term solution to unblock folks that need access to directories and files in Dart, but I strongly advise that we re-evaluate for the long term. I elaborate on this in [this doc](https://docs.google.com/document/d/12pJDtl0yubyc68UqKo2hQ7XJwv86_ixCjNemQ7ENCBQ/edit?usp=sharing) and welcome feedback!
  • Loading branch information
camsim99 committed Apr 29, 2024
1 parent 87a7c51 commit 36c42bd
Show file tree
Hide file tree
Showing 9 changed files with 712 additions and 141 deletions.
2 changes: 2 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ updates:
update-types: ["version-update:semver-minor", "version-update:semver-patch"]
- dependency-name: "androidx.test:*"
update-types: ["version-update:semver-minor", "version-update:semver-patch"]
- dependency-name: "org.robolectric:*"
update-types: ["version-update:semver-minor", "version-update:semver-patch"]

- package-ecosystem: "gradle"
directory: "/packages/file_selector/file_selector_android/example/android/app"
Expand Down
3 changes: 2 additions & 1 deletion packages/file_selector/file_selector_android/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
## NEXT
## 0.5.1

* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Updates compileSdk version to 34.
* Modifies `getDirectoryPath`, `openFile`, and `openFiles` to return file/directory paths instead of URIs.

## 0.5.0+7

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ android {
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-inline:5.1.0'
testImplementation 'androidx.test:core:1.3.0'
testImplementation "org.robolectric:robolectric:4.12.1"

// org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions.
// See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

package dev.flutter.packages.file_selector_android;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
Expand Down Expand Up @@ -106,6 +107,12 @@ public void openFile(
public void onResult(int resultCode, @Nullable Intent data) {
if (resultCode == Activity.RESULT_OK && data != null) {
final Uri uri = data.getData();
if (uri == null) {
// No data retrieved from opening file.
result.error(new Exception("Failed to retrieve data from opening file."));
return;
}

final GeneratedFileSelectorApi.FileResponse file = toFileResponse(uri);
if (file != null) {
result.success(file);
Expand Down Expand Up @@ -183,6 +190,7 @@ public void onResult(int resultCode, @Nullable Intent data) {
}

@Override
@TargetApi(21)
public void getDirectoryPath(
@Nullable String initialDirectory, @NonNull GeneratedFileSelectorApi.Result<String> result) {
if (!sdkChecker.sdkIsAtLeast(android.os.Build.VERSION_CODES.LOLLIPOP)) {
Expand All @@ -204,7 +212,22 @@ public void getDirectoryPath(
public void onResult(int resultCode, @Nullable Intent data) {
if (resultCode == Activity.RESULT_OK && data != null) {
final Uri uri = data.getData();
result.success(uri.toString());
if (uri == null) {
// No data retrieved from opening directory.
result.error(new Exception("Failed to retrieve data from opening directory."));
return;
}

final Uri docUri =
DocumentsContract.buildDocumentUriUsingTree(
uri, DocumentsContract.getTreeDocumentId(uri));
try {
final String path =
FileUtils.getPathFromUri(activityPluginBinding.getActivity(), docUri);
result.success(path);
} catch (UnsupportedOperationException exception) {
result.error(exception);
}
} else {
result.success(null);
}
Expand Down Expand Up @@ -332,10 +355,13 @@ GeneratedFileSelectorApi.FileResponse toFileResponse(@NonNull Uri uri) {
return null;
}

final String uriPath =
FileUtils.getPathFromCopyOfFileFromUri(activityPluginBinding.getActivity(), uri);

return new GeneratedFileSelectorApi.FileResponse.Builder()
.setName(name)
.setBytes(bytes)
.setPath(uri.toString())
.setPath(uriPath)
.setMimeType(contentResolver.getType(uri))
.setSize(size.longValue())
.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/*
* Copyright (C) 2007-2008 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file was modified by the Flutter authors from the following original file:
* https://raw.githubusercontent.com/iPaulPro/aFileChooser/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
*/

package dev.flutter.packages.file_selector_android;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class FileUtils {

/** URI authority that represents access to external storage providers. */
public static final String EXTERNAL_DOCUMENT_AUTHORITY = "com.android.externalstorage.documents";

/**
* Retrieves path of directory represented by the specified {@code Uri}.
*
* <p>Intended to handle any cases needed to return paths from URIs retrieved from open
* documents/directories by starting one of {@code Intent.ACTION_OPEN_FILE}, {@code
* Intent.ACTION_OPEN_FILES}, or {@code Intent.ACTION_OPEN_DOCUMENT_TREE}.
*
* <p>Will return the path for on-device directories, but does not handle external storage
* volumes.
*/
@NonNull
public static String getPathFromUri(@NonNull Context context, @NonNull Uri uri) {
String uriAuthority = uri.getAuthority();

if (EXTERNAL_DOCUMENT_AUTHORITY.equals(uriAuthority)) {
String uriDocumentId = DocumentsContract.getDocumentId(uri);
String[] uriDocumentIdSplit = uriDocumentId.split(":");

if (uriDocumentIdSplit.length < 2) {
// We expect the URI document ID to contain its storage volume and name to determine its path.
throw new UnsupportedOperationException(
"Retrieving the path of a document with an unknown storage volume or name is unsupported by this plugin.");
}

String documentStorageVolume = uriDocumentIdSplit[0];

// Non-primary storage volumes come from SD cards, USB drives, etc. and are
// not handled here.
//
// Constant for primary storage volumes found at
// https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/provider/DocumentsContract.java;l=255?q=Documentscont&ss=android%2Fplatform%2Fsuperproject%2Fmain.
if (!documentStorageVolume.equals("primary")) {
throw new UnsupportedOperationException(
"Retrieving the path of a document from storage volume "
+ documentStorageVolume
+ " is unsupported by this plugin.");
}
String innermostDirectoryName = uriDocumentIdSplit[1];
String externalStorageDirectory = Environment.getExternalStorageDirectory().getPath();

return externalStorageDirectory + "/" + innermostDirectoryName;
} else {
throw new UnsupportedOperationException(
"Retrieving the path from URIs with authority "
+ uriAuthority.toString()
+ " is unsupported by this plugin.");
}
}

/**
* Copies the file from the given content URI to a temporary directory, retaining the original
* file name if possible.
*
* <p>Each file is placed in its own directory to avoid conflicts according to the following
* scheme: {cacheDir}/{randomUuid}/{fileName}
*
* <p>File extension is changed to match MIME type of the file, if known. Otherwise, the extension
* is left unchanged.
*
* <p>If the original file name is unknown, a predefined "file_selector" filename is used and the
* file extension is deduced from the mime type.
*
* <p>Will return null if copying the URI contents into a new file does not complete successfully
* or if a security exception is encountered when opening the input stream to start the copying.
*/
@Nullable
public static String getPathFromCopyOfFileFromUri(@NonNull Context context, @NonNull Uri uri) {
try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
String uuid = UUID.nameUUIDFromBytes(uri.toString().getBytes()).toString();
File targetDirectory = new File(context.getCacheDir(), uuid);
targetDirectory.mkdir();
targetDirectory.deleteOnExit();
String fileName = getFileName(context, uri);
String extension = getFileExtension(context, uri);

if (fileName == null) {
if (extension == null) {
throw new IllegalArgumentException("No name nor extension found for file.");
} else {
fileName = "file_selector" + extension;
}
} else if (extension != null) {
fileName = getBaseName(fileName) + extension;
}

File file = new File(targetDirectory, fileName);

try (OutputStream outputStream = new FileOutputStream(file)) {
copy(inputStream, outputStream);
return file.getPath();
}
} catch (IOException e) {
// If closing the output stream fails, we cannot be sure that the
// target file was written in full. Flushing the stream merely moves
// the bytes into the OS, not necessarily to the file.
return null;
} catch (SecurityException e) {
// Calling `ContentResolver#openInputStream()` has been reported to throw a
// `SecurityException` on some devices in certain circumstances. Instead of crashing, we
// return `null`.
//
// See https://github.com/flutter/flutter/issues/100025 for more details.
return null;
}
}

/** Returns the extension of file with dot, or null if it's empty. */
private static String getFileExtension(Context context, Uri uriFile) {
String extension;

if (uriFile.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uriFile));
} else {
try {
Uri uriFromFile = Uri.fromFile(new File(uriFile.getPath()));
extension = MimeTypeMap.getFileExtensionFromUrl(uriFromFile.toString());
} catch (NullPointerException e) {
// File created from uriFile was null.
return null;
}
}

if (extension == null || extension.isEmpty()) {
return null;
}

return "." + extension;
}

/** Returns the name of the file provided by ContentResolver; this may be null. */
private static String getFileName(Context context, Uri uriFile) {
try (Cursor cursor = queryFileName(context, uriFile)) {
if (cursor == null || !cursor.moveToFirst() || cursor.getColumnCount() < 1) return null;
return cursor.getString(0);
}
}

private static Cursor queryFileName(Context context, Uri uriFile) {
return context
.getContentResolver()
.query(uriFile, new String[] {MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
}

private static void copy(InputStream in, OutputStream out) throws IOException {
final byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
}

private static String getBaseName(String fileName) {
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex < 0) {
return fileName;
}
// Basename is everything before the last '.'.
return fileName.substring(0, lastDotIndex);
}
}
Loading

0 comments on commit 36c42bd

Please sign in to comment.