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