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