undispatched =
mUndispatchedFinishedOperations.remove(operationId);
if (undispatched != null) {
listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
return true;
} else {
return !mServiceHandler.mPendingOperations.isEmpty();
}
}
/**
* Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to
* download.
*
* If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to
* download.
*
* @param user user where the remote file is stored.
* @param file File to check if something is synchronizing / downloading / uploading inside.
*/
public boolean isSynchronizing(User user, OCFile file) {
return mSyncFolderHandler.isSynchronizing(user, file.getRemotePath());
}
}
/**
* Operations worker. Performs the pending operations in the order they were requested.
*
* Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
*/
private static class ServiceHandler extends Handler {
// don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
OperationsService mService;
private ConcurrentLinkedQueue> mPendingOperations =
new ConcurrentLinkedQueue<>();
private RemoteOperation mCurrentOperation;
private Target mLastTarget;
private OwnCloudClient mOwnCloudClient;
public ServiceHandler(Looper looper, OperationsService service) {
super(looper);
if (service == null) {
throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
}
mService = service;
}
@Override
public void handleMessage(Message msg) {
nextOperation();
Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
mService.stopSelf(msg.arg1);
}
/**
* Performs the next operation in the queue
*/
private void nextOperation() {
//Log_OC.e(TAG, "nextOperation init" );
Pair next;
synchronized (mPendingOperations) {
next = mPendingOperations.peek();
}
if (next != null) {
mCurrentOperation = next.second;
RemoteOperationResult result;
try {
/// prepare client object to send the request to the ownCloud server
if (mLastTarget == null || !mLastTarget.equals(next.first)) {
mLastTarget = next.first;
OwnCloudAccount ocAccount;
if (mLastTarget.mAccount != null) {
ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
} else {
ocAccount = new OwnCloudAccount(mLastTarget.mServerUrl, null);
}
mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, mService);
}
/// perform the operation
result = mCurrentOperation.execute(mOwnCloudClient);
} catch (AccountsException e) {
if (mLastTarget.mAccount == null) {
Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
e);
} else {
Log_OC.e(TAG, "Error while trying to get authorization for " +
mLastTarget.mAccount.name, e);
}
result = new RemoteOperationResult(e);
} catch (IOException e) {
if (mLastTarget.mAccount == null) {
Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
e);
} else {
Log_OC.e(TAG, "Error while trying to get authorization for " +
mLastTarget.mAccount.name, e);
}
result = new RemoteOperationResult(e);
} catch (Exception e) {
if (mLastTarget.mAccount == null) {
Log_OC.e(TAG, "Unexpected error for a NULL account", e);
} else {
Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
}
result = new RemoteOperationResult(e);
} finally {
synchronized (mPendingOperations) {
mPendingOperations.poll();
}
}
//sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
mService.dispatchResultToOperationListeners(mCurrentOperation, result);
}
}
}
/**
* Creates a new operation, as described by operationIntent.
*
* TODO - move to ServiceHandler (probably)
*
* @param operationIntent Intent describing a new operation to queue and execute.
* @return Pair with the new operation object and the information about its target server.
*/
private Pair newOperation(Intent operationIntent) {
RemoteOperation operation = null;
Target target = null;
try {
if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
!operationIntent.hasExtra(EXTRA_SERVER_URL)) {
Log_OC.e(TAG, "Not enough information provided in intent");
} else {
Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
User user = toUser(account);
String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl));
String action = operationIntent.getAction();
String remotePath;
String password;
ShareType shareType;
String newParentPath;
long shareId;
FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user,
getContentResolver());
switch (action) {
case ACTION_CREATE_SHARE_VIA_LINK:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
if (!TextUtils.isEmpty(remotePath)) {
operation = new CreateShareViaLinkOperation(remotePath, password, fileDataStorageManager);
}
break;
case ACTION_UPDATE_PUBLIC_SHARE:
shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
if (shareId > 0) {
UpdateShareViaLinkOperation updateLinkOperation =
new UpdateShareViaLinkOperation(shareId, fileDataStorageManager);
password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
updateLinkOperation.setPassword(password);
long expirationDate = operationIntent.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0);
updateLinkOperation.setExpirationDateInMillis(expirationDate);
boolean hideFileDownload = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD,
false);
updateLinkOperation.setHideFileDownload(hideFileDownload);
// if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_UPLOAD)) {
// updateLinkOperation.setPublicUpload(true);
// }
if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
updateLinkOperation.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
}
operation = updateLinkOperation;
}
break;
case ACTION_UPDATE_USER_SHARE:
shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
if (shareId > 0) {
UpdateSharePermissionsOperation updateShare =
new UpdateSharePermissionsOperation(shareId, fileDataStorageManager);
int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
updateShare.setPermissions(permissions);
long expirationDateInMillis = operationIntent
.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
updateShare.setExpirationDateInMillis(expirationDateInMillis);
password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
updateShare.setPassword(password);
operation = updateShare;
}
break;
case ACTION_UPDATE_SHARE_NOTE:
shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
String note = operationIntent.getStringExtra(EXTRA_SHARE_NOTE);
if (shareId > 0) {
operation = new UpdateNoteForShareOperation(shareId, note, fileDataStorageManager);
}
break;
case ACTION_CREATE_SHARE_WITH_SHAREE:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
String shareeName = operationIntent.getStringExtra(EXTRA_SHARE_WITH);
shareType = (ShareType) operationIntent.getSerializableExtra(EXTRA_SHARE_TYPE);
int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
String noteMessage = operationIntent.getStringExtra(EXTRA_SHARE_NOTE);
String sharePassword = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
long expirationDateInMillis = operationIntent
.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
boolean hideFileDownload = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD,
false);
if (!TextUtils.isEmpty(remotePath)) {
CreateShareWithShareeOperation createShareWithShareeOperation =
new CreateShareWithShareeOperation(remotePath,
shareeName,
shareType,
permissions,
noteMessage,
sharePassword,
expirationDateInMillis,
hideFileDownload,
fileDataStorageManager);
if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
createShareWithShareeOperation.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
}
operation = createShareWithShareeOperation;
}
break;
case ACTION_UPDATE_SHARE_INFO:
shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
if (shareId > 0) {
UpdateShareInfoOperation updateShare = new UpdateShareInfoOperation(shareId,
fileDataStorageManager);
int permissionsToChange = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1);
updateShare.setPermissions(permissionsToChange);
long expirationDateInMills = operationIntent
.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0L);
updateShare.setExpirationDateInMillis(expirationDateInMills);
password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD);
updateShare.setPassword(password);
boolean fileDownloadHide = operationIntent.getBooleanExtra(EXTRA_SHARE_HIDE_FILE_DOWNLOAD
, false);
updateShare.setHideFileDownload(fileDownloadHide);
if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_LABEL)) {
updateShare.setLabel(operationIntent.getStringExtra(EXTRA_SHARE_PUBLIC_LABEL));
}
operation = updateShare;
}
break;
case ACTION_UNSHARE:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1);
if (shareId > 0) {
operation = new UnshareOperation(remotePath, shareId, fileDataStorageManager);
}
break;
case ACTION_GET_SERVER_INFO:
operation = new GetServerInfoOperation(serverUrl, this);
break;
case ACTION_GET_USER_NAME:
operation = new GetUserInfoRemoteOperation();
break;
case ACTION_RENAME:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
operation = new RenameFileOperation(remotePath, newName, fileDataStorageManager, getApplicationContext());
break;
case ACTION_REMOVE:
// Remove file or folder
OCFile file = operationIntent.getParcelableExtra(EXTRA_FILE);
boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
boolean inBackground = operationIntent.getBooleanExtra(EXTRA_IN_BACKGROUND, false);
operation = new RemoveFileOperation(file,
onlyLocalCopy,
account,
inBackground,
getApplicationContext(),
fileDataStorageManager);
break;
case ACTION_CREATE_FOLDER:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
operation = new CreateFolderOperation(remotePath,
user,
getApplicationContext(),
fileDataStorageManager);
break;
case ACTION_SYNC_FILE:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
operation = new SynchronizeFileOperation(remotePath,
user,
syncFileContents,
getApplicationContext(),
fileDataStorageManager);
break;
case ACTION_SYNC_FOLDER:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
operation = new SynchronizeFolderOperation(
this, // TODO remove this dependency from construction time
remotePath,
user,
System.currentTimeMillis(), // TODO remove this dependency from construction time
fileDataStorageManager
);
break;
case ACTION_MOVE_FILE:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
operation = new MoveFileOperation(remotePath, newParentPath, fileDataStorageManager);
break;
case ACTION_COPY_FILE:
remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
operation = new CopyFileOperation(remotePath, newParentPath, fileDataStorageManager);
break;
case ACTION_CHECK_CURRENT_CREDENTIALS:
operation = new CheckCurrentCredentialsOperation(user, fileDataStorageManager);
break;
case ACTION_RESTORE_VERSION:
FileVersion fileVersion = operationIntent.getParcelableExtra(EXTRA_FILE_VERSION);
operation = new RestoreFileVersionRemoteOperation(fileVersion.getRemoteId(),
fileVersion.getFileName());
break;
default:
// do nothing
break;
}
}
} catch (IllegalArgumentException e) {
Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
operation = null;
}
if (operation != null) {
return new Pair<>(target, operation);
} else {
return null;
}
}
/**
* This is a temporary compatibility helper to convert legacy {@link Account} instance to new {@link User} model.
*
* @param account Account instance
* @return User model that corresponds to Account
*/
@NonNull
private User toUser(@Nullable Account account) {
String accountName = account != null ? account.name : "";
Optional optionalUser = accountManager.getUser(accountName);
if (optionalUser.isPresent()) {
return optionalUser.get();
} else {
return accountManager.getAnonymousUser();
}
}
/**
* Notifies the currently subscribed listeners about the end of an operation.
*
* @param operation Finished operation.
* @param result Result of the operation.
*/
protected void dispatchResultToOperationListeners(
final RemoteOperation operation, final RemoteOperationResult result
) {
int count = 0;
Iterator listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
while (listeners.hasNext()) {
final OnRemoteOperationListener listener = listeners.next();
final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
if (handler != null) {
handler.post(() -> listener.onRemoteOperationFinish(operation, result));
count += 1;
}
}
if (count == 0) {
Pair undispatched = new Pair<>(operation, result);
mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
}
Log_OC.d(TAG, "Called " + count + " listeners");
}
}