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