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