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