implement mirror/repos on USB OTG via Storage Access Framework

* https://developer.android.com/training/articles/scoped-directory-access

One potential future direction, if this proves too limiting:
https://github.com/magnusja/libaums
This commit is contained in:
Hans-Christoph Steiner 2018-09-11 10:30:00 +02:00
parent 1ce70d3703
commit 525f99b056
8 changed files with 239 additions and 6 deletions

View File

@ -0,0 +1,32 @@
/*
* Copyright (C) 2018 Senecto Limited
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.fdroid.fdroid.nearby;
import android.app.Activity;
import android.content.Intent;
/**
* Dummy version for basic app flavor.
*/
public class TreeUriScannerIntentService {
public static void onActivityResult(Activity activity, Intent intent) {
throw new IllegalStateException("unimplemented");
}
}

View File

@ -20,19 +20,24 @@
package org.fdroid.fdroid.nearby;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.support.v4.provider.DocumentFile;
import android.util.Log;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.fdroid.fdroid.AddRepoIntentService;
import org.fdroid.fdroid.IndexUpdater;
import org.fdroid.fdroid.IndexV1Updater;
import org.fdroid.fdroid.Preferences;
import org.fdroid.fdroid.R;
import org.fdroid.fdroid.Utils;
import org.fdroid.fdroid.data.Repo;
import org.fdroid.fdroid.data.RepoProvider;
@ -57,8 +62,11 @@ import java.util.jar.JarInputStream;
* {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only
* workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.
* It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.
* {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also
* necessary to do this with any kind of rational UX.
*
* @see <a href="https://commonsware.com/blog/2017/11/15/storage-situation-removable-storage.html">The Storage Situation: Removable Storage </a>
* @see <a href="https://commonsware.com/blog/2016/11/18/be-careful-scoped-directory-access.html">Be Careful with Scoped Directory Access</a>
* @see <a href="https://developer.android.com/training/articles/scoped-directory-access.html">Using Scoped Directory Access</a>
* @see <a href="https://developer.android.com/guide/topics/providers/document-provider.html">Open Files using Storage Access Framework</a>
*/
@ -81,6 +89,25 @@ public class TreeUriScannerIntentService extends IntentService {
}
}
/**
* Now determine if it is External Storage that must be handled by the
* {@link TreeUriScannerIntentService} or whether it is External Storage
* like an SD Card that can be directly accessed via the file system.
*/
public static void onActivityResult(Activity activity, Intent intent) {
Uri uri = intent.getData();
if (uri != null) {
if (Build.VERSION.SDK_INT >= 19) {
ContentResolver contentResolver = activity.getContentResolver();
int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
contentResolver.takePersistableUriPermission(uri, perms);
}
String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
scan(activity, uri);
}
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {

View File

@ -0,0 +1,96 @@
package org.fdroid.fdroid.nearby;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract;
import android.support.annotation.Nullable;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
/**
* @see <a href="https://stackoverflow.com/a/36162691">Android 5.0 DocumentFile from tree URI</a>
*/
public final class TreeUriUtils {
public static final String TAG = "TreeUriUtils";
private static final String PRIMARY_VOLUME_NAME = "primary";
@Nullable
public static String getFullPathFromTreeUri(Context context, @Nullable final Uri treeUri) {
if (treeUri == null) return null;
String volumePath = getVolumePath(getVolumeIdFromTreeUri(treeUri), context);
if (volumePath == null) return File.separator;
if (volumePath.endsWith(File.separator))
volumePath = volumePath.substring(0, volumePath.length() - 1);
String documentPath = getDocumentPathFromTreeUri(treeUri);
if (documentPath.endsWith(File.separator))
documentPath = documentPath.substring(0, documentPath.length() - 1);
if (documentPath.length() > 0) {
if (documentPath.startsWith(File.separator))
return volumePath + documentPath;
else
return volumePath + File.separator + documentPath;
} else return volumePath;
}
@SuppressLint("ObsoleteSdkInt")
private static String getVolumePath(final String volumeId, Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null;
try {
StorageManager mStorageManager =
(StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getUuid = storageVolumeClazz.getMethod("getUuid");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String uuid = (String) getUuid.invoke(storageVolumeElement);
Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);
// primary volume?
if (primary && PRIMARY_VOLUME_NAME.equals(volumeId))
return (String) getPath.invoke(storageVolumeElement);
// other volumes?
if (uuid != null && uuid.equals(volumeId))
return (String) getPath.invoke(storageVolumeElement);
}
// not found.
return null;
} catch (Exception ex) {
return null;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if (split.length > 0) return split[0];
else return null;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if ((split.length >= 2) && (split[1] != null)) return split[1];
else return File.separator;
}
}

View File

@ -2,13 +2,20 @@ package org.fdroid.fdroid.views.main;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.provider.DocumentFile;
import android.util.Log;
import android.view.View;
import android.widget.Button;
@ -17,6 +24,8 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.fdroid.fdroid.R;
import org.fdroid.fdroid.Utils;
import org.fdroid.fdroid.nearby.TreeUriUtils;
import org.fdroid.fdroid.nearby.SDCardScannerService;
import org.fdroid.fdroid.nearby.SwapService;
import org.fdroid.fdroid.nearby.TreeUriScannerIntentService;
@ -131,5 +140,31 @@ class NearbyViewBinder {
}
});
}
if (Build.VERSION.SDK_INT < 24) {
return;
}
StorageManager storageManager = (StorageManager) activity.getSystemService(Context.STORAGE_SERVICE);
for (StorageVolume storageVolume : storageManager.getStorageVolumes()) {
if (storageVolume.isRemovable() && !storageVolume.isPrimary()) {
Log.i(TAG, "StorageVolume: " + storageVolume);
final Intent intent = storageVolume.createAccessIntent(null);
if (intent == null) {
Utils.debugLog(TAG, "Got null Storage Volume access Intent");
return;
}
TextView storageVolumeText = swapView.findViewById(R.id.storage_volume_text);
storageVolumeText.setVisibility(View.VISIBLE);
Button requestStorageVolume = swapView.findViewById(R.id.request_storage_volume_button);
requestStorageVolume.setText(storageVolume.getDescription(activity));
requestStorageVolume.setVisibility(View.VISIBLE);
requestStorageVolume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.startActivityForResult(intent, MainActivity.REQUEST_STORAGE_ACCESS);
}
});
}
}
}
}

