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
.datamodel
.FileDataStorageManager
;
27 import com
.owncloud
.android
.lib
.common
.OwnCloudClientFactory
;
28 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
29 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
30 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
31 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
32 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
33 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
34 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
35 import com
.owncloud
.android
.operations
.CreateShareOperation
;
36 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
;
37 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
38 import com
.owncloud
.android
.utils
.Log_OC
;
40 import android
.accounts
.Account
;
41 import android
.accounts
.AccountsException
;
42 import android
.app
.Service
;
43 import android
.content
.Intent
;
44 import android
.net
.Uri
;
45 import android
.os
.Binder
;
46 import android
.os
.Handler
;
47 import android
.os
.HandlerThread
;
48 import android
.os
.IBinder
;
49 import android
.os
.Looper
;
50 import android
.os
.Message
;
51 import android
.os
.Process
;
52 import android
.util
.Pair
;
54 public class OperationsService
extends Service
{
56 private static final String TAG
= OperationsService
.class.getSimpleName();
58 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
59 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
60 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
61 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
62 public static final String EXTRA_RESULT
= "RESULT";
63 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
64 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
65 public static final String EXTRA_USERNAME
= "USERNAME";
66 public static final String EXTRA_PASSWORD
= "PASSWORD";
67 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
68 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
70 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
71 public static final String ACTION_UNSHARE
= "UNSHARE";
72 public static final String ACTION_DETECT_AUTHENTICATION_METHOD
= "DETECT_AUTHENTICATION_METHOD";
73 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
75 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
76 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
78 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
79 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
81 private ConcurrentMap
<Integer
, RemoteOperationResult
> mOperationResults
=
82 new ConcurrentHashMap
<Integer
, RemoteOperationResult
>();
84 private static class Target
{
85 public Uri mServerUrl
= null
;
86 public Account mAccount
= null
;
87 public String mWebDavUrl
= "";
88 public String mUsername
= "";
89 public String mPassword
= "";
90 public String mAuthToken
= "";
91 public boolean mFollowRedirects
= true
;
93 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
94 boolean followRedirects
) {
96 mServerUrl
= serverUrl
;
97 mWebDavUrl
= webdavUrl
;
100 mAuthToken
= authToken
;
101 mFollowRedirects
= followRedirects
;
105 private Looper mServiceLooper
;
106 private ServiceHandler mServiceHandler
;
107 private OperationsServiceBinder mBinder
;
108 private OwnCloudClient mOwnCloudClient
= null
;
109 private Target mLastTarget
= null
;
110 private FileDataStorageManager mStorageManager
;
111 private RemoteOperation mCurrentOperation
= null
;
115 * Service initialization
118 public void onCreate() {
120 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
122 mServiceLooper
= thread
.getLooper();
123 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
124 mBinder
= new OperationsServiceBinder();
129 * Entry point to add a new operation to the queue of operations.
131 * New operations are added calling to startService(), resulting in a call to this method.
132 * This ensures the service will keep on working although the caller activity goes away.
134 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
135 * is taking advantage of it due to time constraints.
138 public int onStartCommand(Intent intent
, int flags
, int startId
) {
139 //Log.wtf(TAG, "onStartCommand init" );
140 Message msg
= mServiceHandler
.obtainMessage();
142 mServiceHandler
.sendMessage(msg
);
143 //Log.wtf(TAG, "onStartCommand end" );
144 return START_NOT_STICKY
;
149 * Provides a binder object that clients can use to perform actions on the queue of operations,
150 * except the addition of new operations.
153 public IBinder
onBind(Intent intent
) {
154 //Log.wtf(TAG, "onBind" );
160 * Called when ALL the bound clients were unbound.
163 public boolean onUnbind(Intent intent
) {
164 ((OperationsServiceBinder
)mBinder
).clearListeners();
165 return false
; // not accepting rebinding (default behaviour)
170 * Binder to let client components to perform actions on the queue of operations.
172 * It provides by itself the available operations.
174 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
177 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
179 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
180 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
183 * Cancels an operation
187 public void cancel() {
192 public void clearListeners() {
194 mBoundListeners
.clear();
199 * Adds a listener interested in being reported about the end of operations.
201 * @param listener Object to notify about the end of operations.
202 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
204 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
205 synchronized (mBoundListeners
) {
206 mBoundListeners
.put(listener
, callbackHandler
);
212 * Removes a listener from the list of objects interested in the being reported about the end of operations.
214 * @param listener Object to notify about progress of transfer.
216 public void removeOperationListener (OnRemoteOperationListener listener
) {
217 synchronized (mBoundListeners
) {
218 mBoundListeners
.remove(listener
);
224 * TODO - IMPORTANT: update implementation when more operations are moved into the service
226 * @return 'True' when an operation that enforces the user to wait for completion is in process.
228 public boolean isPerformingBlockingOperation() {
229 return (!mPendingOperations
.isEmpty());
234 * Creates and adds to the queue a new operation, as described by operationIntent
236 * @param operationIntent Intent describing a new operation to queue and execute.
237 * @return Identifier of the operation created, or -1 if failed.
239 public int newOperation(Intent operationIntent
) {
240 RemoteOperation operation
= null
;
241 Target target
= null
;
243 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
244 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
245 Log_OC
.e(TAG
, "Not enough information provided in intent");
248 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
249 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
250 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
251 String webDavUrl
= serverUrl
+ webDavPath
;
252 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
253 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
254 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
255 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
258 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
259 ((webDavPath
== null
) || (serverUrl
== null
)) ?
"" : webDavUrl
,
260 (username
== null
) ?
"" : username
,
261 (password
== null
) ?
"" : password
,
262 (authToken
== null
) ?
"" : authToken
,
266 String action
= operationIntent
.getAction();
267 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
268 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
269 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
270 if (remotePath
.length() > 0) {
271 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
272 "", false
, "", 1, sendIntent
);
274 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
275 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
276 if (remotePath
.length() > 0) {
277 operation
= new UnshareLinkOperation(
279 OperationsService
.this);
281 } else if (action
.equals(ACTION_DETECT_AUTHENTICATION_METHOD
)) {
282 // Detect Authentication Method
284 serverUrl
+ operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
285 operation
= new DetectAuthenticationMethodOperation(
286 OperationsService
.this,
288 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
290 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
291 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
292 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
297 } catch (IllegalArgumentException e
) {
298 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
302 if (operation
!= null
) {
303 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
304 startService(new Intent(OperationsService
.this, OperationsService
.class));
305 return operation
.hashCode();
312 public RemoteOperationResult
getOperationResultIfFinished(int mDetectAuthOpId
) {
313 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
314 return mOperationResults
.remove(mDetectAuthOpId
);
321 * Operations worker. Performs the pending operations in the order they were requested.
323 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
325 private static class ServiceHandler
extends Handler
{
326 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
327 OperationsService mService
;
328 public ServiceHandler(Looper looper
, OperationsService service
) {
330 if (service
== null
) {
331 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
337 public void handleMessage(Message msg
) {
338 mService
.nextOperation();
339 mService
.stopSelf(msg
.arg1
);
345 * Performs the next operation in the queue
347 private void nextOperation() {
349 //Log.wtf(TAG, "nextOperation init" );
351 Pair
<Target
, RemoteOperation
> next
= null
;
352 synchronized(mPendingOperations
) {
353 next
= mPendingOperations
.peek();
358 mCurrentOperation
= next
.second
;
359 RemoteOperationResult result
= null
;
361 /// prepare client object to send the request to the ownCloud server
362 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
363 mLastTarget
= next
.first
;
364 if (mLastTarget
.mAccount
!= null
) {
365 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
366 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
368 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
369 mLastTarget
.mFollowRedirects
); // this is not good enough
370 if (mLastTarget
.mWebDavUrl
!= "") {
371 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
373 if (mLastTarget
.mUsername
!= "" && mLastTarget
.mPassword
!= "") {
374 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
375 } else if (mLastTarget
.mAuthToken
!= "") {
376 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
378 mStorageManager
= null
;
382 /// perform the operation
383 if (mCurrentOperation
instanceof SyncOperation
) {
384 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
386 result
= mCurrentOperation
.execute(mOwnCloudClient
);
389 } catch (AccountsException e
) {
390 if (mLastTarget
.mAccount
== null
) {
391 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
393 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
395 result
= new RemoteOperationResult(e
);
397 } catch (IOException e
) {
398 if (mLastTarget
.mAccount
== null
) {
399 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
401 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
403 result
= new RemoteOperationResult(e
);
404 } catch (Exception e
) {
405 if (mLastTarget
.mAccount
== null
) {
406 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
408 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
410 result
= new RemoteOperationResult(e
);
413 synchronized(mPendingOperations
) {
414 mPendingOperations
.poll();
415 mOperationResults
.put(mCurrentOperation
.hashCode(), result
);
419 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
420 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
426 * Sends a broadcast when a new operation is added to the queue.
428 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
430 * @param target Account or URL pointing to an OC server.
431 * @param operation Added operation.
433 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
434 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
435 if (target
.mAccount
!= null
) {
436 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
438 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
440 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
441 //lbm.sendBroadcast(intent);
442 sendStickyBroadcast(intent
);
446 // TODO - maybe add a notification for real start of operations
449 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
451 * Local broadcasts are only delivered to activities in the same process.
453 * @param target Account or URL pointing to an OC server.
454 * @param operation Finished operation.
455 * @param result Result of the operation.
457 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
458 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
459 intent
.putExtra(EXTRA_RESULT
, result
);
460 if (target
.mAccount
!= null
) {
461 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
463 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
465 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
466 //lbm.sendBroadcast(intent);
467 sendStickyBroadcast(intent
);
472 * Notifies the currently subscribed listeners about the end of an operation.
474 * @param target Account or URL pointing to an OC server.
475 * @param operation Finished operation.
476 * @param result Result of the operation.
478 private void callbackOperationListeners(
479 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
481 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
482 while (listeners
.hasNext()) {
483 final OnRemoteOperationListener listener
= listeners
.next();
484 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
485 if (handler
!= null
) {
486 handler
.post(new Runnable() {
489 listener
.onRemoteOperationFinish(operation
, result
);
495 Log_OC
.d(TAG
, "Called " + count
+ " listeners");