Search in sources :

Example 1 with OpenMode

use of com.amaze.filemanager.file_operations.filesystem.OpenMode in project AmazeFileManager by TeamAmaze.

the class EncryptService method onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    baseFile = intent.getParcelableExtra(TAG_SOURCE);
    targetFilename = intent.getStringExtra(TAG_ENCRYPT_TARGET);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    accentColor = ((AppConfig) getApplication()).getUtilsProvider().getColorPreference().getCurrentUserColorPreferences(this, sharedPreferences).getAccent();
    OpenMode openMode = OpenMode.values()[intent.getIntExtra(TAG_OPEN_MODE, OpenMode.UNKNOWN.ordinal())];
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Intent.ACTION_MAIN);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationIntent.putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    customSmallContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_small);
    customBigContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_big);
    Intent stopIntent = new Intent(TAG_BROADCAST_CRYPT_CANCEL);
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(context, 1234, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_folder_lock_white_36dp, getString(R.string.stop_ftp), stopPendingIntent);
    notificationBuilder = new NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID);
    notificationBuilder.setContentIntent(pendingIntent).setCustomContentView(customSmallContentViews).setCustomBigContentView(customBigContentViews).setCustomHeadsUpContentView(customSmallContentViews).setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action).setColor(accentColor).setOngoing(true).setSmallIcon(R.drawable.ic_folder_lock_white_36dp);
    NotificationConstants.setMetadata(getApplicationContext(), notificationBuilder, NotificationConstants.TYPE_NORMAL);
    startForeground(NotificationConstants.ENCRYPT_ID, notificationBuilder.build());
    initNotificationViews();
    super.onStartCommand(intent, flags, startId);
    super.progressHalted();
    new BackgroundTask().execute();
    return START_NOT_STICKY;
}
Also used : AppConfig(com.amaze.filemanager.application.AppConfig) RemoteViews(android.widget.RemoteViews) NotificationCompat(androidx.core.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) OpenMode(com.amaze.filemanager.file_operations.filesystem.OpenMode)

Example 2 with OpenMode

use of com.amaze.filemanager.file_operations.filesystem.OpenMode 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)

Example 3 with OpenMode

use of com.amaze.filemanager.file_operations.filesystem.OpenMode in project AmazeFileManager by TeamAmaze.

the class LoadFilesListTask method doInBackground.

