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