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
.OwnCloudClientMap
;
31 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
32 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
33 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
34 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
35 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
36 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
37 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
38 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
39 import com
.owncloud
.android
.operations
.CreateShareOperation
;
40 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
41 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
42 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
43 import com
.owncloud
.android
.operations
.RenameFileOperation
;
44 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
45 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
46 import com
.owncloud
.android
.utils
.Log_OC
;
48 import android
.accounts
.Account
;
49 import android
.accounts
.AccountsException
;
50 import android
.app
.Service
;
51 import android
.content
.Intent
;
52 import android
.net
.Uri
;
53 import android
.os
.Binder
;
54 import android
.os
.Handler
;
55 import android
.os
.HandlerThread
;
56 import android
.os
.IBinder
;
57 import android
.os
.Looper
;
58 import android
.os
.Message
;
59 import android
.os
.Process
;
60 import android
.util
.Pair
;
62 public class OperationsService
extends Service
{
64 private static final String TAG
= OperationsService
.class.getSimpleName();
66 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
67 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
68 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
69 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
70 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
71 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
72 public static final String EXTRA_NEWNAME
= "NEWNAME";
73 public static final String EXTRA_REMOVE_ONLY_LOCAL
= "REMOVE_LOCAL_COPY";
74 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
75 public static final String EXTRA_SYNC_FILE_CONTENTS
= "SYNC_FILE_CONTENTS";
76 public static final String EXTRA_RESULT
= "RESULT";
78 // TODO review if ALL OF THEM are necessary
79 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
80 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
81 public static final String EXTRA_USERNAME
= "USERNAME";
82 public static final String EXTRA_PASSWORD
= "PASSWORD";
83 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
84 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
85 public static final String EXTRA_COOKIE
= "COOKIE";
87 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
88 public static final String ACTION_UNSHARE
= "UNSHARE";
89 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
90 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
91 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
92 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
93 public static final String ACTION_RENAME
= "RENAME";
94 public static final String ACTION_REMOVE
= "REMOVE";
95 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
96 public static final String ACTION_SYNC_FILE
= "SYNC_FILE";
98 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
99 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
101 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
102 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
104 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
105 mUndispatchedFinishedOperations
=
106 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
108 private static class Target
{
109 public Uri mServerUrl
= null
;
110 public Account mAccount
= null
;
111 public String mWebDavUrl
= null
;
112 public String mUsername
= null
;
113 public String mPassword
= null
;
114 public String mAuthToken
= null
;
115 public boolean mFollowRedirects
= true
;
116 public String mCookie
= null
;
118 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
119 boolean followRedirects
, String cookie
) {
121 mServerUrl
= serverUrl
;
122 mWebDavUrl
= webdavUrl
;
123 mUsername
= username
;
124 mPassword
= password
;
125 mAuthToken
= authToken
;
126 mFollowRedirects
= followRedirects
;
131 private Looper mServiceLooper
;
132 private ServiceHandler mServiceHandler
;
133 private OperationsServiceBinder mBinder
;
134 private OwnCloudClient mOwnCloudClient
= null
;
135 private Target mLastTarget
= null
;
136 private FileDataStorageManager mStorageManager
;
137 private RemoteOperation mCurrentOperation
= null
;
141 * Service initialization
144 public void onCreate() {
146 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
148 mServiceLooper
= thread
.getLooper();
149 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
150 mBinder
= new OperationsServiceBinder();
155 * Entry point to add a new operation to the queue of operations.
157 * New operations are added calling to startService(), resulting in a call to this method.
158 * This ensures the service will keep on working although the caller activity goes away.
160 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
161 * is taking advantage of it due to time constraints.
164 public int onStartCommand(Intent intent
, int flags
, int startId
) {
165 //Log_OC.wtf(TAG, "onStartCommand init" );
166 Message msg
= mServiceHandler
.obtainMessage();
168 mServiceHandler
.sendMessage(msg
);
169 //Log_OC.wtf(TAG, "onStartCommand end" );
170 return START_NOT_STICKY
;
174 public void onDestroy() {
175 //Log_OC.wtf(TAG, "onDestroy init" );
177 OwnCloudClientMap
.saveAllClients(this, MainApp
.getAccountType());
179 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
180 mUndispatchedFinishedOperations
.clear();
182 //Log_OC.wtf(TAG, "onDestroy end" );
188 * Provides a binder object that clients can use to perform actions on the queue of operations,
189 * except the addition of new operations.
192 public IBinder
onBind(Intent intent
) {
193 //Log_OC.wtf(TAG, "onBind" );
199 * Called when ALL the bound clients were unbound.
202 public boolean onUnbind(Intent intent
) {
203 ((OperationsServiceBinder
)mBinder
).clearListeners();
204 return false
; // not accepting rebinding (default behaviour)
209 * Binder to let client components to perform actions on the queue of operations.
211 * It provides by itself the available operations.
213 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
216 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
218 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
219 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
222 * Cancels an operation
226 public void cancel() {
231 public void clearListeners() {
233 mBoundListeners
.clear();
238 * Adds a listener interested in being reported about the end of operations.
240 * @param listener Object to notify about the end of operations.
241 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
243 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
244 synchronized (mBoundListeners
) {
245 mBoundListeners
.put(listener
, callbackHandler
);
251 * Removes a listener from the list of objects interested in the being reported about the end of operations.
253 * @param listener Object to notify about progress of transfer.
255 public void removeOperationListener (OnRemoteOperationListener listener
) {
256 synchronized (mBoundListeners
) {
257 mBoundListeners
.remove(listener
);
263 * TODO - IMPORTANT: update implementation when more operations are moved into the service
265 * @return 'True' when an operation that enforces the user to wait for completion is in process.
267 public boolean isPerformingBlockingOperation() {
268 return (!mPendingOperations
.isEmpty());
273 * Creates and adds to the queue a new operation, as described by operationIntent
275 * @param operationIntent Intent describing a new operation to queue and execute.
276 * @return Identifier of the operation created, or null if failed.
278 public long newOperation(Intent operationIntent
) {
279 RemoteOperation operation
= null
;
280 Target target
= null
;
282 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
283 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
284 Log_OC
.e(TAG
, "Not enough information provided in intent");
287 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
288 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
289 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
290 String webDavUrl
= serverUrl
+ webDavPath
;
291 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
292 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
293 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
294 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
295 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
298 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
299 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
307 String action
= operationIntent
.getAction();
308 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
309 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
310 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
311 if (remotePath
.length() > 0) {
312 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
313 "", false
, "", 1, sendIntent
);
316 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
317 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
318 if (remotePath
.length() > 0) {
319 operation
= new UnshareLinkOperation(
321 OperationsService
.this);
324 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
325 // check OC server and get basic information from it
326 String authTokenType
=
327 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
328 operation
= new GetServerInfoOperation(
329 serverUrl
, authTokenType
, OperationsService
.this);
331 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
332 /// GET ACCESS TOKEN to the OAuth server
333 String oauth2QueryParameters
=
334 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
335 operation
= new OAuth2GetAccessToken(
336 getString(R
.string
.oauth2_client_id
),
337 getString(R
.string
.oauth2_redirect_uri
),
338 getString(R
.string
.oauth2_grant_type
),
339 oauth2QueryParameters
);
341 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
343 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
344 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
345 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
347 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
349 operation
= new GetRemoteUserNameOperation();
351 } else if (action
.equals(ACTION_RENAME
)) {
352 // Rename file or folder
353 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
354 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
355 operation
= new RenameFileOperation(remotePath
, account
, newName
);
357 } else if (action
.equals(ACTION_REMOVE
)) {
358 // Remove file or folder
359 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
360 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
361 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
363 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
365 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
366 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
367 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
369 } else if (action
.equals(ACTION_SYNC_FILE
)) {
371 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
372 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
373 operation
= new SynchronizeFileOperation(remotePath
, account
, syncFileContents
, getApplicationContext());
378 } catch (IllegalArgumentException e
) {
379 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
383 if (operation
!= null
) {
384 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
385 startService(new Intent(OperationsService
.this, OperationsService
.class));
386 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
387 // better id than hash? ; should be good enough by the time being
388 return operation
.hashCode();
391 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
392 return Long
.MAX_VALUE
;
396 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
397 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
398 mUndispatchedFinishedOperations
.remove(operationId
);
399 if (undispatched
!= null
) {
400 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
402 //Log_OC.wtf(TAG, "Sending callback later");
404 if (!mPendingOperations
.isEmpty()) {
409 //Log_OC.wtf(TAG, "Not finished yet");
417 * Operations worker. Performs the pending operations in the order they were requested.
419 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
421 private static class ServiceHandler
extends Handler
{
422 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
423 OperationsService mService
;
424 public ServiceHandler(Looper looper
, OperationsService service
) {
426 if (service
== null
) {
427 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
433 public void handleMessage(Message msg
) {
434 mService
.nextOperation();
435 mService
.stopSelf(msg
.arg1
);
441 * Performs the next operation in the queue
443 private void nextOperation() {
445 //Log_OC.wtf(TAG, "nextOperation init" );
447 Pair
<Target
, RemoteOperation
> next
= null
;
448 synchronized(mPendingOperations
) {
449 next
= mPendingOperations
.peek();
454 mCurrentOperation
= next
.second
;
455 RemoteOperationResult result
= null
;
457 /// prepare client object to send the request to the ownCloud server
458 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
459 mLastTarget
= next
.first
;
460 if (mLastTarget
.mAccount
!= null
) {
462 OwnCloudClientMap
.getClientFor(mLastTarget
.mAccount
, this);
464 new FileDataStorageManager(
465 mLastTarget
.mAccount
,
466 getContentResolver());
468 mOwnCloudClient
= OwnCloudClientMap
.getAnonymousClientFor(
469 mLastTarget
.mServerUrl
,
471 mLastTarget
.mFollowRedirects
);
473 if (mLastTarget
.mWebDavUrl
!= null
) {
474 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
476 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
477 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
478 } else if (mLastTarget
.mAuthToken
!= null
) {
479 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
480 } else if (mLastTarget
.mCookie
!= null
) {
481 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
483 mStorageManager
= null
;
487 /// perform the operation
488 if (mCurrentOperation
instanceof SyncOperation
) {
489 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
491 result
= mCurrentOperation
.execute(mOwnCloudClient
);
494 } catch (AccountsException e
) {
495 if (mLastTarget
.mAccount
== null
) {
496 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
498 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
500 result
= new RemoteOperationResult(e
);
502 } catch (IOException e
) {
503 if (mLastTarget
.mAccount
== null
) {
504 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
506 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
508 result
= new RemoteOperationResult(e
);
509 } catch (Exception e
) {
510 if (mLastTarget
.mAccount
== null
) {
511 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
513 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
515 result
= new RemoteOperationResult(e
);
518 synchronized(mPendingOperations
) {
519 mPendingOperations
.poll();
523 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
524 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
530 * Sends a broadcast when a new operation is added to the queue.
532 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
534 * @param target Account or URL pointing to an OC server.
535 * @param operation Added operation.
537 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
538 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
539 if (target
.mAccount
!= null
) {
540 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
542 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
544 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
545 //lbm.sendBroadcast(intent);
546 sendStickyBroadcast(intent
);
550 // TODO - maybe add a notification for real start of operations
553 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
555 * Local broadcasts are only delivered to activities in the same process.
557 * @param target Account or URL pointing to an OC server.
558 * @param operation Finished operation.
559 * @param result Result of the operation.
561 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
562 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
563 intent
.putExtra(EXTRA_RESULT
, result
);
564 if (target
.mAccount
!= null
) {
565 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
567 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
569 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
570 //lbm.sendBroadcast(intent);
571 sendStickyBroadcast(intent
);
576 * Notifies the currently subscribed listeners about the end of an operation.
578 * @param target Account or URL pointing to an OC server.
579 * @param operation Finished operation.
580 * @param result Result of the operation.
582 private void dispatchResultToOperationListeners(
583 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
585 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
586 while (listeners
.hasNext()) {
587 final OnRemoteOperationListener listener
= listeners
.next();
588 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
589 if (handler
!= null
) {
590 handler
.post(new Runnable() {
593 listener
.onRemoteOperationFinish(operation
, result
);
600 //mOperationResults.put(operation.hashCode(), result);
601 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
602 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
603 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
605 Log_OC
.d(TAG
, "Called " + count
+ " listeners");