123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733 |
- package com.owncloud.android.services;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentLinkedQueue;
- import java.util.concurrent.ConcurrentMap;
- import com.owncloud.android.MainApp;
- import com.owncloud.android.R;
- import com.owncloud.android.datamodel.FileDataStorageManager;
- import com.owncloud.android.datamodel.OCFile;
- import com.owncloud.android.lib.common.OwnCloudAccount;
- import com.owncloud.android.lib.common.OwnCloudClient;
- import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
- import com.owncloud.android.lib.common.OwnCloudCredentials;
- import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
- import com.owncloud.android.lib.common.accounts.AccountUtils;
- import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
- import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
- import com.owncloud.android.lib.common.operations.RemoteOperation;
- import com.owncloud.android.lib.common.operations.RemoteOperationResult;
- import com.owncloud.android.lib.common.utils.Log_OC;
- import com.owncloud.android.lib.resources.shares.ShareType;
- import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
- import com.owncloud.android.operations.common.SyncOperation;
- import com.owncloud.android.operations.CreateFolderOperation;
- import com.owncloud.android.operations.CreateShareOperation;
- import com.owncloud.android.operations.GetServerInfoOperation;
- import com.owncloud.android.operations.MoveFileOperation;
- import com.owncloud.android.operations.OAuth2GetAccessToken;
- import com.owncloud.android.operations.RemoveFileOperation;
- import com.owncloud.android.operations.RenameFileOperation;
- import com.owncloud.android.operations.SynchronizeFileOperation;
- import com.owncloud.android.operations.SynchronizeFolderOperation;
- import com.owncloud.android.operations.UnshareLinkOperation;
- import android.accounts.Account;
- import android.accounts.AccountManager;
- import android.accounts.AccountsException;
- import android.accounts.AuthenticatorException;
- import android.accounts.OperationCanceledException;
- import android.app.Service;
- import android.content.Intent;
- import android.net.Uri;
- import android.os.Binder;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.os.IBinder;
- import android.os.Looper;
- import android.os.Message;
- import android.os.Process;
- import android.util.Pair;
- public class OperationsService extends Service {
-
- private static final String TAG = OperationsService.class.getSimpleName();
-
- public static final String EXTRA_ACCOUNT = "ACCOUNT";
- public static final String EXTRA_SERVER_URL = "SERVER_URL";
- public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
- public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
- public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
- public static final String EXTRA_NEWNAME = "NEWNAME";
- public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
- public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
- public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
- public static final String EXTRA_RESULT = "RESULT";
- public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
- public static final String EXTRA_FILE = "FILE";
- public static final String EXTRA_PASSWORD_SHARE = "PASSWORD_SHARE";
- public static final String EXTRA_COOKIE = "COOKIE";
-
- public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
- public static final String ACTION_UNSHARE = "UNSHARE";
- public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
- public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
- public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
- public static final String ACTION_RENAME = "RENAME";
- public static final String ACTION_REMOVE = "REMOVE";
- public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
- public static final String ACTION_SYNC_FILE = "SYNC_FILE";
- public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER";
- public static final String ACTION_MOVE_FILE = "MOVE_FILE";
-
- public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() +
- ".OPERATION_ADDED";
- public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() +
- ".OPERATION_FINISHED";
- private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
- mUndispatchedFinishedOperations =
- new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
-
- private static class Target {
- public Uri mServerUrl = null;
- public Account mAccount = null;
- public String mCookie = null;
-
- public Target(Account account, Uri serverUrl, String cookie) {
- mAccount = account;
- mServerUrl = serverUrl;
- mCookie = cookie;
- }
- }
- private ServiceHandler mOperationsHandler;
- private OperationsServiceBinder mOperationsBinder;
-
- private SyncFolderHandler mSyncFolderHandler;
-
-
- @Override
- public void onCreate() {
- super.onCreate();
- Log_OC.d(TAG, "Creating service");
-
- HandlerThread thread = new HandlerThread("Operations thread",
- Process.THREAD_PRIORITY_BACKGROUND);
- thread.start();
- mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
- mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);
-
-
- thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
- thread.start();
- mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);
- }
-
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log_OC.d(TAG, "Starting command with id " + startId);
-
-
- if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {
- if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
- Log_OC.e(TAG, "Not enough information provided in intent");
- return START_NOT_STICKY;
- }
- Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
- String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
- Pair<Account, String> itemSyncKey = new Pair<Account , String>(account, remotePath);
- Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
- if (itemToQueue != null) {
- mSyncFolderHandler.add(account, remotePath,
- (SynchronizeFolderOperation)itemToQueue.second);
- Message msg = mSyncFolderHandler.obtainMessage();
- msg.arg1 = startId;
- msg.obj = itemSyncKey;
- mSyncFolderHandler.sendMessage(msg);
- }
- } else {
- Message msg = mOperationsHandler.obtainMessage();
- msg.arg1 = startId;
- mOperationsHandler.sendMessage(msg);
- }
-
- return START_NOT_STICKY;
- }
- @Override
- public void onDestroy() {
- Log_OC.v(TAG, "Destroying service" );
-
- try {
- OwnCloudClientManagerFactory.getDefaultSingleton().
- saveAllClients(this, MainApp.getAccountType());
-
-
- } catch (AccountNotFoundException e) {
- e.printStackTrace();
- } catch (AuthenticatorException e) {
- e.printStackTrace();
- } catch (OperationCanceledException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- mUndispatchedFinishedOperations.clear();
- mOperationsBinder = null;
- mOperationsHandler.getLooper().quit();
- mOperationsHandler = null;
- mSyncFolderHandler.getLooper().quit();
- mSyncFolderHandler = null;
- super.onDestroy();
- }
-
- @Override
- public IBinder onBind(Intent intent) {
-
- return mOperationsBinder;
- }
-
-
- @Override
- public boolean onUnbind(Intent intent) {
- mOperationsBinder.clearListeners();
- return false;
- }
-
- public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
-
-
- private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
- new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
-
- private ServiceHandler mServiceHandler = null;
- public OperationsServiceBinder(ServiceHandler serviceHandler) {
- mServiceHandler = serviceHandler;
- }
-
- public void cancel(Account account, OCFile file) {
- mSyncFolderHandler.cancel(account, file);
- }
- public void clearListeners() {
-
- mBoundListeners.clear();
- }
-
-
- public void addOperationListener (OnRemoteOperationListener listener,
- Handler callbackHandler) {
- synchronized (mBoundListeners) {
- mBoundListeners.put(listener, callbackHandler);
- }
- }
-
-
-
- public void removeOperationListener (OnRemoteOperationListener listener) {
- synchronized (mBoundListeners) {
- mBoundListeners.remove(listener);
- }
- }
-
- public boolean isPerformingBlockingOperation() {
- return (!mServiceHandler.mPendingOperations.isEmpty());
- }
-
- public long queueNewOperation(Intent operationIntent) {
- Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
- if (itemToQueue != null) {
- mServiceHandler.mPendingOperations.add(itemToQueue);
- startService(new Intent(OperationsService.this, OperationsService.class));
- return itemToQueue.second.hashCode();
-
- } else {
- return Long.MAX_VALUE;
- }
- }
-
-
- public boolean dispatchResultIfFinished(int operationId,
- OnRemoteOperationListener listener) {
- Pair<RemoteOperation, RemoteOperationResult> undispatched =
- mUndispatchedFinishedOperations.remove(operationId);
- if (undispatched != null) {
- listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
- return true;
-
- } else {
- if (!mServiceHandler.mPendingOperations.isEmpty()) {
- return true;
- } else {
- return false;
- }
-
- }
- }
-
-
-
- public boolean isSynchronizing(Account account, String remotePath) {
- return mSyncFolderHandler.isSynchronizing(account, remotePath);
- }
- }
-
- private static class ServiceHandler extends Handler {
-
-
-
-
- OperationsService mService;
-
-
- private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
- new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
- private RemoteOperation mCurrentOperation = null;
- private Target mLastTarget = null;
- private OwnCloudClient mOwnCloudClient = null;
- private FileDataStorageManager mStorageManager;
-
-
- 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);
- }
-
-
-
- private void nextOperation() {
-
-
-
- Pair<Target, RemoteOperation> next = null;
- synchronized(mPendingOperations) {
- next = mPendingOperations.peek();
- }
- if (next != null) {
-
- mCurrentOperation = next.second;
- RemoteOperationResult result = null;
- try {
-
- if (mLastTarget == null || !mLastTarget.equals(next.first)) {
- mLastTarget = next.first;
- if (mLastTarget.mAccount != null) {
- OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount,
- mService);
- mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
- getClientFor(ocAccount, mService);
- AccountManager am = AccountManager.get(mService.getApplicationContext());
- String version = am.getUserData(mLastTarget.mAccount,
- AccountUtils.Constants.KEY_OC_VERSION);
- mOwnCloudClient.setOwnCloudVersion(version);
- mStorageManager = new FileDataStorageManager(
- mLastTarget.mAccount,
- mService.getContentResolver()
- );
- } else {
- OwnCloudCredentials credentials = null;
- if (mLastTarget.mCookie != null &&
- mLastTarget.mCookie.length() > 0) {
-
-
-
- credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
- mLastTarget.mCookie);
- }
- OwnCloudAccount ocAccount = new OwnCloudAccount(
- mLastTarget.mServerUrl, credentials);
- mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
- getClientFor(ocAccount, mService);
- mStorageManager = null;
- }
- }
-
- if (mCurrentOperation instanceof SyncOperation) {
- result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient,
- mStorageManager);
- } else {
- 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();
- }
- }
-
-
- mService.dispatchResultToOperationListeners(mCurrentOperation, result);
- }
- }
-
- }
-
-
- private Pair<Target , RemoteOperation> 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);
- String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
- String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
- target = new Target(
- account,
- (serverUrl == null) ? null : Uri.parse(serverUrl),
- cookie
- );
-
- String action = operationIntent.getAction();
- if (action.equals(ACTION_CREATE_SHARE)) {
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- String password = operationIntent.getStringExtra(EXTRA_PASSWORD_SHARE);
- Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
- if (remotePath.length() > 0) {
- operation = new CreateShareOperation(OperationsService.this, remotePath,
- ShareType.PUBLIC_LINK,
- "", false, password, 1, sendIntent);
- }
-
- } else if (action.equals(ACTION_UNSHARE)) {
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- if (remotePath.length() > 0) {
- operation = new UnshareLinkOperation(
- remotePath,
- OperationsService.this);
- }
-
- } else if (action.equals(ACTION_GET_SERVER_INFO)) {
-
- operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
-
- } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
-
- String oauth2QueryParameters =
- operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
- operation = new OAuth2GetAccessToken(
- getString(R.string.oauth2_client_id),
- getString(R.string.oauth2_redirect_uri),
- getString(R.string.oauth2_grant_type),
- oauth2QueryParameters);
-
- } else if (action.equals(ACTION_GET_USER_NAME)) {
-
- operation = new GetRemoteUserNameOperation();
-
- } else if (action.equals(ACTION_RENAME)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
- operation = new RenameFileOperation(remotePath, newName);
-
- } else if (action.equals(ACTION_REMOVE)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL,
- false);
- operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
-
- } else if (action.equals(ACTION_CREATE_FOLDER)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH,
- true);
- operation = new CreateFolderOperation(remotePath, createFullPath);
-
- } else if (action.equals(ACTION_SYNC_FILE)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- boolean syncFileContents =
- operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
- operation = new SynchronizeFileOperation(
- remotePath, account, syncFileContents, getApplicationContext()
- );
-
- } else if (action.equals(ACTION_SYNC_FOLDER)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- operation = new SynchronizeFolderOperation(
- this,
- remotePath,
- account,
- System.currentTimeMillis()
- );
-
- } else if (action.equals(ACTION_MOVE_FILE)) {
-
- String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
- String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
- operation = new MoveFileOperation(remotePath,newParentPath,account);
- }
-
- }
-
- } catch (IllegalArgumentException e) {
- Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
- operation = null;
- }
- if (operation != null) {
- return new Pair<Target , RemoteOperation>(target, operation);
- } else {
- return null;
- }
- }
-
-
- private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
- Intent intent = new Intent(ACTION_OPERATION_ADDED);
- if (target.mAccount != null) {
- intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
- } else {
- intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
- }
-
-
- sendStickyBroadcast(intent);
- }
-
-
-
-
- private void sendBroadcastOperationFinished(Target target, RemoteOperation operation,
- RemoteOperationResult result) {
- Intent intent = new Intent(ACTION_OPERATION_FINISHED);
- intent.putExtra(EXTRA_RESULT, result);
- if (target.mAccount != null) {
- intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
- } else {
- intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
- }
-
-
- sendStickyBroadcast(intent);
- }
-
-
- protected void dispatchResultToOperationListeners(
- final RemoteOperation operation, final RemoteOperationResult result
- ) {
- int count = 0;
- Iterator<OnRemoteOperationListener> 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(new Runnable() {
- @Override
- public void run() {
- listener.onRemoteOperationFinish(operation, result);
- }
- });
- count += 1;
- }
- }
- if (count == 0) {
-
- Pair<RemoteOperation, RemoteOperationResult> undispatched =
- new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
- mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
- }
- Log_OC.d(TAG, "Called " + count + " listeners");
- }
- }
|