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
.HashMap
;
22 import java
.util
.HashSet
;
23 import java
.util
.Iterator
;
26 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
28 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
30 import com
.owncloud
.android
.lib
.network
.OnDatatransferProgressListener
;
31 import com
.owncloud
.android
.lib
.network
.OwnCloudClientFactory
;
32 import com
.owncloud
.android
.lib
.network
.OwnCloudClient
;
33 import com
.owncloud
.android
.operations
.CreateShareOperation
;
34 import com
.owncloud
.android
.operations
.GetSharesOperation
;
35 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
36 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
37 import com
.owncloud
.android
.lib
.operations
.common
.OnRemoteOperationListener
;
38 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
39 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
40 import com
.owncloud
.android
.lib
.operations
.common
.ShareType
;
41 import com
.owncloud
.android
.utils
.Log_OC
;
43 import android
.accounts
.Account
;
44 import android
.accounts
.AccountsException
;
45 import android
.app
.Service
;
46 import android
.content
.Intent
;
47 import android
.net
.Uri
;
48 import android
.os
.Binder
;
49 import android
.os
.Handler
;
50 import android
.os
.HandlerThread
;
51 import android
.os
.IBinder
;
52 import android
.os
.Looper
;
53 import android
.os
.Message
;
54 import android
.os
.Process
;
55 //import android.support.v4.content.LocalBroadcastManager;
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_REMOTE_PATH
= "REMOTE_PATH";
65 public static final String EXTRA_SEND_INTENT
= "SEND_INTENT";
66 public static final String EXTRA_RESULT
= "RESULT";
68 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
69 public static final String ACTION_UNSHARE
= "UNSHARE";
71 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
72 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
74 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
= new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
76 private static class Target
{
77 public Uri mServerUrl
= null
;
78 public Account mAccount
= null
;
79 public Target(Account account
, Uri serverUrl
) {
81 mServerUrl
= serverUrl
;
85 private Looper mServiceLooper
;
86 private ServiceHandler mServiceHandler
;
87 private OperationsServiceBinder mBinder
;
88 private OwnCloudClient mOwnCloudClient
= null
;
89 private Target mLastTarget
= null
;
90 private FileDataStorageManager mStorageManager
;
91 private RemoteOperation mCurrentOperation
= null
;
95 * Service initialization
98 public void onCreate() {
100 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
102 mServiceLooper
= thread
.getLooper();
103 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
104 mBinder
= new OperationsServiceBinder();
108 * Entry point to add a new operation to the queue of operations.
110 * New operations are added calling to startService(), resulting in a call to this method.
111 * This ensures the service will keep on working although the caller activity goes away.
113 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
114 * is taking advantage of it due to time constraints.
117 public int onStartCommand(Intent intent
, int flags
, int startId
) {
118 if (!intent
.hasExtra(EXTRA_ACCOUNT
) && !intent
.hasExtra(EXTRA_SERVER_URL
)) {
119 Log_OC
.e(TAG
, "Not enough information provided in intent");
120 return START_NOT_STICKY
;
123 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
124 String serverUrl
= intent
.getStringExtra(EXTRA_SERVER_URL
);
126 Target target
= new Target(account
, (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
));
127 RemoteOperation operation
= null
;
129 String action
= intent
.getAction();
130 if (action
== ACTION_CREATE_SHARE
) { // Create Share
131 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
132 Intent sendIntent
= intent
.getParcelableExtra(EXTRA_SEND_INTENT
);
133 if (remotePath
.length() > 0) {
134 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
135 "", false
, "", 1, sendIntent
);
137 } else if (action
== ACTION_UNSHARE
) { // Unshare file
138 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
139 if (remotePath
.length() > 0) {
140 operation
= new UnshareLinkOperation(remotePath
, this.getApplicationContext());
143 operation
= new GetSharesOperation();
146 mPendingOperations
.add(new Pair
<Target
, RemoteOperation
>(target
, operation
));
147 sendBroadcastNewOperation(target
, operation
);
149 Message msg
= mServiceHandler
.obtainMessage();
151 mServiceHandler
.sendMessage(msg
);
153 } catch (IllegalArgumentException e
) {
154 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
155 return START_NOT_STICKY
;
158 return START_NOT_STICKY
;
163 * Provides a binder object that clients can use to perform actions on the queue of operations,
164 * except the addition of new operations.
167 public IBinder
onBind(Intent intent
) {
173 * Called when ALL the bound clients were unbound.
176 public boolean onUnbind(Intent intent
) {
177 //((OperationsServiceBinder)mBinder).clearListeners();
178 return false
; // not accepting rebinding (default behaviour)
183 * Binder to let client components to perform actions on the queue of operations.
185 * It provides by itself the available operations.
187 public class OperationsServiceBinder
extends Binder
/* implements OnRemoteOperationListener */ {
190 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
192 private Map
<OnRemoteOperationListener
, Handler
> mBoundListeners
= new HashMap
<OnRemoteOperationListener
, Handler
>();
195 * Cancels an operation
199 public void cancel() {
204 public void clearListeners() {
205 mBoundListeners
.clear();
210 * Adds a listener interested in being reported about the end of operations.
212 * @param listener Object to notify about the end of operations.
213 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
215 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
216 mBoundListeners
.put(listener
, callbackHandler
);
221 * Removes a listener from the list of objects interested in the being reported about the end of operations.
223 * @param listener Object to notify about progress of transfer.
225 public void removeOperationListener (OnRemoteOperationListener listener
) {
226 mBoundListeners
.remove(listener
);
231 * TODO - IMPORTANT: update implementation when more operations are moved into the service
233 * @return 'True' when an operation that enforces the user to wait for completion is in process.
235 public boolean isPerformingBlockingOperation() {
236 return (mPendingOperations
.size() > 0);
243 * Operations worker. Performs the pending operations in the order they were requested.
245 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
247 private static class ServiceHandler
extends Handler
{
248 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
249 OperationsService mService
;
250 public ServiceHandler(Looper looper
, OperationsService service
) {
252 if (service
== null
) {
253 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
259 public void handleMessage(Message msg
) {
260 mService
.nextOperation();
261 mService
.stopSelf(msg
.arg1
);
267 * Performs the next operation in the queue
269 private void nextOperation() {
271 Pair
<Target
, RemoteOperation
> next
= null
;
272 synchronized(mPendingOperations
) {
273 next
= mPendingOperations
.peek();
278 mCurrentOperation
= next
.second
;
279 RemoteOperationResult result
= null
;
281 /// prepare client object to send the request to the ownCloud server
282 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
283 mLastTarget
= next
.first
;
284 if (mLastTarget
.mAccount
!= null
) {
285 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
286 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
288 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(), true
); // this is not good enough
289 mStorageManager
= null
;
293 /// perform the operation
294 if (mCurrentOperation
instanceof SyncOperation
) {
295 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
297 result
= mCurrentOperation
.execute(mOwnCloudClient
);
300 } catch (AccountsException e
) {
301 if (mLastTarget
.mAccount
== null
) {
302 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
304 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
306 result
= new RemoteOperationResult(e
);
308 } catch (IOException e
) {
309 if (mLastTarget
.mAccount
== null
) {
310 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
312 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
314 result
= new RemoteOperationResult(e
);
315 } catch (Exception e
) {
316 if (mLastTarget
.mAccount
== null
) {
317 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
319 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
321 result
= new RemoteOperationResult(e
);
324 synchronized(mPendingOperations
) {
325 mPendingOperations
.poll();
329 sendBroadcastOperationFinished(mLastTarget
, mCurrentOperation
, result
);
330 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
336 * Sends a broadcast when a new operation is added to the queue.
338 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
340 * @param target Account or URL pointing to an OC server.
341 * @param operation Added operation.
343 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
344 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
345 if (target
.mAccount
!= null
) {
346 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
348 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
350 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
351 //lbm.sendBroadcast(intent);
352 sendStickyBroadcast(intent
);
356 // TODO - maybe add a notification for real start of operations
359 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
361 * Local broadcasts are only delivered to activities in the same process.
363 * @param target Account or URL pointing to an OC server.
364 * @param operation Finished operation.
365 * @param result Result of the operation.
367 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
368 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
369 intent
.putExtra(EXTRA_RESULT
, result
);
370 if (target
.mAccount
!= null
) {
371 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
373 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
375 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
376 //lbm.sendBroadcast(intent);
377 sendStickyBroadcast(intent
);
382 * Notifies the currently subscribed listeners about the end of an operation.
384 * @param target Account or URL pointing to an OC server.
385 * @param operation Finished operation.
386 * @param result Result of the operation.
388 private void callbackOperationListeners(Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
389 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
390 while (listeners
.hasNext()) {
391 final OnRemoteOperationListener listener
= listeners
.next();
392 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
393 if (handler
!= null
) {
394 handler
.post(new Runnable() {
397 listener
.onRemoteOperationFinish(operation
, result
);