@Override
@Nullable
protected Pair<OpenMode, ArrayList<LayoutElementParcelable>> doInBackground(Void... p) {
    final MainFragment mainFragment = this.mainFragmentReference.get();
    final Context context = this.context.get();
    if (mainFragment == null || context == null || mainFragment.getMainFragmentViewModel() == null) {
        cancel(true);
        return null;
    }
    HybridFile hFile = null;
    if (OpenMode.UNKNOWN.equals(openmode) || OpenMode.CUSTOM.equals(openmode)) {
        hFile = new HybridFile(openmode, path);
        hFile.generateMode(mainFragment.getActivity());
        openmode = hFile.getMode();
        if (hFile.isSmb()) {
            mainFragment.getMainFragmentViewModel().setSmbPath(path);
        }
    }
    if (isCancelled())
        return null;
    mainFragment.getMainFragmentViewModel().setFolderCount(0);
    mainFragment.getMainFragmentViewModel().setFileCount(0);
    final ArrayList<LayoutElementParcelable> list;
    switch(openmode) {
        case SMB:
            if (hFile == null) {
                hFile = new HybridFile(OpenMode.SMB, path);
            }
            if (!hFile.getPath().endsWith("/")) {
                hFile.setPath(hFile.getPath() + "/");
            }
            try {
                SmbFile[] smbFile = hFile.getSmbFile(5000).listFiles();
                list = mainFragment.addToSmb(smbFile, path, showHiddenFiles);
                openmode = OpenMode.SMB;
            } catch (SmbAuthException e) {
                if (!e.getMessage().toLowerCase().contains("denied")) {
                    mainFragment.reauthenticateSmb();
                }
                e.printStackTrace();
                return null;
            } catch (SmbException | NullPointerException e) {
                Log.w(getClass().getSimpleName(), "Failed to load smb files for path: " + path, e);
                mainFragment.reauthenticateSmb();
                return null;
            }
            break;
        case SFTP:
            HybridFile sftpHFile = new HybridFile(OpenMode.SFTP, path);
            list = new ArrayList();
            sftpHFile.forEachChildrenFile(context, false, file -> {
                if (!(dataUtils.isFileHidden(file.getPath()) || file.isHidden() && !showHiddenFiles)) {
                    LayoutElementParcelable elem = createListParcelables(file);
                    if (elem != null) {
                        list.add(elem);
                    }
                }
            });
            break;
        case CUSTOM:
            switch(Integer.parseInt(path)) {
                case 0:
                    list = listImages();
                    break;
                case 1:
                    list = listVideos();
                    break;
                case 2:
                    list = listaudio();
                    break;
                case 3:
                    list = listDocs();
                    break;
                case 4:
                    list = listApks();
                    break;
                case 5:
                    list = listRecent();
                    break;
                case 6:
                    list = listRecentFiles();
                    break;
                default:
                    throw new IllegalStateException();
            }
            break;
        case OTG:
            list = new ArrayList<>();
            listOtg(path, file -> {
                LayoutElementParcelable elem = createListParcelables(file);
                if (elem != null)
                    list.add(elem);
            });
            openmode = OpenMode.OTG;
            break;
        case DOCUMENT_FILE:
            list = new ArrayList<>();
            listDocumentFiles(file -> {
                LayoutElementParcelable elem = createListParcelables(file);
                if (elem != null)
                    list.add(elem);
            });
            openmode = OpenMode.DOCUMENT_FILE;
            break;
        case DROPBOX:
        case BOX:
        case GDRIVE:
        case ONEDRIVE:
            CloudStorage cloudStorage = dataUtils.getAccount(openmode);
            list = new ArrayList<>();
            try {
                listCloud(path, cloudStorage, openmode, file -> {
                    LayoutElementParcelable elem = createListParcelables(file);
                    if (elem != null)
                        list.add(elem);
                });
            } catch (CloudPluginException e) {
                e.printStackTrace();
                AppConfig.toast(context, context.getResources().getString(R.string.failed_no_connection));
                return new Pair<>(openmode, list);
            }
            break;
        default:
            // we're neither in OTG not in SMB, load the list based on root/general filesystem
            list = new ArrayList<>();
            final OpenMode[] currentOpenMode = new OpenMode[1];
            ListFilesCommand.INSTANCE.listFiles(path, mainFragment.getMainActivity().isRootExplorer(), showHiddenFiles, mode -> {
                currentOpenMode[0] = mode;
                return null;
            }, hybridFileParcelable -> {
                LayoutElementParcelable elem = createListParcelables(hybridFileParcelable);
                if (elem != null)
                    list.add(elem);
                return null;
            });
            if (null != currentOpenMode[0]) {
                openmode = currentOpenMode[0];
            }
            break;
    }
    if (list != null && !(openmode == OpenMode.CUSTOM && ((path).equals("5") || (path).equals("6")))) {
        int t = SortHandler.getSortType(context, path);
        int sortby;
        int asc;
        if (t <= 3) {
            sortby = t;
            asc = 1;
        } else {
            asc = -1;
            sortby = t - 4;
        }
        MainFragmentViewModel viewModel = mainFragment.getMainFragmentViewModel();
        if (viewModel != null) {
            Collections.sort(list, new FileListSorter(viewModel.getDsort(), sortby, asc));
        } else {
            Log.e(TAG, "MainFragmentViewModel is null, this is a bug");
        }
    }
    return new Pair<>(openmode, list);
}
Also used : Context(android.content.Context) ArrayList(java.util.ArrayList) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) OpenMode(com.amaze.filemanager.file_operations.filesystem.OpenMode) SmbFile(jcifs.smb.SmbFile) SmbException(jcifs.smb.SmbException) CloudStorage(com.cloudrail.si.interfaces.CloudStorage) HybridFile(com.amaze.filemanager.filesystem.HybridFile) CloudPluginException(com.amaze.filemanager.file_operations.exceptions.CloudPluginException) MainFragment(com.amaze.filemanager.ui.fragments.MainFragment) SmbAuthException(jcifs.smb.SmbAuthException) MainFragmentViewModel(com.amaze.filemanager.ui.fragments.data.MainFragmentViewModel) FileListSorter(com.amaze.filemanager.filesystem.files.FileListSorter) Pair(androidx.core.util.Pair) Nullable(androidx.annotation.Nullable)

