1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 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
.HashSet
;
22 import java
.util
.Iterator
;
24 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
26 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
28 import com
.owncloud
.android
.lib
.network
.OnDatatransferProgressListener
;
29 import com
.owncloud
.android
.lib
.network
.OwnCloudClientFactory
;
30 import com
.owncloud
.android
.lib
.network
.OwnCloudClient
;
31 import com
.owncloud
.android
.operations
.GetSharesOperation
;
32 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
33 import com
.owncloud
.android
.lib
.operations
.common
.OnRemoteOperationListener
;
34 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
35 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
36 import com
.owncloud
.android
.utils
.Log_OC
;
38 import android
.accounts
.Account
;
39 import android
.accounts
.AccountsException
;
40 import android
.app
.Service
;
41 import android
.content
.Intent
;
42 import android
.net
.Uri
;
43 import android
.os
.Binder
;
44 import android
.os
.Handler
;
45 import android
.os
.HandlerThread
;
46 import android
.os
.IBinder
;
47 import android
.os
.Looper
;
48 import android
.os
.Message
;
49 import android
.os
.Process
;
50 //import android.support.v4.content.LocalBroadcastManager;
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_RESULT
= "RESULT";
61 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
62 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
64 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
= new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
66 private static class Target
{
67 public Uri mServerUrl
= null
;
68 public Account mAccount
= null
;
69 public Target(Account account
, Uri serverUrl
) {
71 mServerUrl
= serverUrl
;
75 private Looper mServiceLooper
;
76 private ServiceHandler mServiceHandler
;
77 private OperationsServiceBinder mBinder
;
78 private OwnCloudClient mOwnCloudClient
= null
;
79 private Target mLastTarget
= null
;
80 private FileDataStorageManager mStorageManager
;
81 private RemoteOperation mCurrentOperation
= null
;
85 * Service initialization
88 public void onCreate() {
90 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
92 mServiceLooper
= thread
.getLooper();
93 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
94 mBinder
= new OperationsServiceBinder();
98 * Entry point to add a new operation to the queue of operations.
100 * New operations are added calling to startService(), resulting in a call to this method.
101 * This ensures the service will keep on working although the caller activity goes away.
103 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
104 * is taking advantage of it due to time constraints.
107 public int onStartCommand(Intent intent
, int flags
, int startId
) {
108 if (!intent
.hasExtra(EXTRA_ACCOUNT
) && !intent
.hasExtra(EXTRA_SERVER_URL
)) {
109 Log_OC
.e(TAG
, "Not enough information provided in intent");
110 return START_NOT_STICKY
;
113 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
114 String serverUrl
= intent
.getStringExtra(EXTRA_SERVER_URL
);
115 Target target
= new Target(account
, (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
));
116 GetSharesOperation operation
= new GetSharesOperation();
117 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
118 sendBroadcastNewOperation(target
, operation
);
120 Message msg
= mServiceHandler
.obtainMessage();
122 mServiceHandler
.sendMessage(msg
);
124 } catch (IllegalArgumentException e
) {
125 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
126 return START_NOT_STICKY
;
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
) {
144 * Called when ALL the bound clients were unbound.
147 public boolean onUnbind(Intent intent
) {
148 //((OperationsServiceBinder)mBinder).clearListeners();
149 return false
; // not accepting rebinding (default behaviour)
154 * Binder to let client components to perform actions on the queue of operations.
156 * It provides by itself the available operations.
158 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
161 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
163 private Set
<OnRemoteOperationListener
> mBoundListeners
= new HashSet
<OnRemoteOperationListener
>();
166 * Cancels an operation
170 public void cancel() {
175 public void clearListeners() {
176 mBoundListeners
.clear();
181 * Adds a listener interested in being reported about the end of operations.
183 * @param listener Object to notify about the end of operations.
185 public void addOperationListener (OnRemoteOperationListener listener
) {
186 mBoundListeners
.add(listener
);
191 * Removes a listener from the list of objects interested in the being reported about the end of operations.
193 * @param listener Object to notify about progress of transfer.
195 public void removeOperationListener (OnRemoteOperationListener listener
) {
196 mBoundListeners
.remove(listener
);
201 * TODO - IMPORTANT: update implementation when more operations are moved into the service
203 * @return 'True' when an operation that enforces the user to wait for completion is in process.
205 public boolean isPerformingBlockingOperation() {
206 return (mPendingOperations
.size() > 0);
213 * Operations worker. Performs the pending operations in the order they were requested.
215 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
217 private static class ServiceHandler
extends Handler
{
218 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
219 OperationsService mService
;
220 public ServiceHandler(Looper looper
, OperationsService service
) {
222 if (service
== null
) {
223 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
229 public void handleMessage(Message msg
) {
230 mService
.nextOperation();
231 mService
.stopSelf(msg
.arg1
);
237 * Performs the next operation in the queue
239 private void nextOperation() {
241 Pair
<Target
, RemoteOperation
> next
= null
;
242 synchronized(mPendingOperations
) {
243 next
= mPendingOperations
.peek();
248 mCurrentOperation
= next
.second
;
249 RemoteOperationResult result
= null
;
251 /// prepare client object to send the request to the ownCloud server
252 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
253 mLastTarget
= next
.first
;
254 if (mLastTarget
.mAccount
!= null
) {
255 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
256 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
258 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(), true
); // this is not good enough
259 mStorageManager
= null
;
263 /// perform the operation
264 if (mCurrentOperation
instanceof SyncOperation
) {
265 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
267 result
= mCurrentOperation
.execute(mOwnCloudClient
);
270 } catch (AccountsException e
) {
271 if (mLastTarget
.mAccount
== null
) {
272 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
274 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
276 result
= new RemoteOperationResult(e
);
278 } catch (IOException e
) {
279 if (mLastTarget
.mAccount
== null
) {
280 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
282 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
284 result
= new RemoteOperationResult(e
);
285 } catch (Exception e
) {
286 if (mLastTarget
.mAccount
== null
) {
287 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
289 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
291 result
= new RemoteOperationResult(e
);
294 synchronized(mPendingOperations
) {
295 mPendingOperations
.poll();
299 sendBroadcastOperationFinished(mLastTarget
, mCurrentOperation
, result
);
300 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
306 * Sends a broadcast when a new operation is added to the queue.
308 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
310 * @param target Account or URL pointing to an OC server.
311 * @param operation Added operation.
313 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
314 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
315 if (target
.mAccount
!= null
) {
316 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
318 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
320 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
321 //lbm.sendBroadcast(intent);
322 sendStickyBroadcast(intent
);
326 // TODO - maybe add a notification for real start of operations
329 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
331 * Local broadcasts are only delivered to activities in the same process.
333 * @param target Account or URL pointing to an OC server.
334 * @param operation Finished operation.
335 * @param result Result of the operation.
337 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
338 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
339 intent
.putExtra(EXTRA_RESULT
, result
);
340 if (target
.mAccount
!= null
) {
341 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
343 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
345 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
346 //lbm.sendBroadcast(intent);
347 sendStickyBroadcast(intent
);
352 * Notifies the currently subscribed listeners about the end of an operation.
354 * @param target Account or URL pointing to an OC server.
355 * @param operation Finished operation.
356 * @param result Result of the operation.
358 private void callbackOperationListeners(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
359 Iterator
<OnRemoteOperationListener
> it
= mBinder
.mBoundListeners
.iterator();
360 while (it
.hasNext()) {
361 it
.next().onRemoteOperationFinish(operation
, result
);