Refresh authorization token on failed downloads / uploads when notification error...
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileDownloader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.files.services;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.util.AbstractList;
25 import java.util.Iterator;
26 import java.util.Vector;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29
30 import com.owncloud.android.datamodel.FileDataStorageManager;
31 import com.owncloud.android.datamodel.OCFile;
32 import eu.alefzero.webdav.OnDatatransferProgressListener;
33
34 import com.owncloud.android.network.OwnCloudClientUtils;
35 import com.owncloud.android.operations.DownloadFileOperation;
36 import com.owncloud.android.operations.RemoteOperationResult;
37 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
38 import com.owncloud.android.ui.activity.AuthenticatorActivity;
39 import com.owncloud.android.ui.activity.FileDetailActivity;
40 import com.owncloud.android.ui.fragment.FileDetailFragment;
41
42 import android.accounts.Account;
43 import android.accounts.AccountsException;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.Service;
48 import android.content.Intent;
49 import android.os.Binder;
50 import android.os.Handler;
51 import android.os.HandlerThread;
52 import android.os.IBinder;
53 import android.os.Looper;
54 import android.os.Message;
55 import android.os.Process;
56 import android.util.Log;
57 import android.widget.RemoteViews;
58
59 import com.owncloud.android.R;
60 import eu.alefzero.webdav.WebdavClient;
61
62 public class FileDownloader extends Service implements OnDatatransferProgressListener {
63
64 public static final String EXTRA_ACCOUNT = "ACCOUNT";
65 public static final String EXTRA_FILE = "FILE";
66
67 public static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
68 public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
69 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
70 public static final String EXTRA_FILE_PATH = "FILE_PATH";
71 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
72 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
73
74 private static final String TAG = "FileDownloader";
75
76 private Looper mServiceLooper;
77 private ServiceHandler mServiceHandler;
78 private IBinder mBinder;
79 private WebdavClient mDownloadClient = null;
80 private Account mLastAccount = null;
81 private FileDataStorageManager mStorageManager;
82
83 private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
84 private DownloadFileOperation mCurrentDownload = null;
85
86 private NotificationManager mNotificationManager;
87 private Notification mNotification;
88 private int mLastPercent;
89
90
91 /**
92 * Builds a key for mPendingDownloads from the account and file to download
93 *
94 * @param account Account where the file to download is stored
95 * @param file File to download
96 */
97 private String buildRemoteName(Account account, OCFile file) {
98 return account.name + file.getRemotePath();
99 }
100
101
102 /**
103 * Service initialization
104 */
105 @Override
106 public void onCreate() {
107 super.onCreate();
108 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
109 HandlerThread thread = new HandlerThread("FileDownloaderThread",
110 Process.THREAD_PRIORITY_BACKGROUND);
111 thread.start();
112 mServiceLooper = thread.getLooper();
113 mServiceHandler = new ServiceHandler(mServiceLooper, this);
114 mBinder = new FileDownloaderBinder();
115 }
116
117
118 /**
119 * Entry point to add one or several files to the queue of downloads.
120 *
121 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
122 * although the caller activity goes away.
123 */
124 @Override
125 public int onStartCommand(Intent intent, int flags, int startId) {
126 if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
127 !intent.hasExtra(EXTRA_FILE)
128 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
129 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
130 ) {
131 Log.e(TAG, "Not enough information provided in intent");
132 return START_NOT_STICKY;
133 }
134 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
135 OCFile file = intent.getParcelableExtra(EXTRA_FILE);
136
137 AbstractList<String> requestedDownloads = new Vector<String>(); // dvelasco: now this always contains just one element, but that can change in a near future (download of multiple selection)
138 String downloadKey = buildRemoteName(account, file);
139 try {
140 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
141 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
142 newDownload.addDatatransferProgressListener(this);
143 requestedDownloads.add(downloadKey);
144 sendBroadcastNewDownload(newDownload);
145
146 } catch (IllegalArgumentException e) {
147 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
148 return START_NOT_STICKY;
149 }
150
151 if (requestedDownloads.size() > 0) {
152 Message msg = mServiceHandler.obtainMessage();
153 msg.arg1 = startId;
154 msg.obj = requestedDownloads;
155 mServiceHandler.sendMessage(msg);
156 }
157
158 return START_NOT_STICKY;
159 }
160
161
162 /**
163 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
164 *
165 * Implemented to perform cancellation, pause and resume of existing downloads.
166 */
167 @Override
168 public IBinder onBind(Intent arg0) {
169 return mBinder;
170 }
171
172
173 /**
174 * Binder to let client components to perform operations on the queue of downloads.
175 *
176 * It provides by itself the available operations.
177 */
178 public class FileDownloaderBinder extends Binder {
179
180 /**
181 * Cancels a pending or current download of a remote file.
182 *
183 * @param account Owncloud account where the remote file is stored.
184 * @param file A file in the queue of pending downloads
185 */
186 public void cancel(Account account, OCFile file) {
187 DownloadFileOperation download = null;
188 synchronized (mPendingDownloads) {
189 download = mPendingDownloads.remove(buildRemoteName(account, file));
190 }
191 if (download != null) {
192 download.cancel();
193 }
194 }
195
196
197 /**
198 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
199 *
200 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
201 *
202 * @param account Owncloud account where the remote file is stored.
203 * @param file A file that could be in the queue of downloads.
204 */
205 public boolean isDownloading(Account account, OCFile file) {
206 if (account == null || file == null) return false;
207 String targetKey = buildRemoteName(account, file);
208 synchronized (mPendingDownloads) {
209 if (file.isDirectory()) {
210 // this can be slow if there are many downloads :(
211 Iterator<String> it = mPendingDownloads.keySet().iterator();
212 boolean found = false;
213 while (it.hasNext() && !found) {
214 found = it.next().startsWith(targetKey);
215 }
216 return found;
217 } else {
218 return (mPendingDownloads.containsKey(targetKey));
219 }
220 }
221 }
222 }
223
224
225 /**
226 * Download worker. Performs the pending downloads in the order they were requested.
227 *
228 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
229 */
230 private static class ServiceHandler extends Handler {
231 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
232 FileDownloader mService;
233 public ServiceHandler(Looper looper, FileDownloader service) {
234 super(looper);
235 if (service == null)
236 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
237 mService = service;
238 }
239
240 @Override
241 public void handleMessage(Message msg) {
242 @SuppressWarnings("unchecked")
243 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
244 if (msg.obj != null) {
245 Iterator<String> it = requestedDownloads.iterator();
246 while (it.hasNext()) {
247 mService.downloadFile(it.next());
248 }
249 }
250 mService.stopSelf(msg.arg1);
251 }
252 }
253
254
255
256 /**
257 * Core download method: requests a file to download and stores it.
258 *
259 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
260 */
261 private void downloadFile(String downloadKey) {
262
263 synchronized(mPendingDownloads) {
264 mCurrentDownload = mPendingDownloads.get(downloadKey);
265 }
266
267 if (mCurrentDownload != null) {
268
269 notifyDownloadStart(mCurrentDownload);
270
271 RemoteOperationResult downloadResult = null;
272 try {
273 /// prepare client object to send the request to the ownCloud server
274 if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
275 mLastAccount = mCurrentDownload.getAccount();
276 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
277 mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
278 }
279
280 /// perform the download
281 if (downloadResult == null) {
282 downloadResult = mCurrentDownload.execute(mDownloadClient);
283 }
284 if (downloadResult.isSuccess()) {
285 saveDownloadedFile();
286 }
287
288 } catch (AccountsException e) {
289 Log.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
290 downloadResult = new RemoteOperationResult(e);
291 } catch (IOException e) {
292 Log.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
293 downloadResult = new RemoteOperationResult(e);
294
295 } finally {
296 synchronized(mPendingDownloads) {
297 mPendingDownloads.remove(downloadKey);
298 }
299 }
300
301
302 /// notify result
303 notifyDownloadResult(mCurrentDownload, downloadResult);
304
305 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
306 }
307 }
308
309
310 /**
311 * Updates the OC File after a successful download.
312 */
313 private void saveDownloadedFile() {
314 OCFile file = mCurrentDownload.getFile();
315 long syncDate = System.currentTimeMillis();
316 file.setLastSyncDateForProperties(syncDate);
317 file.setLastSyncDateForData(syncDate);
318 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
319 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
320 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
321 file.setMimetype(mCurrentDownload.getMimeType());
322 file.setStoragePath(mCurrentDownload.getSavePath());
323 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
324 mStorageManager.saveFile(file);
325 }
326
327
328 /**
329 * Creates a status notification to show the download progress
330 *
331 * @param download Download operation starting.
332 */
333 private void notifyDownloadStart(DownloadFileOperation download) {
334 /// create status notification with a progress bar
335 mLastPercent = 0;
336 mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
337 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
338 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
339 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
340 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
341 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
342
343 /// includes a pending intent in the notification showing the details view of the file
344 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
345 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
346 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
347 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
348 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
349
350 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
351 }
352
353
354 /**
355 * Callback method to update the progress bar in the status notification.
356 */
357 @Override
358 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
359 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
360 if (percent != mLastPercent) {
361 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
362 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
363 mNotification.contentView.setTextViewText(R.id.status_text, text);
364 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
365 }
366 mLastPercent = percent;
367 }
368
369
370 /**
371 * Callback method to update the progress bar in the status notification (old version)
372 */
373 @Override
374 public void onTransferProgress(long progressRate) {
375 // NOTHING TO DO HERE ANYMORE
376 }
377
378
379 /**
380 * Updates the status notification with the result of a download operation.
381 *
382 * @param downloadResult Result of the download operation.
383 * @param download Finished download operation
384 */
385 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
386 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
387 if (!downloadResult.isCancelled()) {
388 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
389 int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
390 Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
391 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
392 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED);
393 if (needsToUpdateCredentials) {
394 // let the user update credentials with one click
395 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
396 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
397 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
398 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
399 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
400 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
401 finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
402 finalNotification.setLatestEventInfo( getApplicationContext(),
403 getString(tickerId),
404 String.format(getString(contentId), new File(download.getSavePath()).getName()),
405 finalNotification.contentIntent);
406 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
407
408 } else {
409 // TODO put something smart in the contentIntent below
410 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
411 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
412 }
413 mNotificationManager.notify(tickerId, finalNotification);
414 }
415 }
416
417
418 /**
419 * Sends a broadcast when a download finishes in order to the interested activities can update their view
420 *
421 * @param download Finished download operation
422 * @param downloadResult Result of the download operation
423 */
424 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
425 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
426 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
427 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
428 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
429 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
430 sendStickyBroadcast(end);
431 }
432
433
434 /**
435 * Sends a broadcast when a new download is added to the queue.
436 *
437 * @param download Added download operation
438 */
439 private void sendBroadcastNewDownload(DownloadFileOperation download) {
440 Intent added = new Intent(DOWNLOAD_ADDED_MESSAGE);
441 /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
442 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
443 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
444 sendStickyBroadcast(added);
445 }
446
447 }