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
;
20 import java
.io
.IOException
;
21 import java
.util
.ArrayList
;
22 import java
.util
.Iterator
;
23 import java
.util
.concurrent
.ConcurrentHashMap
;
24 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
25 import java
.util
.concurrent
.ConcurrentMap
;
27 import com
.owncloud
.android
.MainApp
;
28 import com
.owncloud
.android
.R
;
29 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
30 import com
.owncloud
.android
.datamodel
.OCFile
;
31 import com
.owncloud
.android
.files
.services
.FileDownloader
;
32 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
33 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
34 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
35 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
36 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
37 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
38 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
39 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
40 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
41 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
42 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
43 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
44 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
45 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
46 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
47 import com
.owncloud
.android
.operations
.CreateShareOperation
;
48 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
49 import com
.owncloud
.android
.operations
.MoveFileOperation
;
50 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
51 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
52 import com
.owncloud
.android
.operations
.RenameFileOperation
;
53 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
54 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
55 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
56 import com
.owncloud
.android
.utils
.FileStorageUtils
;
58 import android
.accounts
.Account
;
59 import android
.accounts
.AccountsException
;
60 import android
.accounts
.AuthenticatorException
;
61 import android
.accounts
.OperationCanceledException
;
62 import android
.app
.Service
;
63 import android
.content
.Intent
;
64 import android
.net
.Uri
;
65 import android
.os
.Binder
;
66 import android
.os
.Handler
;
67 import android
.os
.HandlerThread
;
68 import android
.os
.IBinder
;
69 import android
.os
.Looper
;
70 import android
.os
.Message
;
71 import android
.os
.Process
;
72 import android
.util
.Pair
;
74 public class OperationsService
extends Service
{
76 private static final String TAG
= OperationsService
.class.getSimpleName();
78 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
79 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
80 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
81 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
82 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
83 public static final String EXTRA_NEWNAME
= "NEWNAME";
84 public static final String EXTRA_REMOVE_ONLY_LOCAL
= "REMOVE_LOCAL_COPY";
85 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
86 public static final String EXTRA_SYNC_FILE_CONTENTS
= "SYNC_FILE_CONTENTS";
87 public static final String EXTRA_RESULT
= "RESULT";
88 public static final String EXTRA_NEW_PARENT_PATH
= "NEW_PARENT_PATH";
89 public static final String EXTRA_FILE
= "FILE";
91 // TODO review if ALL OF THEM are necessary
92 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
93 public static final String EXTRA_USERNAME
= "USERNAME";
94 public static final String EXTRA_PASSWORD
= "PASSWORD";
95 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
96 public static final String EXTRA_COOKIE
= "COOKIE";
98 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
99 public static final String ACTION_UNSHARE
= "UNSHARE";
100 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
101 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
102 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
103 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
104 public static final String ACTION_RENAME
= "RENAME";
105 public static final String ACTION_REMOVE
= "REMOVE";
106 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
107 public static final String ACTION_SYNC_FILE
= "SYNC_FILE";
108 public static final String ACTION_SYNC_FOLDER
= "SYNC_FOLDER"; // for the moment, just to download
109 public static final String ACTION_CANCEL_SYNC_FOLDER
= "CANCEL_SYNC_FOLDER"; // for the moment, just to download
110 public static final String ACTION_MOVE_FILE
= "MOVE_FILE";
112 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
113 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
116 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
117 mUndispatchedFinishedOperations
=
118 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
120 private static class Target
{
121 public Uri mServerUrl
= null
;
122 public Account mAccount
= null
;
123 public String mUsername
= null
;
124 public String mPassword
= null
;
125 public String mAuthToken
= null
;
126 public String mCookie
= null
;
128 public Target(Account account
, Uri serverUrl
, String username
, String password
, String authToken
,
131 mServerUrl
= serverUrl
;
132 mUsername
= username
;
133 mPassword
= password
;
134 mAuthToken
= authToken
;
139 private ServiceHandler mOperationsHandler
;
140 private OperationsServiceBinder mOperationsBinder
;
142 private SyncFolderHandler mSyncFolderHandler
;
145 * Service initialization
148 public void onCreate() {
150 /// First worker thread for most of operations
151 HandlerThread thread
= new HandlerThread("Operations thread", Process
.THREAD_PRIORITY_BACKGROUND
);
153 mOperationsHandler
= new ServiceHandler(thread
.getLooper(), this);
154 mOperationsBinder
= new OperationsServiceBinder(mOperationsHandler
);
156 /// Separated worker thread for download of folders (WIP)
157 thread
= new HandlerThread("Syncfolder thread", Process
.THREAD_PRIORITY_BACKGROUND
);
159 mSyncFolderHandler
= new SyncFolderHandler(thread
.getLooper(), this);
164 * Entry point to add a new operation to the queue of operations.
166 * New operations are added calling to startService(), resulting in a call to this method.
167 * This ensures the service will keep on working although the caller activity goes away.
170 public int onStartCommand(Intent intent
, int flags
, int startId
) {
171 // WIP: for the moment, only SYNC_FOLDER and CANCEL_SYNC_FOLDER is expected here;
172 // the rest of the operations are requested through the Binder
173 if (ACTION_SYNC_FOLDER
.equals(intent
.getAction())) {
174 if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_REMOTE_PATH
)) {
175 Log_OC
.e(TAG
, "Not enough information provided in intent");
176 return START_NOT_STICKY
;
178 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
179 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
181 Pair
<Account
, String
> itemSyncKey
= new Pair
<Account
, String
>(account
, remotePath
);
183 Pair
<Target
, RemoteOperation
> itemToQueue
= newOperation(intent
);
184 if (itemToQueue
!= null
) {
185 mSyncFolderHandler
.add(account
, remotePath
, (SynchronizeFolderOperation
)itemToQueue
.second
);
186 mSyncFolderHandler
.sendBroadcastNewSyncFolder(account
, remotePath
);
187 Message msg
= mSyncFolderHandler
.obtainMessage();
189 msg
.obj
= itemSyncKey
;
190 mSyncFolderHandler
.sendMessage(msg
);
192 } else if (ACTION_CANCEL_SYNC_FOLDER
.equals(intent
.getAction())) {
193 if (!intent
.hasExtra(EXTRA_ACCOUNT
) || !intent
.hasExtra(EXTRA_FILE
)) {
194 Log_OC
.e(TAG
, "Not enough information provided in intent");
195 return START_NOT_STICKY
;
197 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
198 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
200 new Thread(new Runnable() {
202 // Cancel the download
203 mSyncFolderHandler
.cancel(account
,file
);
208 Message msg
= mOperationsHandler
.obtainMessage();
210 mOperationsHandler
.sendMessage(msg
);
213 return START_NOT_STICKY
;
217 public void onDestroy() {
218 //Log_OC.wtf(TAG, "onDestroy init" );
221 OwnCloudClientManagerFactory
.getDefaultSingleton().
222 saveAllClients(this, MainApp
.getAccountType());
224 // TODO - get rid of these exceptions
225 } catch (AccountNotFoundException e
) {
227 } catch (AuthenticatorException e
) {
229 } catch (OperationCanceledException e
) {
231 } catch (IOException e
) {
235 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
236 mUndispatchedFinishedOperations
.clear();
238 //Log_OC.wtf(TAG, "onDestroy end" );
243 * Provides a binder object that clients can use to perform actions on the queue of operations,
244 * except the addition of new operations.
247 public IBinder
onBind(Intent intent
) {
248 //Log_OC.wtf(TAG, "onBind" );
249 return mOperationsBinder
;
254 * Called when ALL the bound clients were unbound.
257 public boolean onUnbind(Intent intent
) {
258 ((OperationsServiceBinder
)mOperationsBinder
).clearListeners();
259 return false
; // not accepting rebinding (default behaviour)
264 * Binder to let client components to perform actions on the queue of operations.
266 * It provides by itself the available operations.
268 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
271 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
273 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
274 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
276 private ServiceHandler mServiceHandler
= null
;
279 public OperationsServiceBinder(ServiceHandler serviceHandler
) {
280 mServiceHandler
= serviceHandler
;
285 * Cancels an operation
289 public void cancel() {
294 public void clearListeners() {
296 mBoundListeners
.clear();
301 * Adds a listener interested in being reported about the end of operations.
303 * @param listener Object to notify about the end of operations.
304 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
306 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
307 synchronized (mBoundListeners
) {
308 mBoundListeners
.put(listener
, callbackHandler
);
314 * Removes a listener from the list of objects interested in the being reported about the end of operations.
316 * @param listener Object to notify about progress of transfer.
318 public void removeOperationListener (OnRemoteOperationListener listener
) {
319 synchronized (mBoundListeners
) {
320 mBoundListeners
.remove(listener
);
326 * TODO - IMPORTANT: update implementation when more operations are moved into the service
328 * @return 'True' when an operation that enforces the user to wait for completion is in process.
330 public boolean isPerformingBlockingOperation() {
331 return (!mServiceHandler
.mPendingOperations
.isEmpty());
336 * Creates and adds to the queue a new operation, as described by operationIntent.
338 * Calls startService to make the operation is processed by the ServiceHandler.
340 * @param operationIntent Intent describing a new operation to queue and execute.
341 * @return Identifier of the operation created, or null if failed.
343 public long queueNewOperation(Intent operationIntent
) {
344 Pair
<Target
, RemoteOperation
> itemToQueue
= newOperation(operationIntent
);
345 if (itemToQueue
!= null
) {
346 mServiceHandler
.mPendingOperations
.add(itemToQueue
);
347 startService(new Intent(OperationsService
.this, OperationsService
.class));
348 return itemToQueue
.second
.hashCode();
351 return Long
.MAX_VALUE
;
356 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
357 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
358 mUndispatchedFinishedOperations
.remove(operationId
);
359 if (undispatched
!= null
) {
360 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
362 //Log_OC.wtf(TAG, "Sending callback later");
364 if (!mServiceHandler
.mPendingOperations
.isEmpty()) {
369 //Log_OC.wtf(TAG, "Not finished yet");
375 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
377 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
379 * @param account ownCloud account where the remote file is stored.
380 * @param file A file that could be affected
383 public boolean isSynchronizing(Account account, String remotePath) {
384 return mSyncFolderHandler.isSynchronizing(account, remotePath);
392 * SyncFolder worker. Performs the pending operations in the order they were requested.
394 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
396 private static class SyncFolderHandler
extends Handler
{
398 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
400 OperationsService mService
;
402 private ConcurrentMap
<String
,SynchronizeFolderOperation
> mPendingOperations
=
403 new ConcurrentHashMap
<String
,SynchronizeFolderOperation
>();
404 private OwnCloudClient mOwnCloudClient
= null
;
405 private FileDataStorageManager mStorageManager
;
406 private SynchronizeFolderOperation mCurrentSyncOperation
;
409 public SyncFolderHandler(Looper looper
, OperationsService service
) {
411 if (service
== null
) {
412 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
418 public boolean isSynchronizing(Account account
, String remotePath
) {
419 if (account
== null
|| remotePath
== null
) return false
;
420 String targetKey
= buildRemoteName(account
, remotePath
);
421 synchronized (mPendingOperations
) {
422 // TODO - this can be slow when synchronizing a big tree - need a better data structure
423 Iterator
<String
> it
= mPendingOperations
.keySet().iterator();
424 boolean found
= false
;
425 while (it
.hasNext() && !found
) {
426 found
= it
.next().startsWith(targetKey
);
434 public void handleMessage(Message msg
) {
435 Pair
<Account
, String
> itemSyncKey
= (Pair
<Account
, String
>) msg
.obj
;
436 doOperation(itemSyncKey
.first
, itemSyncKey
.second
);
437 mService
.stopSelf(msg
.arg1
);
442 * Performs the next operation in the queue
444 private void doOperation(Account account
, String remotePath
) {
446 String syncKey
= buildRemoteName(account
,remotePath
);
448 synchronized(mPendingOperations
) {
449 mCurrentSyncOperation
= mPendingOperations
.get(syncKey
);
452 if (mCurrentSyncOperation
!= null
) {
453 RemoteOperationResult result
= null
;
457 OwnCloudAccount ocAccount
= new OwnCloudAccount(account
, mService
);
458 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
459 getClientFor(ocAccount
, mService
);
460 mStorageManager
= new FileDataStorageManager(
462 mService
.getContentResolver()
465 result
= mCurrentSyncOperation
.execute(mOwnCloudClient
, mStorageManager
);
467 } catch (AccountsException e
) {
468 Log_OC
.e(TAG
, "Error while trying to get autorization", e
);
469 } catch (IOException e
) {
470 Log_OC
.e(TAG
, "Error while trying to get autorization", e
);
472 synchronized(mPendingOperations
) {
473 mPendingOperations
.remove(syncKey
);
476 mService
.dispatchResultToOperationListeners(null
, mCurrentSyncOperation
, result
);
478 sendBroadcastFinishedSyncFolder(account
, remotePath
, result
.isSuccess());
483 public void add(Account account
, String remotePath
, SynchronizeFolderOperation syncFolderOperation
){
484 String syncKey
= buildRemoteName(account
,remotePath
);
485 mPendingOperations
.putIfAbsent(syncKey
,syncFolderOperation
);
489 * Cancels sync operations.
490 * @param account Owncloud account where the remote file is stored.
491 * @param file File OCFile
493 public void cancel(Account account
, OCFile file
){
494 SynchronizeFolderOperation syncOperation
= null
;
495 String targetKey
= buildRemoteName(account
, file
.getRemotePath());
496 ArrayList
<String
> keyItems
= new ArrayList
<String
>();
497 synchronized (mPendingOperations
) {
498 if (file
.isFolder()) {
499 Log_OC
.d(TAG
, "Canceling pending sync operations");
500 Iterator
<String
> it
= mPendingOperations
.keySet().iterator();
501 boolean found
= false
;
502 while (it
.hasNext()) {
503 String keySyncOperation
= it
.next();
504 found
= keySyncOperation
.startsWith(targetKey
);
506 keyItems
.add(keySyncOperation
);
511 // this is not really expected...
512 Log_OC
.d(TAG
, "Canceling sync operation");
513 keyItems
.add(buildRemoteName(account
, file
.getRemotePath()));
515 for (String item
: keyItems
) {
516 syncOperation
= mPendingOperations
.remove(item
);
517 if (syncOperation
!= null
) {
518 syncOperation
.cancel();
523 //sendBroadcastFinishedSyncFolder(account, file.getRemotePath());
525 /// cancellation of download needs to be done separately in any case; a SynchronizeFolderOperation
526 // may finish much sooner than the real download of the files in the folder
527 Intent intent
= new Intent(mService
, FileDownloader
.class);
528 intent
.setAction(FileDownloader
.ACTION_CANCEL_FILE_DOWNLOAD
);
529 intent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
530 intent
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
531 mService
.startService(intent
);
535 * Builds a key from the account and file to download
537 * @param account Account where the file to download is stored
538 * @param path File path
540 private String
buildRemoteName(Account account
, String path
) {
541 return account
.name
+ path
;
546 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
549 private void sendBroadcastNewSyncFolder(Account account
, String remotePath
) {
550 Intent added
= new Intent(FileDownloader
.getDownloadAddedMessage());
551 added
.putExtra(FileDownloader
.ACCOUNT_NAME
, account
.name
);
552 added
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, remotePath
);
553 added
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, FileStorageUtils
.getSavePath(account
.name
) + remotePath
);
554 mService
.sendStickyBroadcast(added
);
558 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
561 private void sendBroadcastFinishedSyncFolder(Account account
, String remotePath
, boolean success
) {
562 Intent finished
= new Intent(FileDownloader
.getDownloadFinishMessage());
563 finished
.putExtra(FileDownloader
.ACCOUNT_NAME
, account
.name
);
564 finished
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, remotePath
);
565 finished
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, FileStorageUtils
.getSavePath(account
.name
) + remotePath
);
566 finished
.putExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, success
);
567 mService
.sendStickyBroadcast(finished
);
575 * Operations worker. Performs the pending operations in the order they were requested.
577 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
579 private static class ServiceHandler
extends Handler
{
580 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
583 OperationsService mService
;
586 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
587 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
588 private RemoteOperation mCurrentOperation
= null
;
589 private Target mLastTarget
= null
;
590 private OwnCloudClient mOwnCloudClient
= null
;
591 private FileDataStorageManager mStorageManager
;
594 public ServiceHandler(Looper looper
, OperationsService service
) {
596 if (service
== null
) {
597 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
603 public void handleMessage(Message msg
) {
605 mService
.stopSelf(msg
.arg1
);
610 * Performs the next operation in the queue
612 private void nextOperation() {
614 //Log_OC.wtf(TAG, "nextOperation init" );
616 Pair
<Target
, RemoteOperation
> next
= null
;
617 synchronized(mPendingOperations
) {
618 next
= mPendingOperations
.peek();
623 mCurrentOperation
= next
.second
;
624 RemoteOperationResult result
= null
;
626 /// prepare client object to send the request to the ownCloud server
627 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
628 mLastTarget
= next
.first
;
629 if (mLastTarget
.mAccount
!= null
) {
630 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastTarget
.mAccount
, mService
);
631 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
632 getClientFor(ocAccount
, mService
);
633 mStorageManager
= new FileDataStorageManager(
634 mLastTarget
.mAccount
,
635 mService
.getContentResolver()
638 OwnCloudCredentials credentials
= null
;
639 if (mLastTarget
.mUsername
!= null
&&
640 mLastTarget
.mUsername
.length() > 0) {
641 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(
642 mLastTarget
.mUsername
,
643 mLastTarget
.mPassword
); // basic
645 } else if (mLastTarget
.mAuthToken
!= null
&&
646 mLastTarget
.mAuthToken
.length() > 0) {
647 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
648 mLastTarget
.mAuthToken
); // bearer token
650 } else if (mLastTarget
.mCookie
!= null
&&
651 mLastTarget
.mCookie
.length() > 0) {
652 credentials
= OwnCloudCredentialsFactory
.newSamlSsoCredentials(
653 mLastTarget
.mCookie
); // SAML SSO
655 OwnCloudAccount ocAccount
= new OwnCloudAccount(
656 mLastTarget
.mServerUrl
, credentials
);
657 mOwnCloudClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
658 getClientFor(ocAccount
, mService
);
659 mStorageManager
= null
;
663 /// perform the operation
664 if (mCurrentOperation
instanceof SyncOperation
) {
665 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
667 result
= mCurrentOperation
.execute(mOwnCloudClient
);
670 } catch (AccountsException e
) {
671 if (mLastTarget
.mAccount
== null
) {
672 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
674 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
676 result
= new RemoteOperationResult(e
);
678 } catch (IOException e
) {
679 if (mLastTarget
.mAccount
== null
) {
680 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
682 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
684 result
= new RemoteOperationResult(e
);
685 } catch (Exception e
) {
686 if (mLastTarget
.mAccount
== null
) {
687 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
689 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
691 result
= new RemoteOperationResult(e
);
694 synchronized(mPendingOperations
) {
695 mPendingOperations
.poll();
699 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
700 mService
.dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
710 * Creates a new operation, as described by operationIntent.
712 * TODO - move to ServiceHandler (probably)
714 * @param operationIntent Intent describing a new operation to queue and execute.
715 * @return Pair with the new operation object and the information about its target server.
717 private Pair
<Target
, RemoteOperation
> newOperation(Intent operationIntent
) {
718 RemoteOperation operation
= null
;
719 Target target
= null
;
721 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
722 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
723 Log_OC
.e(TAG
, "Not enough information provided in intent");
726 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
727 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
728 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
729 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
730 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
731 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
734 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
741 String action
= operationIntent
.getAction();
742 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
743 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
744 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
745 if (remotePath
.length() > 0) {
746 operation
= new CreateShareOperation(OperationsService
.this, remotePath
, ShareType
.PUBLIC_LINK
,
747 "", false
, "", 1, sendIntent
);
750 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
751 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
752 if (remotePath
.length() > 0) {
753 operation
= new UnshareLinkOperation(
755 OperationsService
.this);
758 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
759 // check OC server and get basic information from it
760 operation
= new GetServerInfoOperation(serverUrl
, OperationsService
.this);
762 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
763 /// GET ACCESS TOKEN to the OAuth server
764 String oauth2QueryParameters
=
765 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
766 operation
= new OAuth2GetAccessToken(
767 getString(R
.string
.oauth2_client_id
),
768 getString(R
.string
.oauth2_redirect_uri
),
769 getString(R
.string
.oauth2_grant_type
),
770 oauth2QueryParameters
);
772 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
774 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
775 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, false
);
776 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
778 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
780 operation
= new GetRemoteUserNameOperation();
782 } else if (action
.equals(ACTION_RENAME
)) {
783 // Rename file or folder
784 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
785 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
786 operation
= new RenameFileOperation(remotePath
, newName
);
788 } else if (action
.equals(ACTION_REMOVE
)) {
789 // Remove file or folder
790 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
791 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
792 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
794 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
796 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
797 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
798 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
800 } else if (action
.equals(ACTION_SYNC_FILE
)) {
802 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
803 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
804 operation
= new SynchronizeFileOperation(
805 remotePath
, account
, syncFileContents
, getApplicationContext()
808 } else if (action
.equals(ACTION_SYNC_FOLDER
)) {
810 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
811 operation
= new SynchronizeFolderOperation(
812 this, // TODO remove this dependency from construction time
815 System
.currentTimeMillis() // TODO remove this dependency from construction time
818 } else if (action
.equals(ACTION_MOVE_FILE
)) {
820 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
821 String newParentPath
= operationIntent
.getStringExtra(EXTRA_NEW_PARENT_PATH
);
822 operation
= new MoveFileOperation(remotePath
,newParentPath
,account
);
827 } catch (IllegalArgumentException e
) {
828 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
832 if (operation
!= null
) {
833 return new Pair
<Target
, RemoteOperation
>(target
, operation
);
841 * Sends a broadcast when a new operation is added to the queue.
843 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
845 * @param target Account or URL pointing to an OC server.
846 * @param operation Added operation.
848 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
849 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
850 if (target
.mAccount
!= null
) {
851 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
853 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
855 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
856 //lbm.sendBroadcast(intent);
857 sendStickyBroadcast(intent
);
861 // TODO - maybe add a notification for real start of operations
864 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
866 * Local broadcasts are only delivered to activities in the same process.
868 * @param target Account or URL pointing to an OC server.
869 * @param operation Finished operation.
870 * @param result Result of the operation.
872 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
873 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
874 intent
.putExtra(EXTRA_RESULT
, result
);
875 if (target
.mAccount
!= null
) {
876 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
878 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
880 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
881 //lbm.sendBroadcast(intent);
882 sendStickyBroadcast(intent
);
887 * Notifies the currently subscribed listeners about the end of an operation.
889 * @param target Account or URL pointing to an OC server.
890 * @param operation Finished operation.
891 * @param result Result of the operation.
893 private void dispatchResultToOperationListeners(
894 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
896 Iterator
<OnRemoteOperationListener
> listeners
= mOperationsBinder
.mBoundListeners
.keySet().iterator();
897 while (listeners
.hasNext()) {
898 final OnRemoteOperationListener listener
= listeners
.next();
899 final Handler handler
= mOperationsBinder
.mBoundListeners
.get(listener
);
900 if (handler
!= null
) {
901 handler
.post(new Runnable() {
904 listener
.onRemoteOperationFinish(operation
, result
);
911 //mOperationResults.put(operation.hashCode(), result);
912 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
913 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
914 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
916 Log_OC
.d(TAG
, "Called " + count
+ " listeners");