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