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