1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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
.util
.AbstractList
;
23 import java
.util
.Iterator
;
24 import java
.util
.Vector
;
25 import java
.util
.concurrent
.ConcurrentHashMap
;
26 import java
.util
.concurrent
.ConcurrentMap
;
28 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
29 import com
.owncloud
.android
.datamodel
.OCFile
;
30 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
32 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
33 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
34 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
35 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
36 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
38 import android
.accounts
.Account
;
39 import android
.app
.Notification
;
40 import android
.app
.NotificationManager
;
41 import android
.app
.PendingIntent
;
42 import android
.app
.Service
;
43 import android
.content
.Intent
;
44 import android
.os
.Binder
;
45 import android
.os
.Handler
;
46 import android
.os
.HandlerThread
;
47 import android
.os
.IBinder
;
48 import android
.os
.Looper
;
49 import android
.os
.Message
;
50 import android
.os
.Process
;
51 import android
.util
.Log
;
52 import android
.widget
.ProgressBar
;
53 import android
.widget
.RemoteViews
;
55 import com
.owncloud
.android
.R
;
56 import eu
.alefzero
.webdav
.WebdavClient
;
58 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
60 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
61 public static final String EXTRA_FILE
= "FILE";
63 public static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
64 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
65 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
66 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
67 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
68 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
70 private static final String TAG
= "FileDownloader";
72 private Looper mServiceLooper
;
73 private ServiceHandler mServiceHandler
;
74 private IBinder mBinder
;
75 private WebdavClient mDownloadClient
= null
;
76 private Account mLastAccount
= null
;
77 private FileDataStorageManager mStorageManager
;
79 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
80 private DownloadFileOperation mCurrentDownload
= null
;
82 private NotificationManager mNotificationManager
;
83 private Notification mNotification
;
84 private int mLastPercent
;
88 * Builds a key for mPendingDownloads from the account and file to download
90 * @param account Account where the file to download is stored
91 * @param file File to download
93 private String
buildRemoteName(Account account
, OCFile file
) {
94 return account
.name
+ file
.getRemotePath();
99 * Service initialization
102 public void onCreate() {
104 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
105 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
106 Process
.THREAD_PRIORITY_BACKGROUND
);
108 mServiceLooper
= thread
.getLooper();
109 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
110 mBinder
= new FileDownloaderBinder();
115 * Entry point to add one or several files to the queue of downloads.
117 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
118 * although the caller activity goes away.
121 public int onStartCommand(Intent intent
, int flags
, int startId
) {
122 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
123 !intent
.hasExtra(EXTRA_FILE
)
124 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
125 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
127 Log
.e(TAG
, "Not enough information provided in intent");
128 return START_NOT_STICKY
;
130 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
131 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
133 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)
134 String downloadKey
= buildRemoteName(account
, file
);
136 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
137 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
138 newDownload
.addDatatransferProgressListener(this);
139 requestedDownloads
.add(downloadKey
);
140 sendBroadcastNewDownload(newDownload
);
142 } catch (IllegalArgumentException e
) {
143 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
144 return START_NOT_STICKY
;
147 if (requestedDownloads
.size() > 0) {
148 Message msg
= mServiceHandler
.obtainMessage();
150 msg
.obj
= requestedDownloads
;
151 mServiceHandler
.sendMessage(msg
);
154 return START_NOT_STICKY
;
159 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
161 * Implemented to perform cancellation, pause and resume of existing downloads.
164 public IBinder
onBind(Intent arg0
) {
170 * Binder to let client components to perform operations on the queue of downloads.
172 * It provides by itself the available operations.
174 public class FileDownloaderBinder
extends Binder
{
177 * Cancels a pending or current download of a remote file.
179 * @param account Owncloud account where the remote file is stored.
180 * @param file A file in the queue of pending downloads
182 public void cancel(Account account
, OCFile file
) {
183 DownloadFileOperation download
= null
;
184 synchronized (mPendingDownloads
) {
185 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
187 if (download
!= null
) {
194 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
196 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
198 * @param account Owncloud account where the remote file is stored.
199 * @param file A file that could be in the queue of downloads.
201 public boolean isDownloading(Account account
, OCFile file
) {
202 if (account
== null
|| file
== null
) return false
;
203 String targetKey
= buildRemoteName(account
, file
);
204 synchronized (mPendingDownloads
) {
205 if (file
.isDirectory()) {
206 // this can be slow if there are many downloads :(
207 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
208 boolean found
= false
;
209 while (it
.hasNext() && !found
) {
210 found
= it
.next().startsWith(targetKey
);
214 return (mPendingDownloads
.containsKey(targetKey
));
221 * Adds a listener interested in the progress of the download for a concrete file.
223 * @param listener Object to notify about progress of transfer.
224 * @param account ownCloud account holding the file of interest.
225 * @param file {@link OCfile} of interest for listener.
227 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
228 if (account
== null
|| file
== null
) return;
229 String targetKey
= buildRemoteName(account
, file
);
230 DownloadFileOperation target
= null
;
231 synchronized (mPendingDownloads
) {
232 if (!file
.isDirectory()) {
233 target
= mPendingDownloads
.get(targetKey
);
235 // nothing to do for directories, right now
238 if (target
!= null
) {
239 target
.addDatatransferProgressListener(listener
);
245 * Removes a listener interested in the progress of the download for a concrete file.
247 * @param listener Object to notify about progress of transfer.
248 * @param account ownCloud account holding the file of interest.
249 * @param file {@link OCfile} of interest for listener.
251 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
252 if (account
== null
|| file
== null
) return;
253 String targetKey
= buildRemoteName(account
, file
);
254 DownloadFileOperation target
= null
;
255 synchronized (mPendingDownloads
) {
256 if (!file
.isDirectory()) {
257 target
= mPendingDownloads
.get(targetKey
);
259 // nothing to do for directories, right now
262 if (target
!= null
) {
263 target
.removeDatatransferProgressListener(listener
);
271 * Download worker. Performs the pending downloads in the order they were requested.
273 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
275 private static class ServiceHandler
extends Handler
{
276 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
277 FileDownloader mService
;
278 public ServiceHandler(Looper looper
, FileDownloader service
) {
281 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
286 public void handleMessage(Message msg
) {
287 @SuppressWarnings("unchecked")
288 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
289 if (msg
.obj
!= null
) {
290 Iterator
<String
> it
= requestedDownloads
.iterator();
291 while (it
.hasNext()) {
292 mService
.downloadFile(it
.next());
295 mService
.stopSelf(msg
.arg1
);
302 * Core download method: requests a file to download and stores it.
304 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
306 private void downloadFile(String downloadKey
) {
308 synchronized(mPendingDownloads
) {
309 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
312 if (mCurrentDownload
!= null
) {
314 notifyDownloadStart(mCurrentDownload
);
316 /// prepare client object to send the request to the ownCloud server
317 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
318 mLastAccount
= mCurrentDownload
.getAccount();
319 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
320 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
323 /// perform the download
324 RemoteOperationResult downloadResult
= null
;
326 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
327 if (downloadResult
.isSuccess()) {
328 saveDownloadedFile();
332 synchronized(mPendingDownloads
) {
333 mPendingDownloads
.remove(downloadKey
);
339 notifyDownloadResult(mCurrentDownload
, downloadResult
);
341 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
347 * Updates the OC File after a successful download.
349 private void saveDownloadedFile() {
350 OCFile file
= mCurrentDownload
.getFile();
351 long syncDate
= System
.currentTimeMillis();
352 file
.setLastSyncDateForProperties(syncDate
);
353 file
.setLastSyncDateForData(syncDate
);
354 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
355 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
356 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
357 file
.setMimetype(mCurrentDownload
.getMimeType());
358 file
.setStoragePath(mCurrentDownload
.getSavePath());
359 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
360 mStorageManager
.saveFile(file
);
365 * Creates a status notification to show the download progress
367 * @param download Download operation starting.
369 private void notifyDownloadStart(DownloadFileOperation download
) {
370 /// create status notification with a progress bar
372 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
373 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
374 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
375 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
376 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
377 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
379 /// includes a pending intent in the notification showing the details view of the file
380 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
381 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
382 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
383 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
384 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
386 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
391 * Callback method to update the progress bar in the status notification.
394 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
395 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
396 if (percent
!= mLastPercent
) {
397 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
398 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
399 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
400 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
402 mLastPercent
= percent
;
407 * Callback method to update the progress bar in the status notification (old version)
410 public void onTransferProgress(long progressRate
) {
411 // NOTHING TO DO HERE ANYMORE
416 * Updates the status notification with the result of a download operation.
418 * @param downloadResult Result of the download operation.
419 * @param download Finished download operation
421 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
422 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
423 if (!downloadResult
.isCancelled()) {
424 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
425 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
426 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
427 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
428 // TODO put something smart in the contentIntent below
429 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
430 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
431 mNotificationManager
.notify(tickerId
, finalNotification
);
437 * Sends a broadcast when a download finishes in order to the interested activities can update their view
439 * @param download Finished download operation
440 * @param downloadResult Result of the download operation
442 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
443 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
444 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
445 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
446 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
447 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
448 sendStickyBroadcast(end
);
453 * Sends a broadcast when a new download is added to the queue.
455 * @param download Added download operation
457 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
458 Intent added
= new Intent(DOWNLOAD_ADDED_MESSAGE
);
459 /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
460 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
461 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
462 sendStickyBroadcast(added
);