OperationsService.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. package com.owncloud.android.services;
  20. import android.accounts.Account;
  21. import android.accounts.AccountsException;
  22. import android.accounts.AuthenticatorException;
  23. import android.accounts.OperationCanceledException;
  24. import android.app.Service;
  25. import android.content.Intent;
  26. import android.net.Uri;
  27. import android.os.Binder;
  28. import android.os.Handler;
  29. import android.os.HandlerThread;
  30. import android.os.IBinder;
  31. import android.os.Looper;
  32. import android.os.Message;
  33. import android.os.Process;
  34. import android.util.Pair;
  35. import com.owncloud.android.MainApp;
  36. import com.owncloud.android.R;
  37. import com.owncloud.android.datamodel.FileDataStorageManager;
  38. import com.owncloud.android.datamodel.OCFile;
  39. import com.owncloud.android.lib.common.OwnCloudAccount;
  40. import com.owncloud.android.lib.common.OwnCloudClient;
  41. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  42. import com.owncloud.android.lib.common.OwnCloudCredentials;
  43. import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
  44. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  45. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  46. import com.owncloud.android.lib.common.operations.RemoteOperation;
  47. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  48. import com.owncloud.android.lib.common.utils.Log_OC;
  49. import com.owncloud.android.lib.resources.shares.ShareType;
  50. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  51. import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
  52. import com.owncloud.android.operations.CopyFileOperation;
  53. import com.owncloud.android.operations.CreateFolderOperation;
  54. import com.owncloud.android.operations.CreateShareOperation;
  55. import com.owncloud.android.operations.GetServerInfoOperation;
  56. import com.owncloud.android.operations.MoveFileOperation;
  57. import com.owncloud.android.operations.OAuth2GetAccessToken;
  58. import com.owncloud.android.operations.RemoveFileOperation;
  59. import com.owncloud.android.operations.RenameFileOperation;
  60. import com.owncloud.android.operations.SynchronizeFileOperation;
  61. import com.owncloud.android.operations.SynchronizeFolderOperation;
  62. import com.owncloud.android.operations.UnshareLinkOperation;
  63. import com.owncloud.android.operations.common.SyncOperation;
  64. import java.io.IOException;
  65. import java.util.Iterator;
  66. import java.util.concurrent.ConcurrentHashMap;
  67. import java.util.concurrent.ConcurrentLinkedQueue;
  68. import java.util.concurrent.ConcurrentMap;
  69. public class OperationsService extends Service {
  70. private static final String TAG = OperationsService.class.getSimpleName();
  71. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  72. public static final String EXTRA_SERVER_URL = "SERVER_URL";
  73. public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
  74. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  75. public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
  76. public static final String EXTRA_NEWNAME = "NEWNAME";
  77. public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
  78. public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
  79. public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
  80. public static final String EXTRA_RESULT = "RESULT";
  81. public static final String EXTRA_NEW_PARENT_PATH = "NEW_PARENT_PATH";
  82. public static final String EXTRA_FILE = "FILE";
  83. public static final String EXTRA_PASSWORD_SHARE = "PASSWORD_SHARE";
  84. public static final String EXTRA_COOKIE = "COOKIE";
  85. public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
  86. public static final String ACTION_UNSHARE = "UNSHARE";
  87. public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
  88. public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
  89. public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
  90. public static final String ACTION_RENAME = "RENAME";
  91. public static final String ACTION_REMOVE = "REMOVE";
  92. public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
  93. public static final String ACTION_SYNC_FILE = "SYNC_FILE";
  94. public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER";//for the moment, just to download
  95. public static final String ACTION_MOVE_FILE = "MOVE_FILE";
  96. public static final String ACTION_COPY_FILE = "COPY_FILE";
  97. public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() +
  98. ".OPERATION_ADDED";
  99. public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() +
  100. ".OPERATION_FINISHED";
  101. private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
  102. mUndispatchedFinishedOperations =
  103. new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
  104. private static class Target {
  105. public Uri mServerUrl = null;
  106. public Account mAccount = null;
  107. public String mCookie = null;
  108. public Target(Account account, Uri serverUrl, String cookie) {
  109. mAccount = account;
  110. mServerUrl = serverUrl;
  111. mCookie = cookie;
  112. }
  113. }
  114. private ServiceHandler mOperationsHandler;
  115. private OperationsServiceBinder mOperationsBinder;
  116. private SyncFolderHandler mSyncFolderHandler;
  117. /**
  118. * Service initialization
  119. */
  120. @Override
  121. public void onCreate() {
  122. super.onCreate();
  123. Log_OC.d(TAG, "Creating service");
  124. /// First worker thread for most of operations
  125. HandlerThread thread = new HandlerThread("Operations thread",
  126. Process.THREAD_PRIORITY_BACKGROUND);
  127. thread.start();
  128. mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
  129. mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);
  130. /// Separated worker thread for download of folders (WIP)
  131. thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
  132. thread.start();
  133. mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);
  134. }
  135. /**
  136. * Entry point to add a new operation to the queue of operations.
  137. * <p/>
  138. * New operations are added calling to startService(), resulting in a call to this method.
  139. * This ensures the service will keep on working although the caller activity goes away.
  140. */
  141. @Override
  142. public int onStartCommand(Intent intent, int flags, int startId) {
  143. Log_OC.d(TAG, "Starting command with id " + startId);
  144. // WIP: for the moment, only SYNC_FOLDER is expected here;
  145. // the rest of the operations are requested through the Binder
  146. if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {
  147. if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
  148. Log_OC.e(TAG, "Not enough information provided in intent");
  149. return START_NOT_STICKY;
  150. }
  151. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  152. String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
  153. Pair<Account, String> itemSyncKey = new Pair<Account , String>(account, remotePath);
  154. Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
  155. if (itemToQueue != null) {
  156. mSyncFolderHandler.add(account, remotePath,
  157. (SynchronizeFolderOperation)itemToQueue.second);
  158. Message msg = mSyncFolderHandler.obtainMessage();
  159. msg.arg1 = startId;
  160. msg.obj = itemSyncKey;
  161. mSyncFolderHandler.sendMessage(msg);
  162. }
  163. } else {
  164. Message msg = mOperationsHandler.obtainMessage();
  165. msg.arg1 = startId;
  166. mOperationsHandler.sendMessage(msg);
  167. }
  168. return START_NOT_STICKY;
  169. }
  170. @Override
  171. public void onDestroy() {
  172. Log_OC.v(TAG, "Destroying service" );
  173. // Saving cookies
  174. try {
  175. OwnCloudClientManagerFactory.getDefaultSingleton().
  176. saveAllClients(this, MainApp.getAccountType());
  177. // TODO - get rid of these exceptions
  178. } catch (AccountNotFoundException e) {
  179. e.printStackTrace();
  180. } catch (AuthenticatorException e) {
  181. e.printStackTrace();
  182. } catch (OperationCanceledException e) {
  183. e.printStackTrace();
  184. } catch (IOException e) {
  185. e.printStackTrace();
  186. }
  187. mUndispatchedFinishedOperations.clear();
  188. mOperationsBinder = null;
  189. mOperationsHandler.getLooper().quit();
  190. mOperationsHandler = null;
  191. mSyncFolderHandler.getLooper().quit();
  192. mSyncFolderHandler = null;
  193. super.onDestroy();
  194. }
  195. /**
  196. * Provides a binder object that clients can use to perform actions on the queue of operations,
  197. * except the addition of new operations.
  198. */
  199. @Override
  200. public IBinder onBind(Intent intent) {
  201. //Log_OC.wtf(TAG, "onBind" );
  202. return mOperationsBinder;
  203. }
  204. /**
  205. * Called when ALL the bound clients were unbound.
  206. */
  207. @Override
  208. public boolean onUnbind(Intent intent) {
  209. mOperationsBinder.clearListeners();
  210. return false; // not accepting rebinding (default behaviour)
  211. }
  212. /**
  213. * Binder to let client components to perform actions on the queue of operations.
  214. * <p/>
  215. * It provides by itself the available operations.
  216. */
  217. public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
  218. /**
  219. * Map of listeners that will be reported about the end of operations from a
  220. * {@link OperationsServiceBinder} instance
  221. */
  222. private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
  223. new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
  224. private ServiceHandler mServiceHandler = null;
  225. public OperationsServiceBinder(ServiceHandler serviceHandler) {
  226. mServiceHandler = serviceHandler;
  227. }
  228. /**
  229. * Cancels a pending or current synchronization.
  230. *
  231. * @param account ownCloud account where the remote folder is stored.
  232. * @param file A folder in the queue of pending synchronizations
  233. */
  234. public void cancel(Account account, OCFile file) {
  235. mSyncFolderHandler.cancel(account, file);
  236. }
  237. public void clearListeners() {
  238. mBoundListeners.clear();
  239. }
  240. /**
  241. * Adds a listener interested in being reported about the end of operations.
  242. *
  243. * @param listener Object to notify about the end of operations.
  244. * @param callbackHandler {@link Handler} to access the listener without
  245. * breaking Android threading protection.
  246. */
  247. public void addOperationListener (OnRemoteOperationListener listener,
  248. Handler callbackHandler) {
  249. synchronized (mBoundListeners) {
  250. mBoundListeners.put(listener, callbackHandler);
  251. }
  252. }
  253. /**
  254. * Removes a listener from the list of objects interested in the being reported about
  255. * the end of operations.
  256. *
  257. * @param listener Object to notify about progress of transfer.
  258. */
  259. public void removeOperationListener(OnRemoteOperationListener listener) {
  260. synchronized (mBoundListeners) {
  261. mBoundListeners.remove(listener);
  262. }
  263. }
  264. /**
  265. * TODO - IMPORTANT: update implementation when more operations are moved into the service
  266. *
  267. * @return 'True' when an operation that enforces the user to wait for completion is
  268. * in process.
  269. */
  270. public boolean isPerformingBlockingOperation() {
  271. return (!mServiceHandler.mPendingOperations.isEmpty());
  272. }
  273. /**
  274. * Creates and adds to the queue a new operation, as described by operationIntent.
  275. *
  276. * Calls startService to make the operation is processed by the ServiceHandler.
  277. *
  278. * @param operationIntent Intent describing a new operation to queue and execute.
  279. * @return Identifier of the operation created, or null if failed.
  280. */
  281. public long queueNewOperation(Intent operationIntent) {
  282. Pair<Target, RemoteOperation> itemToQueue = newOperation(operationIntent);
  283. if (itemToQueue != null) {
  284. mServiceHandler.mPendingOperations.add(itemToQueue);
  285. startService(new Intent(OperationsService.this, OperationsService.class));
  286. return itemToQueue.second.hashCode();
  287. } else {
  288. return Long.MAX_VALUE;
  289. }
  290. }
  291. public boolean dispatchResultIfFinished(int operationId,
  292. OnRemoteOperationListener listener) {
  293. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  294. mUndispatchedFinishedOperations.remove(operationId);
  295. if (undispatched != null) {
  296. listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
  297. return true;
  298. //Log_OC.wtf(TAG, "Sending callback later");
  299. } else {
  300. return (!mServiceHandler.mPendingOperations.isEmpty());
  301. }
  302. }
  303. /**
  304. * Returns True when the file described by 'file' in the ownCloud account 'account' is
  305. * downloading or waiting to download.
  306. *
  307. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading
  308. * or waiting to download.
  309. *
  310. * @param account ownCloud account where the remote file is stored.
  311. * @param remotePath Path of the folder to check if something is synchronizing
  312. * / downloading / uploading inside.
  313. */
  314. public boolean isSynchronizing(Account account, String remotePath) {
  315. return mSyncFolderHandler.isSynchronizing(account, remotePath);
  316. }
  317. }
  318. /**
  319. * Operations worker. Performs the pending operations in the order they were requested.
  320. *
  321. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  322. */
  323. private static class ServiceHandler extends Handler {
  324. // don't make it a final class, and don't remove the static ; lint will warn about a p
  325. // ossible memory leak
  326. OperationsService mService;
  327. private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
  328. new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
  329. private RemoteOperation mCurrentOperation = null;
  330. private Target mLastTarget = null;
  331. private OwnCloudClient mOwnCloudClient = null;
  332. private FileDataStorageManager mStorageManager;
  333. public ServiceHandler(Looper looper, OperationsService service) {
  334. super(looper);
  335. if (service == null) {
  336. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  337. }
  338. mService = service;
  339. }
  340. @Override
  341. public void handleMessage(Message msg) {
  342. nextOperation();
  343. Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
  344. mService.stopSelf(msg.arg1);
  345. }
  346. /**
  347. * Performs the next operation in the queue
  348. */
  349. private void nextOperation() {
  350. //Log_OC.wtf(TAG, "nextOperation init" );
  351. Pair<Target, RemoteOperation> next = null;
  352. synchronized(mPendingOperations) {
  353. next = mPendingOperations.peek();
  354. }
  355. if (next != null) {
  356. mCurrentOperation = next.second;
  357. RemoteOperationResult result = null;
  358. try {
  359. /// prepare client object to send the request to the ownCloud server
  360. if (mLastTarget == null || !mLastTarget.equals(next.first)) {
  361. mLastTarget = next.first;
  362. if (mLastTarget.mAccount != null) {
  363. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount,
  364. mService);
  365. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  366. getClientFor(ocAccount, mService);
  367. OwnCloudVersion version = com.owncloud.android.authentication.AccountUtils.getServerVersion(
  368. mLastTarget.mAccount
  369. );
  370. mOwnCloudClient.setOwnCloudVersion(version);
  371. mStorageManager = new FileDataStorageManager(
  372. mLastTarget.mAccount,
  373. mService.getContentResolver()
  374. );
  375. } else {
  376. OwnCloudCredentials credentials = null;
  377. if (mLastTarget.mCookie != null &&
  378. mLastTarget.mCookie.length() > 0) {
  379. // just used for GetUserName
  380. // TODO refactor to run GetUserName as AsyncTask in the context of
  381. // AuthenticatorActivity
  382. credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
  383. null, // unknown
  384. mLastTarget.mCookie); // SAML SSO
  385. }
  386. OwnCloudAccount ocAccount = new OwnCloudAccount(
  387. mLastTarget.mServerUrl, credentials);
  388. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  389. getClientFor(ocAccount, mService);
  390. mStorageManager = null;
  391. }
  392. }
  393. /// perform the operation
  394. if (mCurrentOperation instanceof SyncOperation) {
  395. result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient,
  396. mStorageManager);
  397. } else {
  398. result = mCurrentOperation.execute(mOwnCloudClient);
  399. }
  400. } catch (AccountsException e) {
  401. if (mLastTarget.mAccount == null) {
  402. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  403. e);
  404. } else {
  405. Log_OC.e(TAG, "Error while trying to get authorization for " +
  406. mLastTarget.mAccount.name, e);
  407. }
  408. result = new RemoteOperationResult(e);
  409. } catch (IOException e) {
  410. if (mLastTarget.mAccount == null) {
  411. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  412. e);
  413. } else {
  414. Log_OC.e(TAG, "Error while trying to get authorization for " +
  415. mLastTarget.mAccount.name, e);
  416. }
  417. result = new RemoteOperationResult(e);
  418. } catch (Exception e) {
  419. if (mLastTarget.mAccount == null) {
  420. Log_OC.e(TAG, "Unexpected error for a NULL account", e);
  421. } else {
  422. Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
  423. }
  424. result = new RemoteOperationResult(e);
  425. } finally {
  426. synchronized(mPendingOperations) {
  427. mPendingOperations.poll();
  428. }
  429. }
  430. //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
  431. mService.dispatchResultToOperationListeners(mCurrentOperation, result);
  432. }
  433. }
  434. }
  435. /**
  436. * Creates a new operation, as described by operationIntent.
  437. *
  438. * TODO - move to ServiceHandler (probably)
  439. *
  440. * @param operationIntent Intent describing a new operation to queue and execute.
  441. * @return Pair with the new operation object and the information about its
  442. * target server.
  443. */
  444. private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
  445. RemoteOperation operation = null;
  446. Target target = null;
  447. try {
  448. if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
  449. !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
  450. Log_OC.e(TAG, "Not enough information provided in intent");
  451. } else {
  452. Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
  453. String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
  454. String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
  455. target = new Target(
  456. account,
  457. (serverUrl == null) ? null : Uri.parse(serverUrl),
  458. cookie
  459. );
  460. String action = operationIntent.getAction();
  461. if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
  462. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  463. String password = operationIntent.getStringExtra(EXTRA_PASSWORD_SHARE);
  464. Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
  465. if (remotePath.length() > 0) {
  466. operation = new CreateShareOperation(OperationsService.this, remotePath,
  467. ShareType.PUBLIC_LINK,
  468. "", false, password, 1, sendIntent);
  469. }
  470. } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
  471. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  472. if (remotePath.length() > 0) {
  473. operation = new UnshareLinkOperation(
  474. remotePath,
  475. OperationsService.this);
  476. }
  477. } else if (action.equals(ACTION_GET_SERVER_INFO)) {
  478. // check OC server and get basic information from it
  479. operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
  480. } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
  481. /// GET ACCESS TOKEN to the OAuth server
  482. String oauth2QueryParameters =
  483. operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
  484. operation = new OAuth2GetAccessToken(
  485. getString(R.string.oauth2_client_id),
  486. getString(R.string.oauth2_redirect_uri),
  487. getString(R.string.oauth2_grant_type),
  488. oauth2QueryParameters);
  489. } else if (action.equals(ACTION_GET_USER_NAME)) {
  490. // Get User Name
  491. operation = new GetRemoteUserNameOperation();
  492. } else if (action.equals(ACTION_RENAME)) {
  493. // Rename file or folder
  494. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  495. String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
  496. operation = new RenameFileOperation(remotePath, newName);
  497. } else if (action.equals(ACTION_REMOVE)) {
  498. // Remove file or folder
  499. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  500. boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL,
  501. false);
  502. operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
  503. } else if (action.equals(ACTION_CREATE_FOLDER)) {
  504. // Create Folder
  505. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  506. boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH,
  507. true);
  508. operation = new CreateFolderOperation(remotePath, createFullPath);
  509. } else if (action.equals(ACTION_SYNC_FILE)) {
  510. // Sync file
  511. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  512. boolean syncFileContents =
  513. operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
  514. operation = new SynchronizeFileOperation(
  515. remotePath, account, syncFileContents, getApplicationContext()
  516. );
  517. } else if (action.equals(ACTION_SYNC_FOLDER)) {
  518. // Sync file
  519. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  520. operation = new SynchronizeFolderOperation(
  521. this, // TODO remove this dependency from construction time
  522. remotePath,
  523. account,
  524. System.currentTimeMillis() // TODO remove this dependency from construction time
  525. );
  526. } else if (action.equals(ACTION_MOVE_FILE)) {
  527. // Move file/folder
  528. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  529. String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  530. operation = new MoveFileOperation(remotePath, newParentPath, account);
  531. } else if (action.equals(ACTION_COPY_FILE)) {
  532. // Copy file/folder
  533. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  534. String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  535. operation = new CopyFileOperation(remotePath, newParentPath, account);
  536. }
  537. }
  538. } catch (IllegalArgumentException e) {
  539. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  540. operation = null;
  541. }
  542. if (operation != null) {
  543. return new Pair<Target , RemoteOperation>(target, operation);
  544. } else {
  545. return null;
  546. }
  547. }
  548. /**
  549. * Sends a broadcast when a new operation is added to the queue.
  550. *
  551. * Local broadcasts are only delivered to activities in the same process, but can't be
  552. * done sticky :\
  553. *
  554. * @param target Account or URL pointing to an OC server.
  555. * @param operation Added operation.
  556. */
  557. private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
  558. Intent intent = new Intent(ACTION_OPERATION_ADDED);
  559. if (target.mAccount != null) {
  560. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  561. } else {
  562. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  563. }
  564. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  565. //lbm.sendBroadcast(intent);
  566. sendStickyBroadcast(intent);
  567. }
  568. // TODO - maybe add a notification for real start of operations
  569. /**
  570. * Sends a LOCAL broadcast when an operations finishes in order to the interested activities c
  571. * an update their view
  572. *
  573. * Local broadcasts are only delivered to activities in the same process.
  574. *
  575. * @param target Account or URL pointing to an OC server.
  576. * @param operation Finished operation.
  577. * @param result Result of the operation.
  578. */
  579. private void sendBroadcastOperationFinished(Target target, RemoteOperation operation,
  580. RemoteOperationResult result) {
  581. Intent intent = new Intent(ACTION_OPERATION_FINISHED);
  582. intent.putExtra(EXTRA_RESULT, result);
  583. if (target.mAccount != null) {
  584. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  585. } else {
  586. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  587. }
  588. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  589. //lbm.sendBroadcast(intent);
  590. sendStickyBroadcast(intent);
  591. }
  592. /**
  593. * Notifies the currently subscribed listeners about the end of an operation.
  594. *
  595. * @param operation Finished operation.
  596. * @param result Result of the operation.
  597. */
  598. protected void dispatchResultToOperationListeners(
  599. final RemoteOperation operation, final RemoteOperationResult result
  600. ) {
  601. int count = 0;
  602. Iterator<OnRemoteOperationListener> listeners =
  603. mOperationsBinder.mBoundListeners.keySet().iterator();
  604. while (listeners.hasNext()) {
  605. final OnRemoteOperationListener listener = listeners.next();
  606. final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
  607. if (handler != null) {
  608. handler.post(new Runnable() {
  609. @Override
  610. public void run() {
  611. listener.onRemoteOperationFinish(operation, result);
  612. }
  613. });
  614. count += 1;
  615. }
  616. }
  617. if (count == 0) {
  618. //mOperationResults.put(operation.hashCode(), result);
  619. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  620. new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
  621. mUndispatchedFinishedOperations.put(((Runnable) operation).hashCode(), undispatched);
  622. }
  623. Log_OC.d(TAG, "Called " + count + " listeners");
  624. }
  625. }