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