Search in sources :

Example 46 with OCUpload

use of com.owncloud.android.db.OCUpload in project android by nextcloud.

the class UploadsStorageManager method updateUploadInternal.

private int updateUploadInternal(Cursor c, UploadStatus status, UploadResult result, String remotePath, String localPath) {
    int r = 0;
    while (c.moveToNext()) {
        // read upload object and update
        OCUpload upload = createOCUploadFromCursor(c);
        String path = c.getString(c.getColumnIndexOrThrow(ProviderTableMeta.UPLOADS_LOCAL_PATH));
        Log_OC.v(TAG, "Updating " + path + " with status:" + status + " and result:" + (result == null ? "null" : result.toString()) + " (old:" + upload.toFormattedString() + ")");
        upload.setUploadStatus(status);
        upload.setLastResult(result);
        upload.setRemotePath(remotePath);
        if (localPath != null) {
            upload.setLocalPath(localPath);
        }
        if (status == UploadStatus.UPLOAD_SUCCEEDED) {
            upload.setUploadEndTimestamp(Calendar.getInstance().getTimeInMillis());
        }
        // store update upload object to db
        r = updateUpload(upload);
    }
    return r;
}
Also used : OCUpload(com.owncloud.android.db.OCUpload)

Example 47 with OCUpload

use of com.owncloud.android.db.OCUpload in project android by nextcloud.

the class UploadListAdapter method onBindHeaderViewHolder.

@Override
public void onBindHeaderViewHolder(SectionedViewHolder holder, int section, boolean expanded) {
    HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
    UploadGroup group = uploadGroups[section];
    headerViewHolder.binding.uploadListTitle.setText(String.format(parentActivity.getString(R.string.uploads_view_group_header), group.getGroupName(), group.getGroupItemCount()));
    headerViewHolder.binding.uploadListTitle.setTextColor(ThemeColorUtils.primaryAccentColor(parentActivity));
    headerViewHolder.binding.uploadListTitle.setOnClickListener(v -> toggleSectionExpanded(section));
    switch(group.type) {
        case CURRENT:
        case FINISHED:
            headerViewHolder.binding.uploadListAction.setImageResource(R.drawable.ic_close);
            break;
        case FAILED:
            headerViewHolder.binding.uploadListAction.setImageResource(R.drawable.ic_sync);
            break;
    }
    headerViewHolder.binding.uploadListAction.setOnClickListener(v -> {
        switch(group.type) {
            case CURRENT:
                FileUploader.FileUploaderBinder uploaderBinder = parentActivity.getFileUploaderBinder();
                if (uploaderBinder != null) {
                    for (OCUpload upload : group.getItems()) {
                        uploaderBinder.cancel(upload);
                    }
                }
                break;
            case FINISHED:
                uploadsStorageManager.clearSuccessfulUploads();
                break;
            case FAILED:
                new Thread(() -> FileUploader.retryFailedUploads(parentActivity, uploadsStorageManager, connectivityService, accountManager, powerManagementService)).start();
                break;
            default:
                // do nothing
                break;
        }
        loadUploadItemsFromDb();
    });
}
Also used : OCUpload(com.owncloud.android.db.OCUpload) FileUploader(com.owncloud.android.files.services.FileUploader)

Example 48 with OCUpload

use of com.owncloud.android.db.OCUpload in project android by nextcloud.

the class FilesSyncHelper method restartJobsIfNeeded.

public static void restartJobsIfNeeded(final UploadsStorageManager uploadsStorageManager, final UserAccountManager accountManager, final ConnectivityService connectivityService, final PowerManagementService powerManagementService) {
    final Context context = MainApp.getAppContext();
    boolean accountExists;
    boolean whileChargingOnly = true;
    boolean useWifiOnly = true;
    OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
    for (OCUpload failedUpload : failedUploads) {
        accountExists = false;
        if (!failedUpload.isWhileChargingOnly()) {
            whileChargingOnly = false;
        }
        if (!failedUpload.isUseWifiOnly()) {
            useWifiOnly = false;
        }
        // check if accounts still exists
        for (Account account : accountManager.getAccounts()) {
            if (account.name.equals(failedUpload.getAccountName())) {
                accountExists = true;
                break;
            }
        }
        if (!accountExists) {
            uploadsStorageManager.removeUpload(failedUpload);
        }
    }
    failedUploads = uploadsStorageManager.getFailedUploads();
    if (failedUploads.length == 0) {
        // nothing to do
        return;
    }
    if (whileChargingOnly) {
        final BatteryStatus batteryStatus = powerManagementService.getBattery();
        final boolean charging = batteryStatus.isCharging() || batteryStatus.isFull();
        if (!charging) {
            // all uploads requires charging
            return;
        }
    }
    if (useWifiOnly && !connectivityService.getConnectivity().isWifi()) {
        // all uploads requires wifi
        return;
    }
    new Thread(() -> {
        if (connectivityService.getConnectivity().isConnected() && !connectivityService.isInternetWalled()) {
            FileUploader.retryFailedUploads(context, uploadsStorageManager, connectivityService, accountManager, powerManagementService);
        }
    }).start();
}
Also used : Context(android.content.Context) Account(android.accounts.Account) OCUpload(com.owncloud.android.db.OCUpload) BatteryStatus(com.nextcloud.client.device.BatteryStatus)

