Merge pull request #810 from owncloud/download_folder__better_downloading_icon_for_fo...
[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.files.services.FileDownloader;
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 import com.owncloud.android.utils.FileStorageUtils;
55
56 import android.accounts.Account;
57 import android.accounts.AccountsException;
58 import android.accounts.AuthenticatorException;
59 import android.accounts.OperationCanceledException;
60 import android.app.Service;
61 import android.content.Intent;
62 import android.net.Uri;
63 import android.os.Binder;
64 import android.os.Handler;
65 import android.os.HandlerThread;
66 import android.os.IBinder;
67 import android.os.Looper;
68 import android.os.Message;
69 import android.os.Process;
70 import android.util.Pair;
71
72 public class OperationsService extends Service {
73
74 private static final String TAG = OperationsService.class.getSimpleName();
75
76 public static final String EXTRA_ACCOUNT = "ACCOUNT";
77 public static final String EXTRA_SERVER_URL = "SERVER_URL";
78 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
79 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
80 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
81 public static final String EXTRA_NEWNAME = "NEWNAME";
82 public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
83 public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
84 public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
85 public static final String EXTRA_RESULT = "RESULT";
86 public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
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 if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
172 Log_OC.e(TAG, "Not enough information provided in intent");
173 return START_NOT_STICKY;
174 }
175 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
176 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
177
178 Pair<Account, String> itemSyncKey = new Pair<Account , String>(account, remotePath);
179
180 Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
181 if (itemToQueue != null) {
182 mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation)itemToQueue.second);
183 sendBroadcastNewSyncFolder(account, remotePath);
184 Message msg = mSyncFolderHandler.obtainMessage();
185 msg.arg1 = startId;
186 msg.obj = itemSyncKey;
187 mSyncFolderHandler.sendMessage(msg);
188 }
189 } else if (ACTION_CANCEL_SYNC_FOLDER.equals(intent.getAction())) {
190 if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
191 Log_OC.e(TAG, "Not enough information provided in intent");
192 return START_NOT_STICKY;
193 }
194 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
195 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
196
197 // Cancel operation
198 mSyncFolderHandler.cancel(account,remotePath);
199 } else {
200 Message msg = mOperationsHandler.obtainMessage();
201 msg.arg1 = startId;
202 mOperationsHandler.sendMessage(msg);
203 }
204
205 return START_NOT_STICKY;
206 }
207
208 /**
209 * TODO remove this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
210 * patch.
211 */
212 private void sendBroadcastNewSyncFolder(Account account, String remotePath) {
213 Intent added = new Intent(FileDownloader.getDownloadAddedMessage());
214 added.putExtra(FileDownloader.ACCOUNT_NAME, account.name);
215 added.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath);
216 added.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath);
217 sendStickyBroadcast(added);
218 }
219
220
221 @Override
222 public void onDestroy() {
223 //Log_OC.wtf(TAG, "onDestroy init" );
224 // Saving cookies
225 try {
226 OwnCloudClientManagerFactory.getDefaultSingleton().
227 saveAllClients(this, MainApp.getAccountType());
228
229 // TODO - get rid of these exceptions
230 } catch (AccountNotFoundException e) {
231 e.printStackTrace();
232 } catch (AuthenticatorException e) {
233 e.printStackTrace();
234 } catch (OperationCanceledException e) {
235 e.printStackTrace();
236 } catch (IOException e) {
237 e.printStackTrace();
238 }
239
240 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
241 mUndispatchedFinishedOperations.clear();
242
243 //Log_OC.wtf(TAG, "onDestroy end" );
244 super.onDestroy();
245 }
246
247 /**
248 * Provides a binder object that clients can use to perform actions on the queue of operations,
249 * except the addition of new operations.
250 */
251 @Override
252 public IBinder onBind(Intent intent) {
253 //Log_OC.wtf(TAG, "onBind" );
254 return mOperationsBinder;
255 }
256
257
258 /**
259 * Called when ALL the bound clients were unbound.
260 */
261 @Override
262 public boolean onUnbind(Intent intent) {
263 ((OperationsServiceBinder)mOperationsBinder).clearListeners();
264 return false; // not accepting rebinding (default behaviour)
265 }
266
267
268 /**
269 * Binder to let client components to perform actions on the queue of operations.
270 *
271 * It provides by itself the available operations.
272 */
273 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
274
275 /**
276 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
277 */
278 private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
279 new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
280
281 private ServiceHandler mServiceHandler = null;
282
283
284 public OperationsServiceBinder(ServiceHandler serviceHandler) {
285 mServiceHandler = serviceHandler;
286 }
287
288
289 /**
290 * Cancels an operation
291 *
292 * TODO
293 */
294 public void cancel() {
295 // TODO
296 }
297
298
299 public void clearListeners() {
300
301 mBoundListeners.clear();
302 }
303
304
305 /**
306 * Adds a listener interested in being reported about the end of operations.
307 *
308 * @param listener Object to notify about the end of operations.
309 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
310 */
311 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
312 synchronized (mBoundListeners) {
313 mBoundListeners.put(listener, callbackHandler);
314 }
315 }
316
317
318 /**
319 * Removes a listener from the list of objects interested in the being reported about the end of operations.
320 *
321 * @param listener Object to notify about progress of transfer.
322 */
323 public void removeOperationListener (OnRemoteOperationListener listener) {
324 synchronized (mBoundListeners) {
325 mBoundListeners.remove(listener);
326 }
327 }
328
329
330 /**
331 * TODO - IMPORTANT: update implementation when more operations are moved into the service
332 *
333 * @return 'True' when an operation that enforces the user to wait for completion is in process.
334 */
335 public boolean isPerformingBlockingOperation() {
336 return (!mServiceHandler.mPendingOperations.isEmpty());
337 }
338
339
340 /**
341 * Creates and adds to the queue a new operation, as described by operationIntent.
342 *
343 * Calls startService to make the operation is processed by the ServiceHandler.
344 *
345 * @param operationIntent Intent describing a new operation to queue and execute.
346 * @return Identifier of the operation created, or null if failed.
347 */
348 public long queueNewOperation(Intent operationIntent) {
349 Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
350 if (itemToQueue != null) {
351 mServiceHandler.mPendingOperations.add(itemToQueue);
352 startService(new Intent(OperationsService.this, OperationsService.class));
353 return itemToQueue.second.hashCode();
354
355 } else {
356 return Long.MAX_VALUE;
357 }
358 }
359
360
361 public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
362 Pair<RemoteOperation, RemoteOperationResult> undispatched =
363 mUndispatchedFinishedOperations.remove(operationId);
364 if (undispatched != null) {
365 listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
366 return true;
367 //Log_OC.wtf(TAG, "Sending callback later");
368 } else {
369 if (!mServiceHandler.mPendingOperations.isEmpty()) {
370 return true;
371 } else {
372 return false;
373 }
374 //Log_OC.wtf(TAG, "Not finished yet");
375 }
376 }
377
378
379 /**
380 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
381 *
382 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
383 *
384 * @param account ownCloud account where the remote file is stored.
385 * @param file A file that could be affected
386 */
387 public boolean isSynchronizing(Account account, String remotePath) {
388 return mSyncFolderHandler.isSynchronizing(account, remotePath);
389 }
390
391 }
392
393
394 /**
395 * SyncFolder worker. Performs the pending operations in the order they were requested.
396 *
397 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
398 */
399 private static class SyncFolderHandler extends Handler {
400
401 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
402
403 OperationsService mService;
404
405 private ConcurrentMap<String,SynchronizeFolderOperation> mPendingOperations =
406 new ConcurrentHashMap<String,SynchronizeFolderOperation>();
407 private OwnCloudClient mOwnCloudClient = null;
408 private FileDataStorageManager mStorageManager;
409 private SynchronizeFolderOperation mCurrentSyncOperation;
410
411
412 public SyncFolderHandler(Looper looper, OperationsService service) {
413 super(looper);
414 if (service == null) {
415 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
416 }
417 mService = service;
418 }
419
420
421 public boolean isSynchronizing(Account account, String remotePath) {
422 if (account == null || remotePath == null) return false;
423 String targetKey = buildRemoteName(account, remotePath);
424 synchronized (mPendingOperations) {
425 return (mPendingOperations.containsKey(targetKey));
426 }
427 }
428
429
430 @Override
431 public void handleMessage(Message msg) {
432 Pair<Account, String> itemSyncKey = (Pair<Account, String>) msg.obj;
433 doOperation(itemSyncKey.first, itemSyncKey.second);
434 mService.stopSelf(msg.arg1);
435 }
436
437
438 /**
439 * Performs the next operation in the queue
440 */
441 private void doOperation(Account account, String remotePath) {
442
443 String syncKey = buildRemoteName(account,remotePath);
444
445 synchronized(mPendingOperations) {
446 mCurrentSyncOperation = mPendingOperations.get(syncKey);
447 }
448
449 if (mCurrentSyncOperation != null) {
450
451 try {
452
453 OwnCloudAccount ocAccount = new OwnCloudAccount(account, mService);
454 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
455 getClientFor(ocAccount, mService);
456 mStorageManager = new FileDataStorageManager(
457 account,
458 mService.getContentResolver()
459 );
460
461 mCurrentSyncOperation.execute(mOwnCloudClient, mStorageManager);
462
463 } catch (AccountsException e) {
464 Log_OC.e(TAG, "Error while trying to get autorization", e);
465 } catch (IOException e) {
466 Log_OC.e(TAG, "Error while trying to get autorization", e);
467 } finally {
468 synchronized(mPendingOperations) {
469 mPendingOperations.remove(syncKey);
470 }
471 }
472 }
473 }
474
475 public void add(Account account, String remotePath, SynchronizeFolderOperation syncFolderOperation){
476 String syncKey = buildRemoteName(account,remotePath);
477 mPendingOperations.putIfAbsent(syncKey,syncFolderOperation);
478 }
479
480
481 /**
482 * Cancels a pending or current sync operation.
483 *
484 * @param account Owncloud account where the remote file is stored.
485 * @param remotePath A remote file path
486 */
487 public void cancel(Account account, String remotePath) {
488 SynchronizeFolderOperation syncOperation = null;
489 synchronized (mPendingOperations) {
490 syncOperation = mPendingOperations.remove(buildRemoteName(account, remotePath));
491 }
492 if (syncOperation != null) {
493 syncOperation.cancel();
494 }
495 }
496
497 /**
498 * Builds a key from the account and file to download
499 *
500 * @param account Account where the file to download is stored
501 * @param path File path
502 */
503 private String buildRemoteName(Account account, String path) {
504 return account.name + path;
505 }
506 }
507
508
509 /**
510 * Operations worker. Performs the pending operations in the order they were requested.
511 *
512 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
513 */
514 private static class ServiceHandler extends Handler {
515 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
516
517
518 OperationsService mService;
519
520
521 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
522 new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
523 private RemoteOperation mCurrentOperation = null;
524 private Target mLastTarget = null;
525 private OwnCloudClient mOwnCloudClient = null;
526 private FileDataStorageManager mStorageManager;
527
528
529 public ServiceHandler(Looper looper, OperationsService service) {
530 super(looper);
531 if (service == null) {
532 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
533 }
534 mService = service;
535 }
536
537 @Override
538 public void handleMessage(Message msg) {
539 nextOperation();
540 mService.stopSelf(msg.arg1);
541 }
542
543
544 /**
545 * Performs the next operation in the queue
546 */
547 private void nextOperation() {
548
549 //Log_OC.wtf(TAG, "nextOperation init" );
550
551 Pair<Target, RemoteOperation> next = null;
552 synchronized(mPendingOperations) {
553 next = mPendingOperations.peek();
554 }
555
556 if (next != null) {
557
558 mCurrentOperation = next.second;
559 RemoteOperationResult result = null;
560 try {
561 /// prepare client object to send the request to the ownCloud server
562 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
563 mLastTarget = next.first;
564 if (mLastTarget.mAccount != null) {
565 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService);
566 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
567 getClientFor(ocAccount, mService);
568 mStorageManager = new FileDataStorageManager(
569 mLastTarget.mAccount,
570 mService.getContentResolver()
571 );
572 } else {
573 OwnCloudCredentials credentials = null;
574 if (mLastTarget.mUsername != null &&
575 mLastTarget.mUsername.length() > 0) {
576 credentials = OwnCloudCredentialsFactory.newBasicCredentials(
577 mLastTarget.mUsername,
578 mLastTarget.mPassword); // basic
579
580 } else if (mLastTarget.mAuthToken != null &&
581 mLastTarget.mAuthToken.length() > 0) {
582 credentials = OwnCloudCredentialsFactory.newBearerCredentials(
583 mLastTarget.mAuthToken); // bearer token
584
585 } else if (mLastTarget.mCookie != null &&
586 mLastTarget.mCookie.length() > 0) {
587 credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
588 mLastTarget.mCookie); // SAML SSO
589 }
590 OwnCloudAccount ocAccount = new OwnCloudAccount(
591 mLastTarget.mServerUrl, credentials);
592 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
593 getClientFor(ocAccount, mService);
594 mStorageManager = null;
595 }
596 }
597
598 /// perform the operation
599 if (mCurrentOperation instanceof SyncOperation) {
600 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
601 } else {
602 result = mCurrentOperation.execute(mOwnCloudClient);
603 }
604
605 } catch (AccountsException e) {
606 if (mLastTarget.mAccount == null) {
607 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
608 } else {
609 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
610 }
611 result = new RemoteOperationResult(e);
612
613 } catch (IOException e) {
614 if (mLastTarget.mAccount == null) {
615 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
616 } else {
617 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
618 }
619 result = new RemoteOperationResult(e);
620 } catch (Exception e) {
621 if (mLastTarget.mAccount == null) {
622 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
623 } else {
624 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
625 }
626 result = new RemoteOperationResult(e);
627
628 } finally {
629 synchronized(mPendingOperations) {
630 mPendingOperations.poll();
631 }
632 }
633
634 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
635 mService.dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
636 }
637 }
638
639
640
641 }
642
643
644 /**
645 * Creates a new operation, as described by operationIntent.
646 *
647 * TODO - move to ServiceHandler (probably)
648 *
649 * @param operationIntent Intent describing a new operation to queue and execute.
650 * @return Pair with the new operation object and the information about its target server.
651 */
652 private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
653 RemoteOperation operation = null;
654 Target target = null;
655 try {
656 if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
657 !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
658 Log_OC.e(TAG, "Not enough information provided in intent");
659
660 } else {
661 Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
662 String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
663 String username = operationIntent.getStringExtra(EXTRA_USERNAME);
664 String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
665 String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
666 String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
667 target = new Target(
668 account,
669 (serverUrl == null) ? null : Uri.parse(serverUrl),
670 username,
671 password,
672 authToken,
673 cookie
674 );
675
676 String action = operationIntent.getAction();
677 if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
678 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
679 Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
680 if (remotePath.length() > 0) {
681 operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
682 "", false, "", 1, sendIntent);
683 }
684
685 } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
686 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
687 if (remotePath.length() > 0) {
688 operation = new UnshareLinkOperation(
689 remotePath,
690 OperationsService.this);
691 }
692
693 } else if (action.equals(ACTION_GET_SERVER_INFO)) {
694 // check OC server and get basic information from it
695 operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
696
697 } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
698 /// GET ACCESS TOKEN to the OAuth server
699 String oauth2QueryParameters =
700 operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
701 operation = new OAuth2GetAccessToken(
702 getString(R.string.oauth2_client_id),
703 getString(R.string.oauth2_redirect_uri),
704 getString(R.string.oauth2_grant_type),
705 oauth2QueryParameters);
706
707 } else if (action.equals(ACTION_EXISTENCE_CHECK)) {
708 // Existence Check
709 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
710 boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, false);
711 operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
712
713 } else if (action.equals(ACTION_GET_USER_NAME)) {
714 // Get User Name
715 operation = new GetRemoteUserNameOperation();
716
717 } else if (action.equals(ACTION_RENAME)) {
718 // Rename file or folder
719 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
720 String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
721 operation = new RenameFileOperation(remotePath, newName);
722
723 } else if (action.equals(ACTION_REMOVE)) {
724 // Remove file or folder
725 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
726 boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
727 operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
728
729 } else if (action.equals(ACTION_CREATE_FOLDER)) {
730 // Create Folder
731 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
732 boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
733 operation = new CreateFolderOperation(remotePath, createFullPath);
734
735 } else if (action.equals(ACTION_SYNC_FILE)) {
736 // Sync file
737 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
738 boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
739 operation = new SynchronizeFileOperation(
740 remotePath, account, syncFileContents, getApplicationContext()
741 );
742
743 } else if (action.equals(ACTION_SYNC_FOLDER)) {
744 // Sync file
745 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
746 operation = new SynchronizeFolderOperation(
747 this, // TODO remove this dependency from construction time
748 remotePath,
749 account,
750 System.currentTimeMillis() // TODO remove this dependency from construction time
751 );
752
753 } else if (action.equals(ACTION_MOVE_FILE)) {
754 // Move file/folder
755 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
756 String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
757 operation = new MoveFileOperation(remotePath,newParentPath,account);
758 }
759
760 }
761
762 } catch (IllegalArgumentException e) {
763 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
764 operation = null;
765 }
766
767 if (operation != null) {
768 return new Pair<Target , RemoteOperation>(target, operation);
769 } else {
770 return null;
771 }
772 }
773
774
775 /**
776 * Sends a broadcast when a new operation is added to the queue.
777 *
778 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
779 *
780 * @param target Account or URL pointing to an OC server.
781 * @param operation Added operation.
782 */
783 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
784 Intent intent = new Intent(ACTION_OPERATION_ADDED);
785 if (target.mAccount != null) {
786 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
787 } else {
788 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
789 }
790 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
791 //lbm.sendBroadcast(intent);
792 sendStickyBroadcast(intent);
793 }
794
795
796 // TODO - maybe add a notification for real start of operations
797
798 /**
799 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
800 *
801 * Local broadcasts are only delivered to activities in the same process.
802 *
803 * @param target Account or URL pointing to an OC server.
804 * @param operation Finished operation.
805 * @param result Result of the operation.
806 */
807 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
808 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
809 intent.putExtra(EXTRA_RESULT, result);
810 if (target.mAccount != null) {
811 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
812 } else {
813 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
814 }
815 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
816 //lbm.sendBroadcast(intent);
817 sendStickyBroadcast(intent);
818 }
819
820
821 /**
822 * Notifies the currently subscribed listeners about the end of an operation.
823 *
824 * @param target Account or URL pointing to an OC server.
825 * @param operation Finished operation.
826 * @param result Result of the operation.
827 */
828 private void dispatchResultToOperationListeners(
829 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
830 int count = 0;
831 Iterator<OnRemoteOperationListener> listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
832 while (listeners.hasNext()) {
833 final OnRemoteOperationListener listener = listeners.next();
834 final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
835 if (handler != null) {
836 handler.post(new Runnable() {
837 @Override
838 public void run() {
839 listener.onRemoteOperationFinish(operation, result);
840 }
841 });
842 count += 1;
843 }
844 }
845 if (count == 0) {
846 //mOperationResults.put(operation.hashCode(), result);
847 Pair<RemoteOperation, RemoteOperationResult> undispatched =
848 new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
849 mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
850 }
851 Log_OC.d(TAG, "Called " + count + " listeners");
852 }
853 }