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
.R
;
27 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
28 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
29 import com
.owncloud
.android
.lib
.common
.OwnCloudClientFactory
;
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" );
176 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
177 mUndispatchedFinishedOperations
.clear();
178 //Log_OC.wtf(TAG, "onDestroy end" );
184 * Provides a binder object that clients can use to perform actions on the queue of operations,
185 * except the addition of new operations.
188 public IBinder
onBind(Intent intent
) {
189 //Log_OC.wtf(TAG, "onBind" );
195 * Called when ALL the bound clients were unbound.
198 public boolean onUnbind(Intent intent
) {
199 ((OperationsServiceBinder
)mBinder
).clearListeners();
200 return false
; // not accepting rebinding (default behaviour)
205 * Binder to let client components to perform actions on the queue of operations.
207 * It provides by itself the available operations.
209 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
212 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
214 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
215 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
218 * Cancels an operation
222 public void cancel() {
227 public void clearListeners() {
229 mBoundListeners
.clear();
234 * Adds a listener interested in being reported about the end of operations.
236 * @param listener Object to notify about the end of operations.
237 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
239 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
240 synchronized (mBoundListeners
) {
241 mBoundListeners
.put(listener
, callbackHandler
);
247 * Removes a listener from the list of objects interested in the being reported about the end of operations.
249 * @param listener Object to notify about progress of transfer.
251 public void removeOperationListener (OnRemoteOperationListener listener
) {
252 synchronized (mBoundListeners
) {
253 mBoundListeners
.remove(listener
);
259 * TODO - IMPORTANT: update implementation when more operations are moved into the service
261 * @return 'True' when an operation that enforces the user to wait for completion is in process.
263 public boolean isPerformingBlockingOperation() {
264 return (!mPendingOperations
.isEmpty());
269 * Creates and adds to the queue a new operation, as described by operationIntent
271 * @param operationIntent Intent describing a new operation to queue and execute.
272 * @return Identifier of the operation created, or null if failed.
274 public long newOperation(Intent operationIntent
) {
275 RemoteOperation operation
= null
;
276 Target target
= null
;
278 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
279 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
280 Log_OC
.e(TAG
, "Not enough information provided in intent");
283 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
284 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
285 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
286 String webDavUrl
= serverUrl
+ webDavPath
;
287 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
288 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
289 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
290 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
291 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
294 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
295 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
303 String action
= operationIntent
.getAction();
304 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
305 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
306 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
307 if (remotePath
.length() > 0) {
308 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
309 "", false
, "", 1, sendIntent
);
312 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
313 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
314 if (remotePath
.length() > 0) {
315 operation
= new UnshareLinkOperation(
317 OperationsService
.this);
320 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
321 // check OC server and get basic information from it
322 String authTokenType
=
323 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
324 operation
= new GetServerInfoOperation(
325 serverUrl
, authTokenType
, OperationsService
.this);
327 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
328 /// GET ACCESS TOKEN to the OAuth server
329 String oauth2QueryParameters
=
330 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
331 operation
= new OAuth2GetAccessToken(
332 getString(R
.string
.oauth2_client_id
),
333 getString(R
.string
.oauth2_redirect_uri
),
334 getString(R
.string
.oauth2_grant_type
),
335 oauth2QueryParameters
);
337 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
339 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
340 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
341 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
343 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
345 operation
= new GetRemoteUserNameOperation();
347 } else if (action
.equals(ACTION_RENAME
)) {
348 // Rename file or folder
349 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
350 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
351 operation
= new RenameFileOperation(remotePath
, account
, newName
);
353 } else if (action
.equals(ACTION_REMOVE
)) {
354 // Remove file or folder
355 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
356 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
357 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
359 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
361 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
362 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
363 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
365 } else if (action
.equals(ACTION_SYNC_FILE
)) {
367 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
368 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
369 operation
= new SynchronizeFileOperation(remotePath
, account
, syncFileContents
, getApplicationContext());
374 } catch (IllegalArgumentException e
) {
375 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
379 if (operation
!= null
) {
380 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
381 startService(new Intent(OperationsService
.this, OperationsService
.class));
382 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
383 // better id than hash? ; should be good enough by the time being
384 return operation
.hashCode();
387 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
388 return Long
.MAX_VALUE
;
392 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
393 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
394 mUndispatchedFinishedOperations
.remove(operationId
);
395 if (undispatched
!= null
) {
396 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
398 //Log_OC.wtf(TAG, "Sending callback later");
400 if (!mPendingOperations
.isEmpty()) {
405 //Log_OC.wtf(TAG, "Not finished yet");
413 * Operations worker. Performs the pending operations in the order they were requested.
415 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
417 private static class ServiceHandler
extends Handler
{
418 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
419 OperationsService mService
;
420 public ServiceHandler(Looper looper
, OperationsService service
) {
422 if (service
== null
) {
423 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
429 public void handleMessage(Message msg
) {
430 mService
.nextOperation();
431 mService
.stopSelf(msg
.arg1
);
437 * Performs the next operation in the queue
439 private void nextOperation() {
441 //Log_OC.wtf(TAG, "nextOperation init" );
443 Pair
<Target
, RemoteOperation
> next
= null
;
444 synchronized(mPendingOperations
) {
445 next
= mPendingOperations
.peek();
450 mCurrentOperation
= next
.second
;
451 RemoteOperationResult result
= null
;
453 /// prepare client object to send the request to the ownCloud server
454 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
455 mLastTarget
= next
.first
;
456 if (mLastTarget
.mAccount
!= null
) {
458 OwnCloudClientMap
.getClientFor(mLastTarget
.mAccount
, this);
460 new FileDataStorageManager(
461 mLastTarget
.mAccount
,
462 getContentResolver());
464 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
465 mLastTarget
.mFollowRedirects
); // this is not good enough
466 if (mLastTarget
.mWebDavUrl
!= null
) {
467 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
469 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
470 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
471 } else if (mLastTarget
.mAuthToken
!= null
) {
472 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
473 } else if (mLastTarget
.mCookie
!= null
) {
474 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
476 mStorageManager
= null
;
480 /// perform the operation
481 if (mCurrentOperation
instanceof SyncOperation
) {
482 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
484 result
= mCurrentOperation
.execute(mOwnCloudClient
);
487 } catch (AccountsException e
) {
488 if (mLastTarget
.mAccount
== null
) {
489 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
491 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
493 result
= new RemoteOperationResult(e
);
495 } catch (IOException e
) {
496 if (mLastTarget
.mAccount
== null
) {
497 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
499 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
501 result
= new RemoteOperationResult(e
);
502 } catch (Exception e
) {
503 if (mLastTarget
.mAccount
== null
) {
504 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
506 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
508 result
= new RemoteOperationResult(e
);
511 synchronized(mPendingOperations
) {
512 mPendingOperations
.poll();
516 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
517 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
523 * Sends a broadcast when a new operation is added to the queue.
525 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
527 * @param target Account or URL pointing to an OC server.
528 * @param operation Added operation.
530 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
531 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
532 if (target
.mAccount
!= null
) {
533 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
535 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
537 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
538 //lbm.sendBroadcast(intent);
539 sendStickyBroadcast(intent
);
543 // TODO - maybe add a notification for real start of operations
546 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
548 * Local broadcasts are only delivered to activities in the same process.
550 * @param target Account or URL pointing to an OC server.
551 * @param operation Finished operation.
552 * @param result Result of the operation.
554 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
555 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
556 intent
.putExtra(EXTRA_RESULT
, result
);
557 if (target
.mAccount
!= null
) {
558 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
560 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
562 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
563 //lbm.sendBroadcast(intent);
564 sendStickyBroadcast(intent
);
569 * Notifies the currently subscribed listeners about the end of an operation.
571 * @param target Account or URL pointing to an OC server.
572 * @param operation Finished operation.
573 * @param result Result of the operation.
575 private void dispatchResultToOperationListeners(
576 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
578 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
579 while (listeners
.hasNext()) {
580 final OnRemoteOperationListener listener
= listeners
.next();
581 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
582 if (handler
!= null
) {
583 handler
.post(new Runnable() {
586 listener
.onRemoteOperationFinish(operation
, result
);
593 //mOperationResults.put(operation.hashCode(), result);
594 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
595 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
596 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
598 Log_OC
.d(TAG
, "Called " + count
+ " listeners");