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