OperationsService.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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.R;
  24. import com.owncloud.android.datamodel.FileDataStorageManager;
  25. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  26. import com.owncloud.android.lib.common.OwnCloudClient;
  27. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  28. import com.owncloud.android.lib.common.operations.RemoteOperation;
  29. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  30. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  31. import com.owncloud.android.lib.resources.shares.ShareType;
  32. import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
  33. import com.owncloud.android.operations.common.SyncOperation;
  34. import com.owncloud.android.operations.CreateFolderOperation;
  35. import com.owncloud.android.operations.CreateShareOperation;
  36. import com.owncloud.android.operations.GetServerInfoOperation;
  37. import com.owncloud.android.operations.OAuth2GetAccessToken;
  38. import com.owncloud.android.operations.RemoveFileOperation;
  39. import com.owncloud.android.operations.RenameFileOperation;
  40. import com.owncloud.android.operations.SynchronizeFileOperation;
  41. import com.owncloud.android.operations.UnshareLinkOperation;
  42. import com.owncloud.android.utils.Log_OC;
  43. import android.accounts.Account;
  44. import android.accounts.AccountsException;
  45. import android.app.Service;
  46. import android.content.Intent;
  47. import android.net.Uri;
  48. import android.os.Binder;
  49. import android.os.Handler;
  50. import android.os.HandlerThread;
  51. import android.os.IBinder;
  52. import android.os.Looper;
  53. import android.os.Message;
  54. import android.os.Process;
  55. import android.util.Pair;
  56. public class OperationsService extends Service {
  57. private static final String TAG = OperationsService.class.getSimpleName();
  58. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  59. public static final String EXTRA_SERVER_URL = "SERVER_URL";
  60. public static final String EXTRA_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
  61. public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
  62. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  63. public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
  64. public static final String EXTRA_NEWNAME = "NEWNAME";
  65. public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
  66. public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
  67. public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
  68. public static final String EXTRA_RESULT = "RESULT";
  69. // TODO review if ALL OF THEM are necessary
  70. public static final String EXTRA_WEBDAV_PATH = "WEBDAV_PATH";
  71. public static final String EXTRA_SUCCESS_IF_ABSENT = "SUCCESS_IF_ABSENT";
  72. public static final String EXTRA_USERNAME = "USERNAME";
  73. public static final String EXTRA_PASSWORD = "PASSWORD";
  74. public static final String EXTRA_AUTH_TOKEN = "AUTH_TOKEN";
  75. public static final String EXTRA_FOLLOW_REDIRECTS = "FOLLOW_REDIRECTS";
  76. public static final String EXTRA_COOKIE = "COOKIE";
  77. public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
  78. public static final String ACTION_UNSHARE = "UNSHARE";
  79. public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
  80. public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
  81. public static final String ACTION_EXISTENCE_CHECK = "EXISTENCE_CHECK";
  82. public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
  83. public static final String ACTION_RENAME = "RENAME";
  84. public static final String ACTION_REMOVE = "REMOVE";
  85. public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
  86. public static final String ACTION_SYNC_FILE = "SYNC_FILE";
  87. public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
  88. public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
  89. private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
  90. new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
  91. private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
  92. mUndispatchedFinishedOperations =
  93. new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
  94. private static class Target {
  95. public Uri mServerUrl = null;
  96. public Account mAccount = null;
  97. public String mWebDavUrl = null;
  98. public String mUsername = null;
  99. public String mPassword = null;
  100. public String mAuthToken = null;
  101. public boolean mFollowRedirects = true;
  102. public String mCookie = null;
  103. public Target(Account account, Uri serverUrl, String webdavUrl, String username, String password, String authToken,
  104. boolean followRedirects, String cookie) {
  105. mAccount = account;
  106. mServerUrl = serverUrl;
  107. mWebDavUrl = webdavUrl;
  108. mUsername = username;
  109. mPassword = password;
  110. mAuthToken = authToken;
  111. mFollowRedirects = followRedirects;
  112. mCookie = cookie;
  113. }
  114. }
  115. private Looper mServiceLooper;
  116. private ServiceHandler mServiceHandler;
  117. private OperationsServiceBinder mBinder;
  118. private OwnCloudClient mOwnCloudClient = null;
  119. private Target mLastTarget = null;
  120. private FileDataStorageManager mStorageManager;
  121. private RemoteOperation mCurrentOperation = null;
  122. /**
  123. * Service initialization
  124. */
  125. @Override
  126. public void onCreate() {
  127. super.onCreate();
  128. HandlerThread thread = new HandlerThread("Operations service thread", Process.THREAD_PRIORITY_BACKGROUND);
  129. thread.start();
  130. mServiceLooper = thread.getLooper();
  131. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  132. mBinder = new OperationsServiceBinder();
  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. * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
  141. * is taking advantage of it due to time constraints.
  142. */
  143. @Override
  144. public int onStartCommand(Intent intent, int flags, int startId) {
  145. //Log_OC.wtf(TAG, "onStartCommand init" );
  146. Message msg = mServiceHandler.obtainMessage();
  147. msg.arg1 = startId;
  148. mServiceHandler.sendMessage(msg);
  149. //Log_OC.wtf(TAG, "onStartCommand end" );
  150. return START_NOT_STICKY;
  151. }
  152. @Override
  153. public void onDestroy() {
  154. //Log_OC.wtf(TAG, "onDestroy init" );
  155. //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
  156. mUndispatchedFinishedOperations.clear();
  157. //Log_OC.wtf(TAG, "onDestroy end" );
  158. super.onDestroy();
  159. }
  160. /**
  161. * Provides a binder object that clients can use to perform actions on the queue of operations,
  162. * except the addition of new operations.
  163. */
  164. @Override
  165. public IBinder onBind(Intent intent) {
  166. //Log_OC.wtf(TAG, "onBind" );
  167. return mBinder;
  168. }
  169. /**
  170. * Called when ALL the bound clients were unbound.
  171. */
  172. @Override
  173. public boolean onUnbind(Intent intent) {
  174. ((OperationsServiceBinder)mBinder).clearListeners();
  175. return false; // not accepting rebinding (default behaviour)
  176. }
  177. /**
  178. * Binder to let client components to perform actions on the queue of operations.
  179. *
  180. * It provides by itself the available operations.
  181. */
  182. public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
  183. /**
  184. * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
  185. */
  186. private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
  187. new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
  188. /**
  189. * Cancels an operation
  190. *
  191. * TODO
  192. */
  193. public void cancel() {
  194. // TODO
  195. }
  196. public void clearListeners() {
  197. mBoundListeners.clear();
  198. }
  199. /**
  200. * Adds a listener interested in being reported about the end of operations.
  201. *
  202. * @param listener Object to notify about the end of operations.
  203. * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
  204. */
  205. public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
  206. synchronized (mBoundListeners) {
  207. mBoundListeners.put(listener, callbackHandler);
  208. }
  209. }
  210. /**
  211. * Removes a listener from the list of objects interested in the being reported about the end of operations.
  212. *
  213. * @param listener Object to notify about progress of transfer.
  214. */
  215. public void removeOperationListener (OnRemoteOperationListener listener) {
  216. synchronized (mBoundListeners) {
  217. mBoundListeners.remove(listener);
  218. }
  219. }
  220. /**
  221. * TODO - IMPORTANT: update implementation when more operations are moved into the service
  222. *
  223. * @return 'True' when an operation that enforces the user to wait for completion is in process.
  224. */
  225. public boolean isPerformingBlockingOperation() {
  226. return (!mPendingOperations.isEmpty());
  227. }
  228. /**
  229. * Creates and adds to the queue a new operation, as described by operationIntent
  230. *
  231. * @param operationIntent Intent describing a new operation to queue and execute.
  232. * @return Identifier of the operation created, or null if failed.
  233. */
  234. public long newOperation(Intent operationIntent) {
  235. RemoteOperation operation = null;
  236. Target target = null;
  237. try {
  238. if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
  239. !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
  240. Log_OC.e(TAG, "Not enough information provided in intent");
  241. } else {
  242. Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
  243. String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
  244. String webDavPath = operationIntent.getStringExtra(EXTRA_WEBDAV_PATH);
  245. String webDavUrl = serverUrl + webDavPath;
  246. String username = operationIntent.getStringExtra(EXTRA_USERNAME);
  247. String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
  248. String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
  249. boolean followRedirects = operationIntent.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS, true);
  250. String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
  251. target = new Target(
  252. account,
  253. (serverUrl == null) ? null : Uri.parse(serverUrl),
  254. ((webDavPath == null) || (serverUrl == null)) ? null : webDavUrl,
  255. username,
  256. password,
  257. authToken,
  258. followRedirects,
  259. cookie
  260. );
  261. String action = operationIntent.getAction();
  262. if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
  263. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  264. Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
  265. if (remotePath.length() > 0) {
  266. operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
  267. "", false, "", 1, sendIntent);
  268. }
  269. } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
  270. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  271. if (remotePath.length() > 0) {
  272. operation = new UnshareLinkOperation(
  273. remotePath,
  274. OperationsService.this);
  275. }
  276. } else if (action.equals(ACTION_GET_SERVER_INFO)) {
  277. // check OC server and get basic information from it
  278. String authTokenType =
  279. operationIntent.getStringExtra(EXTRA_AUTH_TOKEN_TYPE);
  280. operation = new GetServerInfoOperation(
  281. serverUrl, authTokenType, OperationsService.this);
  282. } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
  283. /// GET ACCESS TOKEN to the OAuth server
  284. String oauth2QueryParameters =
  285. operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
  286. operation = new OAuth2GetAccessToken(
  287. getString(R.string.oauth2_client_id),
  288. getString(R.string.oauth2_redirect_uri),
  289. getString(R.string.oauth2_grant_type),
  290. oauth2QueryParameters);
  291. } else if (action.equals(ACTION_EXISTENCE_CHECK)) {
  292. // Existence Check
  293. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  294. boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, true);
  295. operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
  296. } else if (action.equals(ACTION_GET_USER_NAME)) {
  297. // Get User Name
  298. operation = new GetRemoteUserNameOperation();
  299. } else if (action.equals(ACTION_RENAME)) {
  300. // Rename file or folder
  301. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  302. String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
  303. operation = new RenameFileOperation(remotePath, account, newName);
  304. } else if (action.equals(ACTION_REMOVE)) {
  305. // Remove file or folder
  306. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  307. boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
  308. operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
  309. } else if (action.equals(ACTION_CREATE_FOLDER)) {
  310. // Create Folder
  311. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  312. boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
  313. operation = new CreateFolderOperation(remotePath, createFullPath);
  314. } else if (action.equals(ACTION_SYNC_FILE)) {
  315. // Sync file
  316. String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
  317. boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
  318. operation = new SynchronizeFileOperation(remotePath, account, syncFileContents, getApplicationContext());
  319. }
  320. }
  321. } catch (IllegalArgumentException e) {
  322. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  323. operation = null;
  324. }
  325. if (operation != null) {
  326. mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
  327. startService(new Intent(OperationsService.this, OperationsService.class));
  328. //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
  329. // better id than hash? ; should be good enough by the time being
  330. return operation.hashCode();
  331. } else {
  332. //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
  333. return Long.MAX_VALUE;
  334. }
  335. }
  336. public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
  337. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  338. mUndispatchedFinishedOperations.remove(operationId);
  339. if (undispatched != null) {
  340. listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
  341. return true;
  342. //Log_OC.wtf(TAG, "Sending callback later");
  343. } else {
  344. if (!mPendingOperations.isEmpty()) {
  345. return true;
  346. } else {
  347. return false;
  348. }
  349. //Log_OC.wtf(TAG, "Not finished yet");
  350. }
  351. }
  352. }
  353. /**
  354. * Operations worker. Performs the pending operations in the order they were requested.
  355. *
  356. * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
  357. */
  358. private static class ServiceHandler extends Handler {
  359. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  360. OperationsService mService;
  361. public ServiceHandler(Looper looper, OperationsService service) {
  362. super(looper);
  363. if (service == null) {
  364. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  365. }
  366. mService = service;
  367. }
  368. @Override
  369. public void handleMessage(Message msg) {
  370. mService.nextOperation();
  371. mService.stopSelf(msg.arg1);
  372. }
  373. }
  374. /**
  375. * Performs the next operation in the queue
  376. */
  377. private void nextOperation() {
  378. //Log_OC.wtf(TAG, "nextOperation init" );
  379. Pair<Target, RemoteOperation> next = null;
  380. synchronized(mPendingOperations) {
  381. next = mPendingOperations.peek();
  382. }
  383. if (next != null) {
  384. mCurrentOperation = next.second;
  385. RemoteOperationResult result = null;
  386. try {
  387. /// prepare client object to send the request to the ownCloud server
  388. if (mLastTarget == null || !mLastTarget.equals(next.first)) {
  389. mLastTarget = next.first;
  390. if (mLastTarget.mAccount != null) {
  391. mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mAccount, getApplicationContext());
  392. mStorageManager = new FileDataStorageManager(mLastTarget.mAccount, getContentResolver());
  393. } else {
  394. mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(),
  395. mLastTarget.mFollowRedirects); // this is not good enough
  396. if (mLastTarget.mWebDavUrl != null) {
  397. mOwnCloudClient.setWebdavUri(Uri.parse(mLastTarget.mWebDavUrl));
  398. }
  399. if (mLastTarget.mUsername != null && mLastTarget.mPassword != null) {
  400. mOwnCloudClient.setBasicCredentials(mLastTarget.mUsername, mLastTarget.mPassword);
  401. } else if (mLastTarget.mAuthToken != null) {
  402. mOwnCloudClient.setBearerCredentials(mLastTarget.mAuthToken);
  403. } else if (mLastTarget.mCookie != null) {
  404. mOwnCloudClient.setSsoSessionCookie(mLastTarget.mCookie);
  405. }
  406. mStorageManager = null;
  407. }
  408. }
  409. /// perform the operation
  410. if (mCurrentOperation instanceof SyncOperation) {
  411. result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
  412. } else {
  413. result = mCurrentOperation.execute(mOwnCloudClient);
  414. }
  415. } catch (AccountsException e) {
  416. if (mLastTarget.mAccount == null) {
  417. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
  418. } else {
  419. Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
  420. }
  421. result = new RemoteOperationResult(e);
  422. } catch (IOException e) {
  423. if (mLastTarget.mAccount == null) {
  424. Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
  425. } else {
  426. Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
  427. }
  428. result = new RemoteOperationResult(e);
  429. } catch (Exception e) {
  430. if (mLastTarget.mAccount == null) {
  431. Log_OC.e(TAG, "Unexpected error for a NULL account", e);
  432. } else {
  433. Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
  434. }
  435. result = new RemoteOperationResult(e);
  436. } finally {
  437. synchronized(mPendingOperations) {
  438. mPendingOperations.poll();
  439. }
  440. }
  441. //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
  442. dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
  443. }
  444. }
  445. /**
  446. * Sends a broadcast when a new operation is added to the queue.
  447. *
  448. * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
  449. *
  450. * @param target Account or URL pointing to an OC server.
  451. * @param operation Added operation.
  452. */
  453. private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
  454. Intent intent = new Intent(ACTION_OPERATION_ADDED);
  455. if (target.mAccount != null) {
  456. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  457. } else {
  458. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  459. }
  460. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  461. //lbm.sendBroadcast(intent);
  462. sendStickyBroadcast(intent);
  463. }
  464. // TODO - maybe add a notification for real start of operations
  465. /**
  466. * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
  467. *
  468. * Local broadcasts are only delivered to activities in the same process.
  469. *
  470. * @param target Account or URL pointing to an OC server.
  471. * @param operation Finished operation.
  472. * @param result Result of the operation.
  473. */
  474. private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
  475. Intent intent = new Intent(ACTION_OPERATION_FINISHED);
  476. intent.putExtra(EXTRA_RESULT, result);
  477. if (target.mAccount != null) {
  478. intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
  479. } else {
  480. intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
  481. }
  482. //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
  483. //lbm.sendBroadcast(intent);
  484. sendStickyBroadcast(intent);
  485. }
  486. /**
  487. * Notifies the currently subscribed listeners about the end of an operation.
  488. *
  489. * @param target Account or URL pointing to an OC server.
  490. * @param operation Finished operation.
  491. * @param result Result of the operation.
  492. */
  493. private void dispatchResultToOperationListeners(
  494. Target target, final RemoteOperation operation, final RemoteOperationResult result) {
  495. int count = 0;
  496. Iterator<OnRemoteOperationListener> listeners = mBinder.mBoundListeners.keySet().iterator();
  497. while (listeners.hasNext()) {
  498. final OnRemoteOperationListener listener = listeners.next();
  499. final Handler handler = mBinder.mBoundListeners.get(listener);
  500. if (handler != null) {
  501. handler.post(new Runnable() {
  502. @Override
  503. public void run() {
  504. listener.onRemoteOperationFinish(operation, result);
  505. }
  506. });
  507. count += 1;
  508. }
  509. }
  510. if (count == 0) {
  511. //mOperationResults.put(operation.hashCode(), result);
  512. Pair<RemoteOperation, RemoteOperationResult> undispatched =
  513. new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
  514. mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
  515. }
  516. Log_OC.d(TAG, "Called " + count + " listeners");
  517. }
  518. }