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
.CreateFolderOperation
;
38 import com
.owncloud
.android
.operations
.CreateShareOperation
;
39 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
40 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
41 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
42 import com
.owncloud
.android
.operations
.RenameFileOperation
;
43 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
44 import com
.owncloud
.android
.utils
.Log_OC
;
46 import android
.accounts
.Account
;
47 import android
.accounts
.AccountsException
;
48 import android
.app
.Service
;
49 import android
.content
.Intent
;
50 import android
.net
.Uri
;
51 import android
.os
.Binder
;
52 import android
.os
.Handler
;
53 import android
.os
.HandlerThread
;
54 import android
.os
.IBinder
;
55 import android
.os
.Looper
;
56 import android
.os
.Message
;
57 import android
.os
.Process
;
58 import android
.util
.Pair
;
60 public class OperationsService
extends Service
{
62 private static final String TAG
= OperationsService
.class.getSimpleName();
64 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
65 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
66 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
67 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
68 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
69 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
70 public static final String EXTRA_NEWNAME
= "NEWNAME";
71 public static final String EXTRA_REMOVE_LOCAL_COPY
= "REMOVE_LOCAL_COPY";
72 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
73 public static final String EXTRA_RESULT
= "RESULT";
75 // TODO review if ALL OF THEM are necessary
76 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
77 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
78 public static final String EXTRA_USERNAME
= "USERNAME";
79 public static final String EXTRA_PASSWORD
= "PASSWORD";
80 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
81 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
82 public static final String EXTRA_COOKIE
= "COOKIE";
84 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
85 public static final String ACTION_UNSHARE
= "UNSHARE";
86 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
87 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
88 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
89 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
90 public static final String ACTION_RENAME
= "RENAME";
91 public static final String ACTION_REMOVE
= "REMOVE";
92 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
94 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
95 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
97 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
98 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
100 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
101 mUndispatchedFinishedOperations
=
102 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
104 private static class Target
{
105 public Uri mServerUrl
= null
;
106 public Account mAccount
= null
;
107 public String mWebDavUrl
= null
;
108 public String mUsername
= null
;
109 public String mPassword
= null
;
110 public String mAuthToken
= null
;
111 public boolean mFollowRedirects
= true
;
112 public String mCookie
= null
;
114 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
115 boolean followRedirects
, String cookie
) {
117 mServerUrl
= serverUrl
;
118 mWebDavUrl
= webdavUrl
;
119 mUsername
= username
;
120 mPassword
= password
;
121 mAuthToken
= authToken
;
122 mFollowRedirects
= followRedirects
;
127 private Looper mServiceLooper
;
128 private ServiceHandler mServiceHandler
;
129 private OperationsServiceBinder mBinder
;
130 private OwnCloudClient mOwnCloudClient
= null
;
131 private Target mLastTarget
= null
;
132 private FileDataStorageManager mStorageManager
;
133 private RemoteOperation mCurrentOperation
= null
;
137 * Service initialization
140 public void onCreate() {
142 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
144 mServiceLooper
= thread
.getLooper();
145 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
146 mBinder
= new OperationsServiceBinder();
151 * Entry point to add a new operation to the queue of operations.
153 * New operations are added calling to startService(), resulting in a call to this method.
154 * This ensures the service will keep on working although the caller activity goes away.
156 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
157 * is taking advantage of it due to time constraints.
160 public int onStartCommand(Intent intent
, int flags
, int startId
) {
161 //Log_OC.wtf(TAG, "onStartCommand init" );
162 Message msg
= mServiceHandler
.obtainMessage();
164 mServiceHandler
.sendMessage(msg
);
165 //Log_OC.wtf(TAG, "onStartCommand end" );
166 return START_NOT_STICKY
;
170 public void onDestroy() {
171 //Log_OC.wtf(TAG, "onDestroy init" );
173 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
174 mUndispatchedFinishedOperations
.clear();
175 //Log_OC.wtf(TAG, "onDestroy end" );
180 * Provides a binder object that clients can use to perform actions on the queue of operations,
181 * except the addition of new operations.
184 public IBinder
onBind(Intent intent
) {
185 //Log_OC.wtf(TAG, "onBind" );
191 * Called when ALL the bound clients were unbound.
194 public boolean onUnbind(Intent intent
) {
195 ((OperationsServiceBinder
)mBinder
).clearListeners();
196 return false
; // not accepting rebinding (default behaviour)
201 * Binder to let client components to perform actions on the queue of operations.
203 * It provides by itself the available operations.
205 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
208 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
210 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
211 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
214 * Cancels an operation
218 public void cancel() {
223 public void clearListeners() {
225 mBoundListeners
.clear();
230 * Adds a listener interested in being reported about the end of operations.
232 * @param listener Object to notify about the end of operations.
233 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
235 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
236 synchronized (mBoundListeners
) {
237 mBoundListeners
.put(listener
, callbackHandler
);
243 * Removes a listener from the list of objects interested in the being reported about the end of operations.
245 * @param listener Object to notify about progress of transfer.
247 public void removeOperationListener (OnRemoteOperationListener listener
) {
248 synchronized (mBoundListeners
) {
249 mBoundListeners
.remove(listener
);
255 * TODO - IMPORTANT: update implementation when more operations are moved into the service
257 * @return 'True' when an operation that enforces the user to wait for completion is in process.
259 public boolean isPerformingBlockingOperation() {
260 return (!mPendingOperations
.isEmpty());
265 * Creates and adds to the queue a new operation, as described by operationIntent
267 * @param operationIntent Intent describing a new operation to queue and execute.
268 * @return Identifier of the operation created, or null if failed.
270 public long newOperation(Intent operationIntent
) {
271 RemoteOperation operation
= null
;
272 Target target
= null
;
274 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
275 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
276 Log_OC
.e(TAG
, "Not enough information provided in intent");
279 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
280 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
281 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
282 String webDavUrl
= serverUrl
+ webDavPath
;
283 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
284 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
285 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
286 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
287 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
290 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
291 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
299 String action
= operationIntent
.getAction();
300 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
301 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
302 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
303 if (remotePath
.length() > 0) {
304 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
305 "", false
, "", 1, sendIntent
);
308 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
309 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
310 if (remotePath
.length() > 0) {
311 operation
= new UnshareLinkOperation(
313 OperationsService
.this);
316 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
317 // check OC server and get basic information from it
318 String authTokenType
=
319 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
320 operation
= new GetServerInfoOperation(
321 serverUrl
, authTokenType
, OperationsService
.this);
323 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
324 /// GET ACCESS TOKEN to the OAuth server
325 String oauth2QueryParameters
=
326 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
327 operation
= new OAuth2GetAccessToken(
328 getString(R
.string
.oauth2_client_id
),
329 getString(R
.string
.oauth2_redirect_uri
),
330 getString(R
.string
.oauth2_grant_type
),
331 oauth2QueryParameters
);
333 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
335 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
336 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
337 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
339 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
341 operation
= new GetRemoteUserNameOperation();
343 } else if (action
.equals(ACTION_RENAME
)) {
344 // Rename file or folder
345 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
346 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
347 operation
= new RenameFileOperation(remotePath
, account
, newName
);
349 } else if (action
.equals(ACTION_REMOVE
)) {
350 // Remove file or folder
351 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
352 boolean removeLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_LOCAL_COPY
, true
);
353 operation
= new RemoveFileOperation(remotePath
, removeLocalCopy
);
355 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
357 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
358 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
359 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
364 } catch (IllegalArgumentException e
) {
365 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
369 if (operation
!= null
) {
370 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
371 startService(new Intent(OperationsService
.this, OperationsService
.class));
372 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
373 // better id than hash? ; should be good enough by the time being
374 return operation
.hashCode();
377 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
378 return Long
.MAX_VALUE
;
382 public void dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
383 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
384 mUndispatchedFinishedOperations
.remove(operationId
);
385 if (undispatched
!= null
) {
386 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
387 //Log_OC.wtf(TAG, "Sending callback later");
389 //Log_OC.wtf(TAG, "Not finished yet");
397 * Operations worker. Performs the pending operations in the order they were requested.
399 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
401 private static class ServiceHandler
extends Handler
{
402 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
403 OperationsService mService
;
404 public ServiceHandler(Looper looper
, OperationsService service
) {
406 if (service
== null
) {
407 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
413 public void handleMessage(Message msg
) {
414 mService
.nextOperation();
415 mService
.stopSelf(msg
.arg1
);
421 * Performs the next operation in the queue
423 private void nextOperation() {
425 //Log_OC.wtf(TAG, "nextOperation init" );
427 Pair
<Target
, RemoteOperation
> next
= null
;
428 synchronized(mPendingOperations
) {
429 next
= mPendingOperations
.peek();
434 mCurrentOperation
= next
.second
;
435 RemoteOperationResult result
= null
;
437 /// prepare client object to send the request to the ownCloud server
438 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
439 mLastTarget
= next
.first
;
440 if (mLastTarget
.mAccount
!= null
) {
441 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
442 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
444 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
445 mLastTarget
.mFollowRedirects
); // this is not good enough
446 if (mLastTarget
.mWebDavUrl
!= null
) {
447 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
449 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
450 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
451 } else if (mLastTarget
.mAuthToken
!= null
) {
452 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
453 } else if (mLastTarget
.mCookie
!= null
) {
454 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
456 mStorageManager
= null
;
460 /// perform the operation
461 if (mCurrentOperation
instanceof SyncOperation
) {
462 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
464 result
= mCurrentOperation
.execute(mOwnCloudClient
);
467 } catch (AccountsException e
) {
468 if (mLastTarget
.mAccount
== null
) {
469 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
471 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
473 result
= new RemoteOperationResult(e
);
475 } catch (IOException e
) {
476 if (mLastTarget
.mAccount
== null
) {
477 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
479 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
481 result
= new RemoteOperationResult(e
);
482 } catch (Exception e
) {
483 if (mLastTarget
.mAccount
== null
) {
484 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
486 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
488 result
= new RemoteOperationResult(e
);
491 synchronized(mPendingOperations
) {
492 mPendingOperations
.poll();
496 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
497 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
503 * Sends a broadcast when a new operation is added to the queue.
505 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
507 * @param target Account or URL pointing to an OC server.
508 * @param operation Added operation.
510 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
511 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
512 if (target
.mAccount
!= null
) {
513 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
515 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
517 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
518 //lbm.sendBroadcast(intent);
519 sendStickyBroadcast(intent
);
523 // TODO - maybe add a notification for real start of operations
526 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
528 * Local broadcasts are only delivered to activities in the same process.
530 * @param target Account or URL pointing to an OC server.
531 * @param operation Finished operation.
532 * @param result Result of the operation.
534 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
535 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
536 intent
.putExtra(EXTRA_RESULT
, result
);
537 if (target
.mAccount
!= null
) {
538 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
540 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
542 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
543 //lbm.sendBroadcast(intent);
544 sendStickyBroadcast(intent
);
549 * Notifies the currently subscribed listeners about the end of an operation.
551 * @param target Account or URL pointing to an OC server.
552 * @param operation Finished operation.
553 * @param result Result of the operation.
555 private void dispatchResultToOperationListeners(
556 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
558 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
559 while (listeners
.hasNext()) {
560 final OnRemoteOperationListener listener
= listeners
.next();
561 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
562 if (handler
!= null
) {
563 handler
.post(new Runnable() {
566 listener
.onRemoteOperationFinish(operation
, result
);
573 //mOperationResults.put(operation.hashCode(), result);
574 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
575 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
576 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
578 Log_OC
.d(TAG
, "Called " + count
+ " listeners");