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