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