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
.OwnCloudClientFactory
;
29 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
30 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
31 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
32 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
33 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
34 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
35 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
36 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
37 import com
.owncloud
.android
.operations
.CreateShareOperation
;
38 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
39 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
40 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
41 import com
.owncloud
.android
.operations
.RenameFileOperation
;
42 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
43 import com
.owncloud
.android
.utils
.Log_OC
;
45 import android
.accounts
.Account
;
46 import android
.accounts
.AccountsException
;
47 import android
.app
.Service
;
48 import android
.content
.Intent
;
49 import android
.net
.Uri
;
50 import android
.os
.Binder
;
51 import android
.os
.Handler
;
52 import android
.os
.HandlerThread
;
53 import android
.os
.IBinder
;
54 import android
.os
.Looper
;
55 import android
.os
.Message
;
56 import android
.os
.Process
;
57 import android
.util
.Pair
;
59 public class OperationsService
extends Service
{
61 private static final String TAG
= OperationsService
.class.getSimpleName();
63 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
64 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
65 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
66 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
67 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
68 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
69 public static final String EXTRA_NEWNAME
= "NEWNAME";
70 public static final String EXTRA_REMOVE_LOCAL_COPY
= "REMOVE_LOCAL_COPY";
71 public static final String EXTRA_RESULT
= "RESULT";
73 // TODO review if ALL OF THEM are necessary
74 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
75 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
76 public static final String EXTRA_USERNAME
= "USERNAME";
77 public static final String EXTRA_PASSWORD
= "PASSWORD";
78 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
79 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
80 public static final String EXTRA_COOKIE
= "COOKIE";
82 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
83 public static final String ACTION_UNSHARE
= "UNSHARE";
84 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
85 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
86 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
87 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
88 public static final String ACTION_RENAME
= "RENAME";
89 public static final String ACTION_REMOVE
= "REMOVE";
91 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
92 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
94 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
95 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
98 private ConcurrentMap<Integer, RemoteOperationResult> mOperationResults =
99 new ConcurrentHashMap<Integer, RemoteOperationResult>();
102 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
103 mUndispatchedFinishedOperations
=
104 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
106 private static class Target
{
107 public Uri mServerUrl
= null
;
108 public Account mAccount
= null
;
109 public String mWebDavUrl
= null
;
110 public String mUsername
= null
;
111 public String mPassword
= null
;
112 public String mAuthToken
= null
;
113 public boolean mFollowRedirects
= true
;
114 public String mCookie
= null
;
116 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
117 boolean followRedirects
, String cookie
) {
119 mServerUrl
= serverUrl
;
120 mWebDavUrl
= webdavUrl
;
121 mUsername
= username
;
122 mPassword
= password
;
123 mAuthToken
= authToken
;
124 mFollowRedirects
= followRedirects
;
129 private Looper mServiceLooper
;
130 private ServiceHandler mServiceHandler
;
131 private OperationsServiceBinder mBinder
;
132 private OwnCloudClient mOwnCloudClient
= null
;
133 private Target mLastTarget
= null
;
134 private FileDataStorageManager mStorageManager
;
135 private RemoteOperation mCurrentOperation
= null
;
139 * Service initialization
142 public void onCreate() {
144 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
146 mServiceLooper
= thread
.getLooper();
147 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
148 mBinder
= new OperationsServiceBinder();
153 * Entry point to add a new operation to the queue of operations.
155 * New operations are added calling to startService(), resulting in a call to this method.
156 * This ensures the service will keep on working although the caller activity goes away.
158 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
159 * is taking advantage of it due to time constraints.
162 public int onStartCommand(Intent intent
, int flags
, int startId
) {
163 //Log_OC.wtf(TAG, "onStartCommand init" );
164 Message msg
= mServiceHandler
.obtainMessage();
166 mServiceHandler
.sendMessage(msg
);
167 //Log_OC.wtf(TAG, "onStartCommand end" );
168 return START_NOT_STICKY
;
172 public void onDestroy() {
173 //Log_OC.wtf(TAG, "onDestroy init" );
175 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
176 mUndispatchedFinishedOperations
.clear();
177 //Log_OC.wtf(TAG, "onDestroy end" );
182 * Provides a binder object that clients can use to perform actions on the queue of operations,
183 * except the addition of new operations.
186 public IBinder
onBind(Intent intent
) {
187 //Log_OC.wtf(TAG, "onBind" );
193 * Called when ALL the bound clients were unbound.
196 public boolean onUnbind(Intent intent
) {
197 ((OperationsServiceBinder
)mBinder
).clearListeners();
198 return false
; // not accepting rebinding (default behaviour)
203 * Binder to let client components to perform actions on the queue of operations.
205 * It provides by itself the available operations.
207 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
210 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
212 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
213 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
216 * Cancels an operation
220 public void cancel() {
225 public void clearListeners() {
227 mBoundListeners
.clear();
232 * Adds a listener interested in being reported about the end of operations.
234 * @param listener Object to notify about the end of operations.
235 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
237 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
238 synchronized (mBoundListeners
) {
239 mBoundListeners
.put(listener
, callbackHandler
);
245 * Removes a listener from the list of objects interested in the being reported about the end of operations.
247 * @param listener Object to notify about progress of transfer.
249 public void removeOperationListener (OnRemoteOperationListener listener
) {
250 synchronized (mBoundListeners
) {
251 mBoundListeners
.remove(listener
);
257 * TODO - IMPORTANT: update implementation when more operations are moved into the service
259 * @return 'True' when an operation that enforces the user to wait for completion is in process.
261 public boolean isPerformingBlockingOperation() {
262 return (!mPendingOperations
.isEmpty());
267 * Creates and adds to the queue a new operation, as described by operationIntent
269 * @param operationIntent Intent describing a new operation to queue and execute.
270 * @return Identifier of the operation created, or null if failed.
272 public long newOperation(Intent operationIntent
) {
273 RemoteOperation operation
= null
;
274 Target target
= null
;
276 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
277 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
278 Log_OC
.e(TAG
, "Not enough information provided in intent");
281 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
282 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
283 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
284 String webDavUrl
= serverUrl
+ webDavPath
;
285 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
286 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
287 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
288 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
289 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
292 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
293 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
301 String action
= operationIntent
.getAction();
302 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
303 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
304 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
305 if (remotePath
.length() > 0) {
306 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
307 "", false
, "", 1, sendIntent
);
310 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
311 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
312 if (remotePath
.length() > 0) {
313 operation
= new UnshareLinkOperation(
315 OperationsService
.this);
318 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
319 // check OC server and get basic information from it
320 String authTokenType
=
321 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
322 operation
= new GetServerInfoOperation(
323 serverUrl
, authTokenType
, OperationsService
.this);
325 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
326 /// GET ACCESS TOKEN to the OAuth server
327 String oauth2QueryParameters
=
328 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
329 operation
= new OAuth2GetAccessToken(
330 getString(R
.string
.oauth2_client_id
),
331 getString(R
.string
.oauth2_redirect_uri
),
332 getString(R
.string
.oauth2_grant_type
),
333 oauth2QueryParameters
);
335 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
337 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
338 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
339 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
341 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
343 operation
= new GetRemoteUserNameOperation();
345 } else if (action
.equals(ACTION_RENAME
)) {
346 // Rename file or folder
347 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
348 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
349 operation
= new RenameFileOperation(remotePath
, account
, newName
);
351 } else if (action
.equals(ACTION_REMOVE
)) {
352 // Remove file or folder
353 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
354 boolean removeLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_LOCAL_COPY
, true
);
355 operation
= new RemoveFileOperation(remotePath
, removeLocalCopy
);
359 } catch (IllegalArgumentException e
) {
360 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
364 if (operation
!= null
) {
365 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
366 startService(new Intent(OperationsService
.this, OperationsService
.class));
367 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
368 // better id than hash? ; should be good enough by the time being
369 return operation
.hashCode();
372 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
373 return Long
.MAX_VALUE
;
377 public void dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
378 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
379 mUndispatchedFinishedOperations
.remove(operationId
);
380 if (undispatched
!= null
) {
381 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
382 //Log_OC.wtf(TAG, "Sending callback later");
384 //Log_OC.wtf(TAG, "Not finished yet");
392 * Operations 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 ServiceHandler
extends Handler
{
397 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
398 OperationsService mService
;
399 public ServiceHandler(Looper looper
, OperationsService service
) {
401 if (service
== null
) {
402 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
408 public void handleMessage(Message msg
) {
409 mService
.nextOperation();
410 mService
.stopSelf(msg
.arg1
);
416 * Performs the next operation in the queue
418 private void nextOperation() {
420 //Log_OC.wtf(TAG, "nextOperation init" );
422 Pair
<Target
, RemoteOperation
> next
= null
;
423 synchronized(mPendingOperations
) {
424 next
= mPendingOperations
.peek();
429 mCurrentOperation
= next
.second
;
430 RemoteOperationResult result
= null
;
432 /// prepare client object to send the request to the ownCloud server
433 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
434 mLastTarget
= next
.first
;
435 if (mLastTarget
.mAccount
!= null
) {
436 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
437 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
439 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
440 mLastTarget
.mFollowRedirects
); // this is not good enough
441 if (mLastTarget
.mWebDavUrl
!= null
) {
442 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
444 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
445 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
446 } else if (mLastTarget
.mAuthToken
!= null
) {
447 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
448 } else if (mLastTarget
.mCookie
!= null
) {
449 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
451 mStorageManager
= null
;
455 /// perform the operation
456 if (mCurrentOperation
instanceof SyncOperation
) {
457 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
459 result
= mCurrentOperation
.execute(mOwnCloudClient
);
462 } catch (AccountsException e
) {
463 if (mLastTarget
.mAccount
== null
) {
464 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
466 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
468 result
= new RemoteOperationResult(e
);
470 } catch (IOException e
) {
471 if (mLastTarget
.mAccount
== null
) {
472 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
474 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
476 result
= new RemoteOperationResult(e
);
477 } catch (Exception e
) {
478 if (mLastTarget
.mAccount
== null
) {
479 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
481 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
483 result
= new RemoteOperationResult(e
);
486 synchronized(mPendingOperations
) {
487 mPendingOperations
.poll();
491 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
492 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
498 * Sends a broadcast when a new operation is added to the queue.
500 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
502 * @param target Account or URL pointing to an OC server.
503 * @param operation Added operation.
505 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
506 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
507 if (target
.mAccount
!= null
) {
508 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
510 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
512 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
513 //lbm.sendBroadcast(intent);
514 sendStickyBroadcast(intent
);
518 // TODO - maybe add a notification for real start of operations
521 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
523 * Local broadcasts are only delivered to activities in the same process.
525 * @param target Account or URL pointing to an OC server.
526 * @param operation Finished operation.
527 * @param result Result of the operation.
529 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
530 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
531 intent
.putExtra(EXTRA_RESULT
, result
);
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
);
544 * Notifies the currently subscribed listeners about the end of an operation.
546 * @param target Account or URL pointing to an OC server.
547 * @param operation Finished operation.
548 * @param result Result of the operation.
550 private void dispatchResultToOperationListeners(
551 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
553 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
554 while (listeners
.hasNext()) {
555 final OnRemoteOperationListener listener
= listeners
.next();
556 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
557 if (handler
!= null
) {
558 handler
.post(new Runnable() {
561 listener
.onRemoteOperationFinish(operation
, result
);
568 //mOperationResults.put(operation.hashCode(), result);
569 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
570 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
571 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
573 Log_OC
.d(TAG
, "Called " + count
+ " listeners");