753630514ce8e224fafeef87b67dfbe75efc585a
[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 = null;
104 public String mUsername = null;
105 public String mPassword = null;
106 public String mAuthToken = null;
107 public boolean mFollowRedirects = true;
108 public String mCookie = null;
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 null if failed.
265 */
266 public long 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)) ? null : webDavUrl,
288 username,
289 password,
290 authToken,
291 followRedirects,
292 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 // better id than hash? ; should be good enough by the time being
351 return operation.hashCode();
352
353 } else {
354 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
355 return Long.MAX_VALUE;
356 }
357 }
358
359 public void dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
360 Pair<RemoteOperation, RemoteOperationResult> undispatched =
361 mUndispatchedFinishedOperations.remove(operationId);
362 if (undispatched != null) {
363 listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
364 //Log_OC.wtf(TAG, "Sending callback later");
365 } else {
366 //Log_OC.wtf(TAG, "Not finished yet");
367 }
368 }
369
370 }
371
372
373 /**
374 * Operations worker. Performs the pending operations in the order they were requested.
375 *
376 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
377 */
378 private static class ServiceHandler extends Handler {
379 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
380 OperationsService mService;
381 public ServiceHandler(Looper looper, OperationsService service) {
382 super(looper);
383 if (service == null) {
384 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
385 }
386 mService = service;
387 }
388
389 @Override
390 public void handleMessage(Message msg) {
391 mService.nextOperation();
392 mService.stopSelf(msg.arg1);
393 }
394 }
395
396
397 /**
398 * Performs the next operation in the queue
399 */
400 private void nextOperation() {
401
402 //Log_OC.wtf(TAG, "nextOperation init" );
403
404 Pair<Target, RemoteOperation> next = null;
405 synchronized(mPendingOperations) {
406 next = mPendingOperations.peek();
407 }
408
409 if (next != null) {
410
411 mCurrentOperation = next.second;
412 RemoteOperationResult result = null;
413 try {
414 /// prepare client object to send the request to the ownCloud server
415 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
416 mLastTarget = next.first;
417 if (mLastTarget.mAccount != null) {
418 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mAccount, getApplicationContext());
419 mStorageManager = new FileDataStorageManager(mLastTarget.mAccount, getContentResolver());
420 } else {
421 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(),
422 mLastTarget.mFollowRedirects); // this is not good enough
423 if (mLastTarget.mWebDavUrl != null) {
424 mOwnCloudClient.setWebdavUri(Uri.parse(mLastTarget.mWebDavUrl));
425 }
426 if (mLastTarget.mUsername != null && mLastTarget.mPassword != null) {
427 mOwnCloudClient.setBasicCredentials(mLastTarget.mUsername, mLastTarget.mPassword);
428 } else if (mLastTarget.mAuthToken != null) {
429 mOwnCloudClient.setBearerCredentials(mLastTarget.mAuthToken);
430 } else if (mLastTarget.mCookie != null) {
431 mOwnCloudClient.setSsoSessionCookie(mLastTarget.mCookie);
432 }
433 mStorageManager = null;
434 }
435 }
436
437 /// perform the operation
438 if (mCurrentOperation instanceof SyncOperation) {
439 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
440 } else {
441 result = mCurrentOperation.execute(mOwnCloudClient);
442 }
443
444 } catch (AccountsException e) {
445 if (mLastTarget.mAccount == null) {
446 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
447 } else {
448 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
449 }
450 result = new RemoteOperationResult(e);
451
452 } catch (IOException e) {
453 if (mLastTarget.mAccount == null) {
454 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
455 } else {
456 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
457 }
458 result = new RemoteOperationResult(e);
459 } catch (Exception e) {
460 if (mLastTarget.mAccount == null) {
461 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
462 } else {
463 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
464 }
465 result = new RemoteOperationResult(e);
466
467 } finally {
468 synchronized(mPendingOperations) {
469 mPendingOperations.poll();
470 }
471 }
472
473 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
474 dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
475 }
476 }
477
478
479 /**
480 * Sends a broadcast when a new operation is added to the queue.
481 *
482 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
483 *
484 * @param target Account or URL pointing to an OC server.
485 * @param operation Added operation.
486 */
487 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
488 Intent intent = new Intent(ACTION_OPERATION_ADDED);
489 if (target.mAccount != null) {
490 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
491 } else {
492 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
493 }
494 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
495 //lbm.sendBroadcast(intent);
496 sendStickyBroadcast(intent);
497 }
498
499
500 // TODO - maybe add a notification for real start of operations
501
502 /**
503 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
504 *
505 * Local broadcasts are only delivered to activities in the same process.
506 *
507 * @param target Account or URL pointing to an OC server.
508 * @param operation Finished operation.
509 * @param result Result of the operation.
510 */
511 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
512 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
513 intent.putExtra(EXTRA_RESULT, result);
514 if (target.mAccount != null) {
515 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
516 } else {
517 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
518 }
519 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
520 //lbm.sendBroadcast(intent);
521 sendStickyBroadcast(intent);
522 }
523
524
525 /**
526 * Notifies the currently subscribed listeners about the end of an operation.
527 *
528 * @param target Account or URL pointing to an OC server.
529 * @param operation Finished operation.
530 * @param result Result of the operation.
531 */
532 private void dispatchResultToOperationListeners(
533 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
534 int count = 0;
535 Iterator<OnRemoteOperationListener> listeners = mBinder.mBoundListeners.keySet().iterator();
536 while (listeners.hasNext()) {
537 final OnRemoteOperationListener listener = listeners.next();
538 final Handler handler = mBinder.mBoundListeners.get(listener);
539 if (handler != null) {
540 handler.post(new Runnable() {
541 @Override
542 public void run() {
543 listener.onRemoteOperationFinish(operation, result);
544 }
545 });
546 count += 1;
547 }
548 }
549 if (count == 0) {
550 //mOperationResults.put(operation.hashCode(), result);
551 Pair<RemoteOperation, RemoteOperationResult> undispatched =
552 new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
553 mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
554 }
555 Log_OC.d(TAG, "Called " + count + " listeners");
556 }
557
558
559 }