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