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