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