Search in sources :

Example 11 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method isWritableNormalOrSaf.

// Utility methods for Android 5
/**
 * Check for a directory if it is possible to create files within this directory, either via normal writing or via
 * Storage Access Framework.
 *
 * @param folder The directory
 * @return true if it is possible to write in this directory.
 */
public static boolean isWritableNormalOrSaf(final File folder, Context c) {
    // Verify that this is a directory.
    if (folder == null)
        return false;
    if (!folder.exists() || !folder.isDirectory()) {
        return false;
    }
    // Find a non-existing file in this directory.
    int i = 0;
    File file;
    do {
        String fileName = "AugendiagnoseDummyFile" + (++i);
        file = new File(folder, fileName);
    } while (file.exists());
    // First check regular writability
    if (isWritable(file)) {
        return true;
    }
    // Next check SAF writability.
    DocumentFile document = getDocumentFile(file, false, c);
    if (document == null) {
        return false;
    }
    // This should have created the file - otherwise something is wrong with access URL.
    boolean result = document.canWrite() && file.exists();
    // Ensure that the dummy file is not remaining.
    deleteFile(file, c);
    return result;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 12 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method getOutputStream.

public static OutputStream getOutputStream(final File target, Context context) throws FileNotFoundException {
    OutputStream outStream = null;
    // First try the normal way
    if (isWritable(target)) {
        // standard way
        outStream = new FileOutputStream(target);
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Storage Access Framework
            DocumentFile targetDocument = getDocumentFile(target, false, context);
            outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            // Workaround for Kitkat ext SD card
            return MediaStoreHack.getOutputStream(context, target.getPath());
        }
    }
    return outStream;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream)

Example 13 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class HybridFile method getUsableSpace.

/**
 * Gets usable i.e. free space of a device
 * @return
 */
public long getUsableSpace() {
    long size = 0L;
    switch(mode) {
        case SMB:
            try {
                size = (new SmbFile(path).getDiskFreeSpace());
            } catch (MalformedURLException e) {
                size = 0L;
                e.printStackTrace();
            } catch (SmbException e) {
                size = 0L;
                e.printStackTrace();
            }
            break;
        case FILE:
        case ROOT:
            size = new File(path).getUsableSpace();
            break;
        case DROPBOX:
        case BOX:
        case GDRIVE:
        case ONEDRIVE:
            SpaceAllocation spaceAllocation = dataUtils.getAccount(mode).getAllocation();
            size = spaceAllocation.getTotal() - spaceAllocation.getUsed();
            break;
        case SFTP:
            size = SshClientUtils.execute(new SFtpClientTemplate(path) {

                @Override
                public Long execute(@NonNull SFTPClient client) throws IOException {
                    try {
                        Statvfs.Response response = new Statvfs.Response(path, client.getSFTPEngine().request(Statvfs.request(client, SshClientUtils.extractRemotePathFrom(path))).retrieve());
                        return response.diskFreeSpace();
                    } catch (SFTPException e) {
                        Log.e(TAG, "Error querying server", e);
                        return 0L;
                    } catch (Buffer.BufferException e) {
                        Log.e(TAG, "Error parsing reply", e);
                        return 0L;
                    }
                }
            });
            break;
        case OTG:
            // TODO: Get free space from OTG when {@link DocumentFile} API adds support
            break;
    }
    return size;
}
Also used : Buffer(net.schmizz.sshj.common.Buffer) MalformedURLException(java.net.MalformedURLException) SFTPClient(net.schmizz.sshj.sftp.SFTPClient) Statvfs(com.amaze.filemanager.filesystem.ssh.Statvfs) SFTPException(net.schmizz.sshj.sftp.SFTPException) SmbFile(jcifs.smb.SmbFile) SmbException(jcifs.smb.SmbException) SFtpClientTemplate(com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate) SpaceAllocation(com.cloudrail.si.types.SpaceAllocation) NonNull(android.support.annotation.NonNull) RemoteFile(net.schmizz.sshj.sftp.RemoteFile) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 14 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class Operations method mkfile.

