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