Modifies OperationsService so that activities can request the resulf of operations...
[pub/Android/ownCloud.git] / src / com / owncloud / android / services / OperationsService.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
3 *
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.
7 *
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.
12 *
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/>.
15 *
16 */
17
18 package com.owncloud.android.services;
19
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;
25
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;
38
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;
52
53 public class OperationsService extends Service {
54
55 private static final String TAG = OperationsService.class.getSimpleName();
56
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";
63
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";
67
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";
70
71 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
72 new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
73
74 private ConcurrentMap<Integer, RemoteOperationResult> mOperationResults =
75 new ConcurrentHashMap<Integer, RemoteOperationResult>();
76
77 private static class Target {
78 public Uri mServerUrl = null;
79 public Account mAccount = null;
80 public Target(Account account, Uri serverUrl) {
81 mAccount = account;
82 mServerUrl = serverUrl;
83 }
84 }
85
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;
93
94
95 /**
96 * Service initialization
97 */
98 @Override
99 public void onCreate() {
100 super.onCreate();
101 HandlerThread thread = new HandlerThread("Operations service thread", Process.THREAD_PRIORITY_BACKGROUND);
102 thread.start();
103 mServiceLooper = thread.getLooper();
104 mServiceHandler = new ServiceHandler(mServiceLooper, this);
105 mBinder = new OperationsServiceBinder();
106 }
107
108
109 /**
110 * Entry point to add a new operation to the queue of operations.
111 *
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.
114 *
115 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
116 * is taking advantage of it due to time constraints.
117 */
118 @Override
119 public int onStartCommand(Intent intent, int flags, int startId) {
120 //Log.wtf(TAG, "onStartCommand init" );
121 Message msg = mServiceHandler.obtainMessage();
122 msg.arg1 = startId;
123 mServiceHandler.sendMessage(msg);
124 //Log.wtf(TAG, "onStartCommand end" );
125 return START_NOT_STICKY;
126 }
127
128
129 /**
130 * Provides a binder object that clients can use to perform actions on the queue of operations,
131 * except the addition of new operations.
132 */
133 @Override
134 public IBinder onBind(Intent intent) {
135 //Log.wtf(TAG, "onBind" );
136 return mBinder;
137 }
138
139
140 /**
141 * Called when ALL the bound clients were unbound.
142 */
143 @Override
144 public boolean onUnbind(Intent intent) {
145 ((OperationsServiceBinder)mBinder).clearListeners();
146 return false; // not accepting rebinding (default behaviour)
147 }
148
149
150 /**
151 * Binder to let client components to perform actions on the queue of operations.
152 *
153 * It provides by itself the available operations.
154 */
155 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
156
157 /**
158 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
159 */
160 private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
161 new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
162
163 /**
164 * Cancels an operation
165 *
166 * TODO
167 */
168 public void cancel() {
169 // TODO
170 }
171
172
173 public void clearListeners() {
174
175 mBoundListeners.clear();
176 }
177
178
179 /**
180 * Adds a listener interested in being reported about the end of operations.
181 *
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.
184 */
185 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
186 synchronized (mBoundListeners) {
187 mBoundListeners.put(listener, callbackHandler);
188 }
189 }
190
191
192 /**
193 * Removes a listener from the list of objects interested in the being reported about the end of operations.
194 *
195 * @param listener Object to notify about progress of transfer.
196 */
197 public void removeOperationListener (OnRemoteOperationListener listener) {
198 synchronized (mBoundListeners) {
199 mBoundListeners.remove(listener);
200 }
201 }
202
203
204 /**
205 * TODO - IMPORTANT: update implementation when more operations are moved into the service
206 *
207 * @return 'True' when an operation that enforces the user to wait for completion is in process.
208 */
209 public boolean isPerformingBlockingOperation() {
210 return (!mPendingOperations.isEmpty());
211 }
212
213
214 /**
215 * Creates and adds to the queue a new operation, as described by operationIntent
216 *
217 * @param operationIntent Intent describing a new operation to queue and execute.
218 * @return Identifier of the operation created, or -1 if failed.
219 */
220 public int newOperation(Intent operationIntent) {
221 RemoteOperation operation = null;
222 Target target = null;
223 try {
224 if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
225 !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
226 Log_OC.e(TAG, "Not enough information provided in intent");
227
228 } else {
229 Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
230 String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
231 target = new Target(
232 account,
233 (serverUrl == null) ? null : Uri.parse(serverUrl)
234 );
235
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);
243 }
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(
248 remotePath,
249 OperationsService.this);
250 }
251 } else if (action.equals(ACTION_DETECT_AUTHENTICATION_METHOD)) {
252 // Detect Authentication Method
253 String webdav_url =
254 serverUrl + operationIntent.getStringExtra(EXTRA_WEBDAV_PATH);
255 operation = new DetectAuthenticationMethodOperation(
256 OperationsService.this,
257 webdav_url);
258 }
259 }
260
261 } catch (IllegalArgumentException e) {
262 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
263 operation = null;
264 }
265
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();
270
271 } else {
272 return -1;
273 }
274 }
275
276 public RemoteOperationResult getOperationResultIfFinished(int mDetectAuthOpId) {
277 //Log_OC.wtf(TAG, "Searching result for operation with id " + mDetectAuthOpId);
278 return mOperationResults.remove(mDetectAuthOpId);
279 }
280
281 }
282
283
284 /**
285 * Operations worker. Performs the pending operations in the order they were requested.
286 *
287 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
288 */
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) {
293 super(looper);
294 if (service == null) {
295 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
296 }
297 mService = service;
298 }
299
300 @Override
301 public void handleMessage(Message msg) {
302 mService.nextOperation();
303 mService.stopSelf(msg.arg1);
304 }
305 }
306
307
308 /**
309 * Performs the next operation in the queue
310 */
311 private void nextOperation() {
312
313 //Log.wtf(TAG, "nextOperation init" );
314
315 Pair<Target, RemoteOperation> next = null;
316 synchronized(mPendingOperations) {
317 next = mPendingOperations.peek();
318 }
319
320 if (next != null) {
321
322 mCurrentOperation = next.second;
323 RemoteOperationResult result = null;
324 try {
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());
331 } else {
332 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(), true); // this is not good enough
333 mStorageManager = null;
334 }
335 }
336
337 /// perform the operation
338 if (mCurrentOperation instanceof SyncOperation) {
339 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
340 } else {
341 result = mCurrentOperation.execute(mOwnCloudClient);
342 }
343
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);
347 } else {
348 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
349 }
350 result = new RemoteOperationResult(e);
351
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);
355 } else {
356 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
357 }
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);
362 } else {
363 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
364 }
365 result = new RemoteOperationResult(e);
366
367 } finally {
368 synchronized(mPendingOperations) {
369 mPendingOperations.poll();
370 mOperationResults.put(mCurrentOperation.hashCode(), result);
371 }
372 }
373
374 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
375 callbackOperationListeners(mLastTarget, mCurrentOperation, result);
376 }
377 }
378
379
380 /**
381 * Sends a broadcast when a new operation is added to the queue.
382 *
383 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
384 *
385 * @param target Account or URL pointing to an OC server.
386 * @param operation Added operation.
387 */
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);
392 } else {
393 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
394 }
395 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
396 //lbm.sendBroadcast(intent);
397 sendStickyBroadcast(intent);
398 }
399
400
401 // TODO - maybe add a notification for real start of operations
402
403 /**
404 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
405 *
406 * Local broadcasts are only delivered to activities in the same process.
407 *
408 * @param target Account or URL pointing to an OC server.
409 * @param operation Finished operation.
410 * @param result Result of the operation.
411 */
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);
417 } else {
418 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
419 }
420 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
421 //lbm.sendBroadcast(intent);
422 sendStickyBroadcast(intent);
423 }
424
425
426 /**
427 * Notifies the currently subscribed listeners about the end of an operation.
428 *
429 * @param target Account or URL pointing to an OC server.
430 * @param operation Finished operation.
431 * @param result Result of the operation.
432 */
433 private void callbackOperationListeners(
434 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
435 int count = 0;
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() {
442 @Override
443 public void run() {
444 listener.onRemoteOperationFinish(operation, result);
445 }
446 });
447 count += 1;
448 }
449 }
450 Log_OC.d(TAG, "Called " + count + " listeners");
451 }
452
453
454 }