Move Stored(File|Directory)Helper into NewPipe
This commit is contained in:
parent
0f75024e03
commit
1164ea52f9
18 changed files with 271 additions and 186 deletions
|
|
@ -49,6 +49,8 @@ import org.schabi.newpipe.extractor.stream.StreamInfo;
|
|||
import org.schabi.newpipe.extractor.stream.SubtitlesStream;
|
||||
import org.schabi.newpipe.extractor.stream.VideoStream;
|
||||
import org.schabi.newpipe.settings.NewPipeSettings;
|
||||
import org.schabi.newpipe.streams.io.StoredDirectoryHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
import org.schabi.newpipe.util.FilePickerActivityHelper;
|
||||
import org.schabi.newpipe.util.FilenameUtils;
|
||||
import org.schabi.newpipe.util.ListHelper;
|
||||
|
|
@ -68,8 +70,6 @@ import icepick.Icepick;
|
|||
import icepick.State;
|
||||
import io.reactivex.rxjava3.disposables.CompositeDisposable;
|
||||
import us.shandian.giga.get.MissionRecoveryInfo;
|
||||
import us.shandian.giga.io.StoredDirectoryHelper;
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
import us.shandian.giga.postprocessing.Postprocessing;
|
||||
import us.shandian.giga.service.DownloadManager;
|
||||
import us.shandian.giga.service.DownloadManagerService;
|
||||
|
|
|
|||
|
|
@ -57,11 +57,11 @@ import org.schabi.newpipe.local.subscription.services.SubscriptionsImportService
|
|||
import org.schabi.newpipe.local.subscription.services.SubscriptionsImportService.KEY_MODE
|
||||
import org.schabi.newpipe.local.subscription.services.SubscriptionsImportService.KEY_VALUE
|
||||
import org.schabi.newpipe.local.subscription.services.SubscriptionsImportService.PREVIOUS_EXPORT_MODE
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper
|
||||
import org.schabi.newpipe.util.FilePickerActivityHelper
|
||||
import org.schabi.newpipe.util.NavigationHelper
|
||||
import org.schabi.newpipe.util.OnClickGesture
|
||||
import org.schabi.newpipe.util.ShareUtils
|
||||
import us.shandian.giga.io.StoredFileHelper
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ import java.util.Collections;
|
|||
import java.util.List;
|
||||
|
||||
import icepick.State;
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
|
||||
import static org.schabi.newpipe.extractor.subscription.SubscriptionExtractor.ContentSource.CHANNEL_URL;
|
||||
import static org.schabi.newpipe.local.subscription.services.SubscriptionsImportService.CHANNEL_URL_MODE;
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import org.schabi.newpipe.R;
|
|||
import org.schabi.newpipe.database.subscription.SubscriptionEntity;
|
||||
import org.schabi.newpipe.extractor.subscription.SubscriptionItem;
|
||||
import org.schabi.newpipe.streams.io.SharpOutputStream;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
|
@ -41,7 +42,6 @@ import java.util.List;
|
|||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.rxjava3.functions.Function;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
|
||||
import static org.schabi.newpipe.MainActivity.DEBUG;
|
||||
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import org.schabi.newpipe.extractor.channel.ChannelInfo;
|
|||
import org.schabi.newpipe.extractor.subscription.SubscriptionItem;
|
||||
import org.schabi.newpipe.ktx.ExceptionUtils;
|
||||
import org.schabi.newpipe.streams.io.SharpInputStream;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
import org.schabi.newpipe.util.Constants;
|
||||
import org.schabi.newpipe.util.ExtractorHelper;
|
||||
|
||||
|
|
@ -52,10 +53,9 @@ import io.reactivex.rxjava3.core.Notification;
|
|||
import io.reactivex.rxjava3.functions.Consumer;
|
||||
import io.reactivex.rxjava3.functions.Function;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
|
||||
import static org.schabi.newpipe.MainActivity.DEBUG;
|
||||
import static us.shandian.giga.io.StoredFileHelper.DEFAULT_MIME;
|
||||
import static org.schabi.newpipe.streams.io.StoredFileHelper.DEFAULT_MIME;
|
||||
|
||||
public class SubscriptionsImportService extends BaseImportExportService {
|
||||
public static final int CHANNEL_URL_MODE = 0;
|
||||
|
|
|
|||
|
|
@ -36,8 +36,8 @@ import java.text.SimpleDateFormat;
|
|||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import us.shandian.giga.io.StoredDirectoryHelper;
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredDirectoryHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
|
||||
import static org.schabi.newpipe.util.Localization.assureCorrectAppLanguage;
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ import java.net.URI;
|
|||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import us.shandian.giga.io.StoredDirectoryHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredDirectoryHelper;
|
||||
|
||||
import static org.schabi.newpipe.util.Localization.assureCorrectAppLanguage;
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,328 @@
|
|||
package org.schabi.newpipe.streams.io;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.provider.DocumentsContract;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
|
||||
import org.schabi.newpipe.settings.NewPipeSettings;
|
||||
import org.schabi.newpipe.util.FilePickerActivityHelper;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
|
||||
import static android.provider.DocumentsContract.Document.COLUMN_DISPLAY_NAME;
|
||||
import static android.provider.DocumentsContract.Root.COLUMN_DOCUMENT_ID;
|
||||
import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;
|
||||
|
||||
public class StoredDirectoryHelper {
|
||||
public static final int PERMISSION_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
|
||||
|
||||
private File ioTree;
|
||||
private DocumentFile docTree;
|
||||
|
||||
private Context context;
|
||||
|
||||
private final String tag;
|
||||
|
||||
public StoredDirectoryHelper(@NonNull final Context context, @NonNull final Uri path,
|
||||
final String tag) throws IOException {
|
||||
this.tag = tag;
|
||||
|
||||
if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(path.getScheme())) {
|
||||
this.ioTree = new File(URI.create(path.toString()));
|
||||
return;
|
||||
}
|
||||
|
||||
this.context = context;
|
||||
|
||||
try {
|
||||
this.context.getContentResolver().takePersistableUriPermission(path, PERMISSION_FLAGS);
|
||||
} catch (final Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
throw new IOException("Storage Access Framework with Directory API is not available");
|
||||
}
|
||||
|
||||
this.docTree = DocumentFile.fromTreeUri(context, path);
|
||||
|
||||
if (this.docTree == null) {
|
||||
throw new IOException("Failed to create the tree from Uri");
|
||||
}
|
||||
}
|
||||
|
||||
public StoredFileHelper createFile(final String filename, final String mime) {
|
||||
return createFile(filename, mime, false);
|
||||
}
|
||||
|
||||
public StoredFileHelper createUniqueFile(final String name, final String mime) {
|
||||
final ArrayList<String> matches = new ArrayList<>();
|
||||
final String[] filename = splitFilename(name);
|
||||
final String lcFilename = filename[0].toLowerCase();
|
||||
|
||||
if (docTree == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
for (final File file : ioTree.listFiles()) {
|
||||
addIfStartWith(matches, lcFilename, file.getName());
|
||||
}
|
||||
} else {
|
||||
// warning: SAF file listing is very slow
|
||||
final Uri docTreeChildren = DocumentsContract.buildChildDocumentsUriUsingTree(
|
||||
docTree.getUri(), DocumentsContract.getDocumentId(docTree.getUri()));
|
||||
|
||||
final String[] projection = new String[]{COLUMN_DISPLAY_NAME};
|
||||
final String selection = "(LOWER(" + COLUMN_DISPLAY_NAME + ") LIKE ?%";
|
||||
final ContentResolver cr = context.getContentResolver();
|
||||
|
||||
try (Cursor cursor = cr.query(docTreeChildren, projection, selection,
|
||||
new String[]{lcFilename}, null)) {
|
||||
if (cursor != null) {
|
||||
while (cursor.moveToNext()) {
|
||||
addIfStartWith(matches, lcFilename, cursor.getString(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.size() < 1) {
|
||||
return createFile(name, mime, true);
|
||||
} else {
|
||||
// check if the filename is in use
|
||||
String lcName = name.toLowerCase();
|
||||
for (final String testName : matches) {
|
||||
if (testName.equals(lcName)) {
|
||||
lcName = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// check if not in use
|
||||
if (lcName != null) {
|
||||
return createFile(name, mime, true);
|
||||
}
|
||||
}
|
||||
|
||||
Collections.sort(matches, String::compareTo);
|
||||
|
||||
for (int i = 1; i < 1000; i++) {
|
||||
if (Collections.binarySearch(matches, makeFileName(lcFilename, i, filename[1])) < 0) {
|
||||
return createFile(makeFileName(filename[0], i, filename[1]), mime, true);
|
||||
}
|
||||
}
|
||||
|
||||
return createFile(String.valueOf(System.currentTimeMillis()).concat(filename[1]), mime,
|
||||
false);
|
||||
}
|
||||
|
||||
private StoredFileHelper createFile(final String filename, final String mime,
|
||||
final boolean safe) {
|
||||
final StoredFileHelper storage;
|
||||
|
||||
try {
|
||||
if (docTree == null) {
|
||||
storage = new StoredFileHelper(ioTree, filename, mime);
|
||||
} else {
|
||||
storage = new StoredFileHelper(context, docTree, filename, mime, safe);
|
||||
}
|
||||
} catch (final IOException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
storage.tag = tag;
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
public Uri getUri() {
|
||||
return docTree == null ? Uri.fromFile(ioTree) : docTree.getUri();
|
||||
}
|
||||
|
||||
public boolean exists() {
|
||||
return docTree == null ? ioTree.exists() : docTree.exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether it's using the {@code java.io} API.
|
||||
*
|
||||
* @return {@code true} for Java I/O API, otherwise, {@code false} for Storage Access Framework
|
||||
*/
|
||||
public boolean isDirect() {
|
||||
return docTree == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only using Java I/O. Creates the directory named by this abstract pathname, including any
|
||||
* necessary but nonexistent parent directories. Note that if this
|
||||
* operation fails it may have succeeded in creating some of the necessary
|
||||
* parent directories.
|
||||
*
|
||||
* @return <code>true</code> if and only if the directory was created,
|
||||
* along with all necessary parent directories or already exists; <code>false</code>
|
||||
* otherwise
|
||||
*/
|
||||
public boolean mkdirs() {
|
||||
if (docTree == null) {
|
||||
return ioTree.exists() || ioTree.mkdirs();
|
||||
}
|
||||
|
||||
if (docTree.exists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentFile parent;
|
||||
String child = docTree.getName();
|
||||
|
||||
while (true) {
|
||||
parent = docTree.getParentFile();
|
||||
if (parent == null || child == null) {
|
||||
break;
|
||||
}
|
||||
if (parent.exists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
parent.createDirectory(child);
|
||||
|
||||
child = parent.getName(); // for the next iteration
|
||||
}
|
||||
} catch (final Exception ignored) {
|
||||
// no more parent directories or unsupported by the storage provider
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getTag() {
|
||||
return tag;
|
||||
}
|
||||
|
||||
public Uri findFile(final String filename) {
|
||||
if (docTree == null) {
|
||||
final File res = new File(ioTree, filename);
|
||||
return res.exists() ? Uri.fromFile(res) : null;
|
||||
}
|
||||
|
||||
final DocumentFile res = findFileSAFHelper(context, docTree, filename);
|
||||
return res == null ? null : res.getUri();
|
||||
}
|
||||
|
||||
public boolean canWrite() {
|
||||
return docTree == null ? ioTree.canWrite() : docTree.canWrite();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return (docTree == null ? Uri.fromFile(ioTree) : docTree.getUri()).toString();
|
||||
}
|
||||
|
||||
////////////////////
|
||||
// Utils
|
||||
///////////////////
|
||||
|
||||
private static void addIfStartWith(final ArrayList<String> list, @NonNull final String base,
|
||||
final String str) {
|
||||
if (isNullOrEmpty(str)) {
|
||||
return;
|
||||
}
|
||||
final String lowerStr = str.toLowerCase();
|
||||
if (lowerStr.startsWith(base)) {
|
||||
list.add(lowerStr);
|
||||
}
|
||||
}
|
||||
|
||||
private static String[] splitFilename(@NonNull final String filename) {
|
||||
final int dotIndex = filename.lastIndexOf('.');
|
||||
|
||||
if (dotIndex < 0 || (dotIndex == filename.length() - 1)) {
|
||||
return new String[]{filename, ""};
|
||||
}
|
||||
|
||||
return new String[]{filename.substring(0, dotIndex), filename.substring(dotIndex)};
|
||||
}
|
||||
|
||||
private static String makeFileName(final String name, final int idx, final String ext) {
|
||||
return name.concat(" (").concat(String.valueOf(idx)).concat(")").concat(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast (but not enough) file/directory finder under the storage access framework.
|
||||
*
|
||||
* @param context The context
|
||||
* @param tree Directory where search
|
||||
* @param filename Target filename
|
||||
* @return A {@link DocumentFile} contain the reference, otherwise, null
|
||||
*/
|
||||
static DocumentFile findFileSAFHelper(@Nullable final Context context, final DocumentFile tree,
|
||||
final String filename) {
|
||||
if (context == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
return tree.findFile(filename); // warning: this is very slow
|
||||
}
|
||||
|
||||
if (!tree.canRead()) {
|
||||
return null; // missing read permission
|
||||
}
|
||||
|
||||
final int name = 0;
|
||||
final int documentId = 1;
|
||||
|
||||
// LOWER() SQL function is not supported
|
||||
final String selection = COLUMN_DISPLAY_NAME + " = ?";
|
||||
//final String selection = COLUMN_DISPLAY_NAME + " LIKE ?%";
|
||||
|
||||
final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(tree.getUri(),
|
||||
DocumentsContract.getDocumentId(tree.getUri()));
|
||||
final String[] projection = {COLUMN_DISPLAY_NAME, COLUMN_DOCUMENT_ID};
|
||||
final ContentResolver contentResolver = context.getContentResolver();
|
||||
|
||||
final String lowerFilename = filename.toLowerCase();
|
||||
|
||||
try (Cursor cursor = contentResolver.query(childrenUri, projection, selection,
|
||||
new String[]{lowerFilename}, null)) {
|
||||
if (cursor == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.isNull(name)
|
||||
|| !cursor.getString(name).toLowerCase().startsWith(lowerFilename)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return DocumentFile.fromSingleUri(context,
|
||||
DocumentsContract.buildDocumentUriUsingTree(tree.getUri(),
|
||||
cursor.getString(documentId)));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Intent getPicker(final Context ctx) {
|
||||
if (NewPipeSettings.useStorageAccessFramework(ctx)) {
|
||||
return new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
|
||||
.putExtra("android.content.extra.SHOW_ADVANCED", true)
|
||||
.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
|
||||
| StoredDirectoryHelper.PERMISSION_FLAGS);
|
||||
} else {
|
||||
return new Intent(ctx, FilePickerActivityHelper.class)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_MULTIPLE, false)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_CREATE_DIR, true)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_MODE,
|
||||
FilePickerActivityHelper.MODE_DIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,511 @@
|
|||
package org.schabi.newpipe.streams.io;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.provider.DocumentsContract;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
|
||||
import com.nononsenseapps.filepicker.Utils;
|
||||
|
||||
import org.schabi.newpipe.settings.NewPipeSettings;
|
||||
import org.schabi.newpipe.util.FilePickerActivityHelper;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.net.URI;
|
||||
|
||||
import us.shandian.giga.io.FileStream;
|
||||
import us.shandian.giga.io.FileStreamSAF;
|
||||
|
||||
public class StoredFileHelper implements Serializable {
|
||||
private static final long serialVersionUID = 0L;
|
||||
public static final String DEFAULT_MIME = "application/octet-stream";
|
||||
|
||||
private transient DocumentFile docFile;
|
||||
private transient DocumentFile docTree;
|
||||
private transient File ioFile;
|
||||
private transient Context context;
|
||||
|
||||
protected String source;
|
||||
private String sourceTree;
|
||||
|
||||
protected String tag;
|
||||
|
||||
private String srcName;
|
||||
private String srcType;
|
||||
|
||||
public StoredFileHelper(final Context context, final Uri uri, final String mime) {
|
||||
if (FilePickerActivityHelper.isOwnFileUri(context, uri)) {
|
||||
ioFile = Utils.getFileForUri(uri);
|
||||
source = Uri.fromFile(ioFile).toString();
|
||||
} else {
|
||||
docFile = DocumentFile.fromSingleUri(context, uri);
|
||||
source = uri.toString();
|
||||
}
|
||||
|
||||
this.context = context;
|
||||
this.srcType = mime;
|
||||
}
|
||||
|
||||
public StoredFileHelper(@Nullable final Uri parent, final String filename, final String mime,
|
||||
final String tag) {
|
||||
this.source = null; // this instance will be "invalid" see invalidate()/isInvalid() methods
|
||||
|
||||
this.srcName = filename;
|
||||
this.srcType = mime == null ? DEFAULT_MIME : mime;
|
||||
if (parent != null) {
|
||||
this.sourceTree = parent.toString();
|
||||
}
|
||||
|
||||
this.tag = tag;
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
StoredFileHelper(@Nullable final Context context, final DocumentFile tree,
|
||||
final String filename, final String mime, final boolean safe)
|
||||
throws IOException {
|
||||
this.docTree = tree;
|
||||
this.context = context;
|
||||
|
||||
final DocumentFile res;
|
||||
|
||||
if (safe) {
|
||||
// no conflicts (the filename is not in use)
|
||||
res = this.docTree.createFile(mime, filename);
|
||||
if (res == null) {
|
||||
throw new IOException("Cannot create the file");
|
||||
}
|
||||
} else {
|
||||
res = createSAF(context, mime, filename);
|
||||
}
|
||||
|
||||
this.docFile = res;
|
||||
|
||||
this.source = docFile.getUri().toString();
|
||||
this.sourceTree = docTree.getUri().toString();
|
||||
|
||||
this.srcName = this.docFile.getName();
|
||||
this.srcType = this.docFile.getType();
|
||||
}
|
||||
|
||||
StoredFileHelper(final File location, final String filename, final String mime)
|
||||
throws IOException {
|
||||
this.ioFile = new File(location, filename);
|
||||
|
||||
if (this.ioFile.exists()) {
|
||||
if (!this.ioFile.isFile() && !this.ioFile.delete()) {
|
||||
throw new IOException("The filename is already in use by non-file entity "
|
||||
+ "and cannot overwrite it");
|
||||
}
|
||||
} else {
|
||||
if (!this.ioFile.createNewFile()) {
|
||||
throw new IOException("Cannot create the file");
|
||||
}
|
||||
}
|
||||
|
||||
this.source = Uri.fromFile(this.ioFile).toString();
|
||||
this.sourceTree = Uri.fromFile(location).toString();
|
||||
|
||||
this.srcName = ioFile.getName();
|
||||
this.srcType = mime;
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.KITKAT)
|
||||
public StoredFileHelper(final Context context, @Nullable final Uri parent,
|
||||
@NonNull final Uri path, final String tag) throws IOException {
|
||||
this.tag = tag;
|
||||
this.source = path.toString();
|
||||
|
||||
if (path.getScheme() == null
|
||||
|| path.getScheme().equalsIgnoreCase(ContentResolver.SCHEME_FILE)) {
|
||||
this.ioFile = new File(URI.create(this.source));
|
||||
} else {
|
||||
final DocumentFile file = DocumentFile.fromSingleUri(context, path);
|
||||
|
||||
if (file == null) {
|
||||
throw new RuntimeException("SAF not available");
|
||||
}
|
||||
|
||||
this.context = context;
|
||||
|
||||
if (file.getName() == null) {
|
||||
this.source = null;
|
||||
return;
|
||||
} else {
|
||||
this.docFile = file;
|
||||
takePermissionSAF();
|
||||
}
|
||||
}
|
||||
|
||||
if (parent != null) {
|
||||
if (!ContentResolver.SCHEME_FILE.equals(parent.getScheme())) {
|
||||
this.docTree = DocumentFile.fromTreeUri(context, parent);
|
||||
}
|
||||
|
||||
this.sourceTree = parent.toString();
|
||||
}
|
||||
|
||||
this.srcName = getName();
|
||||
this.srcType = getType();
|
||||
}
|
||||
|
||||
|
||||
public static StoredFileHelper deserialize(@NonNull final StoredFileHelper storage,
|
||||
final Context context) throws IOException {
|
||||
final Uri treeUri = storage.sourceTree == null ? null : Uri.parse(storage.sourceTree);
|
||||
|
||||
if (storage.isInvalid()) {
|
||||
return new StoredFileHelper(treeUri, storage.srcName, storage.srcType, storage.tag);
|
||||
}
|
||||
|
||||
final StoredFileHelper instance = new StoredFileHelper(context, treeUri,
|
||||
Uri.parse(storage.source), storage.tag);
|
||||
|
||||
// under SAF, if the target document is deleted, conserve the filename and mime
|
||||
if (instance.srcName == null) {
|
||||
instance.srcName = storage.srcName;
|
||||
}
|
||||
if (instance.srcType == null) {
|
||||
instance.srcType = storage.srcType;
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public SharpStream getStream() throws IOException {
|
||||
assertValid();
|
||||
|
||||
if (docFile == null) {
|
||||
return new FileStream(ioFile);
|
||||
} else {
|
||||
return new FileStreamSAF(context.getContentResolver(), docFile.getUri());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether it's using the {@code java.io} API.
|
||||
*
|
||||
* @return {@code true} for Java I/O API, otherwise, {@code false} for Storage Access Framework
|
||||
*/
|
||||
public boolean isDirect() {
|
||||
assertValid();
|
||||
|
||||
return docFile == null;
|
||||
}
|
||||
|
||||
public boolean isInvalid() {
|
||||
return source == null;
|
||||
}
|
||||
|
||||
public Uri getUri() {
|
||||
assertValid();
|
||||
|
||||
return docFile == null ? Uri.fromFile(ioFile) : docFile.getUri();
|
||||
}
|
||||
|
||||
public Uri getParentUri() {
|
||||
assertValid();
|
||||
|
||||
return sourceTree == null ? null : Uri.parse(sourceTree);
|
||||
}
|
||||
|
||||
public void truncate() throws IOException {
|
||||
assertValid();
|
||||
|
||||
try (SharpStream fs = getStream()) {
|
||||
fs.setLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean delete() {
|
||||
if (source == null) {
|
||||
return true;
|
||||
}
|
||||
if (docFile == null) {
|
||||
return ioFile.delete();
|
||||
}
|
||||
|
||||
final boolean res = docFile.delete();
|
||||
|
||||
try {
|
||||
final int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
|
||||
context.getContentResolver().releasePersistableUriPermission(docFile.getUri(), flags);
|
||||
} catch (final Exception ex) {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public long length() {
|
||||
assertValid();
|
||||
|
||||
return docFile == null ? ioFile.length() : docFile.length();
|
||||
}
|
||||
|
||||
public boolean canWrite() {
|
||||
if (source == null) {
|
||||
return false;
|
||||
}
|
||||
return docFile == null ? ioFile.canWrite() : docFile.canWrite();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
if (source == null) {
|
||||
return srcName;
|
||||
} else if (docFile == null) {
|
||||
return ioFile.getName();
|
||||
}
|
||||
|
||||
final String name = docFile.getName();
|
||||
return name == null ? srcName : name;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
if (source == null || docFile == null) {
|
||||
return srcType;
|
||||
}
|
||||
|
||||
final String type = docFile.getType();
|
||||
return type == null ? srcType : type;
|
||||
}
|
||||
|
||||
public String getTag() {
|
||||
return tag;
|
||||
}
|
||||
|
||||
public boolean existsAsFile() {
|
||||
if (source == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// WARNING: DocumentFile.exists() and DocumentFile.isFile() methods are slow
|
||||
final boolean exists = docFile == null ? ioFile.exists() : docFile.exists();
|
||||
// ¿docFile.isVirtual() means is no-physical?
|
||||
final boolean isFile = docFile == null ? ioFile.isFile() : docFile.isFile();
|
||||
|
||||
return exists && isFile;
|
||||
}
|
||||
|
||||
public boolean create() {
|
||||
assertValid();
|
||||
final boolean result;
|
||||
|
||||
if (docFile == null) {
|
||||
try {
|
||||
result = ioFile.createNewFile();
|
||||
} catch (final IOException e) {
|
||||
return false;
|
||||
}
|
||||
} else if (docTree == null) {
|
||||
result = false;
|
||||
} else {
|
||||
if (!docTree.canRead() || !docTree.canWrite()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
docFile = createSAF(context, srcType, srcName);
|
||||
if (docFile.getName() == null) {
|
||||
return false;
|
||||
}
|
||||
result = true;
|
||||
} catch (final IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (result) {
|
||||
source = (docFile == null ? Uri.fromFile(ioFile) : docFile.getUri()).toString();
|
||||
srcName = getName();
|
||||
srcType = getType();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void invalidate() {
|
||||
if (source == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
srcName = getName();
|
||||
srcType = getType();
|
||||
|
||||
source = null;
|
||||
|
||||
docTree = null;
|
||||
docFile = null;
|
||||
ioFile = null;
|
||||
context = null;
|
||||
}
|
||||
|
||||
public boolean equals(final StoredFileHelper storage) {
|
||||
if (this == storage) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// note: do not compare tags, files can have the same parent folder
|
||||
//if (stringMismatch(this.tag, storage.tag)) return false;
|
||||
|
||||
if (stringMismatch(getLowerCase(this.sourceTree), getLowerCase(this.sourceTree))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.isInvalid() || storage.isInvalid()) {
|
||||
if (this.srcName == null || storage.srcName == null || this.srcType == null
|
||||
|| storage.srcType == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.srcName.equalsIgnoreCase(storage.srcName)
|
||||
&& this.srcType.equalsIgnoreCase(storage.srcType);
|
||||
}
|
||||
|
||||
if (this.isDirect() != storage.isDirect()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.isDirect()) {
|
||||
return this.ioFile.getPath().equalsIgnoreCase(storage.ioFile.getPath());
|
||||
}
|
||||
|
||||
return DocumentsContract.getDocumentId(this.docFile.getUri())
|
||||
.equalsIgnoreCase(DocumentsContract.getDocumentId(storage.docFile.getUri()));
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
if (source == null) {
|
||||
return "[Invalid state] name=" + srcName + " type=" + srcType + " tag=" + tag;
|
||||
} else {
|
||||
return "sourceFile=" + source + " treeSource=" + (sourceTree == null ? "" : sourceTree)
|
||||
+ " tag=" + tag;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void assertValid() {
|
||||
if (source == null) {
|
||||
throw new IllegalStateException("In invalid state");
|
||||
}
|
||||
}
|
||||
|
||||
private void takePermissionSAF() throws IOException {
|
||||
try {
|
||||
context.getContentResolver().takePersistableUriPermission(docFile.getUri(),
|
||||
StoredDirectoryHelper.PERMISSION_FLAGS);
|
||||
} catch (final Exception e) {
|
||||
if (docFile.getName() == null) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private DocumentFile createSAF(@Nullable final Context ctx, final String mime,
|
||||
final String filename) throws IOException {
|
||||
DocumentFile res = StoredDirectoryHelper.findFileSAFHelper(ctx, docTree, filename);
|
||||
|
||||
if (res != null && res.exists() && res.isDirectory()) {
|
||||
if (!res.delete()) {
|
||||
throw new IOException("Directory with the same name found but cannot delete");
|
||||
}
|
||||
res = null;
|
||||
}
|
||||
|
||||
if (res == null) {
|
||||
res = this.docTree.createFile(srcType == null ? DEFAULT_MIME : mime, filename);
|
||||
if (res == null) {
|
||||
throw new IOException("Cannot create the file");
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private String getLowerCase(final String str) {
|
||||
return str == null ? null : str.toLowerCase();
|
||||
}
|
||||
|
||||
private boolean stringMismatch(final String str1, final String str2) {
|
||||
if (str1 == null && str2 == null) {
|
||||
return false;
|
||||
}
|
||||
if ((str1 == null) != (str2 == null)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return !str1.equals(str2);
|
||||
}
|
||||
|
||||
public static Intent getPicker(final Context ctx) {
|
||||
if (NewPipeSettings.useStorageAccessFramework(ctx)) {
|
||||
return new Intent(Intent.ACTION_OPEN_DOCUMENT)
|
||||
.putExtra("android.content.extra.SHOW_ADVANCED", true)
|
||||
.setType("*/*")
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
|
||||
| StoredDirectoryHelper.PERMISSION_FLAGS);
|
||||
} else {
|
||||
return new Intent(ctx, FilePickerActivityHelper.class)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_MULTIPLE, false)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_CREATE_DIR, true)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_SINGLE_CLICK, true)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_MODE,
|
||||
FilePickerActivityHelper.MODE_FILE);
|
||||
}
|
||||
}
|
||||
|
||||
public static Intent getNewPicker(@NonNull final Context ctx, @Nullable final String startPath,
|
||||
@Nullable final String filename) {
|
||||
final Intent i;
|
||||
if (NewPipeSettings.useStorageAccessFramework(ctx)) {
|
||||
i = new Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.putExtra("android.content.extra.SHOW_ADVANCED", true)
|
||||
.setType("*/*")
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
|
||||
| StoredDirectoryHelper.PERMISSION_FLAGS);
|
||||
|
||||
if (startPath != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
i.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse(startPath));
|
||||
}
|
||||
if (filename != null) {
|
||||
i.putExtra(Intent.EXTRA_TITLE, filename);
|
||||
}
|
||||
} else {
|
||||
i = new Intent(ctx, FilePickerActivityHelper.class)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_MULTIPLE, false)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_CREATE_DIR, true)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_ALLOW_EXISTING_FILE, true)
|
||||
.putExtra(FilePickerActivityHelper.EXTRA_MODE,
|
||||
FilePickerActivityHelper.MODE_NEW_FILE);
|
||||
|
||||
if (startPath != null || filename != null) {
|
||||
File fullStartPath;
|
||||
if (startPath == null) {
|
||||
fullStartPath = Environment.getExternalStorageDirectory();
|
||||
} else {
|
||||
fullStartPath = new File(startPath);
|
||||
}
|
||||
if (filename != null) {
|
||||
fullStartPath = new File(fullStartPath, filename);
|
||||
}
|
||||
i.putExtra(FilePickerActivityHelper.EXTRA_START_PATH,
|
||||
fullStartPath.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ import java.util.zip.ZipEntry;
|
|||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import us.shandian.giga.io.StoredFileHelper;
|
||||
import org.schabi.newpipe.streams.io.StoredFileHelper;
|
||||
|
||||
/**
|
||||
* Created by Christian Schabesberger on 28.01.18.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue