Progress bar in notifications is hidden when download/upload finishes
[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.lib.common.network.OnDatatransferProgressListener;
37 import com.owncloud.android.lib.common.OwnCloudClientFactory;
38 import com.owncloud.android.lib.common.OwnCloudClient;
39 import com.owncloud.android.operations.DownloadFileOperation;
40 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
41 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.lib.resources.files.FileUtils;
43 import com.owncloud.android.ui.activity.FileActivity;
44 import com.owncloud.android.ui.activity.FileDisplayActivity;
45 import com.owncloud.android.ui.preview.PreviewImageActivity;
46 import com.owncloud.android.ui.preview.PreviewImageFragment;
47 import com.owncloud.android.utils.Log_OC;
48
49 import android.accounts.Account;
50 import android.accounts.AccountsException;
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.support.v4.app.NotificationCompat;
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 OwnCloudClient 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 NotificationCompat.Builder mNotificationBuilder;
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);
150 mPendingDownloads.putIfAbsent(downloadKey, newDownload);
151 newDownload.addDatatransferProgressListener(this);
152 newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
153 requestedDownloads.add(downloadKey);
154 sendBroadcastNewDownload(newDownload);
155
156 } catch (IllegalArgumentException e) {
157 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
158 return START_NOT_STICKY;
159 }
160
161 if (requestedDownloads.size() > 0) {
162 Message msg = mServiceHandler.obtainMessage();
163 msg.arg1 = startId;
164 msg.obj = requestedDownloads;
165 mServiceHandler.sendMessage(msg);
166 }
167
168 return START_NOT_STICKY;
169 }
170
171
172 /**
173 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
174 *
175 * Implemented to perform cancellation, pause and resume of existing downloads.
176 */
177 @Override
178 public IBinder onBind(Intent arg0) {
179 return mBinder;
180 }
181
182
183 /**
184 * Called when ALL the bound clients were onbound.
185 */
186 @Override
187 public boolean onUnbind(Intent intent) {
188 ((FileDownloaderBinder)mBinder).clearListeners();
189 return false; // not accepting rebinding (default behaviour)
190 }
191
192
193 /**
194 * Binder to let client components to perform operations on the queue of downloads.
195 *
196 * It provides by itself the available operations.
197 */
198 public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
199
200 /**
201 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
202 */
203 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
204
205
206 /**
207 * Cancels a pending or current download of a remote file.
208 *
209 * @param account Owncloud account where the remote file is stored.
210 * @param file A file in the queue of pending downloads
211 */
212 public void cancel(Account account, OCFile file) {
213 DownloadFileOperation download = null;
214 synchronized (mPendingDownloads) {
215 download = mPendingDownloads.remove(buildRemoteName(account, file));
216 }
217 if (download != null) {
218 download.cancel();
219 }
220 }
221
222
223 public void clearListeners() {
224 mBoundListeners.clear();
225 }
226
227
228 /**
229 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
230 *
231 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
232 *
233 * @param account Owncloud account where the remote file is stored.
234 * @param file A file that could be in the queue of downloads.
235 */
236 public boolean isDownloading(Account account, OCFile file) {
237 if (account == null || file == null) return false;
238 String targetKey = buildRemoteName(account, file);
239 synchronized (mPendingDownloads) {
240 if (file.isFolder()) {
241 // this can be slow if there are many downloads :(
242 Iterator<String> it = mPendingDownloads.keySet().iterator();
243 boolean found = false;
244 while (it.hasNext() && !found) {
245 found = it.next().startsWith(targetKey);
246 }
247 return found;
248 } else {
249 return (mPendingDownloads.containsKey(targetKey));
250 }
251 }
252 }
253
254
255 /**
256 * Adds a listener interested in the progress of the download for a concrete file.
257 *
258 * @param listener Object to notify about progress of transfer.
259 * @param account ownCloud account holding the file of interest.
260 * @param file {@link OCfile} of interest for listener.
261 */
262 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
263 if (account == null || file == null || listener == null) return;
264 String targetKey = buildRemoteName(account, file);
265 mBoundListeners.put(targetKey, listener);
266 }
267
268
269 /**
270 * Removes a listener interested in the progress of the download for a concrete file.
271 *
272 * @param listener Object to notify about progress of transfer.
273 * @param account ownCloud account holding the file of interest.
274 * @param file {@link OCfile} of interest for listener.
275 */
276 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
277 if (account == null || file == null || listener == null) return;
278 String targetKey = buildRemoteName(account, file);
279 if (mBoundListeners.get(targetKey) == listener) {
280 mBoundListeners.remove(targetKey);
281 }
282 }
283
284 @Override
285 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
286 String fileName) {
287 String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
288 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
289 if (boundListener != null) {
290 boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
291 }
292 }
293
294 }
295
296
297 /**
298 * Download worker. Performs the pending downloads in the order they were requested.
299 *
300 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
301 */
302 private static class ServiceHandler extends Handler {
303 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
304 FileDownloader mService;
305 public ServiceHandler(Looper looper, FileDownloader service) {
306 super(looper);
307 if (service == null)
308 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
309 mService = service;
310 }
311
312 @Override
313 public void handleMessage(Message msg) {
314 @SuppressWarnings("unchecked")
315 AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
316 if (msg.obj != null) {
317 Iterator<String> it = requestedDownloads.iterator();
318 while (it.hasNext()) {
319 mService.downloadFile(it.next());
320 }
321 }
322 mService.stopSelf(msg.arg1);
323 }
324 }
325
326
327 /**
328 * Core download method: requests a file to download and stores it.
329 *
330 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
331 */
332 private void downloadFile(String downloadKey) {
333
334 synchronized(mPendingDownloads) {
335 mCurrentDownload = mPendingDownloads.get(downloadKey);
336 }
337
338 if (mCurrentDownload != null) {
339
340 notifyDownloadStart(mCurrentDownload);
341
342 RemoteOperationResult downloadResult = null;
343 try {
344 /// prepare client object to send the request to the ownCloud server
345 if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
346 mLastAccount = mCurrentDownload.getAccount();
347 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
348 mDownloadClient = OwnCloudClientFactory.createOwnCloudClient(mLastAccount, getApplicationContext());
349 }
350
351 /// perform the download
352 downloadResult = mCurrentDownload.execute(mDownloadClient);
353 if (downloadResult.isSuccess()) {
354 saveDownloadedFile();
355 }
356
357 } catch (AccountsException e) {
358 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
359 downloadResult = new RemoteOperationResult(e);
360 } catch (IOException e) {
361 Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
362 downloadResult = new RemoteOperationResult(e);
363
364 } finally {
365 synchronized(mPendingDownloads) {
366 mPendingDownloads.remove(downloadKey);
367 }
368 }
369
370
371 /// notify result
372 notifyDownloadResult(mCurrentDownload, downloadResult);
373
374 sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
375 }
376 }
377
378
379 /**
380 * Updates the OC File after a successful download.
381 */
382 private void saveDownloadedFile() {
383 OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
384 long syncDate = System.currentTimeMillis();
385 file.setLastSyncDateForProperties(syncDate);
386 file.setLastSyncDateForData(syncDate);
387 file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
388 file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
389 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
390 file.setMimetype(mCurrentDownload.getMimeType());
391 file.setStoragePath(mCurrentDownload.getSavePath());
392 file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
393 mStorageManager.saveFile(file);
394 }
395
396
397 /**
398 * Creates a status notification to show the download progress
399 *
400 * @param download Download operation starting.
401 */
402 private void notifyDownloadStart(DownloadFileOperation download) {
403 /// create status notification with a progress bar
404 mLastPercent = 0;
405 mNotificationBuilder = new NotificationCompat.Builder(this);
406 mNotificationBuilder
407 .setSmallIcon(R.drawable.notification_icon)
408 .setTicker(getString(R.string.downloader_download_in_progress_ticker))
409 .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
410 .setOngoing(true)
411 .setProgress(100, 0, download.getSize() < 0)
412 .setContentText(
413 String.format(getString(R.string.downloader_download_in_progress_content), 0,
414 new File(download.getSavePath()).getName())
415 );
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
428 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
429 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
430 ));
431
432 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
433 }
434
435
436 /**
437 * Callback method to update the progress bar in the status notification.
438 */
439 @Override
440 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
441 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
442 if (percent != mLastPercent) {
443 mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
444 String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
445 String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
446 mNotificationBuilder.setContentText(text);
447 mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
448 }
449 mLastPercent = percent;
450 }
451
452
453 /**
454 * Updates the status notification with the result of a download operation.
455 *
456 * @param downloadResult Result of the download operation.
457 * @param download Finished download operation
458 */
459 private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
460 mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
461 if (!downloadResult.isCancelled()) {
462 int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
463 int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
464 mNotificationBuilder
465 .setTicker(getString(tickerId))
466 .setContentTitle(getString(tickerId))
467 .setAutoCancel(true)
468 .setOngoing(false)
469 .setProgress(0, 0, false);
470 boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
471 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
472 (downloadResult.isIdPRedirection()
473 && mDownloadClient.getCredentials() == null));
474 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
475 if (needsToUpdateCredentials) {
476 // let the user update credentials with one click
477 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
478 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
479 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
480 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
481 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
482 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
483 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
484 mNotificationBuilder
485 .setContentIntent(PendingIntent.getActivity(
486 this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT
487 ))
488 .setContentText(String.format(getString(contentId), new File(download.getSavePath()).getName()));
489 mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
490
491 } else {
492 Intent showDetailsIntent = null;
493 if (downloadResult.isSuccess()) {
494 if (PreviewImageFragment.canBePreviewed(download.getFile())) {
495 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
496 } else {
497 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
498 }
499 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
500 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
501 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
502
503 } else {
504 // TODO put something smart in showDetailsIntent
505 showDetailsIntent = new Intent();
506 }
507 mNotificationBuilder
508 .setContentIntent(PendingIntent.getActivity(
509 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
510 ))
511 .setContentText(String.format(getString(contentId), new File(download.getSavePath()).getName()));
512 }
513 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
514 }
515 }
516
517
518 /**
519 * Sends a broadcast when a download finishes in order to the interested activities can update their view
520 *
521 * @param download Finished download operation
522 * @param downloadResult Result of the download operation
523 */
524 private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
525 Intent end = new Intent(getDownloadFinishMessage());
526 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
527 end.putExtra(ACCOUNT_NAME, download.getAccount().name);
528 end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
529 end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
530 sendStickyBroadcast(end);
531 }
532
533
534 /**
535 * Sends a broadcast when a new download is added to the queue.
536 *
537 * @param download Added download operation
538 */
539 private void sendBroadcastNewDownload(DownloadFileOperation download) {
540 Intent added = new Intent(getDownloadAddedMessage());
541 added.putExtra(ACCOUNT_NAME, download.getAccount().name);
542 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
543 added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
544 sendStickyBroadcast(added);
545 }
546
547 }