Java Code Examples for androidx.documentfile.provider.DocumentFile#fromTreeUri()

The following examples show how to use androidx.documentfile.provider.DocumentFile#fromTreeUri() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LibImportDialogFragment.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
private Map<Site, DocumentFile> getSiteFolders() {
    Helper.assertNonUiThread();
    Map<Site, DocumentFile> result = new EnumMap<>(Site.class);

    if (!Preferences.getStorageUri().isEmpty()) {
        Uri rootUri = Uri.parse(Preferences.getStorageUri());
        DocumentFile rootFolder = DocumentFile.fromTreeUri(requireContext(), rootUri);
        if (rootFolder != null && rootFolder.exists()) {
            List<DocumentFile> subfolders = FileHelper.listFolders(requireContext(), rootFolder);
            String folderName;
            for (DocumentFile f : subfolders)
                if (f.getName() != null) {
                    folderName = f.getName().toLowerCase();
                    for (Site s : Site.values()) {
                        if (folderName.equalsIgnoreCase(s.getFolder())) {
                            result.put(s, f);
                            break;
                        }
                    }
                }
        }
    }
    return result;
}
 
Example 2
Source File: MimiUtil.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
private static DocumentFile directoryToDocumentFile(final Context context, final String dir) {
    if (!TextUtils.isEmpty(dir)) {
        try {
            if (dir.startsWith(Utils.SCHEME_CONTENT)) {
                return DocumentFile.fromTreeUri(context, Uri.parse(dir));
            } else {
                return DocumentFile.fromFile(new File(dir));
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error creating DocumentFile from " + dir, e);
            return null;
        }
    } else {
        DocumentFile defaultDir = DocumentFile.fromFile(new File(getPicturesDirectoryAsFile(), "/Mimi"));
        if (!defaultDir.exists()) {
            DocumentFile externalStorageDir = getPicturesDirectory();
            DocumentFile mimiFolder = externalStorageDir.createDirectory("Mimi");
        }
        return defaultDir;
    }
}
 
Example 3
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
private static Intent getFolderPickerIntent(@NonNull final Context context) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        intent.putExtra(DocumentsContract.EXTRA_PROMPT, "Allow Write Permission");
    }
    // http://stackoverflow.com/a/31334967/1615876
    intent.putExtra("android.content.extra.SHOW_ADVANCED", true);

    // Start the SAF at the specified location
    if (Build.VERSION.SDK_INT >= O && !Preferences.getStorageUri().isEmpty()) {
        DocumentFile file = DocumentFile.fromTreeUri(context, Uri.parse(Preferences.getStorageUri()));
        if (file != null)
            intent.putExtra(EXTRA_INITIAL_URI, file.getUri());
    }

    HentoidApp.LifeCycleListener.disable(); // Prevents the app from displaying the PIN lock when returning from the SAF dialog
    return intent;
}
 
Example 4
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定したUriが存在する時にその下にファイルを生成するためのpathを返す
 * @param context
 * @param treeUri
 * @param mime
 * @param fileName
 * @return
 * @throws UnsupportedOperationException
 * @throws FileNotFoundException
 * @throws IOException
 */
@Deprecated
@NonNull
public static File createStorageFile(
	@NonNull final Context context,
	final Uri treeUri, final String mime, final String fileName)
		throws IOException {

	if (DEBUG) Log.v(TAG, "createStorageFile:" + fileName);

	if (BuildCheck.isLollipop()) {
		if ((treeUri != null) && !TextUtils.isEmpty(fileName)) {
			final DocumentFile saveTree = DocumentFile.fromTreeUri(context, treeUri);
			final DocumentFile target = saveTree.createFile(mime, fileName);
			final String path = UriHelper.getPath(context, target.getUri());
			if (!TextUtils.isEmpty(path)) {
				return new File(path);
			}
		}
		throw new FileNotFoundException();
	} else {
		throw new UnsupportedOperationException("should be API>=21");
	}
}
 
