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