Merge branch 'share_link__unshare_file' into release-1.5.4
[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.Iterator;
23 import java.util.Map;
24 import java.util.concurrent.ConcurrentLinkedQueue;
25
26 import com.owncloud.android.datamodel.FileDataStorageManager;
27
28 import com.owncloud.android.lib.network.OwnCloudClientFactory;
29 import com.owncloud.android.lib.network.OwnCloudClient;
30 import com.owncloud.android.operations.CreateShareOperation;
31 import com.owncloud.android.operations.UnshareLinkOperation;
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.lib.operations.common.ShareType;
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.support.v4.content.LocalBroadcastManager;
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_REMOTE_PATH = "REMOTE_PATH";
61 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
62 public static final String EXTRA_RESULT = "RESULT";
63
64 public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
65 public static final String ACTION_UNSHARE = "UNSHARE";
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 {
139 // nothing we are going to handle
140 return START_NOT_STICKY;
141 }
142
143 mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
144 //sendBroadcastNewOperation(target, operation);
145
146 Message msg = mServiceHandler.obtainMessage();
147 msg.arg1 = startId;
148 mServiceHandler.sendMessage(msg);
149
150 } catch (IllegalArgumentException e) {
151 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
152 return START_NOT_STICKY;
153 }
154
155 return START_NOT_STICKY;
156 }
157
158
159 /**
160 * Provides a binder object that clients can use to perform actions on the queue of operations,
161 * except the addition of new operations.
162 */
163 @Override
164 public IBinder onBind(Intent intent) {
165 return mBinder;
166 }
167
168
169 /**
170 * Called when ALL the bound clients were unbound.
171 */
172 @Override
173 public boolean onUnbind(Intent intent) {
174 //((OperationsServiceBinder)mBinder).clearListeners();
175 return false; // not accepting rebinding (default behaviour)
176 }
177
178
179 /**
180 * Binder to let client components to perform actions on the queue of operations.
181 *
182 * It provides by itself the available operations.
183 */
184 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
185
186 /**
187 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
188 */
189 private Map<OnRemoteOperationListener, Handler> mBoundListeners = new HashMap<OnRemoteOperationListener, Handler>();
190
191 /**
192 * Cancels an operation
193 *
194 * TODO
195 */
196 public void cancel() {
197 // TODO
198 }
199
200
201 public void clearListeners() {
202
203 mBoundListeners.clear();
204 }
205
206
207 /**
208 * Adds a listener interested in being reported about the end of operations.
209 *
210 * @param listener Object to notify about the end of operations.
211 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
212 */
213 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
214 mBoundListeners.put(listener, callbackHandler);
215 }
216
217
218 /**
219 * Removes a listener from the list of objects interested in the being reported about the end of operations.
220 *
221 * @param listener Object to notify about progress of transfer.
222 */
223 public void removeOperationListener (OnRemoteOperationListener listener) {
224 mBoundListeners.remove(listener);
225 }
226
227
228 /**
229 * TODO - IMPORTANT: update implementation when more operations are moved into the service
230 *
231 * @return 'True' when an operation that enforces the user to wait for completion is in process.
232 */
233 public boolean isPerformingBlockingOperation() {
234 return (!mPendingOperations.isEmpty());
235 }
236
237 }
238
239
240 /**
241 * Operations worker. Performs the pending operations in the order they were requested.
242 *
243 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
244 */
245 private static class ServiceHandler extends Handler {
246 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
247 OperationsService mService;
248 public ServiceHandler(Looper looper, OperationsService service) {
249 super(looper);
250 if (service == null) {
251 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
252 }
253 mService = service;
254 }
255
256 @Override
257 public void handleMessage(Message msg) {
258 mService.nextOperation();
259 mService.stopSelf(msg.arg1);
260 }
261 }
262
263
264 /**
265 * Performs the next operation in the queue
266 */
267 private void nextOperation() {
268
269 Pair<Target, RemoteOperation> next = null;
270 synchronized(mPendingOperations) {
271 next = mPendingOperations.peek();
272 }
273
274 if (next != null) {
275
276 mCurrentOperation = next.second;
277 RemoteOperationResult result = null;
278 try {
279 /// prepare client object to send the request to the ownCloud server
280 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
281 mLastTarget = next.first;
282 if (mLastTarget.mAccount != null) {
283 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mAccount, getApplicationContext());
284 mStorageManager = new FileDataStorageManager(mLastTarget.mAccount, getContentResolver());
285 } else {
286 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(), true); // this is not good enough
287 mStorageManager = null;
288 }
289 }
290
291 /// perform the operation
292 if (mCurrentOperation instanceof SyncOperation) {
293 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
294 } else {
295 result = mCurrentOperation.execute(mOwnCloudClient);
296 }
297
298 } catch (AccountsException e) {
299 if (mLastTarget.mAccount == null) {
300 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
301 } else {
302 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
303 }
304 result = new RemoteOperationResult(e);
305
306 } catch (IOException e) {
307 if (mLastTarget.mAccount == null) {
308 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
309 } else {
310 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
311 }
312 result = new RemoteOperationResult(e);
313 } catch (Exception e) {
314 if (mLastTarget.mAccount == null) {
315 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
316 } else {
317 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
318 }
319 result = new RemoteOperationResult(e);
320
321 } finally {
322 synchronized(mPendingOperations) {
323 mPendingOperations.poll();
324 }
325 }
326
327 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
328 callbackOperationListeners(mLastTarget, mCurrentOperation, result);
329 }
330 }
331
332
333 /**
334 * Sends a broadcast when a new operation is added to the queue.
335 *
336 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
337 *
338 * @param target Account or URL pointing to an OC server.
339 * @param operation Added operation.
340 */
341 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
342 Intent intent = new Intent(ACTION_OPERATION_ADDED);
343 if (target.mAccount != null) {
344 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
345 } else {
346 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
347 }
348 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
349 //lbm.sendBroadcast(intent);
350 sendStickyBroadcast(intent);
351 }
352
353
354 // TODO - maybe add a notification for real start of operations
355
356 /**
357 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
358 *
359 * Local broadcasts are only delivered to activities in the same process.
360 *
361 * @param target Account or URL pointing to an OC server.
362 * @param operation Finished operation.
363 * @param result Result of the operation.
364 */
365 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
366 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
367 intent.putExtra(EXTRA_RESULT, result);
368 if (target.mAccount != null) {
369 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
370 } else {
371 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
372 }
373 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
374 //lbm.sendBroadcast(intent);
375 sendStickyBroadcast(intent);
376 }
377
378
379 /**
380 * Notifies the currently subscribed listeners about the end of an operation.
381 *
382 * @param target Account or URL pointing to an OC server.
383 * @param operation Finished operation.
384 * @param result Result of the operation.
385 */
386 private void callbackOperationListeners(Target target, final RemoteOperation operation, final RemoteOperationResult result) {
387 Iterator<OnRemoteOperationListener> listeners = mBinder.mBoundListeners.keySet().iterator();
388 while (listeners.hasNext()) {
389 final OnRemoteOperationListener listener = listeners.next();
390 final Handler handler = mBinder.mBoundListeners.get(listener);
391 if (handler != null) {
392 handler.post(new Runnable() {
393 @Override
394 public void run() {
395 listener.onRemoteOperationFinish(operation, result);
396 }
397 });
398 }
399 }
400
401 }
402
403
404 }