Example 5
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Find the picture files for the given Content
 * NB1 : Pictures with non-supported formats are not included in the results
 * NB2 : Cover picture is not included in the results
 *
 * @param content Content to retrieve picture files for
 * @return List of picture files
 */
public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) {
    Helper.assertNonUiThread();
    String storageUri = content.getStorageUri();

    Timber.d("Opening: %s from: %s", content.getTitle(), storageUri);
    DocumentFile folder = DocumentFile.fromTreeUri(context, Uri.parse(storageUri));
    if (null == folder || !folder.exists()) {
        Timber.d("File not found!! Exiting method.");
        return new ArrayList<>();
    }

    return FileHelper.listFoldersFilter(context,
            folder,
            displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME)
                    && Helper.isImageExtensionSupported(FileHelper.getExtension(displayName))
            )
    );
}
 
Example 6
Source File: LibraryFragment.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Callback for the "open containing folder" action button
 */
private void openItemFolder() {
    Set<ContentItem> selectedItems = selectExtension.getSelectedItems();
    Context context = getActivity();
    if (1 == selectedItems.size() && context != null) {
        Content c = Stream.of(selectedItems).findFirst().get().getContent();
        if (c != null) {
            if (c.getStorageUri().isEmpty()) {
                ToastUtil.toast(R.string.folder_undefined);
                return;
            }

            Uri folderUri = Uri.parse(c.getStorageUri());
            DocumentFile folder = DocumentFile.fromTreeUri(requireContext(), folderUri);
            if (folder != null && folder.exists()) {
                selectExtension.deselect();
                selectionToolbar.setVisibility(View.GONE);
                FileHelper.openFile(requireContext(), folder);
            }
        }
    }
}
 
Example 7
Source File: LocalBackupUtils.java    From SAI with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("DefaultLocale")
@Nullable
private static Uri createBackupUriViaSaf(Context c, Uri backupDirUri, PackageMeta packageMeta, String extension) {
    DocumentFile backupDirFile = DocumentFile.fromTreeUri(c, backupDirUri);
    if (backupDirFile == null)
        return null;

    String backupFileName = getFileNameForPackageMeta(c, packageMeta);

    String actualBackupFileName = String.format("%s.%s", backupFileName, extension);
    int suffix = 0;
    while (true) {
        DocumentFile backupFileCandidate = DocumentFile.fromSingleUri(c, SafUtils.buildChildDocumentUri(backupDirUri, actualBackupFileName));
        if (backupFileCandidate == null || !backupFileCandidate.exists())
            break;

        actualBackupFileName = String.format("%s(%d).%s", backupFileName, ++suffix, extension);
    }

    DocumentFile backupFile = backupDirFile.createFile("saf/sucks", FileUtils.buildValidFatFilename(actualBackupFileName));
    if (backupFile == null)
        return null;

    return backupFile.getUri();
}
 
Example 8
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定したidに対応するUriが存在する時にその下にファイルを生成するためのpathを返す
 * @param context
 * @param treeId
 * @return
 * @throws UnsupportedOperationException
 * @throws FileNotFoundException
 */
@Deprecated
@NonNull
public static File createStorageDir(
	@NonNull final Context context, final int treeId)
	throws FileNotFoundException, UnsupportedOperationException {

	if (BuildCheck.isLollipop()) {
		final Uri treeUri = getStorageUri(context, treeId);
		if (treeUri != null) {
			final DocumentFile saveTree = DocumentFile.fromTreeUri(context, treeUri);
			final String path = UriHelper.getPath(context, saveTree.getUri());
			if (!TextUtils.isEmpty(path)) {
				return new File(path);
			} else {
				throw new FileNotFoundException("specific file not found");
			}
		} else {
			throw new FileNotFoundException("specific dir not found");
		}
	} else {
		throw new UnsupportedOperationException("should be API>=21");
	}
}
 
