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