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

The following examples show how to use androidx.documentfile.provider.DocumentFile#exists() . 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: DCCManager.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
private void checkSystemDownloadsDirectoryAccess() {
    if (mDownloadDirectoryOverrideURI != null && !mAlwaysUseFallbackDir) {
        DocumentFile dir = DocumentFile.fromTreeUri(mContext,
                mDownloadDirectoryOverrideURI);
        mHasSystemDirectoryAccess = dir.exists() && dir.canWrite();
        return;
    }

    File downloadsDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    if (downloadsDir != null && downloadsDir.canWrite() && !mAlwaysUseFallbackDir) {
        mDownloadDirectory = downloadsDir;
        mHasSystemDirectoryAccess = true;
    } else {
        mDownloadDirectory = mFallbackDownloadDirectory;
        mHasSystemDirectoryAccess = false;
    }
    Log.d("DCCManager", "Download directory: " +
            (mDownloadDirectory != null ? mDownloadDirectory.getAbsolutePath() : "null"));
}
 
Example 2
Source File: FileHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
public static boolean checkAndSetRootFolder(@NonNull final Context context, @NonNull final DocumentFile folder, boolean notify) {
    // Validate folder
    if (!folder.exists() && !folder.isDirectory()) {
        if (notify)
            ToastUtil.toast(context, R.string.error_creating_folder);
        return false;
    }

    // Remove and add back the nomedia file to test if the user has the I/O rights to the selected folder
    DocumentFile nomedia = findFile(context, folder, NOMEDIA_FILE_NAME);
    if (nomedia != null) nomedia.delete();

    nomedia = folder.createFile("application/octet-steam", NOMEDIA_FILE_NAME);
    if (null != nomedia && nomedia.exists()) {
        boolean deleted = nomedia.delete();
        if (deleted) Timber.d(".nomedia file deleted");
    } else {
        if (notify)
            ToastUtil.toast(context, R.string.error_write_permission);
        return false;
    }

    Preferences.setStorageUri(folder.getUri().toString());
    return true;
}
 
Example 3
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 4
Source File: MediaFileUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * キャプチャ用のディレクトリを取得、取得できなければnull
 * こっちはSAF経由でアクセス可能な場合のみ指定場所を示すDocumentFileを返す
 * @param context
 * @param saveTreeId 0: SAFを使わない, それ以外: SAFのツリーIDとみなして処理を試みる
 * @return
 */
@Nullable
public static synchronized DocumentFile getSAFRecordingRoot(
	@NonNull final Context context,
	final int saveTreeId) {

	DocumentFile root = null;
	if (SAFUtils.hasPermission(context, saveTreeId)) {
		try {
			root = SAFUtils.getDir(context, saveTreeId, FileUtils.DIR_NAME);
			if (!root.exists() || !root.canWrite()) {
				Log.d(TAG, "path will be wrong, will already be removed,"
					+ (root != null ? root.getUri() : null));
				root = null;
			}
		} catch (final IOException | IllegalStateException e) {
			root = null;
			Log.d(TAG, "path is wrong, will already be removed.", e);
		}
	}
	if (root == null) {
		if (DEBUG) Log.d(TAG, "getSAFRecordingRoot:保存先を取得できなかったので念のためにセカンダリーストレージアクセスのパーミッションも落としておく");
		SAFUtils.releasePersistableUriPermission(context, saveTreeId);
	}
	return root;
}
 
Example 5
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 6
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 7
Source File: ImageViewerViewModel.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
private void cacheJson(@NonNull Context context, @NonNull Content content) {
    Helper.assertNonUiThread();
    if (!content.getJsonUri().isEmpty()) return;

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

    DocumentFile foundFile = FileHelper.findFile(getApplication(), folder, Consts.JSON_FILE_NAME_V2);
    if (null == foundFile) {
        Timber.e("JSON file not detected in %s", content.getStorageUri());
        return;
    }

    // Cache the URI of the JSON to the database
    content.setJsonUri(foundFile.getUri().toString());
    collectionDao.insertContent(content);
}
 
Example 8
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the given page from the disk and the DB
 *
 * @param image Page to be removed
 * @param dao   DAO to be used
 */
public static void removePage(@NonNull ImageFile image, @NonNull CollectionDAO dao, @NonNull final Context context) {
    Helper.assertNonUiThread();
    // Remove from DB
    // NB : start with DB to have a LiveData feedback, because file removal can take much time
    dao.deleteImageFile(image);

    // Remove the page from disk
    if (image.getFileUri() != null && !image.getFileUri().isEmpty()) {
        Uri uri = Uri.parse(image.getFileUri());

        DocumentFile doc = DocumentFile.fromSingleUri(context, uri);
        if (doc != null && doc.exists()) doc.delete();
    }

    // Update content JSON if it exists (i.e. if book is not queued)
    Content content = dao.selectContent(image.content.getTargetId());
    if (!content.getJsonUri().isEmpty()) updateJson(context, content);
}
 
