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
.operations
.common
.SyncOperation
;
36 import com
.owncloud
.android
.operations
.CreateShareOperation
;
37 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
38 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
39 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
40 import com
.owncloud
.android
.utils
.Log_OC
;
42 import android
.accounts
.Account
;
43 import android
.accounts
.AccountsException
;
44 import android
.app
.Service
;
45 import android
.content
.Intent
;
46 import android
.net
.Uri
;
47 import android
.os
.Binder
;
48 import android
.os
.Handler
;
49 import android
.os
.HandlerThread
;
50 import android
.os
.IBinder
;
51 import android
.os
.Looper
;
52 import android
.os
.Message
;
53 import android
.os
.Process
;
54 import android
.util
.Pair
;
56 public class OperationsService
extends Service
{
58 private static final String TAG
= OperationsService
.class.getSimpleName();
60 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
61 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
62 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
63 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
64 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
65 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
66 public static final String EXTRA_RESULT
= "RESULT";
68 // TODO review if ALL OF THEM are necessary
69 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
70 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
71 public static final String EXTRA_USERNAME
= "USERNAME";
72 public static final String EXTRA_PASSWORD
= "PASSWORD";
73 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
74 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
76 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
77 public static final String ACTION_UNSHARE
= "UNSHARE";
78 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
79 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
80 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
82 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
83 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
85 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
86 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
88 private ConcurrentMap
<Integer
, RemoteOperationResult
> mOperationResults
=
89 new ConcurrentHashMap
<Integer
, RemoteOperationResult
>();
91 private static class Target
{
92 public Uri mServerUrl
= null
;
93 public Account mAccount
= null
;
94 public String mWebDavUrl
= "";
95 public String mUsername
= "";
96 public String mPassword
= "";
97 public String mAuthToken
= "";
98 public boolean mFollowRedirects
= true
;
100 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
101 boolean followRedirects
) {
103 mServerUrl
= serverUrl
;
104 mWebDavUrl
= webdavUrl
;
105 mUsername
= username
;
106 mPassword
= password
;
107 mAuthToken
= authToken
;
108 mFollowRedirects
= followRedirects
;
112 private Looper mServiceLooper
;
113 private ServiceHandler mServiceHandler
;
114 private OperationsServiceBinder mBinder
;
115 private OwnCloudClient mOwnCloudClient
= null
;
116 private Target mLastTarget
= null
;
117 private FileDataStorageManager mStorageManager
;
118 private RemoteOperation mCurrentOperation
= null
;
122 * Service initialization
125 public void onCreate() {
127 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
129 mServiceLooper
= thread
.getLooper();
130 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
131 mBinder
= new OperationsServiceBinder();
136 * Entry point to add a new operation to the queue of operations.
138 * New operations are added calling to startService(), resulting in a call to this method.
139 * This ensures the service will keep on working although the caller activity goes away.
141 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
142 * is taking advantage of it due to time constraints.
145 public int onStartCommand(Intent intent
, int flags
, int startId
) {
146 //Log.wtf(TAG, "onStartCommand init" );
147 Message msg
= mServiceHandler
.obtainMessage();
149 mServiceHandler
.sendMessage(msg
);
150 //Log.wtf(TAG, "onStartCommand end" );
151 return START_NOT_STICKY
;
156 * Provides a binder object that clients can use to perform actions on the queue of operations,
157 * except the addition of new operations.
160 public IBinder
onBind(Intent intent
) {
161 //Log.wtf(TAG, "onBind" );
167 * Called when ALL the bound clients were unbound.
170 public boolean onUnbind(Intent intent
) {
171 ((OperationsServiceBinder
)mBinder
).clearListeners();
172 return false
; // not accepting rebinding (default behaviour)
177 * Binder to let client components to perform actions on the queue of operations.
179 * It provides by itself the available operations.
181 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
184 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
186 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
187 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
190 * Cancels an operation
194 public void cancel() {
199 public void clearListeners() {
201 mBoundListeners
.clear();
206 * Adds a listener interested in being reported about the end of operations.
208 * @param listener Object to notify about the end of operations.
209 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
211 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
212 synchronized (mBoundListeners
) {
213 mBoundListeners
.put(listener
, callbackHandler
);
219 * Removes a listener from the list of objects interested in the being reported about the end of operations.
221 * @param listener Object to notify about progress of transfer.
223 public void removeOperationListener (OnRemoteOperationListener listener
) {
224 synchronized (mBoundListeners
) {
225 mBoundListeners
.remove(listener
);
231 * TODO - IMPORTANT: update implementation when more operations are moved into the service
233 * @return 'True' when an operation that enforces the user to wait for completion is in process.
235 public boolean isPerformingBlockingOperation() {
236 return (!mPendingOperations
.isEmpty());
241 * Creates and adds to the queue a new operation, as described by operationIntent
243 * @param operationIntent Intent describing a new operation to queue and execute.
244 * @return Identifier of the operation created, or -1 if failed.
246 public int newOperation(Intent operationIntent
) {
247 RemoteOperation operation
= null
;
248 Target target
= null
;
250 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
251 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
252 Log_OC
.e(TAG
, "Not enough information provided in intent");
255 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
256 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
257 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
258 String webDavUrl
= serverUrl
+ webDavPath
;
259 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
260 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
261 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
262 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
265 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
266 ((webDavPath
== null
) || (serverUrl
== null
)) ?
"" : webDavUrl
,
267 (username
== null
) ?
"" : username
,
268 (password
== null
) ?
"" : password
,
269 (authToken
== null
) ?
"" : authToken
,
273 String action
= operationIntent
.getAction();
274 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
275 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
276 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
277 if (remotePath
.length() > 0) {
278 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
279 "", false
, "", 1, sendIntent
);
282 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
283 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
284 if (remotePath
.length() > 0) {
285 operation
= new UnshareLinkOperation(
287 OperationsService
.this);
290 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
291 // check OC server and get basic information from it
292 String authTokenType
=
293 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
294 operation
= new GetServerInfoOperation(
295 serverUrl
, authTokenType
, OperationsService
.this);
297 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
298 /// GET ACCESS TOKEN to the OAuth server
299 String oauth2QueryParameters
=
300 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
301 operation
= new OAuth2GetAccessToken(
302 getString(R
.string
.oauth2_client_id
),
303 getString(R
.string
.oauth2_redirect_uri
),
304 getString(R
.string
.oauth2_grant_type
),
305 oauth2QueryParameters
);
307 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
309 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
310 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
311 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
316 } catch (IllegalArgumentException e
) {
317 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
321 if (operation
!= null
) {
322 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
323 startService(new Intent(OperationsService
.this, OperationsService
.class));
324 return operation
.hashCode();
331 public RemoteOperationResult
getOperationResultIfFinished(int mDetectAuthOpId
) {
332 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
333 return mOperationResults
.remove(mDetectAuthOpId
);
340 * Operations worker. Performs the pending operations in the order they were requested.
342 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
344 private static class ServiceHandler
extends Handler
{
345 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
346 OperationsService mService
;
347 public ServiceHandler(Looper looper
, OperationsService service
) {
349 if (service
== null
) {
350 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
356 public void handleMessage(Message msg
) {
357 mService
.nextOperation();
358 mService
.stopSelf(msg
.arg1
);
364 * Performs the next operation in the queue
366 private void nextOperation() {
368 //Log.wtf(TAG, "nextOperation init" );
370 Pair
<Target
, RemoteOperation
> next
= null
;
371 synchronized(mPendingOperations
) {
372 next
= mPendingOperations
.peek();
377 mCurrentOperation
= next
.second
;
378 RemoteOperationResult result
= null
;
380 /// prepare client object to send the request to the ownCloud server
381 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
382 mLastTarget
= next
.first
;
383 if (mLastTarget
.mAccount
!= null
) {
384 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
385 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
387 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
388 mLastTarget
.mFollowRedirects
); // this is not good enough
389 if (mLastTarget
.mWebDavUrl
!= "") {
390 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
392 if (mLastTarget
.mUsername
!= "" && mLastTarget
.mPassword
!= "") {
393 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
394 } else if (mLastTarget
.mAuthToken
!= "") {
395 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
397 mStorageManager
= null
;
401 /// perform the operation
402 if (mCurrentOperation
instanceof SyncOperation
) {
403 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
405 result
= mCurrentOperation
.execute(mOwnCloudClient
);
408 } catch (AccountsException e
) {
409 if (mLastTarget
.mAccount
== null
) {
410 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
412 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
414 result
= new RemoteOperationResult(e
);
416 } catch (IOException e
) {
417 if (mLastTarget
.mAccount
== null
) {
418 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
420 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
422 result
= new RemoteOperationResult(e
);
423 } catch (Exception e
) {
424 if (mLastTarget
.mAccount
== null
) {
425 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
427 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
429 result
= new RemoteOperationResult(e
);
432 synchronized(mPendingOperations
) {
433 mPendingOperations
.poll();
434 mOperationResults
.put(mCurrentOperation
.hashCode(), result
);
438 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
439 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
445 * Sends a broadcast when a new operation is added to the queue.
447 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
449 * @param target Account or URL pointing to an OC server.
450 * @param operation Added operation.
452 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
453 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
454 if (target
.mAccount
!= null
) {
455 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
457 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
459 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
460 //lbm.sendBroadcast(intent);
461 sendStickyBroadcast(intent
);
465 // TODO - maybe add a notification for real start of operations
468 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
470 * Local broadcasts are only delivered to activities in the same process.
472 * @param target Account or URL pointing to an OC server.
473 * @param operation Finished operation.
474 * @param result Result of the operation.
476 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
477 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
478 intent
.putExtra(EXTRA_RESULT
, result
);
479 if (target
.mAccount
!= null
) {
480 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
482 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
484 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
485 //lbm.sendBroadcast(intent);
486 sendStickyBroadcast(intent
);
491 * Notifies the currently subscribed listeners about the end of an operation.
493 * @param target Account or URL pointing to an OC server.
494 * @param operation Finished operation.
495 * @param result Result of the operation.
497 private void callbackOperationListeners(
498 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
500 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
501 while (listeners
.hasNext()) {
502 final OnRemoteOperationListener listener
= listeners
.next();
503 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
504 if (handler
!= null
) {
505 handler
.post(new Runnable() {
508 listener
.onRemoteOperationFinish(operation
, result
);
514 Log_OC
.d(TAG
, "Called " + count
+ " listeners");