Example 9
Source File: MainActivity.java    From OneText_For_Android with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == 233 && resultCode == Activity.RESULT_OK) {
        Uri uriTree = resultData.getData();
        if (uriTree != null) {
            final int takeFlags = getIntent().getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            getContentResolver().takePersistableUriPermission(uriTree, takeFlags);
            editor.putString("pic_uri_tree", uriTree.toString());
            editor.apply();
            // 创建所选目录的DocumentFile,可以使用它进行文件操作
            DocumentFile root = DocumentFile.fromTreeUri(this, uriTree);
            // 比如使用它创建文件夹
            //DocumentFile[] rootList = root.listFiles();
            shotOneTextViaSAF(root);
        }
    }
}
 
Example 10
Source File: PreferenceActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DOWNLOAD_PATH_CODE) {
        if (resultCode == RESULT_OK && isAdded() && data.getData() != null) {
            DocumentFile file = DocumentFile.fromTreeUri(requireContext(), data.getData());
            if (file != null)
                Prefs.putString(PK.DD_DOWNLOAD_PATH, file.getUri().toString());
        }

        return;
    }

    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 11
Source File: DocumentUtil.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isFileExist(Context context, String fileName, Uri rootUri, String... subDirs) {
    DocumentFile root;
    if ("content".equals(rootUri.getScheme()))
        root = DocumentFile.fromTreeUri(context, rootUri);
    else
        root = DocumentFile.fromFile(new File(rootUri.getPath()));
    return isFileExist(fileName, root, subDirs);
}
 
Example 12
Source File: LibraryViewModel.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * Archive the given Content into a temp ZIP file
 *
 * @param content   Content to be archived
 * @param onSuccess Callback to run when the operation succeeds
 */
public void archiveContent(@NonNull final Content content, Consumer<File> onSuccess) {
    Timber.d("Building file list for: %s", content.getTitle());

    DocumentFile bookFolder = DocumentFile.fromTreeUri(getApplication(), Uri.parse(content.getStorageUri()));
    if (null == bookFolder || !bookFolder.exists()) return;

    List<DocumentFile> files = FileHelper.listDocumentFiles(getApplication(), bookFolder, null); // Everything (incl. JSON and thumb) gets into the archive
    if (!files.isEmpty()) {
        // Create folder to share from
        File sharedDir = new File(getApplication().getExternalCacheDir() + "/shared");
        if (FileHelper.createDirectory(sharedDir)) {
            Timber.d("Shared folder created.");
        }

        // Clean directory (in case of previous job)
        if (FileHelper.cleanDirectory(sharedDir)) {
            Timber.d("Shared folder cleaned up.");
        }

        // Build destination file
        File dest = new File(getApplication().getExternalCacheDir() + "/shared",
                content.getTitle().replaceAll(AUTHORIZED_CHARS, "_") + ".zip");
        Timber.d("Destination file: %s", dest);

        compositeDisposable.add(
                Single.fromCallable(() -> ZipUtil.zipFiles(getApplication(), files, dest))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(onSuccess::accept,
                                Timber::e)
        );
    }
}
 
Example 13
Source File: DocumentUtil.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
public static boolean deleteFile(Context context, String fileName, Uri rootUri, String... subDirs) {
    DocumentFile root;
    if ("content".equals(rootUri.getScheme()))
        root = DocumentFile.fromTreeUri(context, rootUri);
    else
        root = DocumentFile.fromFile(new File(rootUri.getPath()));
    return deleteFile(fileName, root, subDirs);
}
 
Example 14
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public static DocumentFile createDirIfNotExist(Context context, Uri rootUri, String... subDirs) {
    DocumentFile root;
    if ("content".equals(rootUri.getScheme()))
        root = DocumentFile.fromTreeUri(context, rootUri);
    else
        root = DocumentFile.fromFile(new File(rootUri.getPath()));
    return createDirIfNotExist(root, subDirs);
}
 
