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