1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.ArrayList
;
25 import java
.util
.HashMap
;
26 import java
.util
.Iterator
;
28 import java
.util
.Vector
;
30 import com
.owncloud
.android
.R
;
31 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
32 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
33 import com
.owncloud
.android
.datamodel
.OCFile
;
35 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
36 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
38 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
39 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
40 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
42 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
43 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
44 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
45 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
46 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
47 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
48 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
49 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
50 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
52 import android
.accounts
.Account
;
53 import android
.accounts
.AccountsException
;
54 import android
.app
.NotificationManager
;
55 import android
.app
.PendingIntent
;
56 import android
.app
.Service
;
57 import android
.content
.Intent
;
58 import android
.os
.Binder
;
59 import android
.os
.Handler
;
60 import android
.os
.HandlerThread
;
61 import android
.os
.IBinder
;
62 import android
.os
.Looper
;
63 import android
.os
.Message
;
64 import android
.os
.Process
;
65 import android
.support
.v4
.app
.NotificationCompat
;
67 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
69 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
70 public static final String EXTRA_FILE
= "FILE";
72 public static final String ACTION_CANCEL_FILE_DOWNLOAD
= "CANCEL_FILE_DOWNLOAD";
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";
81 private static final String TAG
= "FileDownloader";
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
;
90 private IndexedForest
<DownloadFileOperation
> mPendingDownloads
= new IndexedForest
<DownloadFileOperation
>();
92 private DownloadFileOperation mCurrentDownload
= null
;
94 private NotificationManager mNotificationManager
;
95 private NotificationCompat
.Builder mNotificationBuilder
;
96 private int mLastPercent
;
99 public static String
getDownloadAddedMessage() {
100 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
103 public static String
getDownloadFinishMessage() {
104 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
108 * Service initialization
111 public void onCreate() {
113 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
114 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
115 Process
.THREAD_PRIORITY_BACKGROUND
);
117 mServiceLooper
= thread
.getLooper();
118 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
119 mBinder
= new FileDownloaderBinder();
123 * Entry point to add one or several files to the queue of downloads.
125 * New downloads are added calling to startService(), resulting in a call to this method.
126 * This ensures the service will keep on working although the caller activity goes away.
129 public int onStartCommand(Intent intent
, int flags
, int startId
) {
130 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
131 !intent
.hasExtra(EXTRA_FILE
)
133 Log_OC
.e(TAG
, "Not enough information provided in intent");
134 return START_NOT_STICKY
;
136 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
137 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
139 if (ACTION_CANCEL_FILE_DOWNLOAD
.equals(intent
.getAction())) {
141 new Thread(new Runnable() {
143 // Cancel the download
144 cancel(account
, file
);
150 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
152 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
153 String downloadKey
= mPendingDownloads
.putIfAbsent(account
, file
.getRemotePath(), newDownload
);
154 newDownload
.addDatatransferProgressListener(this);
155 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
156 requestedDownloads
.add(downloadKey
);
158 // Store file on db with state 'downloading'
160 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
161 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
162 file.setDownloading(true);
163 storageManager.saveFile(file);
166 sendBroadcastNewDownload(newDownload
);
168 } catch (IllegalArgumentException e
) {
169 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
170 return START_NOT_STICKY
;
173 if (requestedDownloads
.size() > 0) {
174 Message msg
= mServiceHandler
.obtainMessage();
176 msg
.obj
= requestedDownloads
;
177 mServiceHandler
.sendMessage(msg
);
182 return START_NOT_STICKY
;
187 * Provides a binder object that clients can use to perform operations on the queue of downloads,
188 * excepting the addition of new files.
190 * Implemented to perform cancellation, pause and resume of existing downloads.
193 public IBinder
onBind(Intent arg0
) {
199 * Called when ALL the bound clients were onbound.
202 public boolean onUnbind(Intent intent
) {
203 ((FileDownloaderBinder
)mBinder
).clearListeners();
204 return false
; // not accepting rebinding (default behaviour)
209 * Binder to let client components to perform operations on the queue of downloads.
211 * It provides by itself the available operations.
213 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
216 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
219 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
220 new HashMap
<Long
, OnDatatransferProgressListener
>();
224 * Cancels a pending or current download of a remote file.
226 * @param account Owncloud account where the remote file is stored.
227 * @param file A file in the queue of pending downloads
229 public void cancel(Account account
, OCFile file
) {
230 DownloadFileOperation download
= null
;
231 download
= mPendingDownloads
.remove(account
, file
.getRemotePath());
232 if (download
!= null
) {
238 public void clearListeners() {
239 mBoundListeners
.clear();
244 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
245 * waiting to download.
247 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
248 * waiting to download.
250 * @param account ownCloud account where the remote file is stored.
251 * @param file A file that could be in the queue of downloads.
253 public boolean isDownloading(Account account
, OCFile file
) {
254 if (account
== null
|| file
== null
) return false
;
255 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
260 * Adds a listener interested in the progress of the download for a concrete file.
262 * @param listener Object to notify about progress of transfer.
263 * @param account ownCloud account holding the file of interest.
264 * @param file {@link OCFile} of interest for listener.
266 public void addDatatransferProgressListener (
267 OnDatatransferProgressListener listener
, Account account
, OCFile file
269 if (account
== null
|| file
== null
|| listener
== null
) return;
270 //String targetKey = buildKey(account, file.getRemotePath());
271 mBoundListeners
.put(file
.getFileId(), listener
);
276 * Removes a listener interested in the progress of the download for a concrete file.
278 * @param listener Object to notify about progress of transfer.
279 * @param account ownCloud account holding the file of interest.
280 * @param file {@link OCFile} of interest for listener.
282 public void removeDatatransferProgressListener (
283 OnDatatransferProgressListener listener
, Account account
, OCFile file
285 if (account
== null
|| file
== null
|| listener
== null
) return;
286 //String targetKey = buildKey(account, file.getRemotePath());
287 Long fileId
= file
.getFileId();
288 if (mBoundListeners
.get(fileId
) == listener
) {
289 mBoundListeners
.remove(fileId
);
294 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
296 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
297 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
298 if (boundListener
!= null
) {
299 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
307 * Download worker. Performs the pending downloads in the order they were requested.
309 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
311 private static class ServiceHandler
extends Handler
{
312 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
313 FileDownloader mService
;
314 public ServiceHandler(Looper looper
, FileDownloader service
) {
317 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
322 public void handleMessage(Message msg
) {
323 @SuppressWarnings("unchecked")
324 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
325 if (msg
.obj
!= null
) {
326 Iterator
<String
> it
= requestedDownloads
.iterator();
327 while (it
.hasNext()) {
328 mService
.downloadFile(it
.next());
331 mService
.stopSelf(msg
.arg1
);
337 * Core download method: requests a file to download and stores it.
339 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
341 private void downloadFile(String downloadKey
) {
343 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
345 if (mCurrentDownload
!= null
) {
347 notifyDownloadStart(mCurrentDownload
);
349 RemoteOperationResult downloadResult
= null
;
351 /// prepare client object to send the request to the ownCloud server
352 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
353 mLastAccount
= mCurrentDownload
.getAccount();
355 new FileDataStorageManager(mLastAccount
, getContentResolver());
356 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
357 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
358 getClientFor(ocAccount
, this);
361 /// perform the download
362 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
363 if (downloadResult
.isSuccess()) {
364 saveDownloadedFile();
366 updateUnsuccessfulDownloadedFile();
370 } catch (AccountsException e
) {
371 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastAccount
.name
, e
);
372 downloadResult
= new RemoteOperationResult(e
);
373 } catch (IOException e
) {
374 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mLastAccount
.name
, e
);
375 downloadResult
= new RemoteOperationResult(e
);
378 mPendingDownloads
.remove(mLastAccount
, mCurrentDownload
.getRemotePath());
383 notifyDownloadResult(mCurrentDownload
, downloadResult
);
385 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
391 * Updates the OC File after a successful download.
393 private void saveDownloadedFile() {
394 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
395 long syncDate
= System
.currentTimeMillis();
396 file
.setLastSyncDateForProperties(syncDate
);
397 file
.setLastSyncDateForData(syncDate
);
398 file
.setNeedsUpdateThumbnail(true
);
399 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
400 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
401 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
402 file
.setMimetype(mCurrentDownload
.getMimeType());
403 file
.setStoragePath(mCurrentDownload
.getSavePath());
404 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
405 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
406 //file.setDownloading(false);
407 mStorageManager
.saveFile(file
);
408 mStorageManager
.triggerMediaScan(file
.getStoragePath());
412 * Update the OC File after a unsuccessful download
414 private void updateUnsuccessfulDownloadedFile() {
415 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
416 file
.setDownloading(false
);
417 mStorageManager
.saveFile(file
);
422 * Creates a status notification to show the download progress
424 * @param download Download operation starting.
426 private void notifyDownloadStart(DownloadFileOperation download
) {
427 /// create status notification with a progress bar
429 mNotificationBuilder
=
430 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
432 .setSmallIcon(R
.drawable
.notification_icon
)
433 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
434 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
436 .setProgress(100, 0, download
.getSize() < 0)
438 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
439 new File(download
.getSavePath()).getName())
442 /// includes a pending intent in the notification showing the details view of the file
443 Intent showDetailsIntent
= null
;
444 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
445 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
447 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
449 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
450 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
451 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
453 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
454 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
457 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
462 * Callback method to update the progress bar in the status notification.
465 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
)
467 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
468 if (percent
!= mLastPercent
) {
469 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
470 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
471 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
472 mNotificationBuilder
.setContentText(text
);
473 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
475 mLastPercent
= percent
;
480 * Updates the status notification with the result of a download operation.
482 * @param downloadResult Result of the download operation.
483 * @param download Finished download operation
485 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
486 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
487 if (!downloadResult
.isCancelled()) {
488 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
489 R
.string
.downloader_download_failed_ticker
;
491 boolean needsToUpdateCredentials
= (
492 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
493 downloadResult
.isIdPRedirection()
495 tickerId
= (needsToUpdateCredentials
) ?
496 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
499 .setTicker(getString(tickerId
))
500 .setContentTitle(getString(tickerId
))
503 .setProgress(0, 0, false
);
505 if (needsToUpdateCredentials
) {
507 // let the user update credentials with one click
508 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
509 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
510 updateAccountCredentials
.putExtra(
511 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
513 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
514 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
515 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
517 .setContentIntent(PendingIntent
.getActivity(
518 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
520 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
523 // TODO put something smart in showDetailsIntent
524 Intent showDetailsIntent
= new Intent();
526 .setContentIntent(PendingIntent
.getActivity(
527 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
530 mNotificationBuilder
.setContentText(
531 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
533 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
535 // Remove success notification
536 if (downloadResult
.isSuccess()) {
537 // Sleep 2 seconds, so show the notification before remove it
538 NotificationDelayer
.cancelWithDelay(
539 mNotificationManager
,
540 R
.string
.downloader_download_succeeded_ticker
,
549 * Sends a broadcast when a download finishes in order to the interested activities can update their view
551 * @param download Finished download operation
552 * @param downloadResult Result of the download operation
554 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
555 Intent end
= new Intent(getDownloadFinishMessage());
556 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
557 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
558 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
559 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
560 sendStickyBroadcast(end
);
565 * Sends a broadcast when a new download is added to the queue.
567 * @param download Added download operation
569 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
570 Intent added
= new Intent(getDownloadAddedMessage());
571 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
572 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
573 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
574 sendStickyBroadcast(added
);
579 * @param account ownCloud account where the remote file is stored.
580 * @param file File OCFile
582 public void cancel(Account account
, OCFile file
){
583 DownloadFileOperation download
= null
;
584 //String targetKey = buildKey(account, file.getRemotePath());
585 ArrayList
<String
> keyItems
= new ArrayList
<String
>();
586 if (file
.isFolder()) {
587 Log_OC
.d(TAG
, "Folder download. Canceling pending downloads (from folder)");
591 Iterator<String> it = mPendingDownloads.keySet().iterator();
592 boolean found = false;
593 while (it.hasNext()) {
594 String keyDownloadOperation = it.next();
595 found = keyDownloadOperation.startsWith(targetKey);
597 keyItems.add(keyDownloadOperation);
601 for (String item: keyItems) {
602 download = mPendingDownloads.remove(item);
603 Log_OC.d(TAG, "Key removed: " + item);
605 if (download != null) {
613 // this is not really expected...
614 Log_OC
.d(TAG
, "Canceling file download");
615 download
= mPendingDownloads
.remove(account
, file
.getRemotePath());
616 if (download
!= null
) {