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