OperationsService.java 31 KB

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