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