1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.services
;
21 import java
.io
.IOException
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Iterator
;
24 import java
.util
.concurrent
.ConcurrentHashMap
;
25 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
26 import java
.util
.concurrent
.ConcurrentMap
;
28 import com
.owncloud
.android
.MainApp
;
29 import com
.owncloud
.android
.R
;
30 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
31 import com
.owncloud
.android
.datamodel
.OCFile
;
32 import com
.owncloud
.android
.files
.services
.FileDownloader
;
33 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
34 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
35 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
36 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
38 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
39 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
40 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
42 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
43 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
44 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
45 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
46 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
47 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
48 import com
.owncloud
.android
.operations
.CreateShareOperation
;
49 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
50 import com
.owncloud
.android
.operations
.MoveFileOperation
;
51 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
52 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
53 import com
.owncloud
.android
.operations
.RenameFileOperation
;
54 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
55 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
56 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
57 import com
.owncloud
.android
.utils
.FileStorageUtils
;
59 import android
.accounts
.Account
;
60 import android
.accounts
.AccountsException
;
61 import android
.accounts
.AuthenticatorException
;
62 import android
.accounts
.OperationCanceledException
;
63 import android
.app
.Service
;
64 import android
.content
.Intent
;
65 import android
.net
.Uri
;
66 import android
.os
.Binder
;
67 import android
.os
.Handler
;
68 import android
.os
.HandlerThread
;
69 import android
.os
.IBinder
;
70 import android
.os
.Looper
;
71 import android
.os
.Message
;
72 import android
.os
.Process
;
73 import android
.util
.Pair
;
75 public class OperationsService
extends Service
{
77 private static final String TAG
= OperationsService
.class.getSimpleName();
79 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
80 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
81 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
82 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
83 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
84 public static final String EXTRA_NEWNAME
= "NEWNAME";
85 public static final String EXTRA_REMOVE_ONLY_LOCAL
= "REMOVE_LOCAL_COPY";
86 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
87 public static final String EXTRA_SYNC_FILE_CONTENTS
= "SYNC_FILE_CONTENTS";
88 public static final String EXTRA_RESULT
= "RESULT";
89 public static final String EXTRA_NEW_PARENT_PATH
= "NEW_PARENT_PATH";
90 public static final String EXTRA_FILE
= "FILE";
92 // TODO review if ALL OF THEM are necessary
93 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
94 public static final String EXTRA_USERNAME
= "USERNAME";
95 public static final String EXTRA_PASSWORD
= "PASSWORD";
96 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
97 public static final String EXTRA_COOKIE
= "COOKIE";
99 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
100 public static final String ACTION_UNSHARE
= "UNSHARE";
101 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
102 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
103 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
104 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
105 public static final String ACTION_RENAME
= "RENAME";
106 public static final String ACTION_REMOVE
= "REMOVE";
107 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
108 public static final String ACTION_SYNC_FILE
= "SYNC_FILE";
109 public static final String ACTION_SYNC_FOLDER
= "SYNC_FOLDER"; // for the moment, just to download
110 public static final String ACTION_CANCEL_SYNC_FOLDER
= "CANCEL_SYNC_FOLDER"; // for the moment, just to download
111 public static final String ACTION_MOVE_FILE
= "MOVE_FILE";
113 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
114 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
117 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
118 mUndispatchedFinishedOperations
=
119 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
121 private static class Target
{
122 public Uri mServerUrl
= null
;
123 public Account mAccount
= null
;
124 public String mUsername
= null
;
125 public String mPassword
= null
;
126 public String mAuthToken
= null
;
127 public String mCookie
= null
;
129 public Target(Account account
, Uri serverUrl
, String username
, String password
, String authToken
,
132 mServerUrl
= serverUrl
;
133 mUsername
= username
;
134 mPassword
= password
;
135 mAuthToken
= authToken
;
140 private ServiceHandler mOperationsHandler
;
141 private OperationsServiceBinder mOperationsBinder
;
143 private SyncFolderHandler mSyncFolderHandler
;
146 * Service initialization
149 public void onCreate() {
151 /// First worker thread for most of operations
152 HandlerThread thread
= new HandlerThread("Operations thread", Process
.THREAD_PRIORITY_BACKGROUND
);
154 mOperationsHandler
= new ServiceHandler(thread
.getLooper(), this);
155 mOperationsBinder
= new OperationsServiceBinder(mOperationsHandler
);
157 /// Separated worker thread for download of folders (WIP)
158 thread
= new HandlerThread("Syncfolder thread", Process
.THREAD_PRIORITY_BACKGROUND
);
160 mSyncFolderHandler
= new SyncFolderHandler(thread
.getLooper(), this);
165 * Entry point to add a new operation to the queue of operations.
167 * New operations are added calling to startService(), resulting in a call to this method.
168 * This ensures the service will keep on working although the caller activity goes away.
171 public int onStartCommand(Intent intent
, int flags
, int startId
) {
172 // WIP: for the moment, only SYNC_FOLDER and CANCEL_SYNC_FOLDER is expected here;
173 // the rest of the operations are requested through the Binder
174 if (ACTION_SYNC_FOLDER
.equals(intent
.getAction())) {
176 if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_REMOTE_PATH
)) {
177 Log_OC
.e(TAG
, "Not enough information provided in intent");
178 return START_NOT_STICKY
;
180 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
181 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
183 Pair
<Account
, String
> itemSyncKey
= new Pair
<Account
, String
>(account
, remotePath
);
185 Pair
<Target
, RemoteOperation
> itemToQueue
= newOperation(intent
);
186 if (itemToQueue
!= null
) {
187 mSyncFolderHandler
.add(account
, remotePath
, (SynchronizeFolderOperation
)itemToQueue
.second
);
188 mSyncFolderHandler
.sendBroadcastNewSyncFolder(account
, remotePath
);
189 Message msg
= mSyncFolderHandler
.obtainMessage();
191 msg
.obj
= itemSyncKey
;
192 mSyncFolderHandler
.sendMessage(msg
);
195 } else if (ACTION_CANCEL_SYNC_FOLDER
.equals(intent
.getAction())) {
196 if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_FILE
)) {
197 Log_OC
.e(TAG
, "Not enough information provided in intent");
198 return START_NOT_STICKY
;
200 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
201 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
203 new Thread(new Runnable() {
205 // Cancel the download
206 mSyncFolderHandler
.cancel(account
,file
);
211 Message msg
= mOperationsHandler
.obtainMessage();
213 mOperationsHandler
.sendMessage(msg
);
216 return START_NOT_STICKY
;
220 public void onDestroy() {
221 //Log_OC.wtf(TAG, "onDestroy init" );
224 OwnCloudClientManagerFactory
.getDefaultSingleton().
225 saveAllClients(this, MainApp
.getAccountType());
227 // TODO - get rid of these exceptions
228 } catch (AccountNotFoundException e
) {
230 } catch (AuthenticatorException e
) {
232 } catch (OperationCanceledException e
) {
234 } catch (IOException e
) {
238 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
239 mUndispatchedFinishedOperations
.clear();
241 //Log_OC.wtf(TAG, "onDestroy end" );
246 * Provides a binder object that clients can use to perform actions on the queue of operations,
247 * except the addition of new operations.
250 public IBinder
onBind(Intent intent
) {
251 //Log_OC.wtf(TAG, "onBind" );
252 return mOperationsBinder
;
257 * Called when ALL the bound clients were unbound.
260 public boolean onUnbind(Intent intent
) {
261 ((OperationsServiceBinder
)mOperationsBinder
).clearListeners();
262 return false
; // not accepting rebinding (default behaviour)
267 * Binder to let client components to perform actions on the queue of operations.
269 * It provides by itself the available operations.
271 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
274 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
276 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
277 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
279 private ServiceHandler mServiceHandler
= null
;
282 public OperationsServiceBinder(ServiceHandler serviceHandler
) {
283 mServiceHandler
= serviceHandler
;
288 * Cancels an operation
292 public void cancel() {
297 public void clearListeners() {
299 mBoundListeners
.clear();
304 * Adds a listener interested in being reported about the end of operations.
306 * @param listener Object to notify about the end of operations.
307 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
309 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
310 synchronized (mBoundListeners
) {
311 mBoundListeners
.put(listener
, callbackHandler
);
317 * Removes a listener from the list of objects interested in the being reported about the end of operations.
319 * @param listener Object to notify about progress of transfer.
321 public void removeOperationListener (OnRemoteOperationListener listener
) {
322 synchronized (mBoundListeners
) {
323 mBoundListeners
.remove(listener
);
329 * TODO - IMPORTANT: update implementation when more operations are moved into the service
331 * @return 'True' when an operation that enforces the user to wait for completion is in process.
333 public boolean isPerformingBlockingOperation() {
334 return (!mServiceHandler
.mPendingOperations
.isEmpty());
339 * Creates and adds to the queue a new operation, as described by operationIntent.
341 * Calls startService to make the operation is processed by the ServiceHandler.
343 * @param operationIntent Intent describing a new operation to queue and execute.
344 * @return Identifier of the operation created, or null if failed.
346 public long queueNewOperation(Intent operationIntent
) {
347 Pair
<Target
, RemoteOperation
> itemToQueue
= newOperation(operationIntent
);
348 if (itemToQueue
!= null
) {
349 mServiceHandler
.mPendingOperations
.add(itemToQueue
);
350 startService(new Intent(OperationsService
.this, OperationsService
.class));
351 return itemToQueue
.second
.hashCode();
354 return Long
.MAX_VALUE
;
359 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
360 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
361 mUndispatchedFinishedOperations
.remove(operationId
);
362 if (undispatched
!= null
) {
363 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
365 //Log_OC.wtf(TAG, "Sending callback later");
367 if (!mServiceHandler
.mPendingOperations
.isEmpty()) {
372 //Log_OC.wtf(TAG, "Not finished yet");
378 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
380 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
382 * @param account ownCloud account where the remote file is stored.
383 * @param file A file that could be affected
386 public boolean isSynchronizing(Account account, String remotePath) {
387 return mSyncFolderHandler.isSynchronizing(account, remotePath);
395 * SyncFolder worker. Performs the pending operations in the order they were requested.
397 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
399 private static class SyncFolderHandler
extends Handler
{
401 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
403 OperationsService mService
;
405 private ConcurrentMap
<String
,SynchronizeFolderOperation
> mPendingOperations
=
406 new ConcurrentHashMap
<String
,SynchronizeFolderOperation
>();
407 private OwnCloudClient mOwnCloudClient
= null
;
408 private FileDataStorageManager mStorageManager
;
409 private SynchronizeFolderOperation mCurrentSyncOperation
;
412 public SyncFolderHandler(Looper looper
, OperationsService service
) {
414 if (service
== null
) {
415 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
421 public boolean isSynchronizing(Account account
, String remotePath
) {
422 if (account
== null
|| remotePath
== null
) return false
;
423 String targetKey
= buildRemoteName(account
, remotePath
);
424 synchronized (mPendingOperations
) {
425 // TODO - this can be slow when synchronizing a big tree - need a better data structure
426 Iterator
<String
> it
= mPendingOperations
.keySet().iterator();
427 boolean found
= false
;
428 while (it
.hasNext() && !found
) {
429 found
= it
.next().startsWith(targetKey
);
437 public void handleMessage(Message msg
) {
438 Pair
<Account
, String
> itemSyncKey
= (Pair
<Account
, String
>) msg
.obj
;
439 doOperation(itemSyncKey
.first
, itemSyncKey
.second
);
440 mService
.stopSelf(msg
.arg1
);
445 * Performs the next operation in the queue
447 private void doOperation(Account account
, String remotePath
) {
449 String syncKey
= buildRemoteName(account
,remotePath
);
451 synchronized(mPendingOperations
) {
452 mCurrentSyncOperation
= mPendingOperations
.get(syncKey
);
455 if (mCurrentSyncOperation
!= null
) {
456 RemoteOperationResult result
= null
;
460 OwnCloudAccount ocAccount
= new OwnCloudAccount(account
, mService
);
461 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
462 getClientFor(ocAccount
, mService
);
463 mStorageManager
= new FileDataStorageManager(
465 mService
.getContentResolver()
468 result
= mCurrentSyncOperation
.execute(mOwnCloudClient
, mStorageManager
);
470 } catch (AccountsException e
) {
471 Log_OC
.e(TAG
, "Error while trying to get autorization", e
);
472 } catch (IOException e
) {
473 Log_OC
.e(TAG
, "Error while trying to get autorization", e
);
475 synchronized (mPendingOperations
) {
476 mPendingOperations
.remove(syncKey
);
478 SynchronizeFolderOperation checkedOp = mCurrentSyncOperation;
479 String checkedKey = syncKey;
480 while (checkedOp.getPendingChildrenCount() <= 0) {
481 // while (!checkedOp.hasChildren()) {
482 mPendingOperations.remove(checkedKey);
483 String parentKey = buildRemoteName(account, (new File(checkedOp.getFolderPath())).getParent());
484 // String parentKey = buildRemoteName(account, checkedOp.getParentPath());
485 SynchronizeFolderOperation parentOp = mPendingOperations.get(parentKey);
486 if (parentOp != null) {
487 parentOp.decreasePendingChildrenCount();
493 mService
.dispatchResultToOperationListeners(null
, mCurrentSyncOperation
, result
);
495 sendBroadcastFinishedSyncFolder(account
, remotePath
, result
.isSuccess());
500 public void add(Account account
, String remotePath
, SynchronizeFolderOperation syncFolderOperation
){
501 String syncKey
= buildRemoteName(account
,remotePath
);
502 mPendingOperations
.putIfAbsent(syncKey
,syncFolderOperation
);
506 * Cancels sync operations.
507 * @param account Owncloud account where the remote file is stored.
508 * @param file File OCFile
510 public void cancel(Account account
, OCFile file
){
511 SynchronizeFolderOperation syncOperation
= null
;
512 String targetKey
= buildRemoteName(account
, file
.getRemotePath());
513 ArrayList
<String
> keyItems
= new ArrayList
<String
>();
514 synchronized (mPendingOperations
) {
515 if (file
.isFolder()) {
516 Log_OC
.d(TAG
, "Canceling pending sync operations");
517 Iterator
<String
> it
= mPendingOperations
.keySet().iterator();
518 boolean found
= false
;
519 while (it
.hasNext()) {
520 String keySyncOperation
= it
.next();
521 found
= keySyncOperation
.startsWith(targetKey
);
523 keyItems
.add(keySyncOperation
);
528 // this is not really expected...
529 Log_OC
.d(TAG
, "Canceling sync operation");
530 keyItems
.add(buildRemoteName(account
, file
.getRemotePath()));
532 for (String item
: keyItems
) {
533 syncOperation
= mPendingOperations
.remove(item
);
534 if (syncOperation
!= null
) {
535 syncOperation
.cancel();
540 //sendBroadcastFinishedSyncFolder(account, file.getRemotePath());
544 * Builds a key from the account and file to download
546 * @param account Account where the file to download is stored
547 * @param path File path
549 private String
buildRemoteName(Account account
, String path
) {
550 return account
.name
+ path
;
555 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
558 private void sendBroadcastNewSyncFolder(Account account
, String remotePath
) {
559 Intent added
= new Intent(FileDownloader
.getDownloadAddedMessage());
560 added
.putExtra(FileDownloader
.ACCOUNT_NAME
, account
.name
);
561 added
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, remotePath
);
562 added
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, FileStorageUtils
.getSavePath(account
.name
) + remotePath
);
563 mService
.sendStickyBroadcast(added
);
567 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
570 private void sendBroadcastFinishedSyncFolder(Account account
, String remotePath
, boolean success
) {
571 Intent finished
= new Intent(FileDownloader
.getDownloadFinishMessage());
572 finished
.putExtra(FileDownloader
.ACCOUNT_NAME
, account
.name
);
573 finished
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, remotePath
);
574 finished
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, FileStorageUtils
.getSavePath(account
.name
) + remotePath
);
575 finished
.putExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, success
);
576 mService
.sendStickyBroadcast(finished
);
584 * Operations worker. Performs the pending operations in the order they were requested.
586 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
588 private static class ServiceHandler
extends Handler
{
589 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
592 OperationsService mService
;
595 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
596 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
597 private RemoteOperation mCurrentOperation
= null
;
598 private Target mLastTarget
= null
;
599 private OwnCloudClient mOwnCloudClient
= null
;
600 private FileDataStorageManager mStorageManager
;
603 public ServiceHandler(Looper looper
, OperationsService service
) {
605 if (service
== null
) {
606 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
612 public void handleMessage(Message msg
) {
614 mService
.stopSelf(msg
.arg1
);
619 * Performs the next operation in the queue
621 private void nextOperation() {
623 //Log_OC.wtf(TAG, "nextOperation init" );
625 Pair
<Target
, RemoteOperation
> next
= null
;
626 synchronized(mPendingOperations
) {
627 next
= mPendingOperations
.peek();
632 mCurrentOperation
= next
.second
;
633 RemoteOperationResult result
= null
;
635 /// prepare client object to send the request to the ownCloud server
636 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
637 mLastTarget
= next
.first
;
638 if (mLastTarget
.mAccount
!= null
) {
639 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastTarget
.mAccount
, mService
);
640 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
641 getClientFor(ocAccount
, mService
);
642 mStorageManager
= new FileDataStorageManager(
643 mLastTarget
.mAccount
,
644 mService
.getContentResolver()
647 OwnCloudCredentials credentials
= null
;
648 if (mLastTarget
.mUsername
!= null
&&
649 mLastTarget
.mUsername
.length() > 0) {
650 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(
651 mLastTarget
.mUsername
,
652 mLastTarget
.mPassword
); // basic
654 } else if (mLastTarget
.mAuthToken
!= null
&&
655 mLastTarget
.mAuthToken
.length() > 0) {
656 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
657 mLastTarget
.mAuthToken
); // bearer token
659 } else if (mLastTarget
.mCookie
!= null
&&
660 mLastTarget
.mCookie
.length() > 0) {
661 credentials
= OwnCloudCredentialsFactory
.newSamlSsoCredentials(
662 mLastTarget
.mCookie
); // SAML SSO
664 OwnCloudAccount ocAccount
= new OwnCloudAccount(
665 mLastTarget
.mServerUrl
, credentials
);
666 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
667 getClientFor(ocAccount
, mService
);
668 mStorageManager
= null
;
672 /// perform the operation
673 if (mCurrentOperation
instanceof SyncOperation
) {
674 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
676 result
= mCurrentOperation
.execute(mOwnCloudClient
);
679 } catch (AccountsException e
) {
680 if (mLastTarget
.mAccount
== null
) {
681 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
683 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
685 result
= new RemoteOperationResult(e
);
687 } catch (IOException e
) {
688 if (mLastTarget
.mAccount
== null
) {
689 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
691 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
693 result
= new RemoteOperationResult(e
);
694 } catch (Exception e
) {
695 if (mLastTarget
.mAccount
== null
) {
696 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
698 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
700 result
= new RemoteOperationResult(e
);
703 synchronized(mPendingOperations
) {
704 mPendingOperations
.poll();
708 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
709 mService
.dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
719 * Creates a new operation, as described by operationIntent.
721 * TODO - move to ServiceHandler (probably)
723 * @param operationIntent Intent describing a new operation to queue and execute.
724 * @return Pair with the new operation object and the information about its target server.
726 private Pair
<Target
, RemoteOperation
> newOperation(Intent operationIntent
) {
727 RemoteOperation operation
= null
;
728 Target target
= null
;
730 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
731 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
732 Log_OC
.e(TAG
, "Not enough information provided in intent");
735 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
736 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
737 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
738 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
739 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
740 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
743 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
750 String action
= operationIntent
.getAction();
751 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
752 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
753 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
754 if (remotePath
.length() > 0) {
755 operation
= new CreateShareOperation(OperationsService
.this, remotePath
, ShareType
.PUBLIC_LINK
,
756 "", false
, "", 1, sendIntent
);
759 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
760 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
761 if (remotePath
.length() > 0) {
762 operation
= new UnshareLinkOperation(
764 OperationsService
.this);
767 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
768 // check OC server and get basic information from it
769 operation
= new GetServerInfoOperation(serverUrl
, OperationsService
.this);
771 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
772 /// GET ACCESS TOKEN to the OAuth server
773 String oauth2QueryParameters
=
774 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
775 operation
= new OAuth2GetAccessToken(
776 getString(R
.string
.oauth2_client_id
),
777 getString(R
.string
.oauth2_redirect_uri
),
778 getString(R
.string
.oauth2_grant_type
),
779 oauth2QueryParameters
);
781 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
783 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
784 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, false
);
785 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
787 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
789 operation
= new GetRemoteUserNameOperation();
791 } else if (action
.equals(ACTION_RENAME
)) {
792 // Rename file or folder
793 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
794 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
795 operation
= new RenameFileOperation(remotePath
, newName
);
797 } else if (action
.equals(ACTION_REMOVE
)) {
798 // Remove file or folder
799 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
800 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
801 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
803 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
805 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
806 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
807 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
809 } else if (action
.equals(ACTION_SYNC_FILE
)) {
811 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
812 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
813 operation
= new SynchronizeFileOperation(
814 remotePath
, account
, syncFileContents
, getApplicationContext()
817 } else if (action
.equals(ACTION_SYNC_FOLDER
)) {
819 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
820 operation
= new SynchronizeFolderOperation(
821 this, // TODO remove this dependency from construction time
824 System
.currentTimeMillis() // TODO remove this dependency from construction time
827 } else if (action
.equals(ACTION_MOVE_FILE
)) {
829 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
830 String newParentPath
= operationIntent
.getStringExtra(EXTRA_NEW_PARENT_PATH
);
831 operation
= new MoveFileOperation(remotePath
,newParentPath
,account
);
836 } catch (IllegalArgumentException e
) {
837 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
841 if (operation
!= null
) {
842 return new Pair
<Target
, RemoteOperation
>(target
, operation
);
850 * Sends a broadcast when a new operation is added to the queue.
852 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
854 * @param target Account or URL pointing to an OC server.
855 * @param operation Added operation.
857 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
858 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
859 if (target
.mAccount
!= null
) {
860 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
862 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
864 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
865 //lbm.sendBroadcast(intent);
866 sendStickyBroadcast(intent
);
870 // TODO - maybe add a notification for real start of operations
873 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
875 * Local broadcasts are only delivered to activities in the same process.
877 * @param target Account or URL pointing to an OC server.
878 * @param operation Finished operation.
879 * @param result Result of the operation.
881 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
882 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
883 intent
.putExtra(EXTRA_RESULT
, result
);
884 if (target
.mAccount
!= null
) {
885 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
887 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
889 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
890 //lbm.sendBroadcast(intent);
891 sendStickyBroadcast(intent
);
896 * Notifies the currently subscribed listeners about the end of an operation.
898 * @param target Account or URL pointing to an OC server.
899 * @param operation Finished operation.
900 * @param result Result of the operation.
902 private void dispatchResultToOperationListeners(
903 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
905 Iterator
<OnRemoteOperationListener
> listeners
= mOperationsBinder
.mBoundListeners
.keySet().iterator();
906 while (listeners
.hasNext()) {
907 final OnRemoteOperationListener listener
= listeners
.next();
908 final Handler handler
= mOperationsBinder
.mBoundListeners
.get(listener
);
909 if (handler
!= null
) {
910 handler
.post(new Runnable() {
913 listener
.onRemoteOperationFinish(operation
, result
);
920 //mOperationResults.put(operation.hashCode(), result);
921 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
922 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
923 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
925 Log_OC
.d(TAG
, "Called " + count
+ " listeners");