Search in sources :

Example 36 with DocumentFile

use of androidx.documentfile.provider.DocumentFile in project Signal-Android by signalapp.

the class LocalBackupJobApi29 method onRun.

@Override
public void onRun() throws IOException {
    Log.i(TAG, "Executing backup job...");
    BackupFileIOError.clearNotification(context);
    if (!BackupUtil.isUserSelectionRequired(context)) {
        throw new IOException("Wrong backup job!");
    }
    Uri backupDirectoryUri = SignalStore.settings().getSignalBackupDirectory();
    if (backupDirectoryUri == null || backupDirectoryUri.getPath() == null) {
        throw new IOException("Backup Directory has not been selected!");
    }
    ProgressUpdater updater = new ProgressUpdater();
    try (NotificationController notification = GenericForegroundService.startForegroundTask(context, context.getString(R.string.LocalBackupJob_creating_signal_backup), NotificationChannels.BACKUPS, R.drawable.ic_signal_backup)) {
        updater.setNotification(notification);
        EventBus.getDefault().register(updater);
        notification.setIndeterminateProgress();
        String backupPassword = BackupPassphrase.get(context);
        DocumentFile backupDirectory = DocumentFile.fromTreeUri(context, backupDirectoryUri);
        String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US).format(new Date());
        String fileName = String.format("signal-%s.backup", timestamp);
        if (backupDirectory == null || !backupDirectory.canWrite()) {
            BackupFileIOError.ACCESS_ERROR.postNotification(context);
            throw new IOException("Cannot write to backup directory location.");
        }
        deleteOldTemporaryBackups(backupDirectory);
        if (backupDirectory.findFile(fileName) != null) {
            throw new IOException("Backup file already exists!");
        }
        String temporaryName = String.format(Locale.US, "%s%s%s", TEMP_BACKUP_FILE_PREFIX, UUID.randomUUID(), TEMP_BACKUP_FILE_SUFFIX);
        DocumentFile temporaryFile = backupDirectory.createFile("application/octet-stream", temporaryName);
        if (temporaryFile == null) {
            throw new IOException("Failed to create temporary backup file.");
        }
        if (backupPassword == null) {
            throw new IOException("Backup password is null");
        }
        try {
            FullBackupExporter.export(context, AttachmentSecretProvider.getInstance(context).getOrCreateAttachmentSecret(), SignalDatabase.getBackupDatabase(), temporaryFile, backupPassword, this::isCanceled);
            if (!temporaryFile.renameTo(fileName)) {
                Log.w(TAG, "Failed to rename temp file");
                throw new IOException("Renaming temporary backup file failed!");
            }
        } catch (FullBackupExporter.BackupCanceledException e) {
            Log.w(TAG, "Backup cancelled");
            throw e;
        } catch (IOException e) {
            Log.w(TAG, "Error during backup!", e);
            BackupFileIOError.postNotificationForException(context, e, getRunAttempt());
            throw e;
        } finally {
            DocumentFile fileToCleanUp = backupDirectory.findFile(temporaryName);
            if (fileToCleanUp != null) {
                if (fileToCleanUp.delete()) {
                    Log.w(TAG, "Backup failed. Deleted temp file");
                } else {
                    Log.w(TAG, "Backup failed. Failed to delete temp file " + temporaryName);
                }
            }
        }
        BackupUtil.deleteOldBackups();
    } finally {
        EventBus.getDefault().unregister(updater);
        updater.setNotification(null);
    }
}
Also used : DocumentFile(androidx.documentfile.provider.DocumentFile) IOException(java.io.IOException) Uri(android.net.Uri) SimpleDateFormat(java.text.SimpleDateFormat) NotificationController(org.thoughtcrime.securesms.service.NotificationController) Date(java.util.Date) FullBackupExporter(org.thoughtcrime.securesms.backup.FullBackupExporter)

Example 37 with DocumentFile

use of androidx.documentfile.provider.DocumentFile in project fdroidclient by f-droid.

the class TreeUriScannerIntentService method onHandleIntent.

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {
        return;
    }
    Uri treeUri = intent.getData();
    if (treeUri == null) {
        return;
    }
    Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
    DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);
    searchDirectory(treeFile);
}
Also used : DocumentFile(androidx.documentfile.provider.DocumentFile) Uri(android.net.Uri)

Example 38 with DocumentFile

use of androidx.documentfile.provider.DocumentFile in project fdroidclient by f-droid.

the class TreeUriScannerIntentService method searchDirectory.

/**
 * Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting
 * from the given directory, looking at files first before recursing into
 * directories.  This is "depth last" since the index file is much more
 * likely to be shallow than deep, and there can be a lot of files to
 * search through starting at 4 or more levels deep, like the fdroid
 * icons dirs and the per-app "external storage" dirs.
 */
private void searchDirectory(DocumentFile documentFileDir) {
    DocumentFile[] documentFiles = documentFileDir.listFiles();
    if (documentFiles == null) {
        return;
    }
    boolean foundIndex = false;
    ArrayList<DocumentFile> dirs = new ArrayList<>();
    for (DocumentFile documentFile : documentFiles) {
        if (documentFile.isDirectory()) {
            dirs.add(documentFile);
        } else if (!foundIndex) {
            if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {
                registerRepo(documentFile);
                foundIndex = true;
            }
        }
    }
    for (DocumentFile dir : dirs) {
        searchDirectory(dir);
    }
}
Also used : DocumentFile(androidx.documentfile.provider.DocumentFile) ArrayList(java.util.ArrayList)