Example 49 with OCUpload

use of com.owncloud.android.db.OCUpload in project android by nextcloud.

the class UploadFileOperation method normalUpload.

private RemoteOperationResult normalUpload(OwnCloudClient client) {
    RemoteOperationResult result = null;
    File temporalFile = null;
    File originalFile = new File(mOriginalStoragePath);
    File expectedFile = null;
    FileLock fileLock = null;
    long size;
    try {
        // check conditions
        result = checkConditions(originalFile);
        if (result != null) {
            return result;
        }
        // check name collision
        RemoteOperationResult collisionResult = checkNameCollision(client, null, false);
        if (collisionResult != null) {
            result = collisionResult;
            return collisionResult;
        }
        String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
        expectedFile = new File(expectedPath);
        result = copyFile(originalFile, expectedPath);
        if (!result.isSuccess()) {
            return result;
        }
        // Get the last modification date of the file from the file system
        String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
        final Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
        FileChannel channel = null;
        try {
            channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
            fileLock = channel.tryLock();
        } catch (FileNotFoundException e) {
            // this basically means that the file is on SD card
            // try to copy file to temporary dir if it doesn't exist
            String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) + mFile.getRemotePath();
            mFile.setStoragePath(temporalPath);
            temporalFile = new File(temporalPath);
            Files.deleteIfExists(Paths.get(temporalPath));
            result = copy(originalFile, temporalFile);
            if (result.isSuccess()) {
                if (temporalFile.length() == originalFile.length()) {
                    channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
                    fileLock = channel.tryLock();
                } else {
                    result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
                }
            }
        }
        try {
            size = channel.size();
        } catch (Exception e1) {
            size = new File(mFile.getStoragePath()).length();
        }
        for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
            if (ocUpload.getUploadId() == getOCUploadId()) {
                ocUpload.setFileSize(size);
                uploadsStorageManager.updateUpload(ocUpload);
                break;
            }
        }
        // perform the upload
        if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
            boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
            mUploadOperation = new ChunkedFileUploadRemoteOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, onWifiConnection, mDisableRetries);
        } else {
            mUploadOperation = new UploadFileRemoteOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, mDisableRetries);
        }
        for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
            mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        if (result.isSuccess() && mUploadOperation != null) {
            result = mUploadOperation.execute(client);
            // location in the Nextcloud local folder
            if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
                result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
            }
        }
    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
        result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
    } catch (OverlappingFileLockException e) {
        Log_OC.d(TAG, "Overlapping file lock exception");
        result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        mUploadStarted.set(false);
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (IOException e) {
                Log_OC.e(TAG, "Failed to unlock file with path " + mOriginalStoragePath);
            }
        }
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        logResult(result, mOriginalStoragePath, mRemotePath);
    }
    if (result.isSuccess()) {
        handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
    } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
        getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
    }
    // delete temporal file
    if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
        Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
    }
    return result;
}
Also used : OnDatatransferProgressListener(com.owncloud.android.lib.common.network.OnDatatransferProgressListener) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileChannel(java.nio.channels.FileChannel) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileNotFoundException(java.io.FileNotFoundException) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) IOException(java.io.IOException) ChunkedFileUploadRemoteOperation(com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation) OCUpload(com.owncloud.android.db.OCUpload) RandomAccessFile(java.io.RandomAccessFile) UploadFileRemoteOperation(com.owncloud.android.lib.resources.files.UploadFileRemoteOperation) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Aggregations

OCUpload (com.owncloud.android.db.OCUpload)49 Test (org.junit.Test)29 OCFile (com.owncloud.android.datamodel.OCFile)22 File (java.io.File)15 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)8 UploadFileOperation (com.owncloud.android.operations.UploadFileOperation)8 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)7 Intent (android.content.Intent)6 SmallTest (androidx.test.filters.SmallTest)5 ScreenshotTest (com.owncloud.android.utils.ScreenshotTest)4 Account (android.accounts.Account)3 Context (android.content.Context)3 Cursor (android.database.Cursor)3 DialogFragment (androidx.fragment.app.DialogFragment)3 BatteryStatus (com.nextcloud.client.device.BatteryStatus)3 Connectivity (com.nextcloud.client.network.Connectivity)3 ConnectivityService (com.nextcloud.client.network.ConnectivityService)3 RemoteFile (com.owncloud.android.lib.resources.files.model.RemoteFile)3 RandomAccessFile (java.io.RandomAccessFile)3 SuppressLint (android.annotation.SuppressLint)2