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
.HashMap
;
25 import java
.util
.Iterator
;
27 import java
.util
.Vector
;
28 import java
.util
.concurrent
.ConcurrentHashMap
;
29 import java
.util
.concurrent
.ConcurrentMap
;
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
;
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
.notifications
.NotificationBuilderWithProgressBar
;
40 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
41 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
42 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
43 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
44 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
45 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
46 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
47 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
48 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
49 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
50 import com
.owncloud
.android
.utils
.Log_OC
;
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 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
73 private static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
74 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
75 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
76 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
77 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
79 private static final String TAG
= "FileDownloader";
81 private Looper mServiceLooper
;
82 private ServiceHandler mServiceHandler
;
83 private IBinder mBinder
;
84 private OwnCloudClient mDownloadClient
= null
;
85 private Account mLastAccount
= null
;
86 private FileDataStorageManager mStorageManager
;
88 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
89 private DownloadFileOperation mCurrentDownload
= null
;
91 private NotificationManager mNotificationManager
;
92 private NotificationCompat
.Builder mNotificationBuilder
;
93 private int mLastPercent
;
96 public static String
getDownloadAddedMessage() {
97 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
100 public static String
getDownloadFinishMessage() {
101 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
105 * Builds a key for mPendingDownloads from the account and file to download
107 * @param account Account where the file to download is stored
108 * @param file File to download
110 private String
buildRemoteName(Account account
, OCFile file
) {
111 return account
.name
+ file
.getRemotePath();
116 * Service initialization
119 public void onCreate() {
121 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
122 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
123 Process
.THREAD_PRIORITY_BACKGROUND
);
125 mServiceLooper
= thread
.getLooper();
126 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
127 mBinder
= new FileDownloaderBinder();
131 * Entry point to add one or several files to the queue of downloads.
133 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
134 * although the caller activity goes away.
137 public int onStartCommand(Intent intent
, int flags
, int startId
) {
138 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
139 !intent
.hasExtra(EXTRA_FILE
)
140 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
141 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
143 Log_OC
.e(TAG
, "Not enough information provided in intent");
144 return START_NOT_STICKY
;
146 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
147 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
149 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)
150 String downloadKey
= buildRemoteName(account
, file
);
152 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
153 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
154 newDownload
.addDatatransferProgressListener(this);
155 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
156 requestedDownloads
.add(downloadKey
);
157 sendBroadcastNewDownload(newDownload
);
159 } catch (IllegalArgumentException e
) {
160 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
161 return START_NOT_STICKY
;
164 if (requestedDownloads
.size() > 0) {
165 Message msg
= mServiceHandler
.obtainMessage();
167 msg
.obj
= requestedDownloads
;
168 mServiceHandler
.sendMessage(msg
);
171 return START_NOT_STICKY
;
176 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
178 * Implemented to perform cancellation, pause and resume of existing downloads.
181 public IBinder
onBind(Intent arg0
) {
187 * Called when ALL the bound clients were onbound.
190 public boolean onUnbind(Intent intent
) {
191 ((FileDownloaderBinder
)mBinder
).clearListeners();
192 return false
; // not accepting rebinding (default behaviour)
197 * Binder to let client components to perform operations on the queue of downloads.
199 * It provides by itself the available operations.
201 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
204 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
206 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
210 * Cancels a pending or current download of a remote file.
212 * @param account Owncloud account where the remote file is stored.
213 * @param file A file in the queue of pending downloads
215 public void cancel(Account account
, OCFile file
) {
216 DownloadFileOperation download
= null
;
217 synchronized (mPendingDownloads
) {
218 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
220 if (download
!= null
) {
226 public void clearListeners() {
227 mBoundListeners
.clear();
232 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
234 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
236 * @param account Owncloud account where the remote file is stored.
237 * @param file A file that could be in the queue of downloads.
239 public boolean isDownloading(Account account
, OCFile file
) {
240 if (account
== null
|| file
== null
) return false
;
241 String targetKey
= buildRemoteName(account
, file
);
242 synchronized (mPendingDownloads
) {
243 if (file
.isFolder()) {
244 // this can be slow if there are many downloads :(
245 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
246 boolean found
= false
;
247 while (it
.hasNext() && !found
) {
248 found
= it
.next().startsWith(targetKey
);
252 return (mPendingDownloads
.containsKey(targetKey
));
259 * Adds a listener interested in the progress of the download for a concrete file.
261 * @param listener Object to notify about progress of transfer.
262 * @param account ownCloud account holding the file of interest.
263 * @param file {@link OCfile} of interest for listener.
265 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
266 if (account
== null
|| file
== null
|| listener
== null
) return;
267 String targetKey
= buildRemoteName(account
, file
);
268 mBoundListeners
.put(targetKey
, listener
);
273 * Removes a listener interested in the progress of the download for a concrete file.
275 * @param listener Object to notify about progress of transfer.
276 * @param account ownCloud account holding the file of interest.
277 * @param file {@link OCfile} of interest for listener.
279 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
280 if (account
== null
|| file
== null
|| listener
== null
) return;
281 String targetKey
= buildRemoteName(account
, file
);
282 if (mBoundListeners
.get(targetKey
) == listener
) {
283 mBoundListeners
.remove(targetKey
);
288 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
290 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
291 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
292 if (boundListener
!= null
) {
293 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
301 * Download worker. Performs the pending downloads in the order they were requested.
303 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
305 private static class ServiceHandler
extends Handler
{
306 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
307 FileDownloader mService
;
308 public ServiceHandler(Looper looper
, FileDownloader service
) {
311 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
316 public void handleMessage(Message msg
) {
317 @SuppressWarnings("unchecked")
318 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
319 if (msg
.obj
!= null
) {
320 Iterator
<String
> it
= requestedDownloads
.iterator();
321 while (it
.hasNext()) {
322 mService
.downloadFile(it
.next());
325 mService
.stopSelf(msg
.arg1
);
331 * Core download method: requests a file to download and stores it.
333 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
335 private void downloadFile(String downloadKey
) {
337 synchronized(mPendingDownloads
) {
338 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
341 if (mCurrentDownload
!= null
) {
343 notifyDownloadStart(mCurrentDownload
);
345 RemoteOperationResult downloadResult
= null
;
347 /// prepare client object to send the request to the ownCloud server
348 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
349 mLastAccount
= mCurrentDownload
.getAccount();
350 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
351 mDownloadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
354 /// perform the download
355 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
356 if (downloadResult
.isSuccess()) {
357 saveDownloadedFile();
360 } catch (AccountsException e
) {
361 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
362 downloadResult
= new RemoteOperationResult(e
);
363 } catch (IOException e
) {
364 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
365 downloadResult
= new RemoteOperationResult(e
);
368 synchronized(mPendingDownloads
) {
369 mPendingDownloads
.remove(downloadKey
);
375 notifyDownloadResult(mCurrentDownload
, downloadResult
);
377 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
383 * Updates the OC File after a successful download.
385 private void saveDownloadedFile() {
386 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
387 long syncDate
= System
.currentTimeMillis();
388 file
.setLastSyncDateForProperties(syncDate
);
389 file
.setLastSyncDateForData(syncDate
);
390 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
391 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
392 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
393 file
.setMimetype(mCurrentDownload
.getMimeType());
394 file
.setStoragePath(mCurrentDownload
.getSavePath());
395 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
396 mStorageManager
.saveFile(file
);
401 * Creates a status notification to show the download progress
403 * @param download Download operation starting.
405 private void notifyDownloadStart(DownloadFileOperation download
) {
406 /// create status notification with a progress bar
408 mNotificationBuilder
=
409 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
411 .setSmallIcon(R
.drawable
.notification_icon
)
412 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
413 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
415 .setProgress(100, 0, download
.getSize() < 0)
417 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
418 new File(download
.getSavePath()).getName())
421 /// includes a pending intent in the notification showing the details view of the file
422 Intent showDetailsIntent
= null
;
423 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
424 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
426 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
428 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
429 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
430 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
432 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
433 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
436 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
441 * Callback method to update the progress bar in the status notification.
444 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
445 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
446 if (percent
!= mLastPercent
) {
447 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
448 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
449 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
450 mNotificationBuilder
.setContentText(text
);
451 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
453 mLastPercent
= percent
;
458 * Updates the status notification with the result of a download operation.
460 * @param downloadResult Result of the download operation.
461 * @param download Finished download operation
463 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
464 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
465 if (!downloadResult
.isCancelled()) {
466 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
467 R
.string
.downloader_download_failed_ticker
;
469 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
470 (downloadResult
.isIdPRedirection()
471 && mDownloadClient
.getCredentials() == null
));
472 tickerId
= (needsToUpdateCredentials
) ?
473 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
476 .setTicker(getString(tickerId
))
477 .setContentTitle(getString(tickerId
))
480 .setProgress(0, 0, false
);
482 if (needsToUpdateCredentials
) {
484 // let the user update credentials with one click
485 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
486 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
487 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
488 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
489 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
490 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
492 .setContentIntent(PendingIntent
.getActivity(
493 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
495 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
498 // TODO put something smart in showDetailsIntent
499 Intent showDetailsIntent
= new Intent();
501 .setContentIntent(PendingIntent
.getActivity(
502 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
505 mNotificationBuilder
.setContentText(ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources()));
506 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
508 // Remove success notification
509 if (downloadResult
.isSuccess()) {
510 // Sleep 2 seconds, so show the notification before remove it
511 NotificationDelayer
.cancelWithDelay(
512 mNotificationManager
,
513 R
.string
.downloader_download_succeeded_ticker
,
522 * Sends a broadcast when a download finishes in order to the interested activities can update their view
524 * @param download Finished download operation
525 * @param downloadResult Result of the download operation
527 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
528 Intent end
= new Intent(getDownloadFinishMessage());
529 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
530 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
531 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
532 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
533 sendStickyBroadcast(end
);
538 * Sends a broadcast when a new download is added to the queue.
540 * @param download Added download operation
542 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
543 Intent added
= new Intent(getDownloadAddedMessage());
544 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
545 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
546 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
547 sendStickyBroadcast(added
);