Example 39 with DocumentFile

use of androidx.documentfile.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class ReadFileTask method doInBackground.

@Override
protected ReturnedValues doInBackground(Void... params) {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        InputStream inputStream = null;
        switch(fileAbstraction.scheme) {
            case CONTENT:
                if (fileAbstraction.uri == null)
                    throw new NullPointerException("Something went really wrong!");
                if (fileAbstraction.uri.getAuthority().equals(AppConfig.getInstance().getPackageName())) {
                    DocumentFile documentFile = DocumentFile.fromSingleUri(AppConfig.getInstance(), fileAbstraction.uri);
                    if (documentFile != null && documentFile.exists() && documentFile.canWrite())
                        inputStream = contentResolver.openInputStream(documentFile.getUri());
                    else
                        inputStream = loadFile(FileUtils.fromContentUri(fileAbstraction.uri));
                } else {
                    inputStream = contentResolver.openInputStream(fileAbstraction.uri);
                }
                break;
            case FILE:
                final HybridFileParcelable hybridFileParcelable = fileAbstraction.hybridFileParcelable;
                if (hybridFileParcelable == null)
                    throw new NullPointerException("Something went really wrong!");
                File file = hybridFileParcelable.getFile();
                inputStream = loadFile(file);
                break;
            default:
                throw new IllegalArgumentException("The scheme for '" + fileAbstraction.scheme + "' cannot be processed!");
        }
        if (inputStream == null)
            throw new StreamNotFoundException();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String buffer;
        while ((buffer = bufferedReader.readLine()) != null) {
            stringBuilder.append(buffer).append("\n");
        }
        inputStream.close();
        bufferedReader.close();
    } catch (StreamNotFoundException e) {
        e.printStackTrace();
        return new ReturnedValues(EXCEPTION_STREAM_NOT_FOUND);
    } catch (IOException e) {
        e.printStackTrace();
        return new ReturnedValues(EXCEPTION_IO);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return new ReturnedValues(EXCEPTION_OOM);
    }
    return new ReturnedValues(stringBuilder.toString(), cachedFile);
}
Also used : DocumentFile(androidx.documentfile.provider.DocumentFile) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) BufferedReader(java.io.BufferedReader) StreamNotFoundException(com.amaze.filemanager.file_operations.exceptions.StreamNotFoundException) File(java.io.File) DocumentFile(androidx.documentfile.provider.DocumentFile)

Example 40 with DocumentFile

use of androidx.documentfile.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class HybridFile method getTotal.

/**
 * Gets total size of the disk
 */
public long getTotal(Context context) {
    long size = 0l;
    switch(mode) {
        case SMB:
            // TODO: Find total storage space of SMB when JCIFS adds support
            try {
                SmbFile smbFile = getSmbFile();
                size = smbFile != null ? smbFile.getDiskFreeSpace() : 0L;
            } catch (SmbException e) {
                e.printStackTrace();
            }
            break;
        case FILE:
        case ROOT:
            size = getFile().getTotalSpace();
            break;
        case DROPBOX:
        case BOX:
        case ONEDRIVE:
        case GDRIVE:
            SpaceAllocation spaceAllocation = dataUtils.getAccount(mode).getAllocation();
            size = spaceAllocation.getTotal();
            break;
        case SFTP:
            final Long returnValue = SshClientUtils.<Long>execute(new SFtpClientTemplate<Long>(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.diskSize();
                    } 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;
                    }
                }
            });
            if (returnValue == null) {
                Log.e(TAG, "Error obtaining total space over SFTP");
            }
            size = returnValue == null ? 0L : returnValue;
            break;
        case OTG:
            // TODO: Find total storage space of OTG when {@link DocumentFile} API adds support
            DocumentFile documentFile = OTGUtil.getDocumentFile(path, context, false);
            size = documentFile.length();
            break;
        case DOCUMENT_FILE:
            size = getDocumentFile(false).length();
            break;
    }
    return size;
}
Also used : DocumentFile(androidx.documentfile.provider.DocumentFile) SFTPClient(net.schmizz.sshj.sftp.SFTPClient) IOException(java.io.IOException) Statvfs(com.amaze.filemanager.filesystem.ssh.Statvfs) SFTPException(net.schmizz.sshj.sftp.SFTPException) SmbFile(jcifs.smb.SmbFile) SmbException(jcifs.smb.SmbException) SpaceAllocation(com.cloudrail.si.types.SpaceAllocation) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Aggregations

DocumentFile (androidx.documentfile.provider.DocumentFile)45 IOException (java.io.IOException)18 Uri (android.net.Uri)14 AssetsDocumentFile (androidx.documentfile.provider.AssetsDocumentFile)10 OutputStream (java.io.OutputStream)10 File (java.io.File)9 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)8 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)7 SFTPClient (net.schmizz.sshj.sftp.SFTPClient)7 OpenMode (com.amaze.filemanager.file_operations.filesystem.OpenMode)6 InputStream (java.io.InputStream)6 Intent (android.content.Intent)5 NonNull (androidx.annotation.NonNull)5 ShellNotRunningException (com.amaze.filemanager.file_operations.exceptions.ShellNotRunningException)5 SFtpClientTemplate (com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate)5 DataUtils (com.amaze.filemanager.utils.DataUtils)5 SmbFile (jcifs.smb.SmbFile)5 ContentResolver (android.content.ContentResolver)4 Context (android.content.Context)4