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