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