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 as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 package com
.owncloud
.android
.files
.services
;
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
.datamodel
.FileDataStorageManager
;
32 import com
.owncloud
.android
.datamodel
.OCFile
;
33 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
35 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
36 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
37 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
38 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
39 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
40 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
41 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
43 import android
.accounts
.Account
;
44 import android
.app
.Notification
;
45 import android
.app
.NotificationManager
;
46 import android
.app
.PendingIntent
;
47 import android
.app
.Service
;
48 import android
.content
.Intent
;
49 import android
.os
.Binder
;
50 import android
.os
.Handler
;
51 import android
.os
.HandlerThread
;
52 import android
.os
.IBinder
;
53 import android
.os
.Looper
;
54 import android
.os
.Message
;
55 import android
.os
.Process
;
56 import android
.util
.Log
;
57 import android
.widget
.RemoteViews
;
59 import com
.owncloud
.android
.AccountUtils
;
60 import com
.owncloud
.android
.R
;
61 import eu
.alefzero
.webdav
.WebdavClient
;
63 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
65 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
66 public static final String EXTRA_FILE
= "FILE";
68 public static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
69 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
70 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
71 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
72 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
73 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
75 private static final String TAG
= "FileDownloader";
77 private Looper mServiceLooper
;
78 private ServiceHandler mServiceHandler
;
79 private IBinder mBinder
;
80 private WebdavClient mDownloadClient
= null
;
81 private Account mLastAccount
= null
;
82 private FileDataStorageManager mStorageManager
;
84 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
85 private DownloadFileOperation mCurrentDownload
= null
;
87 private NotificationManager mNotificationManager
;
88 private Notification mNotification
;
89 private int mLastPercent
;
93 * Builds a key for mPendingDownloads from the account and file to download
95 * @param account Account where the file to download is stored
96 * @param file File to download
98 private String
buildRemoteName(Account account
, OCFile file
) {
99 return account
.name
+ file
.getRemotePath();
104 * Service initialization
107 public void onCreate() {
109 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
110 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
111 Process
.THREAD_PRIORITY_BACKGROUND
);
113 mServiceLooper
= thread
.getLooper();
114 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
115 mBinder
= new FileDownloaderBinder();
120 * Entry point to add one or several files to the queue of downloads.
122 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
123 * although the caller activity goes away.
126 public int onStartCommand(Intent intent
, int flags
, int startId
) {
127 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
128 !intent
.hasExtra(EXTRA_FILE
)
129 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
130 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
132 Log
.e(TAG
, "Not enough information provided in intent");
133 return START_NOT_STICKY
;
135 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
136 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
138 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)
139 String downloadKey
= buildRemoteName(account
, file
);
141 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
142 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
143 newDownload
.addDatatransferProgressListener(this);
144 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
145 requestedDownloads
.add(downloadKey
);
146 sendBroadcastNewDownload(newDownload
);
148 } catch (IllegalArgumentException e
) {
149 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
150 return START_NOT_STICKY
;
153 if (requestedDownloads
.size() > 0) {
154 Message msg
= mServiceHandler
.obtainMessage();
156 msg
.obj
= requestedDownloads
;
157 mServiceHandler
.sendMessage(msg
);
160 return START_NOT_STICKY
;
165 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
167 * Implemented to perform cancellation, pause and resume of existing downloads.
170 public IBinder
onBind(Intent arg0
) {
176 * Called when ALL the bound clients were onbound.
179 public boolean onUnbind(Intent intent
) {
180 ((FileDownloaderBinder
)mBinder
).clearListeners();
181 return false
; // not accepting rebinding (default behaviour)
186 * Binder to let client components to perform operations on the queue of downloads.
188 * It provides by itself the available operations.
190 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
193 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
195 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
199 * Cancels a pending or current download of a remote file.
201 * @param account Owncloud account where the remote file is stored.
202 * @param file A file in the queue of pending downloads
204 public void cancel(Account account
, OCFile file
) {
205 DownloadFileOperation download
= null
;
206 synchronized (mPendingDownloads
) {
207 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
209 if (download
!= null
) {
215 public void clearListeners() {
216 mBoundListeners
.clear();
221 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
223 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
225 * @param account Owncloud account where the remote file is stored.
226 * @param file A file that could be in the queue of downloads.
228 public boolean isDownloading(Account account
, OCFile file
) {
229 if (account
== null
|| file
== null
) return false
;
230 String targetKey
= buildRemoteName(account
, file
);
231 synchronized (mPendingDownloads
) {
232 if (file
.isDirectory()) {
233 // this can be slow if there are many downloads :(
234 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
235 boolean found
= false
;
236 while (it
.hasNext() && !found
) {
237 found
= it
.next().startsWith(targetKey
);
241 return (mPendingDownloads
.containsKey(targetKey
));
248 * Adds a listener interested in the progress of the download for a concrete file.
250 * @param listener Object to notify about progress of transfer.
251 * @param account ownCloud account holding the file of interest.
252 * @param file {@link OCfile} of interest for listener.
254 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
255 if (account
== null
|| file
== null
|| listener
== null
) return;
256 String targetKey
= buildRemoteName(account
, file
);
257 mBoundListeners
.put(targetKey
, listener
);
263 * Removes a listener interested in the progress of the download for a concrete file.
265 * @param listener Object to notify about progress of transfer.
266 * @param account ownCloud account holding the file of interest.
267 * @param file {@link OCfile} of interest for listener.
269 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
270 if (account
== null
|| file
== null
|| listener
== null
) return;
271 String targetKey
= buildRemoteName(account
, file
);
272 if (mBoundListeners
.get(targetKey
) == listener
) {
273 mBoundListeners
.remove(targetKey
);
279 public void onTransferProgress(long progressRate
) {
280 // old way, should not be in use any more
285 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
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
);
298 * Download worker. Performs the pending downloads in the order they were requested.
300 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
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
) {
308 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
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());
322 mService
.stopSelf(msg
.arg1
);
329 * Core download method: requests a file to download and stores it.
331 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
333 private void downloadFile(String downloadKey
) {
335 synchronized(mPendingDownloads
) {
336 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
339 if (mCurrentDownload
!= null
) {
341 notifyDownloadStart(mCurrentDownload
);
343 /// prepare client object to send the request to the ownCloud server
344 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
345 mLastAccount
= mCurrentDownload
.getAccount();
346 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
347 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
350 /// perform the download
351 RemoteOperationResult downloadResult
= null
;
353 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
354 if (downloadResult
.isSuccess()) {
355 saveDownloadedFile();
359 synchronized(mPendingDownloads
) {
360 mPendingDownloads
.remove(downloadKey
);
366 notifyDownloadResult(mCurrentDownload
, downloadResult
);
368 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
374 * Updates the OC File after a successful download.
376 private void saveDownloadedFile() {
377 OCFile file
= mCurrentDownload
.getFile();
378 long syncDate
= System
.currentTimeMillis();
379 file
.setLastSyncDateForProperties(syncDate
);
380 file
.setLastSyncDateForData(syncDate
);
381 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
382 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
383 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
384 file
.setMimetype(mCurrentDownload
.getMimeType());
385 file
.setStoragePath(mCurrentDownload
.getSavePath());
386 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
387 mStorageManager
.saveFile(file
);
392 * Creates a status notification to show the download progress
394 * @param download Download operation starting.
396 private void notifyDownloadStart(DownloadFileOperation download
) {
397 /// create status notification with a progress bar
399 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
400 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
401 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
402 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
403 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
404 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
406 /// includes a pending intent in the notification showing the details view of the file
407 Intent showDetailsIntent
= null
;
408 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
409 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
411 showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
413 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
414 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
415 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
416 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
418 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
423 * Callback method to update the progress bar in the status notification.
426 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
427 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
428 if (percent
!= mLastPercent
) {
429 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
430 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
431 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
432 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
434 mLastPercent
= percent
;
439 * Callback method to update the progress bar in the status notification (old version)
442 public void onTransferProgress(long progressRate
) {
443 // NOTHING TO DO HERE ANYMORE
448 * Updates the status notification with the result of a download operation.
450 * @param downloadResult Result of the download operation.
451 * @param download Finished download operation
453 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
454 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
455 if (!downloadResult
.isCancelled()) {
456 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
457 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
458 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
459 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
460 Intent showDetailsIntent
= null
;
461 if (downloadResult
.isSuccess()) {
462 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
463 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
465 showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
467 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
468 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
469 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
472 // TODO put something smart in showDetailsIntent
473 showDetailsIntent
= new Intent();
475 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
476 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
477 mNotificationManager
.notify(tickerId
, finalNotification
);
483 * Sends a broadcast when a download finishes in order to the interested activities can update their view
485 * @param download Finished download operation
486 * @param downloadResult Result of the download operation
488 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
489 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
490 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
491 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
492 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
493 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
494 sendStickyBroadcast(end
);
499 * Sends a broadcast when a new download is added to the queue.
501 * @param download Added download operation
503 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
504 Intent added
= new Intent(DOWNLOAD_ADDED_MESSAGE
);
505 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
506 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
507 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
508 sendStickyBroadcast(added
);