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