Example 15
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public static boolean deleteFile(Context context, String fileName, Uri rootUri, String... subDirs) {
    DocumentFile root;
    if ("content".equals(rootUri.getScheme()))
        root = DocumentFile.fromTreeUri(context, rootUri);
    else
        root = DocumentFile.fromFile(new File(rootUri.getPath()));
    return deleteFile(fileName, root, subDirs);
}
 
Example 16
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public static DocumentFile getDirDocument(Context context, Uri rootUri, String... subDirs) {
    DocumentFile root;
    if ("content".equals(rootUri.getScheme()))
        root = DocumentFile.fromTreeUri(context, rootUri);
    else
        root = DocumentFile.fromFile(new File(rootUri.getPath()));
    return getDirDocument(root, subDirs);
}
 
Example 17
Source File: FolderActivity.java    From syncthing-android with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.create:
            if (TextUtils.isEmpty(mFolder.id)) {
                Toast.makeText(this, R.string.folder_id_required, Toast.LENGTH_LONG)
                        .show();
                return true;
            }
            if (TextUtils.isEmpty(mFolder.path)) {
                Toast.makeText(this, R.string.folder_path_required, Toast.LENGTH_LONG)
                        .show();
                return true;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                mFolderUri != null) {
                /**
                 * Normally, syncthing takes care of creating the ".stfolder" marker.
                 * This fails on newer android versions if the syncthing binary only has
                 * readonly access on the path and the user tries to configure a
                 * sendonly folder. To fix this, we'll precreate the marker using java code.
                 * We also create an empty file in the marker directory, to hopefully keep
                 * it alive in the face of overzealous disk cleaner apps.
                 */
                DocumentFile dfFolder = DocumentFile.fromTreeUri(this, mFolderUri);
                if (dfFolder != null) {
                    Log.v(TAG, "Creating new directory " + mFolder.path + File.separator + FOLDER_MARKER_NAME);
                    DocumentFile marker = dfFolder.createDirectory(FOLDER_MARKER_NAME);
                    marker.createFile("text/plain", "empty");
                }
            }
            getApi().createFolder(mFolder);
            finish();
            return true;
        case R.id.remove:
            showDeleteDialog();
            return true;
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
 
Example 18
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not
 * existing, it is created.
 *
 * @param file              The file.
 * @param isDirectory       flag indicating if the file should be a directory.
 * @param createDirectories flag indicating if intermediate path directories should be created if not existing.
 * @return The DocumentFile
 */
private static DocumentFile getDocumentFile(Context context, @NonNull final File file, final boolean isDirectory, final boolean createDirectories) {

    Uri treeUri = getTreeUri(context);

    if (treeUri == null) return null;

    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
    String sdcardPath = getSavedSdcardPath(context);
    String suffixPathPart = null;

    if (sdcardPath != null) {
        if ((file.getPath().indexOf(sdcardPath)) != -1)
            suffixPathPart = file.getAbsolutePath().substring(sdcardPath.length());
    } else {
        HashSet<File> storageRoots = StorageHelper.getStorageRoots(context);
        for (File root : storageRoots) {
            if (root != null) {
                if ((file.getPath().indexOf(root.getPath())) != -1)
                    suffixPathPart = file.getAbsolutePath().substring(file.getPath().length());
            }
        }
    }

    if (suffixPathPart == null) {
        Log.d(TAG, "unable to find the document file, filePath:" + file.getPath() + " root: " + "" + sdcardPath);
        return null;
    }

    if (suffixPathPart.startsWith(File.separator)) suffixPathPart = suffixPathPart.substring(1);

    String[] parts = suffixPathPart.split("/");

    for (int i = 0; i < parts.length; i++) { // 3 is the

        DocumentFile tmp = document.findFile(parts[i]);
        if (tmp != null)
            document = document.findFile(parts[i]);
        else {
            if (i < parts.length - 1) {
                if (createDirectories) document = document.createDirectory(parts[i]);
                else return null;
            } else if (isDirectory) document = document.createDirectory(parts[i]);
            else return document.createFile("image", parts[i]);
        }
    }

    return document;
}
 
