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