Example 9
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @param dir The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(Context context, @NonNull final File dir) {
    boolean success = dir.exists();
    // Try the normal way
    if (!success) success = dir.mkdir();

    // Try with Storage Access Framework.
    if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, dir, true, true);
        // getDocumentFile implicitly creates the directory.
        success = document != null && document.exists();
    }

    //let MediaStore know that a dir was created
    if (success) scanFile(context, new String[]{dir.getPath()});

    return success;
}
 
Example 10
Source File: BaseUriFtpFile.java    From ProjectX with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isWritable() {
    if (mDocument.exists())
        return mDocument.canWrite();
    DocumentFile parent = mDocument.getParentFile();
    while (parent != null) {
        if (parent.exists())
            return parent.canWrite();
        parent = parent.getParentFile();
    }
    return false;
}
 
Example 11
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * Create the given Content's JSON file and populate it with its current values
 *
 * @param content Content whose JSON file to create
 */
public static void createJson(@NonNull Context context, @NonNull Content content) {
    Helper.assertNonUiThread();
    DocumentFile folder = DocumentFile.fromTreeUri(context, Uri.parse(content.getStorageUri()));
    if (null == folder || !folder.exists()) return;
    try {
        JsonHelper.createJson(context, JsonContent.fromEntity(content), JsonContent.class, folder);
    } catch (IOException e) {
        Timber.e(e, "Error while writing to %s", content.getStorageUri());
    }
}
 
Example 12
Source File: DCCTransferListAdapter.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
private void delete() {
    if (mFileUri != null && mFileUri.length() > 0) {
        Uri uri = Uri.parse(mFileUri);
        DocumentFile file;
        if (uri.getScheme().equals("file"))
            file = DocumentFile.fromFile(new File(uri.getPath()));
        else
            file = DocumentFile.fromSingleUri(itemView.getContext(), uri);
        if (file.exists())
            file.delete();
    }
    DCCManager.getInstance(itemView.getContext()).getHistory().removeEntry(mEntryId);
}
 
Example 13
Source File: DocumentUtil.java    From a with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isFileExist(String fileName, DocumentFile root, String... subDirs) {
    DocumentFile parent = getDirDocument(root, subDirs);
    if (parent == null)
        return false;
    fileName = filenameFilter(Uri.decode(fileName));
    DocumentFile file = parent.findFile(fileName);
    if (file != null && file.exists())
        return true;
    return false;
}
 
Example 14
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
public static DocumentFile getExistingHentoidDirFrom(@NonNull final Context context, @NonNull final DocumentFile root) {
    if (!root.exists() || !root.isDirectory() || null == root.getName()) return root;

    // Selected folder _is_ the Hentoid folder
    if (isHentoidFolderName(root.getName())) return root;

    // If not, look for it in its children
    List<DocumentFile> hentoidDirs = FileHelper.listFoldersFilter(context, root, hentoidFolderNames);
    if (!hentoidDirs.isEmpty()) return hentoidDirs.get(0);
    else return root;
}
 
Example 15
Source File: DocumentUtil.java    From a with GNU General Public License v3.0 5 votes vote down vote up
public static boolean deleteFile(String fileName, DocumentFile root, String... subDirs) {
    DocumentFile parent = getDirDocument(root, subDirs);
    if (parent == null)
        return false;
    fileName = filenameFilter(Uri.decode(fileName));
    DocumentFile file = parent.findFile(fileName);
    return file != null && file.exists() && file.delete();
}
 
Example 16
Source File: FileUtil.java    From Augendiagnose with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @param file The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(@NonNull final File file) {
	if (file.exists()) {
		// nothing to create.
		return file.isDirectory();
	}

	// Try the normal way
	if (file.mkdir()) {
		return true;
	}

	// Try with Storage Access Framework.
	if (SystemUtil.isAndroid5()) {
		DocumentFile document = getDocumentFile(file, true, true);
		// getDocumentFile implicitly creates the directory.
		return document != null && document.exists();
	}

	// Try the Kitkat workaround.
	if (SystemUtil.isKitkat()) {
		File tempFile = new File(file, "dummyImage.jpg");

		File dummySong = copyDummyFiles();
		if (dummySong == null) {
			return false;
		}
		int albumId = MediaStoreUtil.getAlbumIdFromAudioFile(dummySong);
		Uri albumArtUri = Uri.parse("content://media/external/audio/albumart/" + albumId);

		ContentValues contentValues = new ContentValues();
		contentValues.put(MediaStore.MediaColumns.DATA, tempFile.getAbsolutePath());
		contentValues.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);

		ContentResolver resolver = Application.getAppContext().getContentResolver();
		if (resolver.update(albumArtUri, contentValues, null, null) == 0) {
			resolver.insert(Uri.parse("content://media/external/audio/albumart"), contentValues);
		}
		try {
			ParcelFileDescriptor fd = resolver.openFileDescriptor(albumArtUri, "r");
			if (fd != null) {
				fd.close();
			}
		}
		catch (Exception e) {
			Log.e(Application.TAG, "Could not open file", e);
			return false;
		}
		finally {
			FileUtil.deleteFile(tempFile);
		}

		return true;
	}

	return false;
}
 
