use of com.owncloud.android.operations.ChunkedUploadFileOperation in project android by owncloud.
the class FileUploader method onStartCommand.
/**
* Entry point to add one or several files to the queue of uploads.
* <p>
* New uploads are added calling to startService(), resulting in a call to
* this method. This ensures the service will keep on working although the
* caller activity goes away.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timber.d("Starting command with id %s", startId);
int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
boolean isCameraUploadFile = createdBy == CREATED_AS_CAMERA_UPLOAD_PICTURE || createdBy == CREATED_AS_CAMERA_UPLOAD_VIDEO;
boolean isAvailableOfflineFile = intent.getBooleanExtra(KEY_IS_AVAILABLE_OFFLINE_FILE, false);
boolean isRequestedFromWifiBackEvent = intent.getBooleanExtra(KEY_REQUESTED_FROM_WIFI_BACK_EVENT, false);
if ((isCameraUploadFile || isAvailableOfflineFile || isRequestedFromWifiBackEvent) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Timber.d("Starting FileUploader service in foreground");
if (isCameraUploadFile) {
mNotificationBuilder.setContentTitle(getString(R.string.uploader_upload_camera_upload_files));
} else if (isAvailableOfflineFile) {
mNotificationBuilder.setContentTitle(getString(R.string.uploader_upload_available_offline_files));
} else if (isRequestedFromWifiBackEvent) {
mNotificationBuilder.setContentTitle(getString(R.string.uploader_upload_requested_from_wifi_files));
}
/*
* After calling startForegroundService method from {@link TransferRequester} for camera uploads or
* available offline, we have to call this within five seconds after the service is created to avoid
* an error
*/
startForeground(141, mNotificationBuilder.build());
}
boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
AbstractList<String> requestedUploads = new Vector<>();
if (!intent.hasExtra(KEY_ACCOUNT)) {
Timber.e("Not enough information provided in intent");
return Service.START_NOT_STICKY;
}
Account account = intent.getParcelableExtra(KEY_ACCOUNT);
Timber.d("Account to upload the file to: %s", account);
if (account == null || !AccountUtils.exists(account.name, getApplicationContext())) {
return Service.START_NOT_STICKY;
}
if (!retry) {
if (!(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
Timber.e("Not enough information provided in intent");
return Service.START_NOT_STICKY;
}
String[] localPaths = null, remotePaths = null, mimeTypes = null;
OCFile[] files = null;
if (intent.hasExtra(KEY_FILE)) {
Parcelable[] files_temp = intent.getParcelableArrayExtra(KEY_FILE);
files = new OCFile[files_temp.length];
System.arraycopy(files_temp, 0, files, 0, files_temp.length);
} else {
localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
}
boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
if (intent.hasExtra(KEY_FILE) && files == null) {
Timber.e("Incorrect array for OCFiles provided in upload intent");
return Service.START_NOT_STICKY;
} else if (!intent.hasExtra(KEY_FILE)) {
if (localPaths == null) {
Timber.e("Incorrect array for local paths provided in upload intent");
return Service.START_NOT_STICKY;
}
if (remotePaths == null) {
Timber.e("Incorrect array for remote paths provided in upload intent");
return Service.START_NOT_STICKY;
}
if (localPaths.length != remotePaths.length) {
Timber.e("Different number of remote paths and local paths!");
return Service.START_NOT_STICKY;
}
files = new OCFile[localPaths.length];
for (int i = 0; i < localPaths.length; i++) {
files[i] = UploadFileOperation.obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i] : null), getApplicationContext());
if (files[i] == null) {
Timber.e("obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i] + " and localPaths[i]:" + localPaths[i]);
return Service.START_NOT_STICKY;
}
}
}
// at this point variable "OCFile[] files" is loaded correctly.
String uploadKey;
UploadFileOperation newUploadFileOperation;
try {
FileDataStorageManager storageManager = new FileDataStorageManager(getApplicationContext(), account, getContentResolver());
OCCapability capabilitiesForAccount = storageManager.getCapability(account.name);
boolean isChunkingAllowed = capabilitiesForAccount != null && capabilitiesForAccount.isChunkingAllowed();
Timber.d("Chunking is allowed: %s", isChunkingAllowed);
for (OCFile ocFile : files) {
OCUpload ocUpload = new OCUpload(ocFile, account);
ocUpload.setFileSize(ocFile.getFileLength());
ocUpload.setForceOverwrite(forceOverwrite);
ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
ocUpload.setCreatedBy(createdBy);
ocUpload.setLocalAction(localAction);
/*ocUpload.setUseWifiOnly(isUseWifiOnly);
ocUpload.setWhileChargingOnly(isWhileChargingOnly);*/
ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
if (new File(ocFile.getStoragePath()).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE && isChunkingAllowed) {
ocUpload.setTransferId(SecurityUtils.stringToMD5Hash(ocFile.getRemotePath()) + System.currentTimeMillis());
newUploadFileOperation = new ChunkedUploadFileOperation(account, ocFile, ocUpload, forceOverwrite, localAction, this);
} else {
newUploadFileOperation = new UploadFileOperation(account, ocFile, ocUpload, forceOverwrite, localAction, this);
}
newUploadFileOperation.setCreatedBy(createdBy);
if (isCreateRemoteFolder) {
newUploadFileOperation.setRemoteFolderToBeCreated();
}
newUploadFileOperation.addDatatransferProgressListener(this);
newUploadFileOperation.addDatatransferProgressListener((FileUploaderBinder) mBinder);
newUploadFileOperation.addRenameUploadListener(this);
Pair<String, String> putResult = mPendingUploads.putIfAbsent(account.name, ocFile.getRemotePath(), newUploadFileOperation);
if (putResult != null) {
uploadKey = putResult.first;
requestedUploads.add(uploadKey);
// Save upload in database
long id = mUploadsStorageManager.storeUpload(ocUpload);
newUploadFileOperation.setOCUploadId(id);
}
}
} catch (IllegalArgumentException e) {
Timber.e(e, "Not enough information provided in intent: %s", e.getMessage());
return START_NOT_STICKY;
} catch (IllegalStateException e) {
Timber.e(e, "Bad information provided in intent: %s", e.getMessage());
return START_NOT_STICKY;
} catch (Exception e) {
Timber.e(e, "Unexpected exception while processing upload intent");
return START_NOT_STICKY;
}
// *** TODO REWRITE: block inserted to request A retry; too many code copied, no control exception ***/
} else {
if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_RETRY_UPLOAD)) {
Timber.e("Not enough information provided in intent: no KEY_RETRY_UPLOAD_KEY");
return START_NOT_STICKY;
}
OCUpload upload = intent.getParcelableExtra(KEY_RETRY_UPLOAD);
UploadFileOperation newUploadFileOperation;
if (upload.getFileSize() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
upload.setTransferId(SecurityUtils.stringToMD5Hash(upload.getRemotePath()) + System.currentTimeMillis());
newUploadFileOperation = new ChunkedUploadFileOperation(account, null, upload, upload.isForceOverwrite(), upload.getLocalAction(), this);
} else {
newUploadFileOperation = new UploadFileOperation(account, null, upload, upload.isForceOverwrite(), upload.getLocalAction(), this);
}
newUploadFileOperation.addDatatransferProgressListener(this);
newUploadFileOperation.addDatatransferProgressListener((FileUploaderBinder) mBinder);
newUploadFileOperation.addRenameUploadListener(this);
Pair<String, String> putResult = mPendingUploads.putIfAbsent(account.name, upload.getRemotePath(), newUploadFileOperation);
if (putResult != null) {
String uploadKey = putResult.first;
requestedUploads.add(uploadKey);
// Update upload in database
upload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
mUploadsStorageManager.updateUpload(upload);
}
}
if (requestedUploads.size() > 0) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = requestedUploads;
mServiceHandler.sendMessage(msg);
sendBroadcastUploadsAdded();
}
return Service.START_NOT_STICKY;
}
use of com.owncloud.android.operations.ChunkedUploadFileOperation in project android by owncloud.
the class FileUploader method notifyUploadResult.
/**
* Updates the status notification with the result of an upload operation.
*
* @param uploadResult Result of the upload operation.
* @param upload Finished upload operation
*/
private void notifyUploadResult(UploadFileOperation upload, RemoteOperationResult uploadResult) {
Timber.d("NotifyUploadResult with resultCode: %s", uploadResult.getCode());
// / cancelled operation or success -> silent removal of progress notification
getNotificationManager().cancel(R.string.uploader_upload_in_progress_ticker);
if (uploadResult.isCancelled() && upload instanceof ChunkedUploadFileOperation) {
removeChunksFolder(upload.getOCUploadId());
}
if (!uploadResult.isCancelled() && !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_WIFI)) {
// Show the result: success or fail notification
int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker : R.string.uploader_upload_failed_ticker;
String content;
// check credentials error
boolean needsToUpdateCredentials = (ResultCode.UNAUTHORIZED.equals(uploadResult.getCode()));
tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId;
mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId)).setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);
content = ErrorMessageAdapter.Companion.getResultMessage(uploadResult, upload, getResources());
if (needsToUpdateCredentials) {
// let the user update credentials with one click
PendingIntent pendingIntentToRefreshCredentials = NotificationUtils.INSTANCE.composePendingIntentToRefreshCredentials(this, upload.getAccount());
mNotificationBuilder.setContentIntent(pendingIntentToRefreshCredentials);
} else {
mNotificationBuilder.setContentText(content);
}
if (!uploadResult.isSuccess() && !needsToUpdateCredentials) {
// in case of failure, do not show details file view (because there is no file!)
Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(), showUploadListIntent, 0));
}
mNotificationBuilder.setContentText(content);
getNotificationManager().notify(tickerId, mNotificationBuilder.build());
if (uploadResult.isSuccess()) {
mPendingUploads.remove(upload.getAccount().name, upload.getFile().getRemotePath());
// remove success notification, with a delay of 2 seconds
NotificationUtils.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker, 2000);
}
}
}
Aggregations