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