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