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