View File

@ -72,11 +72,12 @@
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/nearby_splash__read_external_storage"
android:textSize="20sp"
android:textSize="17sp"
android:textColor="?attr/lightGrayTextColor"
android:textAlignment="center"
android:gravity="center"
android:layout_marginEnd="24dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="24dp"
android:layout_marginEnd="24dp" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="24dp"
android:layout_marginStart="24dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="24dp" android:layout_marginTop="48dp"
app:layout_constraintTop_toBottomOf="@+id/both_parties_need_fdroid_text"
@ -96,4 +97,35 @@
app:layout_constraintTop_toBottomOf="@+id/read_external_storage_text"
android:visibility="gone"
tools:visibility="visible"/>
<TextView
android:id="@+id/storage_volume_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/nearby_splash__document_tree"
android:textSize="17sp"
android:textColor="?attr/lightGrayTextColor"
android:textAlignment="center"
android:gravity="center"
android:layout_marginEnd="24dp" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="24dp"
android:layout_marginStart="24dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="24dp" android:layout_marginTop="48dp"
app:layout_constraintTop_toBottomOf="@+id/request_read_external_storage_button"
android:visibility="gone"/>
<Button
android:id="@+id/request_storage_volume_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxEms="16"
android:text="@string/nearby_splash__request_permission"
style="@style/DetailsSecondaryButtonStyle"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="24dp"
app:layout_constraintTop_toBottomOf="@+id/storage_volume_text"
android:visibility="gone"/>
</android.support.constraint.ConstraintLayout>

View File

@ -91,7 +91,7 @@ public class TreeUriDownloader extends Downloader {
@Override
protected long totalDownloadSize() {
return documentFile.length();
return documentFile.length(); // TODO how should this actually be implemented?
}
@Override

View File

@ -58,11 +58,12 @@ import org.fdroid.fdroid.Utils;
import org.fdroid.fdroid.data.NewRepoConfig;
import org.fdroid.fdroid.nearby.SDCardScannerService;
import org.fdroid.fdroid.nearby.SwapService;
import org.fdroid.fdroid.nearby.SwapWorkflowActivity;
import org.fdroid.fdroid.nearby.TreeUriScannerIntentService;
import org.fdroid.fdroid.nearby.WifiStateChangeService;
import org.fdroid.fdroid.views.AppDetailsActivity;
import org.fdroid.fdroid.views.ManageReposActivity;
import org.fdroid.fdroid.views.apps.AppListActivity;
import org.fdroid.fdroid.nearby.SwapWorkflowActivity;
import java.lang.reflect.Field;
@ -89,6 +90,7 @@ public class MainActivity extends AppCompatActivity implements BottomNavigationB
static final int REQUEST_LOCATION_PERMISSIONS = 0xEF0F;
static final int REQUEST_STORAGE_PERMISSIONS = 0xB004;
public static final int REQUEST_STORAGE_ACCESS = 0x40E5;
private static final String ADD_REPO_INTENT_HANDLED = "addRepoIntentHandled";
@ -246,6 +248,14 @@ public class MainActivity extends AppCompatActivity implements BottomNavigationB
checkForAddRepoIntent(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_STORAGE_ACCESS) {
TreeUriScannerIntentService.onActivityResult(this, data);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // NOCHECKSTYLE LineLength
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

View File

@ -458,7 +458,8 @@ This often occurs with apps installed via Google Play or other sources, if they
<!-- The word "nearby" should be the same as used for Google/Android Nearby. This is a button label, it should ideally be 10-20 characters. -->
<string name="nearby_splash__find_people_button">Find people nearby</string>
<string name="nearby_splash__both_parties_need_fdroid">Both parties need %1$s to use nearby.</string>
<string name="nearby_splash__read_external_storage">SD Cards can be used to swap!</string>
<string name="nearby_splash__read_external_storage">Search SD Card for repos and mirrors.</string>
<string name="nearby_splash__document_tree">Search USB OTG for repos and mirrors.</string>
<!-- This is a button label for a small button, the text needs to be under 10 characters, the shorter the better. Also, a literal translation probably will miss the point. "Try it" is more a saying than two words. Google has been pushing these short buttons, like "Got it" and "Try now" so this button is trying to match those buttons in Android. -->
<string name="nearby_splash__request_permission">Try it</string>