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