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