2e60636b936f0775f9735d31f3ef49041682993d
[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.MainApp;
32 import com.owncloud.android.R;
33 import com.owncloud.android.authentication.AuthenticatorActivity;
34 import com.owncloud.android.datamodel.FileDataStorageManager;
35 import com.owncloud.android.datamodel.OCFile;
36
37 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
38 import com.owncloud.android.lib.common.OwnCloudAccount;
39 import com.owncloud.android.lib.common.OwnCloudClient;
40 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
41 import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
42 import com.owncloud.android.notifications.NotificationDelayer;
43 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
44 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
45 import com.owncloud.android.lib.resources.files.FileUtils;
46 import com.owncloud.android.operations.DownloadFileOperation;
47 import com.owncloud.android.ui.activity.FileActivity;
48 import com.owncloud.android.ui.activity.FileDisplayActivity;
49 import com.owncloud.android.ui.preview.PreviewImageActivity;
50 import com.owncloud.android.ui.preview.PreviewImageFragment;
51 import com.owncloud.android.utils.ErrorMessageAdapter;
52 import com.owncloud.android.utils.Log_OC;
53
54 import android.accounts.Account;
55 import android.accounts.AccountsException;
56 import android.app.NotificationManager;
57 import android.app.PendingIntent;
58 import android.app.Service;
59 import android.content.Intent;
60 import android.os.Binder;
61 import android.os.Handler;
62 import android.os.HandlerThread;
63 import android.os.IBinder;
64 import android.os.Looper;
65 import android.os.Message;
66 import android.os.Process;
67 import android.support.v4.app.NotificationCompat;
68
69 public class FileDownloader extends Service implements OnDatatransferProgressListener {
70
71 public static final String EXTRA_ACCOUNT = "ACCOUNT";
72 public static final String EXTRA_FILE = "FILE";
73
74 private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
75 private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
76 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
77 public static final String EXTRA_FILE_PATH = "FILE_PATH";
78 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
79 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
80
81 private static final String TAG = "FileDownloader";
82
83 private Looper mServiceLooper;
84 private ServiceHandler mServiceHandler;
85 private IBinder mBinder;
86 private OwnCloudClient mDownloadClient = null;
87 private Account mLastAccount = null;
88 private FileDataStorageManager mStorageManager;
89
90 private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
91 private DownloadFileOperation mCurrentDownload = null;
92
93 private NotificationManager mNotificationManager;
94 private NotificationCompat.Builder mNotificationBuilder;
95 private int mLastPercent;
96
97
98 public static String getDownloadAddedMessage() {
99 return FileDownloader.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE;
100 }
101
102 public static String getDownloadFinishMessage() {
103 return FileDownloader.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE;
104 }
105
106 /**
107 * Builds a key for mPendingDownloads from the account and file to download
108 *
109 * @param account Account where the file to download is stored
110 * @param file File to download
111 */
112 private String buildRemoteName(Account account, OCFile file) {
113 return account.name + file.getRemotePath();
114 }
115
116
117 /**
118 * Service initialization
119 */
120 @Override
121 public void onCreate() {
122 super.onCreate();
123 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
124 HandlerThread thread = new HandlerThread("FileDownloaderThread",
125 Process.THREAD_PRIORITY_BACKGROUND);
126 thread.start();
127 mServiceLooper = thread.getLooper();
128 mServiceHandler = new ServiceHandler(mServiceLooper, this);
129 mBinder = new FileDownloaderBinder();
130 }
131
132 /**
133 * Entry point to add one or several files to the queue of downloads.
134 *
135 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
136 * although the caller activity goes away.
137 */
138 @Override
139 public int onStartCommand(Intent intent, int flags, int startId) {
140 if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
141 !intent.hasExtra(EXTRA_FILE)
142 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
143 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
144 ) {
145 Log_OC.e(TAG, "Not enough information provided in intent");
146 return START_NOT_STICKY;
147 }
148 Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
149 OCFile file = intent.getParcelableExtra(EXTRA_FILE);
150
151 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)
152 String downloadKey = buildRemoteName(account, file);
153 try {
154 DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
155 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
156 newDownload.addDatatransferProgressListener(this);
157 newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
158 requestedDownloads.add(downloadKey);
159 sendBroadcastNewDownload(newDownload);
160
161 } catch (IllegalArgumentException e) {
162 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
163 return START_NOT_STICKY;
164 }
165
166 if (requestedDownloads.size() > 0) {
167 Message msg = mServiceHandler.obtainMessage();
168 msg.arg1 = startId;
169 msg.obj = requestedDownloads;
170 mServiceHandler.sendMessage(msg);
171 }
172
173 return START_NOT_STICKY;
174 }
175
176
177 /**
178 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
179 *
180 * Implemented to perform cancellation, pause and resume of existing downloads.
181 */
182 @Override
183 public IBinder onBind(Intent arg0) {
184 return mBinder;
185 }
186
187
188 /**
189 * Called when ALL the bound clients were onbound.
190 */
191 @Override
192 public boolean onUnbind(Intent intent) {
193 ((FileDownloaderBinder)mBinder).clearListeners();
194 return false; // not accepting rebinding (default behaviour)
195 }
196
197
198 /**
199 * Binder to let client components to perform operations on the queue of downloads.
200 *
201 * It provides by itself the available operations.
202 */
203 public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
204
205 /**
206 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
207 */
208 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
209
210
211 /**
212 * Cancels a pending or current download of a remote file.
213 *
214 * @param account Owncloud account where the remote file is stored.
215 * @param file A file in the queue of pending downloads
216 */
217 public void cancel(Account account, OCFile file) {
218 DownloadFileOperation download = null;
219 synchronized (mPendingDownloads) {
220 download = mPendingDownloads.remove(buildRemoteName(account, file));
221 }
222 if (download != null) {
223 download.cancel();
224 }
225 }
226
227
228 public void clearListeners() {
229 mBoundListeners.clear();
230 }
231
232
233 /**
234 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
235 *
236 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
237 *
238 * @param account Owncloud account where the remote file is stored.
239 * @param file A file that could be in the queue of downloads.
240 */
241 public boolean isDownloading(Account account, OCFile file) {
242 if (account == null || file == null) return false;
243 String targetKey = buildRemoteName(account, file);
244 synchronized (mPendingDownloads) {
245 if (file.isFolder()) {
246 // this can be slow if there are many downloads :(
247 Iterator<String> it = mPendingDownloads.keySet().iterator();
248 boolean found = false;
249 while (it.hasNext() && !found) {
250 found = it.next().startsWith(targetKey);
251 }
252 return found;
253 } else {
254 return (mPendingDownloads.containsKey(targetKey));
255 }
256 }
257 }
258
259
260 /**
261 * Adds a listener interested in the progress of the download for a concrete file.
262 *
263 * @param listener Object to notify about progress of transfer.
264 * @param account ownCloud account holding the file of interest.
265 * @param file {@link OCfile} of interest for listener.
266 */
267 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
268 if (account == null || file == null || listener == null) return;
269 String targetKey = buildRemoteName(account, file);
270 mBoundListeners.put(targetKey, listener);
271 }
272
273
274 /**
275 * Removes a listener interested in the progress of the download for a concrete file.
276 *
277 * @param listener Object to notify about progress of transfer.
278 * @param account ownCloud account holding the file of interest.
279 * @param file {@link OCfile} of interest for listener.
280 */
281 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
282 if (account == null || file == null || listener == null) return;
283 String targetKey = buildRemoteName(account, file);
284 if (mBoundListeners.get(targetKey) == listener) {
285 mBoundListeners.remove(targetKey);
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 =
353 new FileDataStorageManager(mLastAccount, getContentResolver());
354 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
355 mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
356 getClientFor(ocAccount, this);
357 }
358
359 /// perform the download
360 downloadResult = mCurrentDownload.execute(mDownloadClient);
361 if (downloadResult.isSuccess()) {
362 saveDownloadedFile();
363 }
364
365 } catch (AccountsException e) {
366 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
367 downloadResult = new RemoteOperationResult(e);
368 } catch (IOException e) {
369 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
370 downloadResult = new RemoteOperationResult(e);
371
372 } finally {
373 synchronized(mPendingDownloads) {
374 mPendingDownloads.remove(downloadKey);
375 }
376 }
377
378
379 /// notify result
380 notifyDownloadResult(mCurrentDownload, downloadResult);
381
382 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
383 }
384 }
385
386
387 /**
388 * Updates the OC File after a successful download.
389 */
390 private void saveDownloadedFile() {
391 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
392 long syncDate = System.currentTimeMillis();
393 file.setLastSyncDateForProperties(syncDate);
394 file.setLastSyncDateForData(syncDate);
395 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
396 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
397 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
398 file.setMimetype(mCurrentDownload.getMimeType());
399 file.setStoragePath(mCurrentDownload.getSavePath());
400 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
401 mStorageManager.saveFile(file);
402 }
403
404
405 /**
406 * Creates a status notification to show the download progress
407 *
408 * @param download Download operation starting.
409 */
410 private void notifyDownloadStart(DownloadFileOperation download) {
411 /// create status notification with a progress bar
412 mLastPercent = 0;
413 mNotificationBuilder =
414 NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
415 mNotificationBuilder
416 .setSmallIcon(R.drawable.notification_icon)
417 .setTicker(getString(R.string.downloader_download_in_progress_ticker))
418 .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
419 .setOngoing(true)
420 .setProgress(100, 0, download.getSize() < 0)
421 .setContentText(
422 String.format(getString(R.string.downloader_download_in_progress_content), 0,
423 new File(download.getSavePath()).getName())
424 );
425
426 /// includes a pending intent in the notification showing the details view of the file
427 Intent showDetailsIntent = null;
428 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
429 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
430 } else {
431 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
432 }
433 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
434 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
435 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
436
437 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
438 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
439 ));
440
441 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
442 }
443
444
445 /**
446 * Callback method to update the progress bar in the status notification.
447 */
448 @Override
449 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
450 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
451 if (percent != mLastPercent) {
452 mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
453 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
454 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
455 mNotificationBuilder.setContentText(text);
456 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
457 }
458 mLastPercent = percent;
459 }
460
461
462 /**
463 * Updates the status notification with the result of a download operation.
464 *
465 * @param downloadResult Result of the download operation.
466 * @param download Finished download operation
467 */
468 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
469 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
470 if (!downloadResult.isCancelled()) {
471 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
472 R.string.downloader_download_failed_ticker;
473
474 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
475 (downloadResult.isIdPRedirection()
476 && mDownloadClient.getCredentials() == null));
477 tickerId = (needsToUpdateCredentials) ?
478 R.string.downloader_download_failed_credentials_error : tickerId;
479
480 mNotificationBuilder
481 .setTicker(getString(tickerId))
482 .setContentTitle(getString(tickerId))
483 .setAutoCancel(true)
484 .setOngoing(false)
485 .setProgress(0, 0, false);
486
487 if (needsToUpdateCredentials) {
488
489 // let the user update credentials with one click
490 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
491 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
492 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
493 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
494 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
495 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
496 mNotificationBuilder
497 .setContentIntent(PendingIntent.getActivity(
498 this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
499
500 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
501
502 } else {
503 // TODO put something smart in showDetailsIntent
504 Intent showDetailsIntent = new Intent();
505 mNotificationBuilder
506 .setContentIntent(PendingIntent.getActivity(
507 this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
508 }
509
510 mNotificationBuilder.setContentText(ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
511 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
512
513 // Remove success notification
514 if (downloadResult.isSuccess()) {
515 // Sleep 2 seconds, so show the notification before remove it
516 NotificationDelayer.cancelWithDelay(
517 mNotificationManager,
518 R.string.downloader_download_succeeded_ticker,
519 2000);
520 }
521
522 }
523 }
524
525
526 /**
527 * Sends a broadcast when a download finishes in order to the interested activities can update their view
528 *
529 * @param download Finished download operation
530 * @param downloadResult Result of the download operation
531 */
532 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
533 Intent end = new Intent(getDownloadFinishMessage());
534 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
535 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
536 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
537 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
538 sendStickyBroadcast(end);
539 }
540
541
542 /**
543 * Sends a broadcast when a new download is added to the queue.
544 *
545 * @param download Added download operation
546 */
547 private void sendBroadcastNewDownload(DownloadFileOperation download) {
548 Intent added = new Intent(getDownloadAddedMessage());
549 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
550 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
551 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
552 sendStickyBroadcast(added);
553 }
554
555 }