1 package com
.owncloud
.android
.files
.services
;
4 import java
.util
.AbstractList
;
5 import java
.util
.Iterator
;
6 import java
.util
.Vector
;
7 import java
.util
.concurrent
.ConcurrentHashMap
;
8 import java
.util
.concurrent
.ConcurrentMap
;
10 import com
.owncloud
.android
.datamodel
.OCFile
;
11 import com
.owncloud
.android
.db
.ProviderMeta
.ProviderTableMeta
;
12 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
14 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
15 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
16 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
17 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
18 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
20 import android
.accounts
.Account
;
21 import android
.app
.Notification
;
22 import android
.app
.NotificationManager
;
23 import android
.app
.PendingIntent
;
24 import android
.app
.Service
;
25 import android
.content
.ContentValues
;
26 import android
.content
.Intent
;
27 import android
.net
.Uri
;
28 import android
.os
.Binder
;
29 import android
.os
.Environment
;
30 import android
.os
.Handler
;
31 import android
.os
.HandlerThread
;
32 import android
.os
.IBinder
;
33 import android
.os
.Looper
;
34 import android
.os
.Message
;
35 import android
.os
.Process
;
36 import android
.util
.Log
;
37 import android
.widget
.RemoteViews
;
39 import com
.owncloud
.android
.R
;
40 import eu
.alefzero
.webdav
.WebdavClient
;
42 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
44 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
45 public static final String EXTRA_FILE
= "FILE";
47 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
48 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
49 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
50 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
51 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
53 private static final String TAG
= "FileDownloader";
55 private Looper mServiceLooper
;
56 private ServiceHandler mServiceHandler
;
57 private IBinder mBinder
;
58 private WebdavClient mDownloadClient
= null
;
59 private Account mLastAccount
= null
;
61 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
62 private DownloadFileOperation mCurrentDownload
= null
;
64 private NotificationManager mNotificationManager
;
65 private Notification mNotification
;
66 private int mLastPercent
;
70 * Builds a key for mPendingDownloads from the account and file to download
72 * @param account Account where the file to download is stored
73 * @param file File to download
75 private String
buildRemoteName(Account account
, OCFile file
) {
76 return account
.name
+ file
.getRemotePath();
79 public static final String
getSavePath(String accountName
) {
80 File sdCard
= Environment
.getExternalStorageDirectory();
81 return sdCard
.getAbsolutePath() + "/owncloud/" + Uri
.encode(accountName
, "@");
82 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
85 public static final String
getTemporalPath(String accountName
) {
86 File sdCard
= Environment
.getExternalStorageDirectory();
87 return sdCard
.getAbsolutePath() + "/owncloud/tmp/" + Uri
.encode(accountName
, "@");
88 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
93 * Service initialization
96 public void onCreate() {
98 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
99 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
100 Process
.THREAD_PRIORITY_BACKGROUND
);
102 mServiceLooper
= thread
.getLooper();
103 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
104 mBinder
= new FileDownloaderBinder();
109 * Entry point to add one or several files to the queue of downloads.
111 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
112 * although the caller activity goes away.
115 public int onStartCommand(Intent intent
, int flags
, int startId
) {
116 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
117 !intent
.hasExtra(EXTRA_FILE
)
118 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
119 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
121 Log
.e(TAG
, "Not enough information provided in intent");
122 return START_NOT_STICKY
;
124 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
125 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
127 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)
128 String downloadKey
= buildRemoteName(account
, file
);
130 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
131 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
132 newDownload
.addDatatransferProgressListener(this);
133 requestedDownloads
.add(downloadKey
);
135 } catch (IllegalArgumentException e
) {
136 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
137 return START_NOT_STICKY
;
140 if (requestedDownloads
.size() > 0) {
141 Message msg
= mServiceHandler
.obtainMessage();
143 msg
.obj
= requestedDownloads
;
144 mServiceHandler
.sendMessage(msg
);
147 return START_NOT_STICKY
;
152 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
154 * Implemented to perform cancellation, pause and resume of existing downloads.
157 public IBinder
onBind(Intent arg0
) {
163 * Binder to let client components to perform operations on the queue of downloads.
165 * It provides by itself the available operations.
167 public class FileDownloaderBinder
extends Binder
{
170 * Cancels a pending or current download of a remote file.
172 * @param account Owncloud account where the remote file is stored.
173 * @param file A file in the queue of pending downloads
175 public void cancel(Account account
, OCFile file
) {
176 DownloadFileOperation download
= null
;
177 synchronized (mPendingDownloads
) {
178 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
180 if (download
!= null
) {
187 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download
189 * @param account Owncloud account where the remote file is stored.
190 * @param file A file that could be in the queue of downloads.
192 public boolean isDownloading(Account account
, OCFile file
) {
193 synchronized (mPendingDownloads
) {
194 return (mPendingDownloads
.containsKey(buildRemoteName(account
, file
)));
201 * Download worker. Performs the pending downloads in the order they were requested.
203 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
205 private static class ServiceHandler
extends Handler
{
206 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
207 FileDownloader mService
;
208 public ServiceHandler(Looper looper
, FileDownloader service
) {
211 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
216 public void handleMessage(Message msg
) {
217 @SuppressWarnings("unchecked")
218 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
219 if (msg
.obj
!= null
) {
220 Iterator
<String
> it
= requestedDownloads
.iterator();
221 while (it
.hasNext()) {
222 mService
.downloadFile(it
.next());
225 mService
.stopSelf(msg
.arg1
);
232 * Core download method: requests a file to download and stores it.
234 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
236 private void downloadFile(String downloadKey
) {
238 synchronized(mPendingDownloads
) {
239 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
242 if (mCurrentDownload
!= null
) {
244 notifyDownloadStart(mCurrentDownload
);
246 /// prepare client object to send the request to the ownCloud server
247 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
248 mLastAccount
= mCurrentDownload
.getAccount();
249 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
252 /// perform the download
253 RemoteOperationResult downloadResult
= null
;
255 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
256 if (downloadResult
.isSuccess()) {
257 ContentValues cv
= new ContentValues();
258 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, mCurrentDownload
.getSavePath());
259 getContentResolver().update(
260 ProviderTableMeta
.CONTENT_URI
,
262 ProviderTableMeta
.FILE_NAME
+ "=? AND "
263 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
265 mCurrentDownload
.getSavePath().substring(mCurrentDownload
.getSavePath().lastIndexOf('/') + 1),
266 mLastAccount
.name
});
270 synchronized(mPendingDownloads
) {
271 mPendingDownloads
.remove(downloadKey
);
277 notifyDownloadResult(mCurrentDownload
, downloadResult
);
279 sendFinalBroadcast(mCurrentDownload
, downloadResult
);
285 * Creates a status notification to show the download progress
287 * @param download Download operation starting.
289 private void notifyDownloadStart(DownloadFileOperation download
) {
290 /// create status notification with a progress bar
292 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
293 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
294 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
295 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
296 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
297 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
299 /// includes a pending intent in the notification showing the details view of the file
300 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
301 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
302 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
303 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
304 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, showDetailsIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
);
306 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
311 * Callback method to update the progress bar in the status notification.
314 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
315 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
316 if (percent
!= mLastPercent
) {
317 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
318 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
319 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
320 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
322 mLastPercent
= percent
;
327 * Callback method to update the progress bar in the status notification (old version)
330 public void onTransferProgress(long progressRate
) {
331 // NOTHING TO DO HERE ANYMORE
336 * Updates the status notification with the result of a download operation.
338 * @param downloadResult Result of the download operation.
339 * @param download Finished download operation
341 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
342 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
343 if (!downloadResult
.isCancelled()) {
344 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
345 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
346 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
347 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
348 // TODO put something smart in the contentIntent below
349 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
350 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
351 mNotificationManager
.notify(tickerId
, finalNotification
);
357 * Sends a broadcast in order to the interested activities can update their view
359 * @param download Finished download operation
360 * @param downloadResult Result of the download operation
362 private void sendFinalBroadcast(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
363 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
364 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
365 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
366 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
367 if (downloadResult
.isSuccess()) {
368 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());