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
.Iterator
;
22 import java
.util
.concurrent
.ConcurrentHashMap
;
23 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
24 import java
.util
.concurrent
.ConcurrentMap
;
26 import com
.owncloud
.android
.MainApp
;
27 import com
.owncloud
.android
.R
;
28 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
29 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
30 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
31 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
32 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
33 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
34 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
35 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
36 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
37 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
38 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
39 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
40 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
41 import com
.owncloud
.android
.operations
.CreateShareOperation
;
42 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
43 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
44 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
45 import com
.owncloud
.android
.operations
.RenameFileOperation
;
46 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
47 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
48 import com
.owncloud
.android
.utils
.Log_OC
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountsException
;
52 import android
.accounts
.AuthenticatorException
;
53 import android
.accounts
.OperationCanceledException
;
54 import android
.app
.Service
;
55 import android
.content
.Intent
;
56 import android
.net
.Uri
;
57 import android
.os
.Binder
;
58 import android
.os
.Handler
;
59 import android
.os
.HandlerThread
;
60 import android
.os
.IBinder
;
61 import android
.os
.Looper
;
62 import android
.os
.Message
;
63 import android
.os
.Process
;
64 import android
.util
.Pair
;
66 public class OperationsService
extends Service
{
68 private static final String TAG
= OperationsService
.class.getSimpleName();
70 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
71 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
72 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
73 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
74 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
75 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
76 public static final String EXTRA_NEWNAME
= "NEWNAME";
77 public static final String EXTRA_REMOVE_ONLY_LOCAL
= "REMOVE_LOCAL_COPY";
78 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
79 public static final String EXTRA_SYNC_FILE_CONTENTS
= "SYNC_FILE_CONTENTS";
80 public static final String EXTRA_RESULT
= "RESULT";
82 // TODO review if ALL OF THEM are necessary
83 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
84 public static final String EXTRA_USERNAME
= "USERNAME";
85 public static final String EXTRA_PASSWORD
= "PASSWORD";
86 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
87 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
88 public static final String EXTRA_COOKIE
= "COOKIE";
90 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
91 public static final String ACTION_UNSHARE
= "UNSHARE";
92 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
93 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
94 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
95 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
96 public static final String ACTION_RENAME
= "RENAME";
97 public static final String ACTION_REMOVE
= "REMOVE";
98 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
99 public static final String ACTION_SYNC_FILE
= "SYNC_FILE";
101 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
102 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
104 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
105 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
107 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
108 mUndispatchedFinishedOperations
=
109 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
111 private static class Target
{
112 public Uri mServerUrl
= null
;
113 public Account mAccount
= null
;
114 public String mUsername
= null
;
115 public String mPassword
= null
;
116 public String mAuthToken
= null
;
117 public boolean mFollowRedirects
= true
;
118 public String mCookie
= null
;
120 public Target(Account account
, Uri serverUrl
, String username
, String password
, String authToken
,
121 boolean followRedirects
, String cookie
) {
123 mServerUrl
= serverUrl
;
124 mUsername
= username
;
125 mPassword
= password
;
126 mAuthToken
= authToken
;
127 mFollowRedirects
= followRedirects
;
132 private Looper mServiceLooper
;
133 private ServiceHandler mServiceHandler
;
134 private OperationsServiceBinder mBinder
;
135 private OwnCloudClient mOwnCloudClient
= null
;
136 private Target mLastTarget
= null
;
137 private FileDataStorageManager mStorageManager
;
138 private RemoteOperation mCurrentOperation
= null
;
142 * Service initialization
145 public void onCreate() {
147 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
149 mServiceLooper
= thread
.getLooper();
150 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
151 mBinder
= new OperationsServiceBinder();
156 * Entry point to add a new operation to the queue of operations.
158 * New operations are added calling to startService(), resulting in a call to this method.
159 * This ensures the service will keep on working although the caller activity goes away.
161 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
162 * is taking advantage of it due to time constraints.
165 public int onStartCommand(Intent intent
, int flags
, int startId
) {
166 //Log_OC.wtf(TAG, "onStartCommand init" );
167 Message msg
= mServiceHandler
.obtainMessage();
169 mServiceHandler
.sendMessage(msg
);
170 //Log_OC.wtf(TAG, "onStartCommand end" );
171 return START_NOT_STICKY
;
175 public void onDestroy() {
176 //Log_OC.wtf(TAG, "onDestroy init" );
179 ((MainApp
)getApplicationContext()).getOwnCloudClientManager().
180 saveAllClients(this, MainApp
.getAccountType());
182 // TODO - get rid of these exceptions
183 } catch (AccountNotFoundException e
) {
185 } catch (AuthenticatorException e
) {
187 } catch (OperationCanceledException e
) {
189 } catch (IOException e
) {
193 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
194 mUndispatchedFinishedOperations
.clear();
196 //Log_OC.wtf(TAG, "onDestroy end" );
202 * Provides a binder object that clients can use to perform actions on the queue of operations,
203 * except the addition of new operations.
206 public IBinder
onBind(Intent intent
) {
207 //Log_OC.wtf(TAG, "onBind" );
213 * Called when ALL the bound clients were unbound.
216 public boolean onUnbind(Intent intent
) {
217 ((OperationsServiceBinder
)mBinder
).clearListeners();
218 return false
; // not accepting rebinding (default behaviour)
223 * Binder to let client components to perform actions on the queue of operations.
225 * It provides by itself the available operations.
227 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
230 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
232 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
233 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
236 * Cancels an operation
240 public void cancel() {
245 public void clearListeners() {
247 mBoundListeners
.clear();
252 * Adds a listener interested in being reported about the end of operations.
254 * @param listener Object to notify about the end of operations.
255 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
257 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
258 synchronized (mBoundListeners
) {
259 mBoundListeners
.put(listener
, callbackHandler
);
265 * Removes a listener from the list of objects interested in the being reported about the end of operations.
267 * @param listener Object to notify about progress of transfer.
269 public void removeOperationListener (OnRemoteOperationListener listener
) {
270 synchronized (mBoundListeners
) {
271 mBoundListeners
.remove(listener
);
277 * TODO - IMPORTANT: update implementation when more operations are moved into the service
279 * @return 'True' when an operation that enforces the user to wait for completion is in process.
281 public boolean isPerformingBlockingOperation() {
282 return (!mPendingOperations
.isEmpty());
287 * Creates and adds to the queue a new operation, as described by operationIntent
289 * @param operationIntent Intent describing a new operation to queue and execute.
290 * @return Identifier of the operation created, or null if failed.
292 public long newOperation(Intent operationIntent
) {
293 RemoteOperation operation
= null
;
294 Target target
= null
;
296 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
297 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
298 Log_OC
.e(TAG
, "Not enough information provided in intent");
301 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
302 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
303 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
304 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
305 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
306 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
307 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
310 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
318 String action
= operationIntent
.getAction();
319 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
320 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
321 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
322 if (remotePath
.length() > 0) {
323 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
324 "", false
, "", 1, sendIntent
);
327 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
328 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
329 if (remotePath
.length() > 0) {
330 operation
= new UnshareLinkOperation(
332 OperationsService
.this);
335 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
336 // check OC server and get basic information from it
337 String authTokenType
=
338 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
339 operation
= new GetServerInfoOperation(
340 serverUrl
, authTokenType
, OperationsService
.this);
342 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
343 /// GET ACCESS TOKEN to the OAuth server
344 String oauth2QueryParameters
=
345 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
346 operation
= new OAuth2GetAccessToken(
347 getString(R
.string
.oauth2_client_id
),
348 getString(R
.string
.oauth2_redirect_uri
),
349 getString(R
.string
.oauth2_grant_type
),
350 oauth2QueryParameters
);
352 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
354 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
355 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
356 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
358 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
360 operation
= new GetRemoteUserNameOperation();
362 } else if (action
.equals(ACTION_RENAME
)) {
363 // Rename file or folder
364 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
365 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
366 operation
= new RenameFileOperation(remotePath
, account
, newName
);
368 } else if (action
.equals(ACTION_REMOVE
)) {
369 // Remove file or folder
370 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
371 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
372 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
374 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
376 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
377 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
378 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
380 } else if (action
.equals(ACTION_SYNC_FILE
)) {
382 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
383 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
384 operation
= new SynchronizeFileOperation(remotePath
, account
, syncFileContents
, getApplicationContext());
389 } catch (IllegalArgumentException e
) {
390 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
394 if (operation
!= null
) {
395 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
396 startService(new Intent(OperationsService
.this, OperationsService
.class));
397 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
398 // better id than hash? ; should be good enough by the time being
399 return operation
.hashCode();
402 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
403 return Long
.MAX_VALUE
;
407 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
408 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
409 mUndispatchedFinishedOperations
.remove(operationId
);
410 if (undispatched
!= null
) {
411 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
413 //Log_OC.wtf(TAG, "Sending callback later");
415 if (!mPendingOperations
.isEmpty()) {
420 //Log_OC.wtf(TAG, "Not finished yet");
428 * Operations worker. Performs the pending operations in the order they were requested.
430 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
432 private static class ServiceHandler
extends Handler
{
433 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
434 OperationsService mService
;
435 public ServiceHandler(Looper looper
, OperationsService service
) {
437 if (service
== null
) {
438 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
444 public void handleMessage(Message msg
) {
445 mService
.nextOperation();
446 mService
.stopSelf(msg
.arg1
);
452 * Performs the next operation in the queue
454 private void nextOperation() {
456 //Log_OC.wtf(TAG, "nextOperation init" );
458 Pair
<Target
, RemoteOperation
> next
= null
;
459 synchronized(mPendingOperations
) {
460 next
= mPendingOperations
.peek();
465 mCurrentOperation
= next
.second
;
466 RemoteOperationResult result
= null
;
468 /// prepare client object to send the request to the ownCloud server
469 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
470 mLastTarget
= next
.first
;
471 if (mLastTarget
.mAccount
!= null
) {
472 mOwnCloudClient
= ((MainApp
)getApplicationContext()).
473 getOwnCloudClientManager().getClientFor(
474 mLastTarget
.mAccount
,
477 new FileDataStorageManager(
478 mLastTarget
.mAccount
,
479 getContentResolver());
481 OwnCloudCredentials credentials
= null
;
482 if (mLastTarget
.mUsername
!= null
) {
483 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(
484 mLastTarget
.mUsername
,
485 mLastTarget
.mPassword
); // basic
487 } else if (mLastTarget
.mAuthToken
!= null
) {
488 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
489 mLastTarget
.mAuthToken
); // bearer token
491 } else if (mLastTarget
.mCookie
!= null
) {
492 credentials
= OwnCloudCredentialsFactory
.newSamlSsoCredentials(
493 mLastTarget
.mCookie
); // SAML SSO
496 mOwnCloudClient
= ((MainApp
)getApplicationContext()).
497 getOwnCloudClientManager().getClientFor(
498 mLastTarget
.mServerUrl
,
499 credentials
, // still can be null, and that is right
501 mOwnCloudClient
.setFollowRedirects(mLastTarget
.mFollowRedirects
);
502 mStorageManager
= null
;
506 /// perform the operation
507 if (mCurrentOperation
instanceof SyncOperation
) {
508 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
510 result
= mCurrentOperation
.execute(mOwnCloudClient
);
513 } catch (AccountsException e
) {
514 if (mLastTarget
.mAccount
== null
) {
515 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
517 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
519 result
= new RemoteOperationResult(e
);
521 } catch (IOException e
) {
522 if (mLastTarget
.mAccount
== null
) {
523 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
525 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
527 result
= new RemoteOperationResult(e
);
528 } catch (Exception e
) {
529 if (mLastTarget
.mAccount
== null
) {
530 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
532 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
534 result
= new RemoteOperationResult(e
);
537 synchronized(mPendingOperations
) {
538 mPendingOperations
.poll();
542 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
543 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
549 * Sends a broadcast when a new operation is added to the queue.
551 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
553 * @param target Account or URL pointing to an OC server.
554 * @param operation Added operation.
556 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
557 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
558 if (target
.mAccount
!= null
) {
559 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
561 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
563 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
564 //lbm.sendBroadcast(intent);
565 sendStickyBroadcast(intent
);
569 // TODO - maybe add a notification for real start of operations
572 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
574 * Local broadcasts are only delivered to activities in the same process.
576 * @param target Account or URL pointing to an OC server.
577 * @param operation Finished operation.
578 * @param result Result of the operation.
580 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
581 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
582 intent
.putExtra(EXTRA_RESULT
, result
);
583 if (target
.mAccount
!= null
) {
584 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
586 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
588 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
589 //lbm.sendBroadcast(intent);
590 sendStickyBroadcast(intent
);
595 * Notifies the currently subscribed listeners about the end of an operation.
597 * @param target Account or URL pointing to an OC server.
598 * @param operation Finished operation.
599 * @param result Result of the operation.
601 private void dispatchResultToOperationListeners(
602 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
604 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
605 while (listeners
.hasNext()) {
606 final OnRemoteOperationListener listener
= listeners
.next();
607 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
608 if (handler
!= null
) {
609 handler
.post(new Runnable() {
612 listener
.onRemoteOperationFinish(operation
, result
);
619 //mOperationResults.put(operation.hashCode(), result);
620 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
621 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
622 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
624 Log_OC
.d(TAG
, "Called " + count
+ " listeners");