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
.shares
.ShareType
;
34 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
35 import com
.owncloud
.android
.operations
.CreateShareOperation
;
36 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
37 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
38 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
39 import com
.owncloud
.android
.utils
.Log_OC
;
41 import android
.accounts
.Account
;
42 import android
.accounts
.AccountsException
;
43 import android
.app
.Service
;
44 import android
.content
.Intent
;
45 import android
.net
.Uri
;
46 import android
.os
.Binder
;
47 import android
.os
.Handler
;
48 import android
.os
.HandlerThread
;
49 import android
.os
.IBinder
;
50 import android
.os
.Looper
;
51 import android
.os
.Message
;
52 import android
.os
.Process
;
53 import android
.util
.Pair
;
55 public class OperationsService
extends Service
{
57 private static final String TAG
= OperationsService
.class.getSimpleName();
59 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
60 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
61 public static final String EXTRA_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
62 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS
= "OAUTH2_QUERY_PARAMETERS";
63 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
64 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
65 public static final String EXTRA_RESULT
= "RESULT";
67 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
68 public static final String ACTION_UNSHARE
= "UNSHARE";
69 public static final String ACTION_GET_SERVER_INFO
= "GET_SERVER_INFO";
70 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN
= "OAUTH2_GET_ACCESS_TOKEN";
72 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
73 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
75 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
76 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
78 private ConcurrentMap
<Integer
, RemoteOperationResult
> mOperationResults
=
79 new ConcurrentHashMap
<Integer
, RemoteOperationResult
>();
81 private static class Target
{
82 public Uri mServerUrl
= null
;
83 public Account mAccount
= null
;
84 public Target(Account account
, Uri serverUrl
) {
86 mServerUrl
= serverUrl
;
90 private Looper mServiceLooper
;
91 private ServiceHandler mServiceHandler
;
92 private OperationsServiceBinder mBinder
;
93 private OwnCloudClient mOwnCloudClient
= null
;
94 private Target mLastTarget
= null
;
95 private FileDataStorageManager mStorageManager
;
96 private RemoteOperation mCurrentOperation
= null
;
100 * Service initialization
103 public void onCreate() {
105 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
107 mServiceLooper
= thread
.getLooper();
108 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
109 mBinder
= new OperationsServiceBinder();
114 * Entry point to add a new operation to the queue of operations.
116 * New operations are added calling to startService(), resulting in a call to this method.
117 * This ensures the service will keep on working although the caller activity goes away.
119 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
120 * is taking advantage of it due to time constraints.
123 public int onStartCommand(Intent intent
, int flags
, int startId
) {
124 //Log.wtf(TAG, "onStartCommand init" );
125 Message msg
= mServiceHandler
.obtainMessage();
127 mServiceHandler
.sendMessage(msg
);
128 //Log.wtf(TAG, "onStartCommand end" );
129 return START_NOT_STICKY
;
134 * Provides a binder object that clients can use to perform actions on the queue of operations,
135 * except the addition of new operations.
138 public IBinder
onBind(Intent intent
) {
139 //Log.wtf(TAG, "onBind" );
145 * Called when ALL the bound clients were unbound.
148 public boolean onUnbind(Intent intent
) {
149 ((OperationsServiceBinder
)mBinder
).clearListeners();
150 return false
; // not accepting rebinding (default behaviour)
155 * Binder to let client components to perform actions on the queue of operations.
157 * It provides by itself the available operations.
159 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
162 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
164 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
165 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
168 * Cancels an operation
172 public void cancel() {
177 public void clearListeners() {
179 mBoundListeners
.clear();
184 * Adds a listener interested in being reported about the end of operations.
186 * @param listener Object to notify about the end of operations.
187 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
189 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
190 synchronized (mBoundListeners
) {
191 mBoundListeners
.put(listener
, callbackHandler
);
197 * Removes a listener from the list of objects interested in the being reported about the end of operations.
199 * @param listener Object to notify about progress of transfer.
201 public void removeOperationListener (OnRemoteOperationListener listener
) {
202 synchronized (mBoundListeners
) {
203 mBoundListeners
.remove(listener
);
209 * TODO - IMPORTANT: update implementation when more operations are moved into the service
211 * @return 'True' when an operation that enforces the user to wait for completion is in process.
213 public boolean isPerformingBlockingOperation() {
214 return (!mPendingOperations
.isEmpty());
219 * Creates and adds to the queue a new operation, as described by operationIntent
221 * @param operationIntent Intent describing a new operation to queue and execute.
222 * @return Identifier of the operation created, or -1 if failed.
224 public int newOperation(Intent operationIntent
) {
225 RemoteOperation operation
= null
;
226 Target target
= null
;
228 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
229 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
230 Log_OC
.e(TAG
, "Not enough information provided in intent");
233 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
234 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
237 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
)
240 String action
= operationIntent
.getAction();
241 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
242 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
243 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
244 if (remotePath
.length() > 0) {
245 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
246 "", false
, "", 1, sendIntent
);
248 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
249 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
250 if (remotePath
.length() > 0) {
251 operation
= new UnshareLinkOperation(
253 OperationsService
.this);
255 } else if (action
.equals(ACTION_GET_SERVER_INFO
)) {
256 // check OC server and get basic information from it
257 String authTokenType
=
258 operationIntent
.getStringExtra(EXTRA_AUTH_TOKEN_TYPE
);
259 operation
= new GetServerInfoOperation(
260 serverUrl
, authTokenType
, OperationsService
.this);
262 } else if (action
.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN
)) {
263 /// GET ACCESS TOKEN to the OAuth server
264 String oauth2QueryParameters
=
265 operationIntent
.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS
);
266 operation
= new OAuth2GetAccessToken(
267 getString(R
.string
.oauth2_client_id
),
268 getString(R
.string
.oauth2_redirect_uri
),
269 getString(R
.string
.oauth2_grant_type
),
270 oauth2QueryParameters
);
274 } catch (IllegalArgumentException e
) {
275 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
279 if (operation
!= null
) {
280 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
281 startService(new Intent(OperationsService
.this, OperationsService
.class));
282 return operation
.hashCode();
289 public RemoteOperationResult
getOperationResultIfFinished(int mDetectAuthOpId
) {
290 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
291 return mOperationResults
.remove(mDetectAuthOpId
);
298 * Operations worker. Performs the pending operations in the order they were requested.
300 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
302 private static class ServiceHandler
extends Handler
{
303 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
304 OperationsService mService
;
305 public ServiceHandler(Looper looper
, OperationsService service
) {
307 if (service
== null
) {
308 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
314 public void handleMessage(Message msg
) {
315 mService
.nextOperation();
316 mService
.stopSelf(msg
.arg1
);
322 * Performs the next operation in the queue
324 private void nextOperation() {
326 //Log.wtf(TAG, "nextOperation init" );
328 Pair
<Target
, RemoteOperation
> next
= null
;
329 synchronized(mPendingOperations
) {
330 next
= mPendingOperations
.peek();
335 mCurrentOperation
= next
.second
;
336 RemoteOperationResult result
= null
;
338 /// prepare client object to send the request to the ownCloud server
339 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
340 mLastTarget
= next
.first
;
341 if (mLastTarget
.mAccount
!= null
) {
342 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
343 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
345 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(), true
); // this is not good enough
346 mStorageManager
= null
;
350 /// perform the operation
351 if (mCurrentOperation
instanceof SyncOperation
) {
352 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
354 result
= mCurrentOperation
.execute(mOwnCloudClient
);
357 } catch (AccountsException e
) {
358 if (mLastTarget
.mAccount
== null
) {
359 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
361 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
363 result
= new RemoteOperationResult(e
);
365 } catch (IOException e
) {
366 if (mLastTarget
.mAccount
== null
) {
367 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
369 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
371 result
= new RemoteOperationResult(e
);
372 } catch (Exception e
) {
373 if (mLastTarget
.mAccount
== null
) {
374 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
376 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
378 result
= new RemoteOperationResult(e
);
381 synchronized(mPendingOperations
) {
382 mPendingOperations
.poll();
383 mOperationResults
.put(mCurrentOperation
.hashCode(), result
);
387 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
388 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
394 * Sends a broadcast when a new operation is added to the queue.
396 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
398 * @param target Account or URL pointing to an OC server.
399 * @param operation Added operation.
401 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
402 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
403 if (target
.mAccount
!= null
) {
404 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
406 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
408 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
409 //lbm.sendBroadcast(intent);
410 sendStickyBroadcast(intent
);
414 // TODO - maybe add a notification for real start of operations
417 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
419 * Local broadcasts are only delivered to activities in the same process.
421 * @param target Account or URL pointing to an OC server.
422 * @param operation Finished operation.
423 * @param result Result of the operation.
425 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
426 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
427 intent
.putExtra(EXTRA_RESULT
, result
);
428 if (target
.mAccount
!= null
) {
429 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
431 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
433 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
434 //lbm.sendBroadcast(intent);
435 sendStickyBroadcast(intent
);
440 * Notifies the currently subscribed listeners about the end of an operation.
442 * @param target Account or URL pointing to an OC server.
443 * @param operation Finished operation.
444 * @param result Result of the operation.
446 private void callbackOperationListeners(
447 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
449 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
450 while (listeners
.hasNext()) {
451 final OnRemoteOperationListener listener
= listeners
.next();
452 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
453 if (handler
!= null
) {
454 handler
.post(new Runnable() {
457 listener
.onRemoteOperationFinish(operation
, result
);
463 Log_OC
.d(TAG
, "Called " + count
+ " listeners");