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
.RenameFileOperation
;
41 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
42 import com
.owncloud
.android
.utils
.Log_OC
;
44 import android
.accounts
.Account
;
45 import android
.accounts
.AccountsException
;
46 import android
.app
.Service
;
47 import android
.content
.Intent
;
48 import android
.net
.Uri
;
49 import android
.os
.Binder
;
50 import android
.os
.Handler
;
51 import android
.os
.HandlerThread
;
52 import android
.os
.IBinder
;
53 import android
.os
.Looper
;
54 import android
.os
.Message
;
55 import android
.os
.Process
;
56 import android
.util
.Pair
;
58 public class OperationsService
extends Service
{
60 private static final String TAG
= OperationsService
.class.getSimpleName();
62 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
63 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
64 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
65 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
66 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
67 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
68 public static final String EXTRA_NEWNAME
= "NEWNAME";
69 public static final String EXTRA_RESULT
= "RESULT";
71 // TODO review if ALL OF THEM are necessary
72 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
73 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
74 public static final String EXTRA_USERNAME
= "USERNAME";
75 public static final String EXTRA_PASSWORD
= "PASSWORD";
76 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
77 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
78 public static final String EXTRA_COOKIE
= "COOKIE";
80 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
81 public static final String ACTION_UNSHARE
= "UNSHARE";
82 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
83 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
84 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
85 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
86 public static final String ACTION_RENAME
= "RENAME";
88 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
89 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
91 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
92 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
95 private ConcurrentMap<Integer, RemoteOperationResult> mOperationResults =
96 new ConcurrentHashMap<Integer, RemoteOperationResult>();
99 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
100 mUndispatchedFinishedOperations
=
101 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
103 private static class Target
{
104 public Uri mServerUrl
= null
;
105 public Account mAccount
= null
;
106 public String mWebDavUrl
= null
;
107 public String mUsername
= null
;
108 public String mPassword
= null
;
109 public String mAuthToken
= null
;
110 public boolean mFollowRedirects
= true
;
111 public String mCookie
= null
;
113 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
114 boolean followRedirects
, String cookie
) {
116 mServerUrl
= serverUrl
;
117 mWebDavUrl
= webdavUrl
;
118 mUsername
= username
;
119 mPassword
= password
;
120 mAuthToken
= authToken
;
121 mFollowRedirects
= followRedirects
;
126 private Looper mServiceLooper
;
127 private ServiceHandler mServiceHandler
;
128 private OperationsServiceBinder mBinder
;
129 private OwnCloudClient mOwnCloudClient
= null
;
130 private Target mLastTarget
= null
;
131 private FileDataStorageManager mStorageManager
;
132 private RemoteOperation mCurrentOperation
= null
;
136 * Service initialization
139 public void onCreate() {
141 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
143 mServiceLooper
= thread
.getLooper();
144 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
145 mBinder
= new OperationsServiceBinder();
150 * Entry point to add a new operation to the queue of operations.
152 * New operations are added calling to startService(), resulting in a call to this method.
153 * This ensures the service will keep on working although the caller activity goes away.
155 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
156 * is taking advantage of it due to time constraints.
159 public int onStartCommand(Intent intent
, int flags
, int startId
) {
160 //Log_OC.wtf(TAG, "onStartCommand init" );
161 Message msg
= mServiceHandler
.obtainMessage();
163 mServiceHandler
.sendMessage(msg
);
164 //Log_OC.wtf(TAG, "onStartCommand end" );
165 return START_NOT_STICKY
;
169 public void onDestroy() {
170 //Log_OC.wtf(TAG, "onDestroy init" );
172 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
173 mUndispatchedFinishedOperations
.clear();
174 //Log_OC.wtf(TAG, "onDestroy end" );
179 * Provides a binder object that clients can use to perform actions on the queue of operations,
180 * except the addition of new operations.
183 public IBinder
onBind(Intent intent
) {
184 //Log_OC.wtf(TAG, "onBind" );
190 * Called when ALL the bound clients were unbound.
193 public boolean onUnbind(Intent intent
) {
194 ((OperationsServiceBinder
)mBinder
).clearListeners();
195 return false
; // not accepting rebinding (default behaviour)
200 * Binder to let client components to perform actions on the queue of operations.
202 * It provides by itself the available operations.
204 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
207 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
209 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
210 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
213 * Cancels an operation
217 public void cancel() {
222 public void clearListeners() {
224 mBoundListeners
.clear();
229 * Adds a listener interested in being reported about the end of operations.
231 * @param listener Object to notify about the end of operations.
232 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
234 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
235 synchronized (mBoundListeners
) {
236 mBoundListeners
.put(listener
, callbackHandler
);
242 * Removes a listener from the list of objects interested in the being reported about the end of operations.
244 * @param listener Object to notify about progress of transfer.
246 public void removeOperationListener (OnRemoteOperationListener listener
) {
247 synchronized (mBoundListeners
) {
248 mBoundListeners
.remove(listener
);
254 * TODO - IMPORTANT: update implementation when more operations are moved into the service
256 * @return 'True' when an operation that enforces the user to wait for completion is in process.
258 public boolean isPerformingBlockingOperation() {
259 return (!mPendingOperations
.isEmpty());
264 * Creates and adds to the queue a new operation, as described by operationIntent
266 * @param operationIntent Intent describing a new operation to queue and execute.
267 * @return Identifier of the operation created, or null if failed.
269 public long newOperation(Intent operationIntent
) {
270 RemoteOperation operation
= null
;
271 Target target
= null
;
273 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
274 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
275 Log_OC
.e(TAG
, "Not enough information provided in intent");
278 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
279 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
280 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
281 String webDavUrl
= serverUrl
+ webDavPath
;
282 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
283 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
284 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
285 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
286 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
289 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
290 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
298 String action
= operationIntent
.getAction();
299 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
300 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
301 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
302 if (remotePath
.length() > 0) {
303 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
304 "", false
, "", 1, sendIntent
);
307 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
308 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
309 if (remotePath
.length() > 0) {
310 operation
= new UnshareLinkOperation(
312 OperationsService
.this);
315 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
316 // check OC server and get basic information from it
317 String authTokenType
=
318 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
319 operation
= new GetServerInfoOperation(
320 serverUrl
, authTokenType
, OperationsService
.this);
322 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
323 /// GET ACCESS TOKEN to the OAuth server
324 String oauth2QueryParameters
=
325 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
326 operation
= new OAuth2GetAccessToken(
327 getString(R
.string
.oauth2_client_id
),
328 getString(R
.string
.oauth2_redirect_uri
),
329 getString(R
.string
.oauth2_grant_type
),
330 oauth2QueryParameters
);
332 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
334 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
335 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
336 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
338 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
340 operation
= new GetRemoteUserNameOperation();
342 } else if (action
.equals(ACTION_RENAME
)) {
343 // Rename file or folder
344 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
345 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
346 operation
= new RenameFileOperation(remotePath
, account
, newName
);
350 } catch (IllegalArgumentException e
) {
351 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
355 if (operation
!= null
) {
356 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
357 startService(new Intent(OperationsService
.this, OperationsService
.class));
358 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
359 // better id than hash? ; should be good enough by the time being
360 return operation
.hashCode();
363 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
364 return Long
.MAX_VALUE
;
368 public void dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
369 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
370 mUndispatchedFinishedOperations
.remove(operationId
);
371 if (undispatched
!= null
) {
372 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
373 //Log_OC.wtf(TAG, "Sending callback later");
375 //Log_OC.wtf(TAG, "Not finished yet");
383 * Operations worker. Performs the pending operations in the order they were requested.
385 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
387 private static class ServiceHandler
extends Handler
{
388 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
389 OperationsService mService
;
390 public ServiceHandler(Looper looper
, OperationsService service
) {
392 if (service
== null
) {
393 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
399 public void handleMessage(Message msg
) {
400 mService
.nextOperation();
401 mService
.stopSelf(msg
.arg1
);
407 * Performs the next operation in the queue
409 private void nextOperation() {
411 //Log_OC.wtf(TAG, "nextOperation init" );
413 Pair
<Target
, RemoteOperation
> next
= null
;
414 synchronized(mPendingOperations
) {
415 next
= mPendingOperations
.peek();
420 mCurrentOperation
= next
.second
;
421 RemoteOperationResult result
= null
;
423 /// prepare client object to send the request to the ownCloud server
424 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
425 mLastTarget
= next
.first
;
426 if (mLastTarget
.mAccount
!= null
) {
427 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
428 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
430 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
431 mLastTarget
.mFollowRedirects
); // this is not good enough
432 if (mLastTarget
.mWebDavUrl
!= null
) {
433 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
435 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
436 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
437 } else if (mLastTarget
.mAuthToken
!= null
) {
438 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
439 } else if (mLastTarget
.mCookie
!= null
) {
440 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
442 mStorageManager
= null
;
446 /// perform the operation
447 if (mCurrentOperation
instanceof SyncOperation
) {
448 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
450 result
= mCurrentOperation
.execute(mOwnCloudClient
);
453 } catch (AccountsException e
) {
454 if (mLastTarget
.mAccount
== null
) {
455 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
457 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
459 result
= new RemoteOperationResult(e
);
461 } catch (IOException e
) {
462 if (mLastTarget
.mAccount
== null
) {
463 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
465 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
467 result
= new RemoteOperationResult(e
);
468 } catch (Exception e
) {
469 if (mLastTarget
.mAccount
== null
) {
470 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
472 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
474 result
= new RemoteOperationResult(e
);
477 synchronized(mPendingOperations
) {
478 mPendingOperations
.poll();
482 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
483 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
489 * Sends a broadcast when a new operation is added to the queue.
491 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
493 * @param target Account or URL pointing to an OC server.
494 * @param operation Added operation.
496 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
497 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
498 if (target
.mAccount
!= null
) {
499 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
501 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
503 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
504 //lbm.sendBroadcast(intent);
505 sendStickyBroadcast(intent
);
509 // TODO - maybe add a notification for real start of operations
512 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
514 * Local broadcasts are only delivered to activities in the same process.
516 * @param target Account or URL pointing to an OC server.
517 * @param operation Finished operation.
518 * @param result Result of the operation.
520 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
521 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
522 intent
.putExtra(EXTRA_RESULT
, result
);
523 if (target
.mAccount
!= null
) {
524 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
526 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
528 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
529 //lbm.sendBroadcast(intent);
530 sendStickyBroadcast(intent
);
535 * Notifies the currently subscribed listeners about the end of an operation.
537 * @param target Account or URL pointing to an OC server.
538 * @param operation Finished operation.
539 * @param result Result of the operation.
541 private void dispatchResultToOperationListeners(
542 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
544 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
545 while (listeners
.hasNext()) {
546 final OnRemoteOperationListener listener
= listeners
.next();
547 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
548 if (handler
!= null
) {
549 handler
.post(new Runnable() {
552 listener
.onRemoteOperationFinish(operation
, result
);
559 //mOperationResults.put(operation.hashCode(), result);
560 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
561 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
562 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
564 Log_OC
.d(TAG
, "Called " + count
+ " listeners");