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
.HashMap
;
22 import java
.util
.Iterator
;
24 import java
.util
.concurrent
.ConcurrentLinkedQueue
;
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";
63 public static final String ACTION_CREATE_SHARE
= "CREATE_SHARE";
64 public static final String ACTION_UNSHARE
= "UNSHARE";
65 public static final String ACTION_DETECT_AUTHENTICATION_METHOD
= "DETECT_AUTHENTICATION_METHOD";
67 public static final String ACTION_OPERATION_ADDED
= OperationsService
.class.getName() + ".OPERATION_ADDED";
68 public static final String ACTION_OPERATION_FINISHED
= OperationsService
.class.getName() + ".OPERATION_FINISHED";
70 private ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>> mPendingOperations
= new ConcurrentLinkedQueue
<Pair
<Target
, RemoteOperation
>>();
72 private static class Target
{
73 public Uri mServerUrl
= null
;
74 public Account mAccount
= null
;
75 public Target(Account account
, Uri serverUrl
) {
77 mServerUrl
= serverUrl
;
81 private Looper mServiceLooper
;
82 private ServiceHandler mServiceHandler
;
83 private OperationsServiceBinder mBinder
;
84 private OwnCloudClient mOwnCloudClient
= null
;
85 private Target mLastTarget
= null
;
86 private FileDataStorageManager mStorageManager
;
87 private RemoteOperation mCurrentOperation
= null
;
91 * Service initialization
94 public void onCreate() {
96 HandlerThread thread
= new HandlerThread("Operations service thread", Process
.THREAD_PRIORITY_BACKGROUND
);
98 mServiceLooper
= thread
.getLooper();
99 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
100 mBinder
= new OperationsServiceBinder();
104 * Entry point to add a new operation to the queue of operations.
106 * New operations are added calling to startService(), resulting in a call to this method.
107 * This ensures the service will keep on working although the caller activity goes away.
109 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
110 * is taking advantage of it due to time constraints.
113 public int onStartCommand(Intent intent
, int flags
, int startId
) {
114 if (!intent
.hasExtra(EXTRA_ACCOUNT
) && !intent
.hasExtra(EXTRA_SERVER_URL
)) {
115 Log_OC
.e(TAG
, "Not enough information provided in intent");
116 return START_NOT_STICKY
;
119 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
120 String serverUrl
= intent
.getStringExtra(EXTRA_SERVER_URL
);
122 Target target
= new Target(account
, (serverUrl
== null
) ? null
: Uri
.parse(serverUrl
));
123 RemoteOperation operation
= null
;
125 String action
= intent
.getAction();
126 if (action
.equals(ACTION_CREATE_SHARE
)) { // Create Share
127 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
128 Intent sendIntent
= intent
.getParcelableExtra(EXTRA_SEND_INTENT
);
129 if (remotePath
.length() > 0) {
130 operation
= new CreateShareOperation(remotePath
, ShareType
.PUBLIC_LINK
,
131 "", false
, "", 1, sendIntent
);
133 } else if (action
.equals(ACTION_UNSHARE
)) { // Unshare file
134 String remotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
135 if (remotePath
.length() > 0) {
136 operation
= new UnshareLinkOperation(remotePath
, this.getApplicationContext());
138 } else if (action
.equals(ACTION_DETECT_AUTHENTICATION_METHOD
)) { // Detect Authentication Method
139 operation
= new DetectAuthenticationMethodOperation(this.getApplicationContext());
142 // nothing we are going to handle
143 return START_NOT_STICKY
;
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() {
206 mBoundListeners
.clear();
211 * Adds a listener interested in being reported about the end of operations.
213 * @param listener Object to notify about the end of operations.
214 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
216 public void addOperationListener (OnRemoteOperationListener listener
, Handler callbackHandler
) {
217 mBoundListeners
.put(listener
, callbackHandler
);
222 * Removes a listener from the list of objects interested in the being reported about the end of operations.
224 * @param listener Object to notify about progress of transfer.
226 public void removeOperationListener (OnRemoteOperationListener listener
) {
227 mBoundListeners
.remove(listener
);
232 * TODO - IMPORTANT: update implementation when more operations are moved into the service
234 * @return 'True' when an operation that enforces the user to wait for completion is in process.
236 public boolean isPerformingBlockingOperation() {
237 return (!mPendingOperations
.isEmpty());
244 * Operations worker. Performs the pending operations in the order they were requested.
246 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
248 private static class ServiceHandler
extends Handler
{
249 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
250 OperationsService mService
;
251 public ServiceHandler(Looper looper
, OperationsService service
) {
253 if (service
== null
) {
254 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
260 public void handleMessage(Message msg
) {
261 mService
.nextOperation();
262 mService
.stopSelf(msg
.arg1
);
268 * Performs the next operation in the queue
270 private void nextOperation() {
272 Pair
<Target
, RemoteOperation
> next
= null
;
273 synchronized(mPendingOperations
) {
274 next
= mPendingOperations
.peek();
279 mCurrentOperation
= next
.second
;
280 RemoteOperationResult result
= null
;
282 /// prepare client object to send the request to the ownCloud server
283 if (mLastTarget
== null
|| !mLastTarget
.equals(next
.first
)) {
284 mLastTarget
= next
.first
;
285 if (mLastTarget
.mAccount
!= null
) {
286 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mAccount
, getApplicationContext());
287 mStorageManager
= new FileDataStorageManager(mLastTarget
.mAccount
, getContentResolver());
289 mOwnCloudClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastTarget
.mServerUrl
, getApplicationContext(), true
); // this is not good enough
290 mStorageManager
= null
;
294 /// perform the operation
295 if (mCurrentOperation
instanceof SyncOperation
) {
296 result
= ((SyncOperation
)mCurrentOperation
).execute(mOwnCloudClient
, mStorageManager
);
298 result
= mCurrentOperation
.execute(mOwnCloudClient
);
301 } catch (AccountsException e
) {
302 if (mLastTarget
.mAccount
== null
) {
303 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
305 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
307 result
= new RemoteOperationResult(e
);
309 } catch (IOException e
) {
310 if (mLastTarget
.mAccount
== null
) {
311 Log_OC
.e(TAG
, "Error while trying to get autorization for a NULL account", e
);
313 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastTarget
.mAccount
.name
, e
);
315 result
= new RemoteOperationResult(e
);
316 } catch (Exception e
) {
317 if (mLastTarget
.mAccount
== null
) {
318 Log_OC
.e(TAG
, "Unexpected error for a NULL account", e
);
320 Log_OC
.e(TAG
, "Unexpected error for " + mLastTarget
.mAccount
.name
, e
);
322 result
= new RemoteOperationResult(e
);
325 synchronized(mPendingOperations
) {
326 mPendingOperations
.poll();
330 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
331 callbackOperationListeners(mLastTarget
, mCurrentOperation
, result
);
337 * Sends a broadcast when a new operation is added to the queue.
339 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
341 * @param target Account or URL pointing to an OC server.
342 * @param operation Added operation.
344 private void sendBroadcastNewOperation(Target target
, RemoteOperation operation
) {
345 Intent intent
= new Intent(ACTION_OPERATION_ADDED
);
346 if (target
.mAccount
!= null
) {
347 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
349 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
351 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
352 //lbm.sendBroadcast(intent);
353 sendStickyBroadcast(intent
);
357 // TODO - maybe add a notification for real start of operations
360 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
362 * Local broadcasts are only delivered to activities in the same process.
364 * @param target Account or URL pointing to an OC server.
365 * @param operation Finished operation.
366 * @param result Result of the operation.
368 private void sendBroadcastOperationFinished(Target target
, RemoteOperation operation
, RemoteOperationResult result
) {
369 Intent intent
= new Intent(ACTION_OPERATION_FINISHED
);
370 intent
.putExtra(EXTRA_RESULT
, result
);
371 if (target
.mAccount
!= null
) {
372 intent
.putExtra(EXTRA_ACCOUNT
, target
.mAccount
);
374 intent
.putExtra(EXTRA_SERVER_URL
, target
.mServerUrl
);
376 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
377 //lbm.sendBroadcast(intent);
378 sendStickyBroadcast(intent
);
383 * Notifies the currently subscribed listeners about the end of an operation.
385 * @param target Account or URL pointing to an OC server.
386 * @param operation Finished operation.
387 * @param result Result of the operation.
389 private void callbackOperationListeners(Target target
, final RemoteOperation operation
, final RemoteOperationResult result
) {
390 Iterator
<OnRemoteOperationListener
> listeners
= mBinder
.mBoundListeners
.keySet().iterator();
391 while (listeners
.hasNext()) {
392 final OnRemoteOperationListener listener
= listeners
.next();
393 final Handler handler
= mBinder
.mBoundListeners
.get(listener
);
394 if (handler
!= null
) {
395 handler
.post(new Runnable() {
398 listener
.onRemoteOperationFinish(operation
, result
);