ea9fcd88db34c2b26cc0962dd122505e9ddf2e1a
[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.concurrent.ConcurrentLinkedQueue;
22
23 import com.owncloud.android.datamodel.FileDataStorageManager;
24
25 import com.owncloud.android.lib.network.OwnCloudClientFactory;
26 import com.owncloud.android.lib.network.OwnCloudClient;
27 import com.owncloud.android.operations.CreateShareOperation;
28 import com.owncloud.android.operations.GetSharesOperation;
29 import com.owncloud.android.operations.common.SyncOperation;
30 import com.owncloud.android.lib.operations.common.RemoteOperation;
31 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
32 import com.owncloud.android.lib.operations.common.ShareType;
33 import com.owncloud.android.utils.Log_OC;
34
35 import android.accounts.Account;
36 import android.accounts.AccountsException;
37 import android.app.Service;
38 import android.content.Intent;
39 import android.net.Uri;
40 import android.os.Binder;
41 import android.os.Handler;
42 import android.os.HandlerThread;
43 import android.os.IBinder;
44 import android.os.Looper;
45 import android.os.Message;
46 import android.os.Process;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android.util.Pair;
49
50 public class OperationsService extends Service {
51
52 private static final String TAG = OperationsService.class.getSimpleName();
53
54 public static final String EXTRA_ACCOUNT = "ACCOUNT";
55 public static final String EXTRA_SERVER_URL = "SERVER_URL";
56 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
57 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
58 public static final String EXTRA_RESULT = "RESULT";
59
60 public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
61 public static final String ACTION_UNSHARE = "UNSHARE";
62
63 public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
64 public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
65
66 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations = new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
67
68 private static class Target {
69 public Uri mServerUrl = null;
70 public Account mAccount = null;
71 public Target(Account account, Uri serverUrl) {
72 mAccount = account;
73 mServerUrl = serverUrl;
74 }
75 }
76
77 private Looper mServiceLooper;
78 private ServiceHandler mServiceHandler;
79 private IBinder mBinder;
80 private OwnCloudClient mOwnCloudClient = null;
81 private Target mLastTarget = null;
82 private FileDataStorageManager mStorageManager;
83 private RemoteOperation mCurrentOperation = null;
84
85
86 /**
87 * Service initialization
88 */
89 @Override
90 public void onCreate() {
91 super.onCreate();
92 HandlerThread thread = new HandlerThread("Operations service thread", Process.THREAD_PRIORITY_BACKGROUND);
93 thread.start();
94 mServiceLooper = thread.getLooper();
95 mServiceHandler = new ServiceHandler(mServiceLooper, this);
96 mBinder = new OperationsServiceBinder();
97 }
98
99 /**
100 * Entry point to add a new operation to the queue of operations.
101 *
102 * New operations are added calling to startService(), resulting in a call to this method.
103 * This ensures the service will keep on working although the caller activity goes away.
104 *
105 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
106 * is taking advantage of it due to time constraints.
107 */
108 @Override
109 public int onStartCommand(Intent intent, int flags, int startId) {
110 if (!intent.hasExtra(EXTRA_ACCOUNT) && !intent.hasExtra(EXTRA_SERVER_URL)) {
111 Log_OC.e(TAG, "Not enough information provided in intent");
112 return START_NOT_STICKY;
113 }
114 try {
115 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
116 String serverUrl = intent.getStringExtra(EXTRA_SERVER_URL);
117
118 Target target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl));
119 RemoteOperation operation = null;
120
121 String action = intent.getAction();
122 if (action == ACTION_CREATE_SHARE) {
123 String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
124 Intent sendIntent = intent.getParcelableExtra(EXTRA_SEND_INTENT);
125 if (remotePath.length() > 0) {
126 operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
127 "", false, "", 1, sendIntent);
128 }
129 } else if (action == ACTION_UNSHARE) {
130
131 } else {
132 operation = new GetSharesOperation();
133 }
134
135 mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
136 sendBroadcastNewOperation(target, operation);
137
138 Message msg = mServiceHandler.obtainMessage();
139 msg.arg1 = startId;
140 mServiceHandler.sendMessage(msg);
141
142 } catch (IllegalArgumentException e) {
143 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
144 return START_NOT_STICKY;
145 }
146
147 return START_NOT_STICKY;
148 }
149
150
151 /**
152 * Provides a binder object that clients can use to perform actions on the queue of operations,
153 * except the addition of new operations.
154 */
155 @Override
156 public IBinder onBind(Intent intent) {
157 return mBinder;
158 }
159
160
161 /**
162 * Called when ALL the bound clients were unbound.
163 */
164 @Override
165 public boolean onUnbind(Intent intent) {
166 //((OperationsServiceBinder)mBinder).clearListeners();
167 return false; // not accepting rebinding (default behaviour)
168 }
169
170
171 /**
172 * Binder to let client components to perform actions on the queue of operations.
173 *
174 * It provides by itself the available operations.
175 */
176 public class OperationsServiceBinder extends Binder {
177 // TODO
178 }
179
180
181 /**
182 * Operations worker. Performs the pending operations in the order they were requested.
183 *
184 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
185 */
186 private static class ServiceHandler extends Handler {
187 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
188 OperationsService mService;
189 public ServiceHandler(Looper looper, OperationsService service) {
190 super(looper);
191 if (service == null) {
192 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
193 }
194 mService = service;
195 }
196
197 @Override
198 public void handleMessage(Message msg) {
199 mService.nextOperation();
200 mService.stopSelf(msg.arg1);
201 }
202 }
203
204
205 /**
206 * Performs the next operation in the queue
207 */
208 private void nextOperation() {
209
210 Pair<Target, RemoteOperation> next = null;
211 synchronized(mPendingOperations) {
212 next = mPendingOperations.peek();
213 }
214
215 if (next != null) {
216
217 mCurrentOperation = next.second;
218 RemoteOperationResult result = null;
219 try {
220 /// prepare client object to send the request to the ownCloud server
221 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
222 mLastTarget = next.first;
223 if (mLastTarget.mAccount != null) {
224 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mAccount, getApplicationContext());
225 mStorageManager = new FileDataStorageManager(mLastTarget.mAccount, getContentResolver());
226 } else {
227 mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(), true); // this is not good enough
228 mStorageManager = null;
229 }
230 }
231
232 /// perform the operation
233 if (mCurrentOperation instanceof SyncOperation) {
234 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
235 } else {
236 result = mCurrentOperation.execute(mOwnCloudClient);
237 }
238
239 } catch (AccountsException e) {
240 if (mLastTarget.mAccount == null) {
241 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
242 } else {
243 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
244 }
245 result = new RemoteOperationResult(e);
246
247 } catch (IOException e) {
248 if (mLastTarget.mAccount == null) {
249 Log_OC.e(TAG, "Error while trying to get autorization for a NULL account", e);
250 } else {
251 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastTarget.mAccount.name, e);
252 }
253 result = new RemoteOperationResult(e);
254 } catch (Exception e) {
255 if (mLastTarget.mAccount == null) {
256 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
257 } else {
258 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
259 }
260 result = new RemoteOperationResult(e);
261
262 } finally {
263 synchronized(mPendingOperations) {
264 mPendingOperations.poll();
265 }
266 }
267
268 sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
269 }
270 }
271
272
273 /**
274 * Sends a LOCAL broadcast when a new operation is added to the queue.
275 *
276 * Local broadcasts are only delivered to activities in the same process.
277 *
278 * @param target Account or URL pointing to an OC server.
279 * @param operation Added operation.
280 */
281 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
282 Intent intent = new Intent(ACTION_OPERATION_ADDED);
283 if (target.mAccount != null) {
284 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
285 } else {
286 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
287 }
288 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
289 //lbm.sendBroadcast(intent);
290 sendStickyBroadcast(intent);
291 }
292
293
294 // TODO - maybe add a notification for real start of operations
295
296 /**
297 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
298 *
299 * Local broadcasts are only delivered to activities in the same process.
300 *
301 * @param target Account or URL pointing to an OC server.
302 * @param operation Finished operation.
303 * @param result Result of the operation.
304 */
305 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
306 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
307 intent.putExtra(EXTRA_RESULT, result);
308 if (target.mAccount != null) {
309 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
310 } else {
311 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
312 }
313 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
314 //lbm.sendBroadcast(intent);
315 sendStickyBroadcast(intent);
316 }
317
318
319 }