Example 4 with OpenMode

use of com.amaze.filemanager.file_operations.filesystem.OpenMode in project AmazeFileManager by TeamAmaze.

the class DecryptService method onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    baseFile = intent.getParcelableExtra(TAG_SOURCE);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    accentColor = ((AppConfig) getApplication()).getUtilsProvider().getColorPreference().getCurrentUserColorPreferences(this, sharedPreferences).getAccent();
    OpenMode openMode = OpenMode.values()[intent.getIntExtra(TAG_OPEN_MODE, OpenMode.UNKNOWN.ordinal())];
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Intent.ACTION_MAIN);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationIntent.putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    customSmallContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_small);
    customBigContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_big);
    Intent stopIntent = new Intent(TAG_BROADCAST_CRYPT_CANCEL);
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(context, 1234, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_folder_lock_open_white_36dp, getString(R.string.stop_ftp), stopPendingIntent);
    notificationBuilder = new NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID);
    notificationBuilder.setContentIntent(pendingIntent).setCustomContentView(customSmallContentViews).setCustomBigContentView(customBigContentViews).setCustomHeadsUpContentView(customSmallContentViews).setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action).setOngoing(true).setColor(accentColor);
    decryptPath = intent.getStringExtra(TAG_DECRYPT_PATH);
    notificationBuilder.setSmallIcon(R.drawable.ic_folder_lock_open_white_36dp);
    NotificationConstants.setMetadata(context, notificationBuilder, NotificationConstants.TYPE_NORMAL);
    startForeground(NotificationConstants.DECRYPT_ID, notificationBuilder.build());
    initNotificationViews();
    super.onStartCommand(intent, flags, startId);
    super.progressHalted();
    new DecryptService.BackgroundTask().execute();
    return START_NOT_STICKY;
}
Also used : AppConfig(com.amaze.filemanager.application.AppConfig) RemoteViews(android.widget.RemoteViews) NotificationCompat(androidx.core.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) OpenMode(com.amaze.filemanager.file_operations.filesystem.OpenMode)

Aggregations

OpenMode (com.amaze.filemanager.file_operations.filesystem.OpenMode)4 PendingIntent (android.app.PendingIntent)2 Intent (android.content.Intent)2 RemoteViews (android.widget.RemoteViews)2 NotificationCompat (androidx.core.app.NotificationCompat)2 AppConfig (com.amaze.filemanager.application.AppConfig)2 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)2 ArrayList (java.util.ArrayList)2 SmbFile (jcifs.smb.SmbFile)2 Context (android.content.Context)1 Uri (android.net.Uri)1 Nullable (androidx.annotation.Nullable)1 Pair (androidx.core.util.Pair)1 DocumentFile (androidx.documentfile.provider.DocumentFile)1 LayoutElementParcelable (com.amaze.filemanager.adapters.data.LayoutElementParcelable)1 NotAllowedException (com.amaze.filemanager.exceptions.NotAllowedException)1 OperationWouldOverwriteException (com.amaze.filemanager.exceptions.OperationWouldOverwriteException)1 CloudPluginException (com.amaze.filemanager.file_operations.exceptions.CloudPluginException)1 HybridFile (com.amaze.filemanager.filesystem.HybridFile)1 FileListSorter (com.amaze.filemanager.filesystem.files.FileListSorter)1