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
.shares
.ShareType
;
33 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
34 import com
.owncloud
.android
.operations
.CreateShareOperation
;
35 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
;
36 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
37 import com
.owncloud
.android
.utils
.Log_OC
;
39 import android
.accounts
.Account
;
40 import android
.accounts
.AccountsException
;
41 import android
.app
.Service
;
42 import android
.content
.Intent
;
43 import android
.net
.Uri
;
44 import android
.os
.Binder
;
45 import android
.os
.Handler
;
46 import android
.os
.HandlerThread
;
47 import android
.os
.IBinder
;
48 import android
.os
.Looper
;
49 import android
.os
.Message
;
50 import android
.os
.Process
;
51 import android
.util
.Pair
;
53 public class OperationsService
extends Service
{
55 private static final String TAG
= OperationsService
.class.getSimpleName();
57 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
58 public static final String EXTRA_SERVER_URL
= "SERVER_URL";
59 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
60 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
61 public static final String EXTRA_RESULT
= "RESULT";
62 public static final String EXTRA_WEBDAV_PATH
= "WEBDAV_PATH";
64 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
65 public static final String ACTION_UNSHARE
= "UNSHARE";
66 public static final String ACTION_DETECT_AUTHENTICATION_METHOD
= "DETECT_AUTHENTICATION_METHOD";
68 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
69 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
71 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
=
72 new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
74 private ConcurrentMap
<Integer
, RemoteOperationResult
> mOperationResults
=
75 new ConcurrentHashMap
<Integer
, RemoteOperationResult
>();
77 private static class Target
{
78 public Uri mServerUrl
= null
;
79 public Account mAccount
= null
;
80 public Target(Account account
, Uri serverUrl
) {
82 mServerUrl
= serverUrl
;
86 private Looper mServiceLooper
;
87 private ServiceHandler mServiceHandler
;
88 private OperationsServiceBinder mBinder
;
89 private OwnCloudClient mOwnCloudClient
= null
;
90 private Target mLastTarget
= null
;
91 private FileDataStorageManager mStorageManager
;
92 private RemoteOperation mCurrentOperation
= null
;
96 * Service initialization
99 public void onCreate() {
101 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
103 mServiceLooper
= thread
.getLooper();
104 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
105 mBinder
= new OperationsServiceBinder();
110 * Entry point to add a new operation to the queue of operations.
112 * New operations are added calling to startService(), resulting in a call to this method.
113 * This ensures the service will keep on working although the caller activity goes away.
115 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
116 * is taking advantage of it due to time constraints.
119 public int onStartCommand(Intent intent
, int flags
, int startId
) {
120 //Log.wtf(TAG, "onStartCommand init" );
121 Message msg
= mServiceHandler
.obtainMessage();
123 mServiceHandler
.sendMessage(msg
);
124 //Log.wtf(TAG, "onStartCommand end" );
125 return START_NOT_STICKY
;
130 * Provides a binder object that clients can use to perform actions on the queue of operations,
131 * except the addition of new operations.
134 public IBinder
onBind(Intent intent
) {
135 //Log.wtf(TAG, "onBind" );
141 * Called when ALL the bound clients were unbound.
144 public boolean onUnbind(Intent intent
) {
145 ((OperationsServiceBinder
)mBinder
).clearListeners();
146 return false
; // not accepting rebinding (default behaviour)
151 * Binder to let client components to perform actions on the queue of operations.
153 * It provides by itself the available operations.
155 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
158 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
160 private ConcurrentMap
<OnRemoteOperationListener
, Handler
> mBoundListeners
=
161 new ConcurrentHashMap
<OnRemoteOperationListener
, Handler
>();
164 * Cancels an operation
168 public void cancel() {
173 public void clearListeners() {
175 mBoundListeners
.clear();
180 * Adds a listener interested in being reported about the end of operations.
182 * @param listener Object to notify about the end of operations.
183 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
185 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
186 synchronized (mBoundListeners
) {
187 mBoundListeners
.put(listener
, callbackHandler
);
193 * Removes a listener from the list of objects interested in the being reported about the end of operations.
195 * @param listener Object to notify about progress of transfer.
197 public void removeOperationListener (OnRemoteOperationListener listener
) {
198 synchronized (mBoundListeners
) {
199 mBoundListeners
.remove(listener
);
205 * TODO - IMPORTANT: update implementation when more operations are moved into the service
207 * @return 'True' when an operation that enforces the user to wait for completion is in process.
209 public boolean isPerformingBlockingOperation() {
210 return (!mPendingOperations
.isEmpty());
215 * Creates and adds to the queue a new operation, as described by operationIntent
217 * @param operationIntent Intent describing a new operation to queue and execute.
218 * @return Identifier of the operation created, or -1 if failed.
220 public int newOperation(Intent operationIntent
) {
221 RemoteOperation operation
= null
;
222 Target target
= null
;
224 if (!operationIntent
.hasExtra(EXTRA_ACCOUNT
) &&
225 !operationIntent
.hasExtra(EXTRA_SERVER_URL
)) {
226 Log_OC
.e(TAG
, "Not enough information provided in intent");
229 Account account
= operationIntent
.getParcelableExtra(EXTRA_ACCOUNT
);
230 String serverUrl
= operationIntent
.getStringExtra(EXTRA_SERVER_URL
);
233 (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
)
236 String action
= operationIntent
.getAction();
237 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
238 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
239 Intent sendIntent
= operationIntent
.getParcelableExtra(EXTRA_SEND_INTENT
);
240 if (remotePath
.length() > 0) {
241 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
242 "", false
, "", 1, sendIntent
);
244 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
245 String remotePath
= operationIntent
.getStringExtra(EXTRA_REMOTE_PATH
);
246 if (remotePath
.length() > 0) {
247 operation
= new UnshareLinkOperation(
249 OperationsService
.this);
251 } else if (action
.equals(ACTION_DETECT_AUTHENTICATION_METHOD
)) {
252 // Detect Authentication Method
254 serverUrl
+ operationIntent
.getStringExtra(EXTRA_WEBDAV_PATH
);
255 operation
= new DetectAuthenticationMethodOperation(
256 OperationsService
.this,
261 } catch (IllegalArgumentException e
) {
262 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
266 if (operation
!= null
) {
267 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
268 startService(new Intent(OperationsService
.this, OperationsService
.class));
269 return operation
.hashCode();
276 public RemoteOperationResult
getOperationResultIfFinished(int mDetectAuthOpId
) {
277 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
278 return mOperationResults
.remove(mDetectAuthOpId
);
285 * Operations worker. Performs the pending operations in the order they were requested.
287 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
289 private static class ServiceHandler
extends Handler
{
290 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
291 OperationsService mService
;
292 public ServiceHandler(Looper looper
, OperationsService service
) {
294 if (service
== null
) {
295 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
301 public void handleMessage(Message msg
) {
302 mService
.nextOperation();
303 mService
.stopSelf(msg
.arg1
);
309 * Performs the next operation in the queue
311 private void nextOperation() {
313 //Log.wtf(TAG, "nextOperation init" );
315 Pair
<Target
, RemoteOperation
> next
= null
;
316 synchronized(mPendingOperations
) {
317 next
= mPendingOperations
.peek();
322 mCurrentOperation
= next
.second
;
323 RemoteOperationResult result
= null
;
325 /// prepare client object to send the request to the ownCloud server
326 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
327 mLastTarget
= next
.first
;
328 if (mLastTarget
.mAccount
!= null
) {
329 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
330 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
332 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(), true
); // this is not good enough
333 mStorageManager
= null
;
337 /// perform the operation
338 if (mCurrentOperation
instanceof SyncOperation
) {
339 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
341 result
= mCurrentOperation
.execute(mOwnCloudClient
);
344 } catch (AccountsException e
) {
345 if (mLastTarget
.mAccount
== null
) {
346 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
348 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
350 result
= new RemoteOperationResult(e
);
352 } catch (IOException e
) {
353 if (mLastTarget
.mAccount
== null
) {
354 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
356 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
358 result
= new RemoteOperationResult(e
);
359 } catch (Exception e
) {
360 if (mLastTarget
.mAccount
== null
) {
361 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
363 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
365 result
= new RemoteOperationResult(e
);
368 synchronized(mPendingOperations
) {
369 mPendingOperations
.poll();
370 mOperationResults
.put(mCurrentOperation
.hashCode(), result
);
374 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
375 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
381 * Sends a broadcast when a new operation is added to the queue.
383 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
385 * @param target Account or URL pointing to an OC server.
386 * @param operation Added operation.
388 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
389 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
390 if (target
.mAccount
!= null
) {
391 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
393 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
395 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
396 //lbm.sendBroadcast(intent);
397 sendStickyBroadcast(intent
);
401 // TODO - maybe add a notification for real start of operations
404 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
406 * Local broadcasts are only delivered to activities in the same process.
408 * @param target Account or URL pointing to an OC server.
409 * @param operation Finished operation.
410 * @param result Result of the operation.
412 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
413 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
414 intent
.putExtra(EXTRA_RESULT
, result
);
415 if (target
.mAccount
!= null
) {
416 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
418 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
420 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
421 //lbm.sendBroadcast(intent);
422 sendStickyBroadcast(intent
);
427 * Notifies the currently subscribed listeners about the end of an operation.
429 * @param target Account or URL pointing to an OC server.
430 * @param operation Finished operation.
431 * @param result Result of the operation.
433 private void callbackOperationListeners(
434 Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
436 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
437 while (listeners
.hasNext()) {
438 final OnRemoteOperationListener listener
= listeners
.next();
439 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
440 if (handler
!= null
) {
441 handler
.post(new Runnable() {
444 listener
.onRemoteOperationFinish(operation
, result
);
450 Log_OC
.d(TAG
, "Called " + count
+ " listeners");