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