public static void mkfile(@NonNull final HybridFile file, final Context context, final boolean rootMode, @NonNull final ErrorCallBack errorCallBack) {
    new AsyncTask<Void, Void, Void>() {

        private DataUtils dataUtils = DataUtils.getInstance();

        @Override
        protected Void doInBackground(Void... params) {
            // check whether filename is valid or not
            if (!Operations.isFileNameValid(file.getName(context))) {
                errorCallBack.invalidName(file);
                return null;
            }
            if (file.exists()) {
                errorCallBack.exists(file);
                return null;
            }
            if (file.isSftp()) {
                OutputStream out = file.getOutputStream(context);
                try {
                    out.close();
                    errorCallBack.done(file, true);
                    return null;
                } catch (IOException e) {
                    errorCallBack.done(file, false);
                    return null;
                }
            }
            if (file.isSmb()) {
                try {
                    file.getSmbFile(2000).createNewFile();
                } catch (SmbException e) {
                    e.printStackTrace();
                    errorCallBack.done(file, false);
                    return null;
                }
                errorCallBack.done(file, file.exists());
                return null;
            } else if (file.isDropBoxFile()) {
                CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
                try {
                    byte[] tempBytes = new byte[0];
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
                    cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()), byteArrayInputStream, 0l, true);
                    errorCallBack.done(file, true);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorCallBack.done(file, false);
                }
            } else if (file.isBoxFile()) {
                CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
                try {
                    byte[] tempBytes = new byte[0];
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
                    cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()), byteArrayInputStream, 0l, true);
                    errorCallBack.done(file, true);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorCallBack.done(file, false);
                }
            } else if (file.isOneDriveFile()) {
                CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
                try {
                    byte[] tempBytes = new byte[0];
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
                    cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()), byteArrayInputStream, 0l, true);
                    errorCallBack.done(file, true);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorCallBack.done(file, false);
                }
            } else if (file.isGoogleDriveFile()) {
                CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
                try {
                    byte[] tempBytes = new byte[0];
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
                    cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()), byteArrayInputStream, 0l, true);
                    errorCallBack.done(file, true);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorCallBack.done(file, false);
                }
            } else if (file.isOtgFile()) {
                // first check whether new file already exists
                DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
                if (fileToCreate != null)
                    errorCallBack.exists(file);
                DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
                if (parentDirectory.isDirectory()) {
                    parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")), file.getName(context));
                    errorCallBack.done(file, true);
                } else
                    errorCallBack.done(file, false);
                return null;
            } else {
                if (file.isLocal() || file.isRoot()) {
                    int mode = checkFolder(new File(file.getParent()), context);
                    if (mode == 2) {
                        errorCallBack.launchSAF(file);
                        return null;
                    }
                    if (mode == 1 || mode == 0)
                        try {
                            FileUtil.mkfile(file.getFile(), context);
                        } catch (IOException e) {
                        }
                    if (!file.exists() && rootMode) {
                        file.setMode(OpenMode.ROOT);
                        if (file.exists())
                            errorCallBack.exists(file);
                        try {
                            RootUtils.mkFile(file.getPath());
                        } catch (ShellNotRunningException e) {
                            e.printStackTrace();
                        }
                        errorCallBack.done(file, file.exists());
                        return null;
                    }
                    errorCallBack.done(file, file.exists());
                    return null;
                }
                errorCallBack.done(file, file.exists());
            }
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) OutputStream(java.io.OutputStream) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) IOException(java.io.IOException) SmbException(jcifs.smb.SmbException) SmbException(jcifs.smb.SmbException) CloudStorage(com.cloudrail.si.interfaces.CloudStorage) ByteArrayInputStream(java.io.ByteArrayInputStream) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) DataUtils(com.amaze.filemanager.utils.DataUtils) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(android.support.v4.provider.DocumentFile)

Example 15 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class OTGUtil method getDocumentFile.

/**
 * Traverse to a specified path in OTG
 *
 * @param createRecursive flag used to determine whether to create new file while traversing to path,
 *                        in case path is not present. Notably useful in opening an output stream.
 */
public static DocumentFile getDocumentFile(String path, Context context, boolean createRecursive) {
    SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
    String rootUriString = manager.getString(MainActivity.KEY_PREF_OTG, null);
    // start with root of SD card and then parse through document tree.
    DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));
    String[] parts = path.split("/");
    for (String part : parts) {
        if (path.equals("otg:/"))
            break;
        if (part.equals("otg:") || part.equals(""))
            continue;
        // iterating through the required path to find the end point
        DocumentFile nextDocument = rootUri.findFile(part);
        if (createRecursive && (nextDocument == null || !nextDocument.exists())) {
            nextDocument = rootUri.createFile(part.substring(part.lastIndexOf(".")), part);
        }
        rootUri = nextDocument;
    }
    return rootUri;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) SharedPreferences(android.content.SharedPreferences)

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