Merge pull request #797 from owncloud/download_folder__in_a_separate_worker_thread
[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.MainApp;
27 import com.owncloud.android.R;
28 import com.owncloud.android.datamodel.FileDataStorageManager;
29 import com.owncloud.android.lib.common.OwnCloudAccount;
30 import com.owncloud.android.lib.common.OwnCloudClient;
31 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
32 import com.owncloud.android.lib.common.OwnCloudCredentials;
33 import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
34 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
35 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
36 import com.owncloud.android.lib.common.operations.RemoteOperation;
37 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
38 import com.owncloud.android.lib.common.utils.Log_OC;
39 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
40 import com.owncloud.android.lib.resources.shares.ShareType;
41 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
42 import com.owncloud.android.operations.common.SyncOperation;
43 import com.owncloud.android.operations.CreateFolderOperation;
44 import com.owncloud.android.operations.CreateShareOperation;
45 import com.owncloud.android.operations.GetServerInfoOperation;
46 import com.owncloud.android.operations.MoveFileOperation;
47 import com.owncloud.android.operations.OAuth2GetAccessToken;
48 import com.owncloud.android.operations.RemoveFileOperation;
49 import com.owncloud.android.operations.RenameFileOperation;
50 import com.owncloud.android.operations.SynchronizeFileOperation;
51 import com.owncloud.android.operations.SynchronizeFolderOperation;
52 import com.owncloud.android.operations.UnshareLinkOperation;
53
54 import android.accounts.Account;
55 import android.accounts.AccountsException;
56 import android.accounts.AuthenticatorException;
57 import android.accounts.OperationCanceledException;
58 import android.app.Service;
59 import android.content.Intent;
60 import android.net.Uri;
61 import android.os.Binder;
62 import android.os.Handler;
63 import android.os.HandlerThread;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.Message;
67 import android.os.Process;
68 import android.util.Pair;
69
70 public class OperationsService extends Service {
71
72 private static final String TAG = OperationsService.class.getSimpleName();
73
74 public static final String EXTRA_ACCOUNT = "ACCOUNT";
75 public static final String EXTRA_SERVER_URL = "SERVER_URL";
76 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
77 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
78 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
79 public static final String EXTRA_NEWNAME = "NEWNAME";
80 public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
81 public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
82 public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
83 public static final String EXTRA_RESULT = "RESULT";
84 public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
85
86 // TODO review if ALL OF THEM are necessary
87 public static final String EXTRA_SUCCESS_IF_ABSENT = "SUCCESS_IF_ABSENT";
88 public static final String EXTRA_USERNAME = "USERNAME";
89 public static final String EXTRA_PASSWORD = "PASSWORD";
90 public static final String EXTRA_AUTH_TOKEN = "AUTH_TOKEN";
91 public static final String EXTRA_COOKIE = "COOKIE";
92
93 public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
94 public static final String ACTION_UNSHARE = "UNSHARE";
95 public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
96 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
97 public static final String ACTION_EXISTENCE_CHECK = "EXISTENCE_CHECK";
98 public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
99 public static final String ACTION_RENAME = "RENAME";
100 public static final String ACTION_REMOVE = "REMOVE";
101 public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
102 public static final String ACTION_SYNC_FILE = "SYNC_FILE";
103 public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER"; // for the moment, just to download
104 public static final String ACTION_MOVE_FILE = "MOVE_FILE";
105
106 public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
107 public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
108
109
110 private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
111 mUndispatchedFinishedOperations =
112 new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
113
114 private static class Target {
115 public Uri mServerUrl = null;
116 public Account mAccount = null;
117 public String mUsername = null;
118 public String mPassword = null;
119 public String mAuthToken = null;
120 public String mCookie = null;
121
122 public Target(Account account, Uri serverUrl, String username, String password, String authToken,
123 String cookie) {
124 mAccount = account;
125 mServerUrl = serverUrl;
126 mUsername = username;
127 mPassword = password;
128 mAuthToken = authToken;
129 mCookie = cookie;
130 }
131 }
132
133 private ServiceHandler mOperationsHandler;
134 private OperationsServiceBinder mOperationsBinder;
135
136 private ServiceHandler mSyncFolderHandler;
137
138 /**
139 * Service initialization
140 */
141 @Override
142 public void onCreate() {
143 super.onCreate();
144 /// First worker thread for most of operations
145 HandlerThread thread = new HandlerThread("Operations thread", Process.THREAD_PRIORITY_BACKGROUND);
146 thread.start();
147 mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
148 mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);
149
150 /// Separated worker thread for download of folders (WIP)
151 thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
152 thread.start();
153 mSyncFolderHandler = new ServiceHandler(thread.getLooper(), this);
154 }
155
156
157 /**
158 * Entry point to add a new operation to the queue of operations.
159 *
160 * New operations are added calling to startService(), resulting in a call to this method.
161 * This ensures the service will keep on working although the caller activity goes away.
162 */
163 @Override
164 public int onStartCommand(Intent intent, int flags, int startId) {
165 if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {
166 // WIP: for the moment, only SYNC_FOLDER is expected here; the rest of the operations are requested through
167 // the Binder
168 Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
169 if (itemToQueue != null) {
170 mSyncFolderHandler.mPendingOperations.add(itemToQueue);
171 Message msg = mSyncFolderHandler.obtainMessage();
172 msg.arg1 = startId;
173 mSyncFolderHandler.sendMessage(msg);
174 }
175
176 } else {
177 Message msg = mOperationsHandler.obtainMessage();
178 msg.arg1 = startId;
179 mOperationsHandler.sendMessage(msg);
180 }
181
182 return START_NOT_STICKY;
183 }
184
185 @Override
186 public void onDestroy() {
187 //Log_OC.wtf(TAG, "onDestroy init" );
188 // Saving cookies
189 try {
190 OwnCloudClientManagerFactory.getDefaultSingleton().
191 saveAllClients(this, MainApp.getAccountType());
192
193 // TODO - get rid of these exceptions
194 } catch (AccountNotFoundException e) {
195 e.printStackTrace();
196 } catch (AuthenticatorException e) {
197 e.printStackTrace();
198 } catch (OperationCanceledException e) {
199 e.printStackTrace();
200 } catch (IOException e) {
201 e.printStackTrace();
202 }
203
204 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
205 mUndispatchedFinishedOperations.clear();
206
207 //Log_OC.wtf(TAG, "onDestroy end" );
208 super.onDestroy();
209 }
210
211
212 /**
213 * Provides a binder object that clients can use to perform actions on the queue of operations,
214 * except the addition of new operations.
215 */
216 @Override
217 public IBinder onBind(Intent intent) {
218 //Log_OC.wtf(TAG, "onBind" );
219 return mOperationsBinder;
220 }
221
222
223 /**
224 * Called when ALL the bound clients were unbound.
225 */
226 @Override
227 public boolean onUnbind(Intent intent) {
228 ((OperationsServiceBinder)mOperationsBinder).clearListeners();
229 return false; // not accepting rebinding (default behaviour)
230 }
231
232
233 /**
234 * Binder to let client components to perform actions on the queue of operations.
235 *
236 * It provides by itself the available operations.
237 */
238 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
239
240 /**
241 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
242 */
243 private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
244 new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
245
246 private ServiceHandler mServiceHandler = null;
247
248
249 public OperationsServiceBinder(ServiceHandler serviceHandler) {
250 mServiceHandler = serviceHandler;
251 }
252
253
254 /**
255 * Cancels an operation
256 *
257 * TODO
258 */
259 public void cancel() {
260 // TODO
261 }
262
263
264 public void clearListeners() {
265
266 mBoundListeners.clear();
267 }
268
269
270 /**
271 * Adds a listener interested in being reported about the end of operations.
272 *
273 * @param listener Object to notify about the end of operations.
274 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
275 */
276 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
277 synchronized (mBoundListeners) {
278 mBoundListeners.put(listener, callbackHandler);
279 }
280 }
281
282
283 /**
284 * Removes a listener from the list of objects interested in the being reported about the end of operations.
285 *
286 * @param listener Object to notify about progress of transfer.
287 */
288 public void removeOperationListener (OnRemoteOperationListener listener) {
289 synchronized (mBoundListeners) {
290 mBoundListeners.remove(listener);
291 }
292 }
293
294
295 /**
296 * TODO - IMPORTANT: update implementation when more operations are moved into the service
297 *
298 * @return 'True' when an operation that enforces the user to wait for completion is in process.
299 */
300 public boolean isPerformingBlockingOperation() {
301 return (!mServiceHandler.mPendingOperations.isEmpty());
302 }
303
304
305 /**
306 * Creates and adds to the queue a new operation, as described by operationIntent.
307 *
308 * Calls startService to make the operation is processed by the ServiceHandler.
309 *
310 * @param operationIntent Intent describing a new operation to queue and execute.
311 * @return Identifier of the operation created, or null if failed.
312 */
313 public long queueNewOperation(Intent operationIntent) {
314 Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
315 if (itemToQueue != null) {
316 mServiceHandler.mPendingOperations.add(itemToQueue);
317 startService(new Intent(OperationsService.this, OperationsService.class));
318 return itemToQueue.second.hashCode();
319
320 } else {
321 return Long.MAX_VALUE;
322 }
323 }
324
325
326 public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
327 Pair<RemoteOperation, RemoteOperationResult> undispatched =
328 mUndispatchedFinishedOperations.remove(operationId);
329 if (undispatched != null) {
330 listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
331 return true;
332 //Log_OC.wtf(TAG, "Sending callback later");
333 } else {
334 if (!mServiceHandler.mPendingOperations.isEmpty()) {
335 return true;
336 } else {
337 return false;
338 }
339 //Log_OC.wtf(TAG, "Not finished yet");
340 }
341 }
342
343 }
344
345
346 /**
347 * Operations worker. Performs the pending operations in the order they were requested.
348 *
349 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
350 */
351 private static class ServiceHandler extends Handler {
352 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
353
354
355 OperationsService mService;
356
357
358 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
359 new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
360 private RemoteOperation mCurrentOperation = null;
361 private Target mLastTarget = null;
362 private OwnCloudClient mOwnCloudClient = null;
363 private FileDataStorageManager mStorageManager;
364
365
366 public ServiceHandler(Looper looper, OperationsService service) {
367 super(looper);
368 if (service == null) {
369 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
370 }
371 mService = service;
372 }
373
374 @Override
375 public void handleMessage(Message msg) {
376 nextOperation();
377 mService.stopSelf(msg.arg1);
378 }
379
380
381 /**
382 * Performs the next operation in the queue
383 */
384 private void nextOperation() {
385
386 //Log_OC.wtf(TAG, "nextOperation init" );
387
388 Pair<Target, RemoteOperation> next = null;
389 synchronized(mPendingOperations) {
390 next = mPendingOperations.peek();
391 }
392
393 if (next != null) {
394
395 mCurrentOperation = next.second;
396 RemoteOperationResult result = null;
397 try {
398 /// prepare client object to send the request to the ownCloud server
399 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
400 mLastTarget = next.first;
401 if (mLastTarget.mAccount != null) {
402 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
403 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
404 getClientFor(ocAccount, mService);
405 mStorageManager = new FileDataStorageManager(
406 mLastTarget.mAccount,
407 mService.getContentResolver()
408 );
409 } else {
410 OwnCloudCredentials credentials = null;
411 if (mLastTarget.mUsername != null &&
412 mLastTarget.mUsername.length() > 0) {
413 credentials = OwnCloudCredentialsFactory.newBasicCredentials(
414 mLastTarget.mUsername,
415 mLastTarget.mPassword); // basic
416
417 } else if (mLastTarget.mAuthToken != null &&
418 mLastTarget.mAuthToken.length() > 0) {
419 credentials = OwnCloudCredentialsFactory.newBearerCredentials(
420 mLastTarget.mAuthToken); // bearer token
421
422 } else if (mLastTarget.mCookie != null &&
423 mLastTarget.mCookie.length() > 0) {
424 credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
425 mLastTarget.mCookie); // SAML SSO
426 }
427 OwnCloudAccount ocAccount = new OwnCloudAccount(
428 mLastTarget.mServerUrl, credentials);
429 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
430 getClientFor(ocAccount, mService);
431 mStorageManager = null;
432 }
433 }
434
435 /// perform the operation
436 if (mCurrentOperation instanceof SyncOperation) {
437 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
438 } else {
439 result = mCurrentOperation.execute(mOwnCloudClient);
440 }
441
442 } catch (AccountsException e) {
443 if (mLastTarget.mAccount == null) {
444 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
445 } else {
446 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
447 }
448 result = new RemoteOperationResult(e);
449
450 } catch (IOException e) {
451 if (mLastTarget.mAccount == null) {
452 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
453 } else {
454 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
455 }
456 result = new RemoteOperationResult(e);
457 } catch (Exception e) {
458 if (mLastTarget.mAccount == null) {
459 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
460 } else {
461 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
462 }
463 result = new RemoteOperationResult(e);
464
465 } finally {
466 synchronized(mPendingOperations) {
467 mPendingOperations.poll();
468 }
469 }
470
471 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
472 mService.dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
473 }
474 }
475
476
477
478 }
479
480
481 /**
482 * Creates a new operation, as described by operationIntent.
483 *
484 * TODO - move to ServiceHandler (probably)
485 *
486 * @param operationIntent Intent describing a new operation to queue and execute.
487 * @return Pair with the new operation object and the information about its target server.
488 */
489 private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
490 RemoteOperation operation = null;
491 Target target = null;
492 try {
493 if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
494 !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
495 Log_OC.e(TAG, "Not enough information provided in intent");
496
497 } else {
498 Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
499 String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
500 String username = operationIntent.getStringExtra(EXTRA_USERNAME);
501 String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
502 String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
503 String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
504 target = new Target(
505 account,
506 (serverUrl == null) ? null : Uri.parse(serverUrl),
507 username,
508 password,
509 authToken,
510 cookie
511 );
512
513 String action = operationIntent.getAction();
514 if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
515 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
516 Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
517 if (remotePath.length() > 0) {
518 operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
519 "", false, "", 1, sendIntent);
520 }
521
522 } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
523 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
524 if (remotePath.length() > 0) {
525 operation = new UnshareLinkOperation(
526 remotePath,
527 OperationsService.this);
528 }
529
530 } else if (action.equals(ACTION_GET_SERVER_INFO)) {
531 // check OC server and get basic information from it
532 operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
533
534 } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
535 /// GET ACCESS TOKEN to the OAuth server
536 String oauth2QueryParameters =
537 operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
538 operation = new OAuth2GetAccessToken(
539 getString(R.string.oauth2_client_id),
540 getString(R.string.oauth2_redirect_uri),
541 getString(R.string.oauth2_grant_type),
542 oauth2QueryParameters);
543
544 } else if (action.equals(ACTION_EXISTENCE_CHECK)) {
545 // Existence Check
546 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
547 boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, false);
548 operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
549
550 } else if (action.equals(ACTION_GET_USER_NAME)) {
551 // Get User Name
552 operation = new GetRemoteUserNameOperation();
553
554 } else if (action.equals(ACTION_RENAME)) {
555 // Rename file or folder
556 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
557 String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
558 operation = new RenameFileOperation(remotePath, newName);
559
560 } else if (action.equals(ACTION_REMOVE)) {
561 // Remove file or folder
562 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
563 boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
564 operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
565
566 } else if (action.equals(ACTION_CREATE_FOLDER)) {
567 // Create Folder
568 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
569 boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
570 operation = new CreateFolderOperation(remotePath, createFullPath);
571
572 } else if (action.equals(ACTION_SYNC_FILE)) {
573 // Sync file
574 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
575 boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
576 operation = new SynchronizeFileOperation(
577 remotePath, account, syncFileContents, getApplicationContext()
578 );
579
580 } else if (action.equals(ACTION_SYNC_FOLDER)) {
581 // Sync file
582 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
583 operation = new SynchronizeFolderOperation(
584 this, // TODO remove this dependency from construction time
585 remotePath,
586 account,
587 System.currentTimeMillis() // TODO remove this dependency from construction time
588 );
589
590 } else if (action.equals(ACTION_MOVE_FILE)) {
591 // Move file/folder
592 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
593 String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
594 operation = new MoveFileOperation(remotePath,newParentPath,account);
595 }
596
597 }
598
599 } catch (IllegalArgumentException e) {
600 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
601 operation = null;
602 }
603
604 if (operation != null) {
605 return new Pair<Target , RemoteOperation>(target, operation);
606 } else {
607 return null;
608 }
609 }
610
611
612 /**
613 * Sends a broadcast when a new operation is added to the queue.
614 *
615 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
616 *
617 * @param target Account or URL pointing to an OC server.
618 * @param operation Added operation.
619 */
620 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
621 Intent intent = new Intent(ACTION_OPERATION_ADDED);
622 if (target.mAccount != null) {
623 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
624 } else {
625 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
626 }
627 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
628 //lbm.sendBroadcast(intent);
629 sendStickyBroadcast(intent);
630 }
631
632
633 // TODO - maybe add a notification for real start of operations
634
635 /**
636 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
637 *
638 * Local broadcasts are only delivered to activities in the same process.
639 *
640 * @param target Account or URL pointing to an OC server.
641 * @param operation Finished operation.
642 * @param result Result of the operation.
643 */
644 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
645 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
646 intent.putExtra(EXTRA_RESULT, result);
647 if (target.mAccount != null) {
648 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
649 } else {
650 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
651 }
652 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
653 //lbm.sendBroadcast(intent);
654 sendStickyBroadcast(intent);
655 }
656
657
658 /**
659 * Notifies the currently subscribed listeners about the end of an operation.
660 *
661 * @param target Account or URL pointing to an OC server.
662 * @param operation Finished operation.
663 * @param result Result of the operation.
664 */
665 private void dispatchResultToOperationListeners(
666 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
667 int count = 0;
668 Iterator<OnRemoteOperationListener> listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
669 while (listeners.hasNext()) {
670 final OnRemoteOperationListener listener = listeners.next();
671 final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
672 if (handler != null) {
673 handler.post(new Runnable() {
674 @Override
675 public void run() {
676 listener.onRemoteOperationFinish(operation, result);
677 }
678 });
679 count += 1;
680 }
681 }
682 if (count == 0) {
683 //mOperationResults.put(operation.hashCode(), result);
684 Pair<RemoteOperation, RemoteOperationResult> undispatched =
685 new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
686 mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
687 }
688 Log_OC.d(TAG, "Called " + count + " listeners");
689 }
690
691
692 }