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