Search in sources :

Example 31 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class StorageHelper method mkdir.

/**
 * 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;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile)

Example 32 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class StorageHelper method getDocumentFile.

/**
 * 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;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Uri(android.net.Uri) File(java.io.File) DocumentFile(android.support.v4.provider.DocumentFile)

Example 33 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class StorageHelper method rmdir.

/**
 * Delete a folder.
 *
 * @param file The folder name.
 * @return true if successful.
 */
public static boolean rmdir(Context context, @NonNull final File file) {
    if (!file.exists() && !file.isDirectory())
        return false;
    String[] fileList = file.list();
    if (fileList != null && fileList.length > 0)
        // Delete only empty folder.
        return false;
    // Try the normal way
    if (file.delete())
        return true;
    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, file, true, true);
        return document != null && document.delete();
    }
    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // Delete the created entry, such that content provider will delete the file.
        resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", new String[] { file.getAbsolutePath() });
    }
    return !file.exists();
}
Also used : ContentValues(android.content.ContentValues) DocumentFile(android.support.v4.provider.DocumentFile) ContentResolver(android.content.ContentResolver)

Example 34 with DocumentFile

use of android.support.v4.provider.DocumentFile in project Shuttle by timusus.

the class TaggerTask method doInBackground.

@Override
protected Boolean doInBackground(Object... params) {
    boolean success = false;
    boolean requiresPermission = TaggerUtils.requiresPermission(paths);
    for (int i = 0; i < paths.size(); i++) {
        final String path = paths.get(i);
        try {
            File orig = new File(path);
            AudioFile audioFile = AudioFileIO.read(orig);
            Tag tag = audioFile.getTag();
            if (tag == null) {
                break;
            }
            TagUpdate tagUpdate = new TagUpdate(tag);
            tagUpdate.softSetArtist(artistText);
            tagUpdate.softSetAlbumArtist(albumArtistText);
            tagUpdate.softSetGenre(genreText);
            tagUpdate.softSetYear(yearText);
            if (showAlbum) {
                tagUpdate.softSetAlbum(albumText);
                tagUpdate.softSetDiscTotal(discTotalText);
            }
            if (showTrack) {
                tagUpdate.softSetTitle(titleText);
                tagUpdate.softSetTrack(trackText);
                tagUpdate.softSetTrackTotal(trackTotalText);
                tagUpdate.softSetDisc(discText);
                tagUpdate.softSetLyrics(lyricsText);
                tagUpdate.softSetComment(commentText);
            }
            File temp = null;
            if (tagUpdate.hasChanged()) {
                if (TaggerUtils.requiresPermission(paths)) {
                    temp = new File(ShuttleApplication.getInstance().getFilesDir(), orig.getName());
                    tempFiles.add(temp);
                    TaggerUtils.copyFile(orig, temp);
                    audioFile = AudioFileIO.read(temp);
                    tag = audioFile.getTag();
                    if (tag == null) {
                        break;
                    }
                }
                tagUpdate.updateTag(tag);
                AudioFileIO.write(audioFile);
                if (requiresPermission && temp != null) {
                    DocumentFile documentFile = documentFiles.get(i);
                    if (documentFile != null) {
                        ParcelFileDescriptor pfd = ShuttleApplication.getInstance().getContentResolver().openFileDescriptor(documentFile.getUri(), "w");
                        if (pfd != null) {
                            FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
                            TaggerUtils.copyFile(temp, fileOutputStream);
                            pfd.close();
                        }
                        if (temp.delete()) {
                            if (tempFiles.contains(temp)) {
                                tempFiles.remove(temp);
                            }
                        }
                    }
                }
            }
            publishProgress(i);
            success = true;
        } catch (CannotWriteException | IOException | CannotReadException | InvalidAudioFrameException | TagException | ReadOnlyFileException e) {
            e.printStackTrace();
        } finally {
            // Try to clean up our temp files
            if (tempFiles != null && tempFiles.size() != 0) {
                for (int j = tempFiles.size() - 1; j >= 0; j--) {
                    File file = tempFiles.get(j);
                    file.delete();
                    tempFiles.remove(j);
                }
            }
        }
    }
    return success;
}
Also used : CannotWriteException(org.jaudiotagger.audio.exceptions.CannotWriteException) DocumentFile(android.support.v4.provider.DocumentFile) CannotReadException(org.jaudiotagger.audio.exceptions.CannotReadException) InvalidAudioFrameException(org.jaudiotagger.audio.exceptions.InvalidAudioFrameException) IOException(java.io.IOException) TagUpdate(com.simplecity.amp_library.model.TagUpdate) AudioFile(org.jaudiotagger.audio.AudioFile) TagException(org.jaudiotagger.tag.TagException) FileOutputStream(java.io.FileOutputStream) ParcelFileDescriptor(android.os.ParcelFileDescriptor) ReadOnlyFileException(org.jaudiotagger.audio.exceptions.ReadOnlyFileException) Tag(org.jaudiotagger.tag.Tag) File(java.io.File) AudioFile(org.jaudiotagger.audio.AudioFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 35 with DocumentFile

use of android.support.v4.provider.DocumentFile in project Shuttle by timusus.

the class TaggerUtils method hasDocumentTreePermission.

/**
 * Checks the passed in paths to see whether the file at the given path is available in our
 * document tree. If it is, and we have write permission, the document file is added to the
 * passed in list of document files.
 *
 * @param documentFiles a list of document files to be populated
 * @param paths         a list of paths
 * @return true if we have permission for all files at the passed in paths
 */
static boolean hasDocumentTreePermission(List<DocumentFile> documentFiles, List<String> paths) {
    boolean hasDocumentTreePermission = false;
    String treeUri = getDocumentTree();
    if (treeUri == null) {
        // We don't have any document tree at all - so we're not going to have permission for any files.
        return false;
    }
    // we're satisfied we don't have permission.
    for (String path : paths) {
        File file = new File(path);
        DocumentFile documentFile = getDocumentFile(Uri.parse(treeUri), file);
        if (documentFile != null) {
            hasDocumentTreePermission = documentFile.canWrite();
        }
        if (hasDocumentTreePermission) {
            documentFiles.add(documentFile);
        } else {
            documentFiles.clear();
            break;
        }
    }
    return hasDocumentTreePermission;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) File(java.io.File) DocumentFile(android.support.v4.provider.DocumentFile)

Aggregations

DocumentFile (android.support.v4.provider.DocumentFile)65 File (java.io.File)36 IOException (java.io.IOException)22 Uri (android.net.Uri)21 ContentResolver (android.content.ContentResolver)12 SmbFile (jcifs.smb.SmbFile)11 MalformedURLException (java.net.MalformedURLException)10 SmbException (jcifs.smb.SmbException)10 FileOutputStream (java.io.FileOutputStream)9 ShellNotRunningException (com.amaze.filemanager.exceptions.ShellNotRunningException)8 OutputStream (java.io.OutputStream)8 InputStream (java.io.InputStream)7 SuppressLint (android.annotation.SuppressLint)6 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)6 FileInputStream (java.io.FileInputStream)6 SFtpClientTemplate (com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate)4 BufferedOutputStream (java.io.BufferedOutputStream)4 FileNotFoundException (java.io.FileNotFoundException)4 FileChannel (java.nio.channels.FileChannel)4 SFTPClient (net.schmizz.sshj.sftp.SFTPClient)4