OperationsService.java 32 KB

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