Merge branch 'develop' into delete_local_files
[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 /*Log_OC.v("NOW " + TAG + ", thread " + Thread.currentThread().getName(), "Received request to sync folder");*/
173
174 if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
175 Log_OC.e(TAG, "Not enough information provided in intent");
176 return START_NOT_STICKY;
177 }
178 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
179 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
180
181 Pair<Account, String> itemSyncKey = new Pair<Account , String>(account, remotePath);
182
183 Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
184 if (itemToQueue != null) {
185 mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation)itemToQueue.second);
186 Message msg = mSyncFolderHandler.obtainMessage();
187 msg.arg1 = startId;
188 msg.obj = itemSyncKey;
189 /*Log_OC.v(
190 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
191 "Sync folder " + remotePath + " added to queue"
192 );*/
193 mSyncFolderHandler.sendMessage(msg);
194 }
195
196 } else {
197 Message msg = mOperationsHandler.obtainMessage();
198 msg.arg1 = startId;
199 mOperationsHandler.sendMessage(msg);
200 }
201
202 return START_NOT_STICKY;
203 }
204
205 @Override
206 public void onDestroy() {
207 //Log_OC.wtf(TAG, "onDestroy init" );
208 // Saving cookies
209 try {
210 OwnCloudClientManagerFactory.getDefaultSingleton().
211 saveAllClients(this, MainApp.getAccountType());
212
213 // TODO - get rid of these exceptions
214 } catch (AccountNotFoundException e) {
215 e.printStackTrace();
216 } catch (AuthenticatorException e) {
217 e.printStackTrace();
218 } catch (OperationCanceledException e) {
219 e.printStackTrace();
220 } catch (IOException e) {
221 e.printStackTrace();
222 }
223
224 //Log_OC.wtf(TAG, "Clear mUndispatchedFinishedOperations" );
225 mUndispatchedFinishedOperations.clear();
226
227 //Log_OC.wtf(TAG, "onDestroy end" );
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 //Log_OC.wtf(TAG, "onBind" );
238 return mOperationsBinder;
239 }
240
241
242 /**
243 * Called when ALL the bound clients were unbound.
244 */
245 @Override
246 public boolean onUnbind(Intent intent) {
247 ((OperationsServiceBinder)mOperationsBinder).clearListeners();
248 return false; // not accepting rebinding (default behaviour)
249 }
250
251
252 /**
253 * Binder to let client components to perform actions on the queue of operations.
254 *
255 * It provides by itself the available operations.
256 */
257 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
258
259 /**
260 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
261 */
262 private 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 /*Log_OC.v(
280 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
281 "Received request to cancel folder " + file.getRemotePath()
282 );*/
283 mSyncFolderHandler.cancel(account, file);
284 }
285
286
287 public void clearListeners() {
288
289 mBoundListeners.clear();
290 }
291
292
293 /**
294 * Adds a listener interested in being reported about the end of operations.
295 *
296 * @param listener Object to notify about the end of operations.
297 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
298 */
299 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
300 synchronized (mBoundListeners) {
301 mBoundListeners.put(listener, callbackHandler);
302 }
303 }
304
305
306 /**
307 * Removes a listener from the list of objects interested in the being reported about the end of operations.
308 *
309 * @param listener Object to notify about progress of transfer.
310 */
311 public void removeOperationListener (OnRemoteOperationListener listener) {
312 synchronized (mBoundListeners) {
313 mBoundListeners.remove(listener);
314 }
315 }
316
317
318 /**
319 * TODO - IMPORTANT: update implementation when more operations are moved into the service
320 *
321 * @return 'True' when an operation that enforces the user to wait for completion is 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, 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 if (!mServiceHandler.mPendingOperations.isEmpty()) {
358 return true;
359 } else {
360 return false;
361 }
362 //Log_OC.wtf(TAG, "Not finished yet");
363 }
364 }
365
366
367 /**
368 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting
369 * to download.
370 *
371 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting
372 * to download.
373 *
374 * @param account ownCloud account where the remote file is stored.
375 * @param remotePath Path of the folder to check if something is synchronizing / downloading / uploading
376 * inside.
377 */
378 public boolean isSynchronizing(Account account, String remotePath) {
379 return mSyncFolderHandler.isSynchronizing(account, remotePath);
380 }
381
382 }
383
384
385 /**
386 * Operations worker. Performs the pending operations in the order they were requested.
387 *
388 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
389 */
390 private static class ServiceHandler extends Handler {
391 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
392
393
394 OperationsService mService;
395
396
397 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
398 new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
399 private RemoteOperation mCurrentOperation = null;
400 private Target mLastTarget = null;
401 private OwnCloudClient mOwnCloudClient = null;
402 private FileDataStorageManager mStorageManager;
403
404
405 public ServiceHandler(Looper looper, OperationsService service) {
406 super(looper);
407 if (service == null) {
408 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
409 }
410 mService = service;
411 }
412
413 @Override
414 public void handleMessage(Message msg) {
415 nextOperation();
416 mService.stopSelf(msg.arg1);
417 }
418
419
420 /**
421 * Performs the next operation in the queue
422 */
423 private void nextOperation() {
424
425 //Log_OC.wtf(TAG, "nextOperation init" );
426
427 Pair<Target, RemoteOperation> next = null;
428 synchronized(mPendingOperations) {
429 next = mPendingOperations.peek();
430 }
431
432 if (next != null) {
433
434 mCurrentOperation = next.second;
435 RemoteOperationResult result = null;
436 try {
437 /// prepare client object to send the request to the ownCloud server
438 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
439 mLastTarget = next.first;
440 if (mLastTarget.mAccount != null) {
441 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
442 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
443 getClientFor(ocAccount, mService);
444 mStorageManager = new FileDataStorageManager(
445 mLastTarget.mAccount,
446 mService.getContentResolver()
447 );
448 } else {
449 OwnCloudCredentials credentials = null;
450 if (mLastTarget.mUsername != null &&
451 mLastTarget.mUsername.length() > 0) {
452 credentials = OwnCloudCredentialsFactory.newBasicCredentials(
453 mLastTarget.mUsername,
454 mLastTarget.mPassword); // basic
455
456 } else if (mLastTarget.mAuthToken != null &&
457 mLastTarget.mAuthToken.length() > 0) {
458 credentials = OwnCloudCredentialsFactory.newBearerCredentials(
459 mLastTarget.mAuthToken); // bearer token
460
461 } else if (mLastTarget.mCookie != null &&
462 mLastTarget.mCookie.length() > 0) {
463 credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
464 mLastTarget.mCookie); // SAML SSO
465 }
466 OwnCloudAccount ocAccount = new OwnCloudAccount(
467 mLastTarget.mServerUrl, credentials);
468 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
469 getClientFor(ocAccount, mService);
470 mStorageManager = null;
471 }
472 }
473
474 /// perform the operation
475 if (mCurrentOperation instanceof SyncOperation) {
476 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
477 } else {
478 result = mCurrentOperation.execute(mOwnCloudClient);
479 }
480
481 } catch (AccountsException e) {
482 if (mLastTarget.mAccount == null) {
483 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
484 } else {
485 Log_OC.e(TAG, "Error while trying to get authorization for " + 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", e);
492 } else {
493 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
494 }
495 result = new RemoteOperationResult(e);
496 } catch (Exception e) {
497 if (mLastTarget.mAccount == null) {
498 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
499 } else {
500 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
501 }
502 result = new RemoteOperationResult(e);
503
504 } finally {
505 synchronized(mPendingOperations) {
506 mPendingOperations.poll();
507 }
508 }
509
510 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
511 mService.dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
512 }
513 }
514
515
516
517 }
518
519
520 /**
521 * Creates a new operation, as described by operationIntent.
522 *
523 * TODO - move to ServiceHandler (probably)
524 *
525 * @param operationIntent Intent describing a new operation to queue and execute.
526 * @return Pair with the new operation object and the information about its target server.
527 */
528 private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
529 RemoteOperation operation = null;
530 Target target = null;
531 try {
532 if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
533 !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
534 Log_OC.e(TAG, "Not enough information provided in intent");
535
536 } else {
537 Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
538 String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
539 String username = operationIntent.getStringExtra(EXTRA_USERNAME);
540 String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
541 String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
542 String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
543 target = new Target(
544 account,
545 (serverUrl == null) ? null : Uri.parse(serverUrl),
546 username,
547 password,
548 authToken,
549 cookie
550 );
551
552 String action = operationIntent.getAction();
553 if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
554 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
555 Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
556 if (remotePath.length() > 0) {
557 operation = new CreateShareOperation(OperationsService.this, remotePath, ShareType.PUBLIC_LINK,
558 "", false, "", 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_EXISTENCE_CHECK)) {
584 // Existence Check
585 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
586 boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, false);
587 operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
588
589 } else if (action.equals(ACTION_GET_USER_NAME)) {
590 // Get User Name
591 operation = new GetRemoteUserNameOperation();
592
593 } else if (action.equals(ACTION_RENAME)) {
594 // Rename file or folder
595 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
596 String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
597 operation = new RenameFileOperation(remotePath, newName);
598
599 } else if (action.equals(ACTION_REMOVE)) {
600 // Remove file or folder
601 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
602 boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
603 operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
604
605 } else if (action.equals(ACTION_CREATE_FOLDER)) {
606 // Create Folder
607 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
608 boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
609 operation = new CreateFolderOperation(remotePath, createFullPath);
610
611 } else if (action.equals(ACTION_SYNC_FILE)) {
612 // Sync file
613 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
614 boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
615 operation = new SynchronizeFileOperation(
616 remotePath, account, syncFileContents, getApplicationContext()
617 );
618
619 } else if (action.equals(ACTION_SYNC_FOLDER)) {
620 // Sync file
621 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
622 operation = new SynchronizeFolderOperation(
623 this, // TODO remove this dependency from construction time
624 remotePath,
625 account,
626 System.currentTimeMillis() // TODO remove this dependency from construction time
627 );
628
629 } else if (action.equals(ACTION_MOVE_FILE)) {
630 // Move file/folder
631 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
632 String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
633 operation = new MoveFileOperation(remotePath,newParentPath,account);
634 }
635
636 }
637
638 } catch (IllegalArgumentException e) {
639 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
640 operation = null;
641 }
642
643 if (operation != null) {
644 return new Pair<Target , RemoteOperation>(target, operation);
645 } else {
646 return null;
647 }
648 }
649
650
651 /**
652 * Sends a broadcast when a new operation is added to the queue.
653 *
654 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
655 *
656 * @param target Account or URL pointing to an OC server.
657 * @param operation Added operation.
658 */
659 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
660 Intent intent = new Intent(ACTION_OPERATION_ADDED);
661 if (target.mAccount != null) {
662 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
663 } else {
664 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
665 }
666 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
667 //lbm.sendBroadcast(intent);
668 sendStickyBroadcast(intent);
669 }
670
671
672 // TODO - maybe add a notification for real start of operations
673
674 /**
675 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
676 *
677 * Local broadcasts are only delivered to activities in the same process.
678 *
679 * @param target Account or URL pointing to an OC server.
680 * @param operation Finished operation.
681 * @param result Result of the operation.
682 */
683 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
684 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
685 intent.putExtra(EXTRA_RESULT, result);
686 if (target.mAccount != null) {
687 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
688 } else {
689 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
690 }
691 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
692 //lbm.sendBroadcast(intent);
693 sendStickyBroadcast(intent);
694 }
695
696
697 /**
698 * Notifies the currently subscribed listeners about the end of an operation.
699 *
700 * @param target Account or URL pointing to an OC server.
701 * @param operation Finished operation.
702 * @param result Result of the operation.
703 */
704 protected void dispatchResultToOperationListeners(
705 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
706 int count = 0;
707 Iterator<OnRemoteOperationListener> listeners = 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 }