Example 19
Source File: API29MigrationService.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
/**
 * Import books from known source folders
 */
private void performMigration() throws InterruptedException {
    List<LogUtil.LogEntry> log = new ArrayList<>();

    DocumentFile rootFolder = DocumentFile.fromTreeUri(this, Uri.parse(Preferences.getStorageUri()));
    if (null == rootFolder || !rootFolder.exists()) {
        Timber.e("rootFolder is not defined (%s)", Preferences.getStorageUri());
        return;
    }
    trace(Log.INFO, log, "Using root folder %s", rootFolder.getUri().toString());

    // 1st pass : cache all book folders
    List<DocumentFile> siteFolders = FileHelper.listFolders(this, rootFolder);
    trace(Log.INFO, log, "%s site folders detected", siteFolders.size() + "");

    List<DocumentFile> bookFolders;
    int foldersCount = 1;
    for (DocumentFile siteFolder : siteFolders) {
        bookFolders = FileHelper.listFolders(this, siteFolder);
        Map<String, DocumentFile> siteFoldersCache = new HashMap<>(bookFolders.size());
        for (DocumentFile bookFolder : bookFolders)
            siteFoldersCache.put(bookFolder.getName(), bookFolder);
        bookFoldersCache.put(siteFolder.getName(), siteFoldersCache);
        trace(Log.INFO, log, "Site %s : %s book folders detected", siteFolder.getName(), siteFoldersCache.size() + "");
        eventProgress(2, siteFolders.size(), foldersCount++, 0);
    }

    // tasks are used to execute Rx's observeOn on current thread
    // See https://github.com/square/retrofit/issues/370#issuecomment-315868381
    LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();

    // 2nd pass : scan every book in the library and match actual URIs to it
    dao = new ObjectBoxDAO(this);
    searchDisposable = dao.getOldStoredBookIds()
            .observeOn(Schedulers.from(tasks::add))
            .subscribe(
                    list -> {
                        eventComplete(2, siteFolders.size(), siteFolders.size(), 0, null);
                        searchDisposable.dispose();
                        migrateLibrary(log, list);
                    },
                    throwable -> {
                        Timber.w(throwable);
                        ToastUtil.toast("Book list loading failed");
                    }
            );

    tasks.take().run();
}
 
Example 20
Source File: Api29MigrationActivity.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public void onSelectSAFRootFolder(@NonNull final Uri treeUri) {

        boolean isUriPermissionPeristed = false;
        ContentResolver contentResolver = getContentResolver();
        String treeUriId = DocumentsContract.getTreeDocumentId(treeUri);

        for (UriPermission p : contentResolver.getPersistedUriPermissions()) {
            if (DocumentsContract.getTreeDocumentId(p.getUri()).equals(treeUriId)) {
                isUriPermissionPeristed = true;
                Timber.d("Uri permission already persisted for %s", treeUri);
                break;
            }
        }

        if (!isUriPermissionPeristed) {
            Timber.d("Persisting Uri permission for %s", treeUri);
            // Release previous access permissions, if different than the new one
            FileHelper.revokePreviousPermissions(contentResolver, treeUri);
            // Persist new access permission
            contentResolver.takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        DocumentFile selectedFolder = DocumentFile.fromTreeUri(this, treeUri);
        if (selectedFolder != null) {
            String folderName = selectedFolder.getName();
            if (null == folderName) folderName = "";

            // Make sure we detect the Hentoid folder if it's a child of the selected folder
            if (!ImportHelper.isHentoidFolderName(folderName))
                selectedFolder = ImportHelper.getExistingHentoidDirFrom(this, selectedFolder);
        }

        // If no existing hentoid folder is detected, tell the user to select it again
        if (null == selectedFolder || null == selectedFolder.getName() || !ImportHelper.isHentoidFolderName(selectedFolder.getName()))
        {
            ToastUtil.toast("Please select an existing Hentoid folder. Its location is displayed on screen.");
            return;
        }
        scanLibrary(selectedFolder);
    }