Search in sources :

Example 1 with NotAllowedException

use of com.amaze.filemanager.exceptions.NotAllowedException in project AmazeFileManager by TeamAmaze.

the class FileUtil method writeUriToStorage.

/**
 * Writes uri stream from external application to the specified path
 */
public static final void writeUriToStorage(@NonNull final MainActivity mainActivity, @NonNull final ArrayList<Uri> uris, @NonNull final ContentResolver contentResolver, @NonNull final String currentPath) {
    MaybeOnSubscribe<List<String>> writeUri = (MaybeOnSubscribe<List<String>>) emitter -> {
        List<String> retval = new ArrayList<>();
        for (Uri uri : uris) {
            BufferedInputStream bufferedInputStream = null;
            try {
                bufferedInputStream = new BufferedInputStream(contentResolver.openInputStream(uri));
            } catch (FileNotFoundException e) {
                emitter.onError(e);
                return;
            }
            BufferedOutputStream bufferedOutputStream = null;
            try {
                DocumentFile documentFile = DocumentFile.fromSingleUri(mainActivity, uri);
                String filename = documentFile.getName();
                if (filename == null) {
                    filename = uri.getLastPathSegment();
                    if (filename.contains("/"))
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                }
                String finalFilePath = currentPath + "/" + filename;
                DataUtils dataUtils = DataUtils.getInstance();
                HybridFile hFile = new HybridFile(OpenMode.UNKNOWN, currentPath);
                hFile.generateMode(mainActivity);
                switch(hFile.getMode()) {
                    case FILE:
                    case ROOT:
                        File targetFile = new File(finalFilePath);
                        if (!FileProperties.isWritableNormalOrSaf(targetFile.getParentFile(), mainActivity.getApplicationContext())) {
                            emitter.onError(new NotAllowedException());
                            return;
                        }
                        DocumentFile targetDocumentFile = ExternalSdCardOperation.getDocumentFile(targetFile, false, mainActivity.getApplicationContext());
                        if (targetDocumentFile == null) {
                            targetDocumentFile = DocumentFile.fromFile(targetFile);
                        }
                        if (targetDocumentFile.exists() && targetDocumentFile.length() > 0) {
                            emitter.onError(new OperationWouldOverwriteException());
                            return;
                        }
                        bufferedOutputStream = new BufferedOutputStream(contentResolver.openOutputStream(targetDocumentFile.getUri()));
                        retval.add(targetFile.getPath());
                        break;
                    case SMB:
                        SmbFile targetSmbFile = SmbUtil.create(finalFilePath);
                        if (targetSmbFile.exists()) {
                            emitter.onError(new OperationWouldOverwriteException());
                            return;
                        } else {
                            OutputStream outputStream = targetSmbFile.getOutputStream();
                            bufferedOutputStream = new BufferedOutputStream(outputStream);
                            retval.add(HybridFile.parseAndFormatUriForDisplay(targetSmbFile.getPath()));
                        }
                        break;
                    case SFTP:
                        AppConfig.toast(mainActivity, mainActivity.getString(R.string.not_allowed));
                        emitter.onError(new NotImplementedError());
                        return;
                    case DROPBOX:
                    case BOX:
                    case ONEDRIVE:
                    case GDRIVE:
                        OpenMode mode = hFile.getMode();
                        CloudStorage cloudStorage = dataUtils.getAccount(mode);
                        String path = CloudUtil.stripPath(mode, finalFilePath);
                        cloudStorage.upload(path, bufferedInputStream, documentFile.length(), true);
                        retval.add(path);
                        break;
                    case OTG:
                        DocumentFile documentTargetFile = OTGUtil.getDocumentFile(finalFilePath, mainActivity, true);
                        if (documentTargetFile.exists()) {
                            emitter.onError(new OperationWouldOverwriteException());
                            return;
                        }
                        bufferedOutputStream = new BufferedOutputStream(contentResolver.openOutputStream(documentTargetFile.getUri()), GenericCopyUtil.DEFAULT_BUFFER_SIZE);
                        retval.add(documentTargetFile.getUri().getPath());
                        break;
                    default:
                        return;
                }
                int count = 0;
                byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
                while (count != -1) {
                    count = bufferedInputStream.read(buffer);
                    if (count != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }
                }
                bufferedOutputStream.flush();
            } catch (IOException e) {
                emitter.onError(e);
                return;
            } finally {
                try {
                    if (bufferedInputStream != null) {
                        bufferedInputStream.close();
                    }
                    if (bufferedOutputStream != null) {
                        bufferedOutputStream.close();
                    }
                } catch (IOException e) {
                    emitter.onError(e);
                }
            }
        }
        if (retval.size() > 0) {
            emitter.onSuccess(retval);
        } else {
            emitter.onError(new Exception());
        }
    };
    Maybe.create(writeUri).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new MaybeObserver<List<String>>() {

        @Override
        public void onSubscribe(@NonNull Disposable d) {
        }

        @Override
        public void onSuccess(@NonNull List<String> paths) {
            MediaScannerConnection.scanFile(mainActivity.getApplicationContext(), paths.toArray(new String[0]), new String[paths.size()], null);
            if (paths.size() == 1) {
                Toast.makeText(mainActivity, mainActivity.getString(R.string.saved_single_file, paths.get(0)), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(mainActivity, mainActivity.getString(R.string.saved_multi_files, paths.size()), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onError(@NonNull Throwable e) {
            if (e instanceof OperationWouldOverwriteException) {
                AppConfig.toast(mainActivity, mainActivity.getString(R.string.cannot_overwrite));
                return;
            }
            if (e instanceof NotAllowedException) {
                AppConfig.toast(mainActivity, mainActivity.getResources().getString(R.string.not_allowed));
            }
            Log.e(getClass().getSimpleName(), "Failed to write uri to storage due to " + e.getCause());
            e.printStackTrace();
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : NotAllowedException(com.amaze.filemanager.exceptions.NotAllowedException) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Uri(android.net.Uri) CloudStorage(com.cloudrail.si.interfaces.CloudStorage) BufferedInputStream(java.io.BufferedInputStream) ArrayList(java.util.ArrayList) List(java.util.List) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe) BufferedOutputStream(java.io.BufferedOutputStream) OperationWouldOverwriteException(com.amaze.filemanager.exceptions.OperationWouldOverwriteException) Disposable(io.reactivex.disposables.Disposable) DocumentFile(androidx.documentfile.provider.DocumentFile) NotImplementedError(kotlin.NotImplementedError) IOException(java.io.IOException) OpenMode(com.amaze.filemanager.file_operations.filesystem.OpenMode) NotAllowedException(com.amaze.filemanager.exceptions.NotAllowedException) OperationWouldOverwriteException(com.amaze.filemanager.exceptions.OperationWouldOverwriteException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SmbFile(jcifs.smb.SmbFile) DataUtils(com.amaze.filemanager.utils.DataUtils) File(java.io.File) SmbFile(jcifs.smb.SmbFile) DocumentFile(androidx.documentfile.provider.DocumentFile)

Aggregations

Uri (android.net.Uri)1 DocumentFile (androidx.documentfile.provider.DocumentFile)1 NotAllowedException (com.amaze.filemanager.exceptions.NotAllowedException)1 OperationWouldOverwriteException (com.amaze.filemanager.exceptions.OperationWouldOverwriteException)1 OpenMode (com.amaze.filemanager.file_operations.filesystem.OpenMode)1 DataUtils (com.amaze.filemanager.utils.DataUtils)1 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)1 MaybeOnSubscribe (io.reactivex.MaybeOnSubscribe)1 Disposable (io.reactivex.disposables.Disposable)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 SmbFile (jcifs.smb.SmbFile)1 NotImplementedError (kotlin.NotImplementedError)1