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