OperationsService.java 24 KB

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