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