Example 17
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public static @Result
int setAndScanFolder(
        @NonNull final Context context,
        @NonNull final Uri treeUri,
        boolean askScanExisting,
        @Nullable final ImportOptions options) {

    boolean isUriPermissionPeristed = false;
    ContentResolver contentResolver = context.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 docFile = DocumentFile.fromTreeUri(context, treeUri);
    if (null == docFile || !docFile.exists()) {
        Timber.e("Could not find the selected file %s", treeUri.toString());
        return Result.INVALID_FOLDER;
    }
    DocumentFile hentoidFolder = addHentoidFolder(context, docFile);
    if (null == hentoidFolder) {
        Timber.e("Could not create Hentoid folder in root %s", docFile.getUri().toString());
        return Result.CREATE_FAIL;
    }
    if (!FileHelper.checkAndSetRootFolder(context, hentoidFolder, true)) {
        Timber.e("Could not set the selected root folder %s", hentoidFolder.getUri().toString());
        return Result.INVALID_FOLDER;
    }

    if (hasBooks(context)) {
        if (!askScanExisting) {
            runImport(context, options);
            return Result.OK_LIBRARY_DETECTED;
        } else return Result.OK_LIBRARY_DETECTED_ASK;
    } else {
        // New library created - drop and recreate db (in case user is re-importing)
        new ObjectBoxDAO(context).deleteAllLibraryBooks(true);
        return Result.OK_EMPTY_FOLDER;
    }
}
 
Example 18
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 19
Source File: ImageBottomSheetFragment.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
/**
 * Handle click on "Share" action button
 */
private void onShareClick() {
    DocumentFile docFile = FileHelper.getFileFromUriString(requireContext(), image.getFileUri());
    if (docFile != null && docFile.exists())
        FileHelper.shareFile(requireContext(), docFile, "Share picture");
}
 
Example 20
Source File: ContentDownloadService.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
/**
 * Create the given file in the given destination folder, and write binary data to it
 *
 * @param img           ImageFile that is being processed
 * @param dir           Destination folder
 * @param contentType   Content type of the image (because some sources don't serve images with extensions)
 * @param binaryContent Binary content of the image
 * @throws IOException IOException if image cannot be saved at given location
 */
@Nullable
private DocumentFile processAndSaveImage(@NonNull ImageFile img,
                                         @NonNull DocumentFile dir,
                                         @Nullable String contentType,
                                         byte[] binaryContent,
                                         boolean hasImageProcessing) throws IOException, UnsupportedContentException {

    if (!dir.exists()) {
        Timber.w("processAndSaveImage : Directory %s does not exist - image not saved", dir.getUri().toString());
        return null;
    }

    byte[] finalBinaryContent = null;
    if (hasImageProcessing && !img.getName().equals(Consts.THUMB_FILE_NAME)) {
        if (img.getDownloadParams() != null && !img.getDownloadParams().isEmpty())
            finalBinaryContent = processImage(img.getDownloadParams(), binaryContent);
        else throw new InvalidParameterException("No processing parameters found");
    }
    img.setSize(binaryContent.length);

    String fileExt = null;
    String mimeType = null;
    // Determine the extension of the file

    // Use the Content-type contained in the HTTP headers of the response
    if (null != contentType) {
        mimeType = HttpHelper.cleanContentType(contentType).first;
        // Ignore neutral binary content-type
        if (!contentType.equalsIgnoreCase("application/octet-stream")) {
            fileExt = FileHelper.getExtensionFromMimeType(contentType);
            Timber.d("Using content-type %s to determine file extension -> %s", contentType, fileExt);
        }
    }
    // Content-type has not been useful to determine the extension => See if the URL contains an extension
    if (null == fileExt || fileExt.isEmpty()) {
        fileExt = HttpHelper.getExtensionFromUri(img.getUrl());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExt);
        Timber.d("Using url to determine file extension (content-type was %s) for %s -> %s", contentType, img.getUrl(), fileExt);
    }
    // No extension detected in the URL => Read binary header of the file to detect known formats
    // If PNG, peek into the file to see if it is an animated PNG or not (no other way to do that)
    if (fileExt.isEmpty() || fileExt.equals("png")) {
        mimeType = FileHelper.getMimeTypeFromPictureBinary(binaryContent);
        fileExt = FileHelper.getExtensionFromMimeType(mimeType);
        Timber.d("Reading headers to determine file extension for %s -> %s (from detected mime-type %s)", img.getUrl(), fileExt, mimeType);
    }
    // If all else fails, fall back to jpg as default
    if (null == fileExt || fileExt.isEmpty()) {
        fileExt = "jpg";
        mimeType = "image/jpeg";
        Timber.d("Using default extension for %s -> %s", img.getUrl(), fileExt);
    }
    if (null == mimeType) mimeType = "image/*";
    img.setMimeType(mimeType);

    if (!Helper.isImageExtensionSupported(fileExt))
        throw new UnsupportedContentException(String.format("Unsupported extension %s for %s - image not processed", fileExt, img.getUrl()));
    else
        return saveImage(dir, img.getName() + "." + fileExt, mimeType, (null == finalBinaryContent) ? binaryContent : finalBinaryContent);
}