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