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
{
43 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
44 public static final String EXTRA_FILE
= "FILE";
46 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
47 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
48 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
49 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
50 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
52 private static final String TAG
= "FileDownloader";
54 private Looper mServiceLooper
;
55 private ServiceHandler mServiceHandler
;
56 private IBinder mBinder
;
57 private WebdavClient mDownloadClient
= null
;
58 private Account mLastAccount
= null
;
60 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
61 private DownloadFileOperation mCurrentDownload
= null
;
63 private NotificationManager mNotificationMngr
;
64 private Notification mNotification
;
65 private int mLastPercent
;
69 * Builds a key for mDownloadsInProgress from the accountName and remotePath
71 private String
buildRemoteName(Account account
, OCFile file
) {
72 return account
.name
+ file
.getRemotePath();
75 public static final String
getSavePath(String accountName
) {
76 File sdCard
= Environment
.getExternalStorageDirectory();
77 return sdCard
.getAbsolutePath() + "/owncloud/" + Uri
.encode(accountName
, "@");
78 // 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
81 public static final String
getTemporalPath(String accountName
) {
82 File sdCard
= Environment
.getExternalStorageDirectory();
83 return sdCard
.getAbsolutePath() + "/owncloud/tmp/" + Uri
.encode(accountName
, "@");
84 // 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
89 * Service initialization
92 public void onCreate() {
94 mNotificationMngr
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
95 HandlerThread thread
= new HandlerThread("FileDownladerThread",
96 Process
.THREAD_PRIORITY_BACKGROUND
);
98 mServiceLooper
= thread
.getLooper();
99 mServiceHandler
= new ServiceHandler(mServiceLooper
);
100 mBinder
= new FileDownloaderBinder();
105 * Entry point to add one or several files to the queue of downloads.
107 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
108 * although the caller activity goes away.
111 public int onStartCommand(Intent intent
, int flags
, int startId
) {
112 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
113 !intent
.hasExtra(EXTRA_FILE
)
114 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
115 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
117 Log
.e(TAG
, "Not enough information provided in intent");
118 return START_NOT_STICKY
;
120 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
121 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
123 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)
124 String downloadKey
= buildRemoteName(account
, file
);
126 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
127 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
128 newDownload
.addDatatransferProgressListener(this);
129 requestedDownloads
.add(downloadKey
);
131 } catch (IllegalArgumentException e
) {
132 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
133 return START_NOT_STICKY
;
136 if (requestedDownloads
.size() > 0) {
137 Message msg
= mServiceHandler
.obtainMessage();
139 msg
.obj
= requestedDownloads
;
140 mServiceHandler
.sendMessage(msg
);
143 return START_NOT_STICKY
;
148 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
150 * Implemented to perform cancellation, pause and resume of existing downloads.
153 public IBinder
onBind(Intent arg0
) {
159 * Binder to let client components to perform operations on the queue of downloads.
161 * It provides by itself the available operations.
163 public class FileDownloaderBinder
extends Binder
{
166 * Cancels a pending or current download of a remote file.
168 * @param account Owncloud account where the remote file is stored.
169 * @param file A file in the queue of pending downloads
171 public void cancel(Account account
, OCFile file
) {
172 DownloadFileOperation download
= null
;
173 synchronized (mPendingDownloads
) {
174 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
176 if (download
!= null
) {
183 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
185 * @param account Owncloud account where the remote file is stored.
186 * @param file A file in the queue of downloads.
188 public boolean isDownloading(Account account
, OCFile file
) {
189 synchronized (mPendingDownloads
) {
190 return (mPendingDownloads
.containsKey(buildRemoteName(account
, file
)));
197 * Download worker. Performs the pending downloads in the order they were requested.
199 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
201 private final class ServiceHandler
extends Handler
{
202 public ServiceHandler(Looper looper
) {
207 public void handleMessage(Message msg
) {
208 @SuppressWarnings("unchecked")
209 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
210 if (msg
.obj
!= null
) {
211 Iterator
<String
> it
= requestedDownloads
.iterator();
212 while (it
.hasNext()) {
213 downloadFile(it
.next());
223 * Core download method: requests a file to download and stores it.
225 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
227 private void downloadFile(String downloadKey
) {
229 synchronized(mPendingDownloads
) {
230 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
233 if (mCurrentDownload
!= null
) {
235 notifyDownloadStart(mCurrentDownload
);
237 /// prepare client object to send the request to the ownCloud server
238 if (mDownloadClient
== null
|| mLastAccount
!= mCurrentDownload
.getAccount()) {
239 mLastAccount
= mCurrentDownload
.getAccount();
240 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
243 /// perform the download
244 RemoteOperationResult downloadResult
= null
;
246 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
247 if (downloadResult
.isSuccess()) {
248 ContentValues cv
= new ContentValues();
249 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, mCurrentDownload
.getSavePath());
250 getContentResolver().update(
251 ProviderTableMeta
.CONTENT_URI
,
253 ProviderTableMeta
.FILE_NAME
+ "=? AND "
254 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
256 mCurrentDownload
.getSavePath().substring(mCurrentDownload
.getSavePath().lastIndexOf('/') + 1),
257 mLastAccount
.name
});
261 mPendingDownloads
.remove(downloadKey
);
266 notifyDownloadResult(mCurrentDownload
, downloadResult
);
268 sendFinalBroadcast(mCurrentDownload
, downloadResult
);
274 * Callback method to update the progress bar in the status notification.
277 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
278 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
279 if (percent
!= mLastPercent
) {
280 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
== -1);
281 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
));
282 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
284 mLastPercent
= percent
;
289 * Callback method to update the progress bar in the status notification (old version)
292 public void onTransferProgress(long progressRate
) {
293 // NOTHING TO DO HERE ANYMORE
298 * Creates a status notification to show the download progress
300 * @param download Download operation starting.
302 private void notifyDownloadStart(DownloadFileOperation download
) {
303 /// create status notification to show the download progress
305 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
306 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
307 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
308 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() == -1);
309 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
310 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
312 /// includes a pending intent in the notification showing the details view of the file
313 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
314 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
315 showDetailsIntent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, download
.getAccount());
316 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
317 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, showDetailsIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
);
319 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
324 * Updates the status notification with the result of a download operation.
326 * @param downloadResult Result of the download operation.
327 * @param download Finished download operation
329 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
330 mNotificationMngr
.cancel(R
.string
.downloader_download_in_progress_ticker
);
331 if (!downloadResult
.isCancelled()) {
332 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
333 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
334 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
335 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
336 // TODO put something smart in the contentIntent below
337 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
338 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
339 mNotificationMngr
.notify(tickerId
, finalNotification
);
345 * Sends a broadcast in order to the interested activities can update their view
347 * @param download Finished download operation
348 * @param downloadResult Result of the download operation
350 private void sendFinalBroadcast(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
351 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
352 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
353 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
354 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
355 if (downloadResult
.isSuccess()) {
356 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());