Merge pull request #398 from owncloud/share_link__unshare_file__share_in_operation_se...
[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.CreateShareOperation;
32 import com.owncloud.android.operations.GetSharesOperation;
33 import com.owncloud.android.operations.UnshareLinkOperation;
34 import com.owncloud.android.operations.common.SyncOperation;
35 import com.owncloud.android.lib.operations.common.OnRemoteOperationListener;
36 import com.owncloud.android.lib.operations.common.RemoteOperation;
37 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
38 import com.owncloud.android.lib.operations.common.ShareType;
39 import com.owncloud.android.utils.Log_OC;
40
41 import android.accounts.Account;
42 import android.accounts.AccountsException;
43 import android.app.Service;
44 import android.content.Intent;
45 import android.net.Uri;
46 import android.os.Binder;
47 import android.os.Handler;
48 import android.os.HandlerThread;
49 import android.os.IBinder;
50 import android.os.Looper;
51 import android.os.Message;
52 import android.os.Process;
53 //import android.support.v4.content.LocalBroadcastManager;
54 import android.util.Pair;
55
56 public class OperationsService extends Service {
57
58 private static final String TAG = OperationsService.class.getSimpleName();
59
60 public static final String EXTRA_ACCOUNT = "ACCOUNT";
61 public static final String EXTRA_SERVER_URL = "SERVER_URL";
62 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
63 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
64 public static final String EXTRA_RESULT = "RESULT";
65
66 public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
67 public static final String ACTION_UNSHARE = "UNSHARE";
68
69 public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
70 public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
71
72 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations = new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
73
74 private static class Target {
75 public Uri mServerUrl = null;
76 public Account mAccount = null;
77 public Target(Account account, Uri serverUrl) {
78 mAccount = account;
79 mServerUrl = serverUrl;
80 }
81 }
82
83 private Looper mServiceLooper;
84 private ServiceHandler mServiceHandler;
85 private OperationsServiceBinder mBinder;
86 private OwnCloudClient mOwnCloudClient = null;
87 private Target mLastTarget = null;
88 private FileDataStorageManager mStorageManager;
89 private RemoteOperation mCurrentOperation = null;
90
91
92 /**
93 * Service initialization
94 */
95 @Override
96 public void onCreate() {
97 super.onCreate();
98 HandlerThread thread = new HandlerThread("Operations service thread", Process.THREAD_PRIORITY_BACKGROUND);
99 thread.start();
100 mServiceLooper = thread.getLooper();
101 mServiceHandler = new ServiceHandler(mServiceLooper, this);
102 mBinder = new OperationsServiceBinder();
103 }
104
105 /**
106 * Entry point to add a new operation to the queue of operations.
107 *
108 * New operations are added calling to startService(), resulting in a call to this method.
109 * This ensures the service will keep on working although the caller activity goes away.
110 *
111 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
112 * is taking advantage of it due to time constraints.
113 */
114 @Override
115 public int onStartCommand(Intent intent, int flags, int startId) {
116 if (!intent.hasExtra(EXTRA_ACCOUNT) && !intent.hasExtra(EXTRA_SERVER_URL)) {
117 Log_OC.e(TAG, "Not enough information provided in intent");
118 return START_NOT_STICKY;
119 }
120 try {
121 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
122 String serverUrl = intent.getStringExtra(EXTRA_SERVER_URL);
123
124 Target target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl));
125 RemoteOperation operation = null;
126
127 String action = intent.getAction();
128 if (action == ACTION_CREATE_SHARE) { // Create Share
129 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
130 Intent sendIntent = intent.getParcelableExtra(EXTRA_SEND_INTENT);
131 if (remotePath.length() > 0) {
132 operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
133 "", false, "", 1, sendIntent);
134 }
135 } else if (action == ACTION_UNSHARE) { // Unshare file
136 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
137 if (remotePath.length() > 0) {
138 operation = new UnshareLinkOperation(remotePath, this.getApplicationContext());
139 }
140 } else {
141 operation = new GetSharesOperation();
142 }
143
144 mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
145 sendBroadcastNewOperation(target, operation);
146
147 Message msg = mServiceHandler.obtainMessage();
148 msg.arg1 = startId;
149 mServiceHandler.sendMessage(msg);
150
151 } catch (IllegalArgumentException e) {
152 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
153 return START_NOT_STICKY;
154 }
155
156 return START_NOT_STICKY;
157 }
158
159
160 /**
161 * Provides a binder object that clients can use to perform actions on the queue of operations,
162 * except the addition of new operations.
163 */
164 @Override
165 public IBinder onBind(Intent intent) {
166 return mBinder;
167 }
168
169
170 /**
171 * Called when ALL the bound clients were unbound.
172 */
173 @Override
174 public boolean onUnbind(Intent intent) {
175 //((OperationsServiceBinder)mBinder).clearListeners();
176 return false; // not accepting rebinding (default behaviour)
177 }
178
179
180 /**
181 * Binder to let client components to perform actions on the queue of operations.
182 *
183 * It provides by itself the available operations.
184 */
185 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
186
187 /**
188 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
189 */
190 private Set<OnRemoteOperationListener> mBoundListeners = new HashSet<OnRemoteOperationListener>();
191
192 /**
193 * Cancels an operation
194 *
195 * TODO
196 */
197 public void cancel() {
198 // TODO
199 }
200
201
202 public void clearListeners() {
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 */
212 public void addOperationListener (OnRemoteOperationListener listener) {
213 mBoundListeners.add(listener);
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.size() > 0);
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, RemoteOperation operation, RemoteOperationResult result) {
386 Iterator<OnRemoteOperationListener> it = mBinder.mBoundListeners.iterator();
387 while (it.hasNext()) {
388 it.next().onRemoteOperationFinish(operation, result);
389 }
390 }
391
392
393 }