OperationsService.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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.AccountNotFoundException;
  35. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  36. import com.owncloud.android.lib.common.operations.RemoteOperation;
  37. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  39. import com.owncloud.android.lib.resources.shares.ShareType;
  40. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  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. return (!mServiceHandler.mPendingOperations.isEmpty());
  300. }
  301. }
  302. /**
  303. * Returns True when the file described by 'file' in the ownCloud account 'account' is
  304. * downloading or waiting to download.
  305. *
  306. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading
  307. * or waiting to download.
  308. *
  309. * @param account ownCloud account where the remote file is stored.
  310. * @param remotePath Path of the folder to check if something is synchronizing
  311. * / downloading / uploading inside.
  312. */
  313. public boolean isSynchronizing(Account account, String remotePath) {
  314. return mSyncFolderHandler.isSynchronizing(account, remotePath);
  315. }
  316. }
  317. /**
  318. * Operations worker. Performs the pending operations in the order they were requested.
  319. *
  320. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  321. */
  322. private static class ServiceHandler extends Handler {
  323. // don't make it a final class, and don't remove the static ; lint will warn about a p
  324. // ossible memory leak
  325. OperationsService mService;
  326. private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
  327. new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
  328. private RemoteOperation mCurrentOperation = null;
  329. private Target mLastTarget = null;
  330. private OwnCloudClient mOwnCloudClient = null;
  331. private FileDataStorageManager mStorageManager;
  332. public ServiceHandler(Looper looper, OperationsService service) {
  333. super(looper);
  334. if (service == null) {
  335. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  336. }
  337. mService = service;
  338. }
  339. @Override
  340. public void handleMessage(Message msg) {
  341. nextOperation();
  342. Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
  343. mService.stopSelf(msg.arg1);
  344. }
  345. /**
  346. * Performs the next operation in the queue
  347. */
  348. private void nextOperation() {
  349. //Log_OC.wtf(TAG, "nextOperation init" );
  350. Pair<Target, RemoteOperation> next = null;
  351. synchronized(mPendingOperations) {
  352. next = mPendingOperations.peek();
  353. }
  354. if (next != null) {
  355. mCurrentOperation = next.second;
  356. RemoteOperationResult result = null;
  357. try {
  358. /// prepare client object to send the request to the ownCloud server
  359. if (mLastTarget == null || !mLastTarget.equals(next.first)) {
  360. mLastTarget = next.first;
  361. if (mLastTarget.mAccount != null) {
  362. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount,
  363. mService);
  364. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  365. getClientFor(ocAccount, mService);
  366. OwnCloudVersion version = com.owncloud.android.authentication.AccountUtils.getServerVersion(
  367. mLastTarget.mAccount
  368. );
  369. mOwnCloudClient.setOwnCloudVersion(version);
  370. mStorageManager = new FileDataStorageManager(
  371. mLastTarget.mAccount,
  372. mService.getContentResolver()
  373. );
  374. } else {
  375. OwnCloudCredentials credentials = null;
  376. if (mLastTarget.mCookie != null &&
  377. mLastTarget.mCookie.length() > 0) {
  378. // just used for GetUserName
  379. // TODO refactor to run GetUserName as AsyncTask in the context of
  380. // AuthenticatorActivity
  381. credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
  382. null, // unknown
  383. mLastTarget.mCookie); // SAML SSO
  384. }
  385. OwnCloudAccount ocAccount = new OwnCloudAccount(
  386. mLastTarget.mServerUrl, credentials);
  387. mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  388. getClientFor(ocAccount, mService);
  389. mStorageManager = null;
  390. }
  391. }
  392. /// perform the operation
  393. if (mCurrentOperation instanceof SyncOperation) {
  394. result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient,
  395. mStorageManager);
  396. } else {
  397. result = mCurrentOperation.execute(mOwnCloudClient);
  398. }
  399. } catch (AccountsException e) {
  400. if (mLastTarget.mAccount == null) {
  401. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  402. e);
  403. } else {
  404. Log_OC.e(TAG, "Error while trying to get authorization for " +
  405. mLastTarget.mAccount.name, e);
  406. }
  407. result = new RemoteOperationResult(e);
  408. } catch (IOException e) {
  409. if (mLastTarget.mAccount == null) {
  410. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account",
  411. e);
  412. } else {
  413. Log_OC.e(TAG, "Error while trying to get authorization for " +
  414. mLastTarget.mAccount.name, e);
  415. }
  416. result = new RemoteOperationResult(e);
  417. } catch (Exception e) {
  418. if (mLastTarget.mAccount == null) {
  419. Log_OC.e(TAG, "Unexpected error for a NULL account", e);
  420. } else {
  421. Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
  422. }
  423. result = new RemoteOperationResult(e);
  424. } finally {
  425. synchronized(mPendingOperations) {
  426. mPendingOperations.poll();
  427. }
  428. }
  429. //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
  430. mService.dispatchResultToOperationListeners(mCurrentOperation, result);
  431. }
  432. }
  433. }
  434. /**
  435. * Creates a new operation, as described by operationIntent.
  436. *
  437. * TODO - move to ServiceHandler (probably)
  438. *
  439. * @param operationIntent Intent describing a new operation to queue and execute.
  440. * @return Pair with the new operation object and the information about its
  441. * target server.
  442. */
  443. private Pair<Target , RemoteOperation> newOperation(Intent operationIntent) {
  444. RemoteOperation operation = null;
  445. Target target = null;
  446. try {
  447. if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
  448. !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
  449. Log_OC.e(TAG, "Not enough information provided in intent");
  450. } else {
  451. Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
  452. String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
  453. String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
  454. target = new Target(
  455. account,
  456. (serverUrl == null) ? null : Uri.parse(serverUrl),
  457. cookie
  458. );
  459. String action = operationIntent.getAction();
  460. if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
  461. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  462. String password = operationIntent.getStringExtra(EXTRA_PASSWORD_SHARE);
  463. Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
  464. if (remotePath.length() > 0) {
  465. operation = new CreateShareOperation(OperationsService.this, remotePath,
  466. ShareType.PUBLIC_LINK,
  467. "", false, password, 1, sendIntent);
  468. }
  469. } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
  470. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  471. if (remotePath.length() > 0) {
  472. operation = new UnshareLinkOperation(
  473. remotePath,
  474. OperationsService.this);
  475. }
  476. } else if (action.equals(ACTION_GET_SERVER_INFO)) {
  477. // check OC server and get basic information from it
  478. operation = new GetServerInfoOperation(serverUrl, OperationsService.this);
  479. } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
  480. /// GET ACCESS TOKEN to the OAuth server
  481. String oauth2QueryParameters =
  482. operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
  483. operation = new OAuth2GetAccessToken(
  484. getString(R.string.oauth2_client_id),
  485. getString(R.string.oauth2_redirect_uri),
  486. getString(R.string.oauth2_grant_type),
  487. oauth2QueryParameters);
  488. } else if (action.equals(ACTION_GET_USER_NAME)) {
  489. // Get User Name
  490. operation = new GetRemoteUserNameOperation();
  491. } else if (action.equals(ACTION_RENAME)) {
  492. // Rename file or folder
  493. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  494. String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
  495. operation = new RenameFileOperation(remotePath, newName);
  496. } else if (action.equals(ACTION_REMOVE)) {
  497. // Remove file or folder
  498. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  499. boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL,
  500. false);
  501. operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
  502. } else if (action.equals(ACTION_CREATE_FOLDER)) {
  503. // Create Folder
  504. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  505. boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH,
  506. true);
  507. operation = new CreateFolderOperation(remotePath, createFullPath);
  508. } else if (action.equals(ACTION_SYNC_FILE)) {
  509. // Sync file
  510. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  511. boolean syncFileContents =
  512. operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
  513. operation = new SynchronizeFileOperation(
  514. remotePath, account, syncFileContents, getApplicationContext()
  515. );
  516. } else if (action.equals(ACTION_SYNC_FOLDER)) {
  517. // Sync file
  518. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  519. operation = new SynchronizeFolderOperation(
  520. this, // TODO remove this dependency from construction time
  521. remotePath,
  522. account,
  523. System.currentTimeMillis() // TODO remove this dependency from construction time
  524. );
  525. } else if (action.equals(ACTION_MOVE_FILE)) {
  526. // Move file/folder
  527. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  528. String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH);
  529. operation = new MoveFileOperation(remotePath,newParentPath,account);
  530. }
  531. }
  532. } catch (IllegalArgumentException e) {
  533. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  534. operation = null;
  535. }
  536. if (operation != null) {
  537. return new Pair<Target , RemoteOperation>(target, operation);
  538. } else {
  539. return null;
  540. }
  541. }
  542. /**
  543. * Sends a broadcast when a new operation is added to the queue.
  544. *
  545. * Local broadcasts are only delivered to activities in the same process, but can't be
  546. * done sticky :\
  547. *
  548. * @param target Account or URL pointing to an OC server.
  549. * @param operation Added operation.
  550. */
  551. private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
  552. Intent intent = new Intent(ACTION_OPERATION_ADDED);
  553. if (target.mAccount != null) {
  554. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  555. } else {
  556. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  557. }
  558. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  559. //lbm.sendBroadcast(intent);
  560. sendStickyBroadcast(intent);
  561. }
  562. // TODO - maybe add a notification for real start of operations
  563. /**
  564. * Sends a LOCAL broadcast when an operations finishes in order to the interested activities c
  565. * an update their view
  566. *
  567. * Local broadcasts are only delivered to activities in the same process.
  568. *
  569. * @param target Account or URL pointing to an OC server.
  570. * @param operation Finished operation.
  571. * @param result Result of the operation.
  572. */
  573. private void sendBroadcastOperationFinished(Target target, RemoteOperation operation,
  574. RemoteOperationResult result) {
  575. Intent intent = new Intent(ACTION_OPERATION_FINISHED);
  576. intent.putExtra(EXTRA_RESULT, result);
  577. if (target.mAccount != null) {
  578. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  579. } else {
  580. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  581. }
  582. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  583. //lbm.sendBroadcast(intent);
  584. sendStickyBroadcast(intent);
  585. }
  586. /**
  587. * Notifies the currently subscribed listeners about the end of an operation.
  588. *
  589. * @param operation Finished operation.
  590. * @param result Result of the operation.
  591. */
  592. protected void dispatchResultToOperationListeners(
  593. final RemoteOperation operation, final RemoteOperationResult result
  594. ) {
  595. int count = 0;
  596. Iterator<OnRemoteOperationListener> listeners =
  597. 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. }