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