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