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