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
.UnshareLinkOperation
;
41 import com
.owncloud
.android
.utils
.Log_OC
;
43 import android
.accounts
.Account
;
44 import android
.accounts
.AccountsException
;
45 import android
.app
.Service
;
46 import android
.content
.Intent
;
47 import android
.net
.Uri
;
48 import android
.os
.Binder
;
49 import android
.os
.Handler
;
50 import android
.os
.HandlerThread
;
51 import android
.os
.IBinder
;
52 import android
.os
.Looper
;
53 import android
.os
.Message
;
54 import android
.os
.Process
;
55 import android
.util
.Pair
;
57 public class OperationsService
extends Service
{
59 private static final String TAG
= OperationsService
.class.getSimpleName();
61 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
62 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
63 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
64 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
65 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
66 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
67 public static final String EXTRA_RESULT
= "RESULT";
69 // TODO review if ALL OF THEM are necessary
70 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
71 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
72 public static final String EXTRA_USERNAME
= "USERNAME";
73 public static final String EXTRA_PASSWORD
= "PASSWORD";
74 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
75 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
76 public static final String EXTRA_COOKIE
= "COOKIE";
78 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
79 public static final String ACTION_UNSHARE
= "UNSHARE";
80 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
81 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
82 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
83 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
85 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
86 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
88 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
89 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
91 private ConcurrentMap
<Integer
, RemoteOperationResult
> mOperationResults
=
92 new ConcurrentHashMap
<Integer
, RemoteOperationResult
>();
94 private static class Target
{
95 public Uri mServerUrl
= null
;
96 public Account mAccount
= null
;
97 public String mWebDavUrl
= "";
98 public String mUsername
= "";
99 public String mPassword
= "";
100 public String mAuthToken
= "";
101 public boolean mFollowRedirects
= true
;
102 public String mCookie
= "";
104 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
105 boolean followRedirects
, String cookie
) {
107 mServerUrl
= serverUrl
;
108 mWebDavUrl
= webdavUrl
;
109 mUsername
= username
;
110 mPassword
= password
;
111 mAuthToken
= authToken
;
112 mFollowRedirects
= followRedirects
;
117 private Looper mServiceLooper
;
118 private ServiceHandler mServiceHandler
;
119 private OperationsServiceBinder mBinder
;
120 private OwnCloudClient mOwnCloudClient
= null
;
121 private Target mLastTarget
= null
;
122 private FileDataStorageManager mStorageManager
;
123 private RemoteOperation mCurrentOperation
= null
;
127 * Service initialization
130 public void onCreate() {
132 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
134 mServiceLooper
= thread
.getLooper();
135 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
136 mBinder
= new OperationsServiceBinder();
141 * Entry point to add a new operation to the queue of operations.
143 * New operations are added calling to startService(), resulting in a call to this method.
144 * This ensures the service will keep on working although the caller activity goes away.
146 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
147 * is taking advantage of it due to time constraints.
150 public int onStartCommand(Intent intent
, int flags
, int startId
) {
151 //Log.wtf(TAG, "onStartCommand init" );
152 Message msg
= mServiceHandler
.obtainMessage();
154 mServiceHandler
.sendMessage(msg
);
155 //Log.wtf(TAG, "onStartCommand end" );
156 return START_NOT_STICKY
;
161 * Provides a binder object that clients can use to perform actions on the queue of operations,
162 * except the addition of new operations.
165 public IBinder
onBind(Intent intent
) {
166 //Log.wtf(TAG, "onBind" );
172 * Called when ALL the bound clients were unbound.
175 public boolean onUnbind(Intent intent
) {
176 ((OperationsServiceBinder
)mBinder
).clearListeners();
177 return false
; // not accepting rebinding (default behaviour)
182 * Binder to let client components to perform actions on the queue of operations.
184 * It provides by itself the available operations.
186 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
189 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
191 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
192 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
195 * Cancels an operation
199 public void cancel() {
204 public void clearListeners() {
206 mBoundListeners
.clear();
211 * Adds a listener interested in being reported about the end of operations.
213 * @param listener Object to notify about the end of operations.
214 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
216 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
217 synchronized (mBoundListeners
) {
218 mBoundListeners
.put(listener
, callbackHandler
);
224 * Removes a listener from the list of objects interested in the being reported about the end of operations.
226 * @param listener Object to notify about progress of transfer.
228 public void removeOperationListener (OnRemoteOperationListener listener
) {
229 synchronized (mBoundListeners
) {
230 mBoundListeners
.remove(listener
);
236 * TODO - IMPORTANT: update implementation when more operations are moved into the service
238 * @return 'True' when an operation that enforces the user to wait for completion is in process.
240 public boolean isPerformingBlockingOperation() {
241 return (!mPendingOperations
.isEmpty());
246 * Creates and adds to the queue a new operation, as described by operationIntent
248 * @param operationIntent Intent describing a new operation to queue and execute.
249 * @return Identifier of the operation created, or -1 if failed.
251 public int newOperation(Intent operationIntent
) {
252 RemoteOperation operation
= null
;
253 Target target
= null
;
255 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
256 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
257 Log_OC
.e(TAG
, "Not enough information provided in intent");
260 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
261 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
262 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
263 String webDavUrl
= serverUrl
+ webDavPath
;
264 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
265 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
266 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
267 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
268 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
271 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
272 ((webDavPath
== null
) || (serverUrl
== null
)) ?
"" : webDavUrl
,
273 (username
== null
) ?
"" : username
,
274 (password
== null
) ?
"" : password
,
275 (authToken
== null
) ?
"" : authToken
,
277 (cookie
== null
) ?
"" : cookie
280 String action
= operationIntent
.getAction();
281 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
282 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
283 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
284 if (remotePath
.length() > 0) {
285 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
286 "", false
, "", 1, sendIntent
);
289 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
290 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
291 if (remotePath
.length() > 0) {
292 operation
= new UnshareLinkOperation(
294 OperationsService
.this);
297 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
298 // check OC server and get basic information from it
299 String authTokenType
=
300 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
301 operation
= new GetServerInfoOperation(
302 serverUrl
, authTokenType
, OperationsService
.this);
304 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
305 /// GET ACCESS TOKEN to the OAuth server
306 String oauth2QueryParameters
=
307 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
308 operation
= new OAuth2GetAccessToken(
309 getString(R
.string
.oauth2_client_id
),
310 getString(R
.string
.oauth2_redirect_uri
),
311 getString(R
.string
.oauth2_grant_type
),
312 oauth2QueryParameters
);
314 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
316 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
317 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
318 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
320 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
322 operation
= new GetRemoteUserNameOperation();
326 } catch (IllegalArgumentException e
) {
327 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
331 if (operation
!= null
) {
332 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
333 startService(new Intent(OperationsService
.this, OperationsService
.class));
334 return operation
.hashCode();
341 public RemoteOperationResult
getOperationResultIfFinished(int mDetectAuthOpId
) {
342 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
343 return mOperationResults
.remove(mDetectAuthOpId
);
350 * Operations worker. Performs the pending operations in the order they were requested.
352 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
354 private static class ServiceHandler
extends Handler
{
355 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
356 OperationsService mService
;
357 public ServiceHandler(Looper looper
, OperationsService service
) {
359 if (service
== null
) {
360 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
366 public void handleMessage(Message msg
) {
367 mService
.nextOperation();
368 mService
.stopSelf(msg
.arg1
);
374 * Performs the next operation in the queue
376 private void nextOperation() {
378 //Log.wtf(TAG, "nextOperation init" );
380 Pair
<Target
, RemoteOperation
> next
= null
;
381 synchronized(mPendingOperations
) {
382 next
= mPendingOperations
.peek();
387 mCurrentOperation
= next
.second
;
388 RemoteOperationResult result
= null
;
390 /// prepare client object to send the request to the ownCloud server
391 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
392 mLastTarget
= next
.first
;
393 if (mLastTarget
.mAccount
!= null
) {
394 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
395 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
397 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
398 mLastTarget
.mFollowRedirects
); // this is not good enough
399 if (mLastTarget
.mWebDavUrl
!= "") {
400 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
402 if (mLastTarget
.mUsername
!= "" && mLastTarget
.mPassword
!= "") {
403 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
404 } else if (mLastTarget
.mAuthToken
!= "") {
405 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
406 } else if (mLastTarget
.mCookie
!= "") {
407 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
409 mStorageManager
= null
;
413 /// perform the operation
414 if (mCurrentOperation
instanceof SyncOperation
) {
415 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
417 result
= mCurrentOperation
.execute(mOwnCloudClient
);
420 } catch (AccountsException e
) {
421 if (mLastTarget
.mAccount
== null
) {
422 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
424 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
426 result
= new RemoteOperationResult(e
);
428 } catch (IOException e
) {
429 if (mLastTarget
.mAccount
== null
) {
430 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
432 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
434 result
= new RemoteOperationResult(e
);
435 } catch (Exception e
) {
436 if (mLastTarget
.mAccount
== null
) {
437 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
439 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
441 result
= new RemoteOperationResult(e
);
444 synchronized(mPendingOperations
) {
445 mPendingOperations
.poll();
449 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
450 dispatchOperationListeners(mLastTarget
, mCurrentOperation
, result
);
456 * Sends a broadcast when a new operation is added to the queue.
458 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
460 * @param target Account or URL pointing to an OC server.
461 * @param operation Added operation.
463 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
464 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
465 if (target
.mAccount
!= null
) {
466 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
468 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
470 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
471 //lbm.sendBroadcast(intent);
472 sendStickyBroadcast(intent
);
476 // TODO - maybe add a notification for real start of operations
479 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
481 * Local broadcasts are only delivered to activities in the same process.
483 * @param target Account or URL pointing to an OC server.
484 * @param operation Finished operation.
485 * @param result Result of the operation.
487 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
488 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
489 intent
.putExtra(EXTRA_RESULT
, result
);
490 if (target
.mAccount
!= null
) {
491 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
493 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
495 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
496 //lbm.sendBroadcast(intent);
497 sendStickyBroadcast(intent
);
502 * Notifies the currently subscribed listeners about the end of an operation.
504 * @param target Account or URL pointing to an OC server.
505 * @param operation Finished operation.
506 * @param result Result of the operation.
508 private void dispatchOperationListeners(
509 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
511 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
512 while (listeners
.hasNext()) {
513 final OnRemoteOperationListener listener
= listeners
.next();
514 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
515 if (handler
!= null
) {
516 handler
.post(new Runnable() {
519 listener
.onRemoteOperationFinish(operation
, result
);
526 mOperationResults
.put(operation
.hashCode(), result
);
528 Log_OC
.d(TAG
, "Called " + count
+ " listeners");