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
.SynchronizeFileOperation
;
44 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
45 import com
.owncloud
.android
.utils
.Log_OC
;
47 import android
.accounts
.Account
;
48 import android
.accounts
.AccountsException
;
49 import android
.app
.Service
;
50 import android
.content
.Intent
;
51 import android
.net
.Uri
;
52 import android
.os
.Binder
;
53 import android
.os
.Handler
;
54 import android
.os
.HandlerThread
;
55 import android
.os
.IBinder
;
56 import android
.os
.Looper
;
57 import android
.os
.Message
;
58 import android
.os
.Process
;
59 import android
.util
.Pair
;
61 public class OperationsService
extends Service
{
63 private static final String TAG
= OperationsService
.class.getSimpleName();
65 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
66 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
67 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
68 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
69 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
70 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
71 public static final String EXTRA_NEWNAME
= "NEWNAME";
72 public static final String EXTRA_REMOVE_ONLY_LOCAL
= "REMOVE_LOCAL_COPY";
73 public static final String EXTRA_CREATE_FULL_PATH
= "CREATE_FULL_PATH";
74 public static final String EXTRA_SYNC_FILE_CONTENTS
= "SYNC_FILE_CONTENTS";
75 public static final String EXTRA_RESULT
= "RESULT";
77 // TODO review if ALL OF THEM are necessary
78 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
79 public static final String EXTRA_SUCCESS_IF_ABSENT
= "SUCCESS_IF_ABSENT";
80 public static final String EXTRA_USERNAME
= "USERNAME";
81 public static final String EXTRA_PASSWORD
= "PASSWORD";
82 public static final String EXTRA_AUTH_TOKEN
= "AUTH_TOKEN";
83 public static final String EXTRA_FOLLOW_REDIRECTS
= "FOLLOW_REDIRECTS";
84 public static final String EXTRA_COOKIE
= "COOKIE";
86 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
87 public static final String ACTION_UNSHARE
= "UNSHARE";
88 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
89 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
90 public static final String ACTION_EXISTENCE_CHECK
= "EXISTENCE_CHECK";
91 public static final String ACTION_GET_USER_NAME
= "GET_USER_NAME";
92 public static final String ACTION_RENAME
= "RENAME";
93 public static final String ACTION_REMOVE
= "REMOVE";
94 public static final String ACTION_CREATE_FOLDER
= "CREATE_FOLDER";
95 public static final String ACTION_SYNC_FILE
= "SYNC_FILE";
97 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
98 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
100 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
101 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
103 private ConcurrentMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>
104 mUndispatchedFinishedOperations
=
105 new ConcurrentHashMap
<Integer
, Pair
<RemoteOperation
, RemoteOperationResult
>>();
107 private static class Target
{
108 public Uri mServerUrl
= null
;
109 public Account mAccount
= null
;
110 public String mWebDavUrl
= null
;
111 public String mUsername
= null
;
112 public String mPassword
= null
;
113 public String mAuthToken
= null
;
114 public boolean mFollowRedirects
= true
;
115 public String mCookie
= null
;
117 public Target(Account account
, Uri serverUrl
, String webdavUrl
, String username
, String password
, String authToken
,
118 boolean followRedirects
, String cookie
) {
120 mServerUrl
= serverUrl
;
121 mWebDavUrl
= webdavUrl
;
122 mUsername
= username
;
123 mPassword
= password
;
124 mAuthToken
= authToken
;
125 mFollowRedirects
= followRedirects
;
130 private Looper mServiceLooper
;
131 private ServiceHandler mServiceHandler
;
132 private OperationsServiceBinder mBinder
;
133 private OwnCloudClient mOwnCloudClient
= null
;
134 private Target mLastTarget
= null
;
135 private FileDataStorageManager mStorageManager
;
136 private RemoteOperation mCurrentOperation
= null
;
140 * Service initialization
143 public void onCreate() {
145 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
147 mServiceLooper
= thread
.getLooper();
148 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
149 mBinder
= new OperationsServiceBinder();
154 * Entry point to add a new operation to the queue of operations.
156 * New operations are added calling to startService(), resulting in a call to this method.
157 * This ensures the service will keep on working although the caller activity goes away.
159 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
160 * is taking advantage of it due to time constraints.
163 public int onStartCommand(Intent intent
, int flags
, int startId
) {
164 //Log_OC.wtf(TAG, "onStartCommand init" );
165 Message msg
= mServiceHandler
.obtainMessage();
167 mServiceHandler
.sendMessage(msg
);
168 //Log_OC.wtf(TAG, "onStartCommand end" );
169 return START_NOT_STICKY
;
173 public void onDestroy() {
174 //Log_OC.wtf(TAG, "onDestroy init" );
175 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
176 mUndispatchedFinishedOperations
.clear();
177 //Log_OC.wtf(TAG, "onDestroy end" );
183 * Provides a binder object that clients can use to perform actions on the queue of operations,
184 * except the addition of new operations.
187 public IBinder
onBind(Intent intent
) {
188 //Log_OC.wtf(TAG, "onBind" );
194 * Called when ALL the bound clients were unbound.
197 public boolean onUnbind(Intent intent
) {
198 ((OperationsServiceBinder
)mBinder
).clearListeners();
199 return false
; // not accepting rebinding (default behaviour)
204 * Binder to let client components to perform actions on the queue of operations.
206 * It provides by itself the available operations.
208 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
211 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
213 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
214 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
217 * Cancels an operation
221 public void cancel() {
226 public void clearListeners() {
228 mBoundListeners
.clear();
233 * Adds a listener interested in being reported about the end of operations.
235 * @param listener Object to notify about the end of operations.
236 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
238 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
239 synchronized (mBoundListeners
) {
240 mBoundListeners
.put(listener
, callbackHandler
);
246 * Removes a listener from the list of objects interested in the being reported about the end of operations.
248 * @param listener Object to notify about progress of transfer.
250 public void removeOperationListener (OnRemoteOperationListener listener
) {
251 synchronized (mBoundListeners
) {
252 mBoundListeners
.remove(listener
);
258 * TODO - IMPORTANT: update implementation when more operations are moved into the service
260 * @return 'True' when an operation that enforces the user to wait for completion is in process.
262 public boolean isPerformingBlockingOperation() {
263 return (!mPendingOperations
.isEmpty());
268 * Creates and adds to the queue a new operation, as described by operationIntent
270 * @param operationIntent Intent describing a new operation to queue and execute.
271 * @return Identifier of the operation created, or null if failed.
273 public long newOperation(Intent operationIntent
) {
274 RemoteOperation operation
= null
;
275 Target target
= null
;
277 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
278 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
279 Log_OC
.e(TAG
, "Not enough information provided in intent");
282 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
283 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
284 String webDavPath
= operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
285 String webDavUrl
= serverUrl
+ webDavPath
;
286 String username
= operationIntent
.getStringExtra(EXTRA_USERNAME
);
287 String password
= operationIntent
.getStringExtra(EXTRA_PASSWORD
);
288 String authToken
= operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN
);
289 boolean followRedirects
= operationIntent
.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS
, true
);
290 String cookie
= operationIntent
.getStringExtra(EXTRA_COOKIE
);
293 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
),
294 ((webDavPath
== null
) || (serverUrl
== null
)) ? null
: webDavUrl
,
302 String action
= operationIntent
.getAction();
303 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
304 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
305 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
306 if (remotePath
.length() > 0) {
307 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
308 "", false
, "", 1, sendIntent
);
311 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
312 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
313 if (remotePath
.length() > 0) {
314 operation
= new UnshareLinkOperation(
316 OperationsService
.this);
319 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
320 // check OC server and get basic information from it
321 String authTokenType
=
322 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
323 operation
= new GetServerInfoOperation(
324 serverUrl
, authTokenType
, OperationsService
.this);
326 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
327 /// GET ACCESS TOKEN to the OAuth server
328 String oauth2QueryParameters
=
329 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
330 operation
= new OAuth2GetAccessToken(
331 getString(R
.string
.oauth2_client_id
),
332 getString(R
.string
.oauth2_redirect_uri
),
333 getString(R
.string
.oauth2_grant_type
),
334 oauth2QueryParameters
);
336 } else if (action
.equals(ACTION_EXISTENCE_CHECK
)) {
338 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
339 boolean successIfAbsent
= operationIntent
.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT
, true
);
340 operation
= new ExistenceCheckRemoteOperation(remotePath
, OperationsService
.this, successIfAbsent
);
342 } else if (action
.equals(ACTION_GET_USER_NAME
)) {
344 operation
= new GetRemoteUserNameOperation();
346 } else if (action
.equals(ACTION_RENAME
)) {
347 // Rename file or folder
348 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
349 String newName
= operationIntent
.getStringExtra(EXTRA_NEWNAME
);
350 operation
= new RenameFileOperation(remotePath
, account
, newName
);
352 } else if (action
.equals(ACTION_REMOVE
)) {
353 // Remove file or folder
354 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
355 boolean onlyLocalCopy
= operationIntent
.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL
, false
);
356 operation
= new RemoveFileOperation(remotePath
, onlyLocalCopy
);
358 } else if (action
.equals(ACTION_CREATE_FOLDER
)) {
360 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
361 boolean createFullPath
= operationIntent
.getBooleanExtra(EXTRA_CREATE_FULL_PATH
, true
);
362 operation
= new CreateFolderOperation(remotePath
, createFullPath
);
364 } else if (action
.equals(ACTION_SYNC_FILE
)) {
366 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
367 boolean syncFileContents
= operationIntent
.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS
, true
);
368 operation
= new SynchronizeFileOperation(remotePath
, account
, syncFileContents
, getApplicationContext());
373 } catch (IllegalArgumentException e
) {
374 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
378 if (operation
!= null
) {
379 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
380 startService(new Intent(OperationsService
.this, OperationsService
.class));
381 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
382 // better id than hash? ; should be good enough by the time being
383 return operation
.hashCode();
386 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
387 return Long
.MAX_VALUE
;
391 public boolean dispatchResultIfFinished(int operationId
, OnRemoteOperationListener listener
) {
392 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
393 mUndispatchedFinishedOperations
.remove(operationId
);
394 if (undispatched
!= null
) {
395 listener
.onRemoteOperationFinish(undispatched
.first
, undispatched
.second
);
397 //Log_OC.wtf(TAG, "Sending callback later");
399 if (!mPendingOperations
.isEmpty()) {
404 //Log_OC.wtf(TAG, "Not finished yet");
412 * Operations worker. Performs the pending operations in the order they were requested.
414 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
416 private static class ServiceHandler
extends Handler
{
417 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
418 OperationsService mService
;
419 public ServiceHandler(Looper looper
, OperationsService service
) {
421 if (service
== null
) {
422 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
428 public void handleMessage(Message msg
) {
429 mService
.nextOperation();
430 mService
.stopSelf(msg
.arg1
);
436 * Performs the next operation in the queue
438 private void nextOperation() {
440 //Log_OC.wtf(TAG, "nextOperation init" );
442 Pair
<Target
, RemoteOperation
> next
= null
;
443 synchronized(mPendingOperations
) {
444 next
= mPendingOperations
.peek();
449 mCurrentOperation
= next
.second
;
450 RemoteOperationResult result
= null
;
452 /// prepare client object to send the request to the ownCloud server
453 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
454 mLastTarget
= next
.first
;
455 if (mLastTarget
.mAccount
!= null
) {
456 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
457 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
459 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(),
460 mLastTarget
.mFollowRedirects
); // this is not good enough
461 if (mLastTarget
.mWebDavUrl
!= null
) {
462 mOwnCloudClient
.setWebdavUri(Uri
.parse(mLastTarget
.mWebDavUrl
));
464 if (mLastTarget
.mUsername
!= null
&& mLastTarget
.mPassword
!= null
) {
465 mOwnCloudClient
.setBasicCredentials(mLastTarget
.mUsername
, mLastTarget
.mPassword
);
466 } else if (mLastTarget
.mAuthToken
!= null
) {
467 mOwnCloudClient
.setBearerCredentials(mLastTarget
.mAuthToken
);
468 } else if (mLastTarget
.mCookie
!= null
) {
469 mOwnCloudClient
.setSsoSessionCookie(mLastTarget
.mCookie
);
471 mStorageManager
= null
;
475 /// perform the operation
476 if (mCurrentOperation
instanceof SyncOperation
) {
477 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
479 result
= mCurrentOperation
.execute(mOwnCloudClient
);
482 } catch (AccountsException e
) {
483 if (mLastTarget
.mAccount
== null
) {
484 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
486 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
488 result
= new RemoteOperationResult(e
);
490 } catch (IOException e
) {
491 if (mLastTarget
.mAccount
== null
) {
492 Log_OC
.e(TAG
, "Error while trying to get authorization for a NULL account", e
);
494 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastTarget
.mAccount
.name
, e
);
496 result
= new RemoteOperationResult(e
);
497 } catch (Exception e
) {
498 if (mLastTarget
.mAccount
== null
) {
499 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
501 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
503 result
= new RemoteOperationResult(e
);
506 synchronized(mPendingOperations
) {
507 mPendingOperations
.poll();
511 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
512 dispatchResultToOperationListeners(mLastTarget
, mCurrentOperation
, result
);
518 * Sends a broadcast when a new operation is added to the queue.
520 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
522 * @param target Account or URL pointing to an OC server.
523 * @param operation Added operation.
525 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
526 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
527 if (target
.mAccount
!= null
) {
528 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
530 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
532 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
533 //lbm.sendBroadcast(intent);
534 sendStickyBroadcast(intent
);
538 // TODO - maybe add a notification for real start of operations
541 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
543 * Local broadcasts are only delivered to activities in the same process.
545 * @param target Account or URL pointing to an OC server.
546 * @param operation Finished operation.
547 * @param result Result of the operation.
549 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
550 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
551 intent
.putExtra(EXTRA_RESULT
, result
);
552 if (target
.mAccount
!= null
) {
553 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
555 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
557 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
558 //lbm.sendBroadcast(intent);
559 sendStickyBroadcast(intent
);
564 * Notifies the currently subscribed listeners about the end of an operation.
566 * @param target Account or URL pointing to an OC server.
567 * @param operation Finished operation.
568 * @param result Result of the operation.
570 private void dispatchResultToOperationListeners(
571 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
573 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
574 while (listeners
.hasNext()) {
575 final OnRemoteOperationListener listener
= listeners
.next();
576 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
577 if (handler
!= null
) {
578 handler
.post(new Runnable() {
581 listener
.onRemoteOperationFinish(operation
, result
);
588 //mOperationResults.put(operation.hashCode(), result);
589 Pair
<RemoteOperation
, RemoteOperationResult
> undispatched
=
590 new Pair
<RemoteOperation
, RemoteOperationResult
>(operation
, result
);
591 mUndispatchedFinishedOperations
.put(operation
.hashCode(), undispatched
);
593 Log_OC
.d(TAG
, "Called " + count
+ " listeners");