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