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