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
.io
.IOException
;
24 import java
.util
.AbstractList
;
25 import java
.util
.Iterator
;
26 import java
.util
.Vector
;
27 import java
.util
.concurrent
.ConcurrentHashMap
;
28 import java
.util
.concurrent
.ConcurrentMap
;
30 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
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
.operations
.RemoteOperationResult
.ResultCode
;
39 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
40 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
42 import android
.accounts
.Account
;
43 import android
.accounts
.AccountsException
;
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
.R
;
60 import eu
.alefzero
.webdav
.WebdavClient
;
62 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
64 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
65 public static final String EXTRA_FILE
= "FILE";
67 public static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
68 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
69 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
70 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
71 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
72 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
74 private static final String TAG
= "FileDownloader";
76 private Looper mServiceLooper
;
77 private ServiceHandler mServiceHandler
;
78 private IBinder mBinder
;
79 private WebdavClient mDownloadClient
= null
;
80 private Account mLastAccount
= null
;
81 private FileDataStorageManager mStorageManager
;
83 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
84 private DownloadFileOperation mCurrentDownload
= null
;
86 private NotificationManager mNotificationManager
;
87 private Notification mNotification
;
88 private int mLastPercent
;
92 * Builds a key for mPendingDownloads from the account and file to download
94 * @param account Account where the file to download is stored
95 * @param file File to download
97 private String
buildRemoteName(Account account
, OCFile file
) {
98 return account
.name
+ file
.getRemotePath();
103 * Service initialization
106 public void onCreate() {
108 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
109 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
110 Process
.THREAD_PRIORITY_BACKGROUND
);
112 mServiceLooper
= thread
.getLooper();
113 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
114 mBinder
= new FileDownloaderBinder();
119 * Entry point to add one or several files to the queue of downloads.
121 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
122 * although the caller activity goes away.
125 public int onStartCommand(Intent intent
, int flags
, int startId
) {
126 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
127 !intent
.hasExtra(EXTRA_FILE
)
128 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
129 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
131 Log
.e(TAG
, "Not enough information provided in intent");
132 return START_NOT_STICKY
;
134 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
135 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
137 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)
138 String downloadKey
= buildRemoteName(account
, file
);
140 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
141 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
142 newDownload
.addDatatransferProgressListener(this);
143 requestedDownloads
.add(downloadKey
);
144 sendBroadcastNewDownload(newDownload
);
146 } catch (IllegalArgumentException e
) {
147 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
148 return START_NOT_STICKY
;
151 if (requestedDownloads
.size() > 0) {
152 Message msg
= mServiceHandler
.obtainMessage();
154 msg
.obj
= requestedDownloads
;
155 mServiceHandler
.sendMessage(msg
);
158 return START_NOT_STICKY
;
163 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
165 * Implemented to perform cancellation, pause and resume of existing downloads.
168 public IBinder
onBind(Intent arg0
) {
174 * Binder to let client components to perform operations on the queue of downloads.
176 * It provides by itself the available operations.
178 public class FileDownloaderBinder
extends Binder
{
181 * Cancels a pending or current download of a remote file.
183 * @param account Owncloud account where the remote file is stored.
184 * @param file A file in the queue of pending downloads
186 public void cancel(Account account
, OCFile file
) {
187 DownloadFileOperation download
= null
;
188 synchronized (mPendingDownloads
) {
189 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
191 if (download
!= null
) {
198 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
200 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
202 * @param account Owncloud account where the remote file is stored.
203 * @param file A file that could be in the queue of downloads.
205 public boolean isDownloading(Account account
, OCFile file
) {
206 if (account
== null
|| file
== null
) return false
;
207 String targetKey
= buildRemoteName(account
, file
);
208 synchronized (mPendingDownloads
) {
209 if (file
.isDirectory()) {
210 // this can be slow if there are many downloads :(
211 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
212 boolean found
= false
;
213 while (it
.hasNext() && !found
) {
214 found
= it
.next().startsWith(targetKey
);
218 return (mPendingDownloads
.containsKey(targetKey
));
226 * Download worker. Performs the pending downloads in the order they were requested.
228 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
230 private static class ServiceHandler
extends Handler
{
231 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
232 FileDownloader mService
;
233 public ServiceHandler(Looper looper
, FileDownloader service
) {
236 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
241 public void handleMessage(Message msg
) {
242 @SuppressWarnings("unchecked")
243 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
244 if (msg
.obj
!= null
) {
245 Iterator
<String
> it
= requestedDownloads
.iterator();
246 while (it
.hasNext()) {
247 mService
.downloadFile(it
.next());
250 mService
.stopSelf(msg
.arg1
);
257 * Core download method: requests a file to download and stores it.
259 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
261 private void downloadFile(String downloadKey
) {
263 synchronized(mPendingDownloads
) {
264 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
267 if (mCurrentDownload
!= null
) {
269 notifyDownloadStart(mCurrentDownload
);
271 RemoteOperationResult downloadResult
= null
;
273 /// prepare client object to send the request to the ownCloud server
274 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
275 mLastAccount
= mCurrentDownload
.getAccount();
276 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
277 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
280 /// perform the download
281 if (downloadResult
== null
) {
282 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
284 if (downloadResult
.isSuccess()) {
285 saveDownloadedFile();
288 } catch (AccountsException e
) {
289 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
290 downloadResult
= new RemoteOperationResult(e
);
291 } catch (IOException e
) {
292 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
293 downloadResult
= new RemoteOperationResult(e
);
296 synchronized(mPendingDownloads
) {
297 mPendingDownloads
.remove(downloadKey
);
303 notifyDownloadResult(mCurrentDownload
, downloadResult
);
305 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
311 * Updates the OC File after a successful download.
313 private void saveDownloadedFile() {
314 OCFile file
= mCurrentDownload
.getFile();
315 long syncDate
= System
.currentTimeMillis();
316 file
.setLastSyncDateForProperties(syncDate
);
317 file
.setLastSyncDateForData(syncDate
);
318 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
319 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
320 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
321 file
.setMimetype(mCurrentDownload
.getMimeType());
322 file
.setStoragePath(mCurrentDownload
.getSavePath());
323 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
324 mStorageManager
.saveFile(file
);
329 * Creates a status notification to show the download progress
331 * @param download Download operation starting.
333 private void notifyDownloadStart(DownloadFileOperation download
) {
334 /// create status notification with a progress bar
336 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
337 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
338 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
339 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
340 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
341 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
343 /// includes a pending intent in the notification showing the details view of the file
344 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
345 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
346 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
347 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
348 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
350 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
355 * Callback method to update the progress bar in the status notification.
358 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
359 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
360 if (percent
!= mLastPercent
) {
361 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
362 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
363 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
364 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
366 mLastPercent
= percent
;
371 * Callback method to update the progress bar in the status notification (old version)
374 public void onTransferProgress(long progressRate
) {
375 // NOTHING TO DO HERE ANYMORE
380 * Updates the status notification with the result of a download operation.
382 * @param downloadResult Result of the download operation.
383 * @param download Finished download operation
385 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
386 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
387 if (!downloadResult
.isCancelled()) {
388 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
389 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
390 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
391 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
392 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
);
393 if (needsToUpdateCredentials
) {
394 // let the user update credentials with one click
395 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
396 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
397 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
398 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
399 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
400 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
401 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
402 finalNotification
.setLatestEventInfo( getApplicationContext(),
404 String
.format(getString(contentId
), new File(download
.getSavePath()).getName()),
405 finalNotification
.contentIntent
);
406 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
409 // TODO put something smart in the contentIntent below
410 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
411 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
413 mNotificationManager
.notify(tickerId
, finalNotification
);
419 * Sends a broadcast when a download finishes in order to the interested activities can update their view
421 * @param download Finished download operation
422 * @param downloadResult Result of the download operation
424 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
425 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
426 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
427 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
428 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
429 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
430 sendStickyBroadcast(end
);
435 * Sends a broadcast when a new download is added to the queue.
437 * @param download Added download operation
439 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
440 Intent added
= new Intent(DOWNLOAD_ADDED_MESSAGE
);
441 /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
442 added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
443 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
444 sendStickyBroadcast(added
);