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