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 version 2,
7 * as published by the Free Software Foundation.
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
.io
.IOException
;
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
.authentication
.AuthenticatorActivity
;
32 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
33 import com
.owncloud
.android
.datamodel
.OCFile
;
34 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
36 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
37 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
38 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
40 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
41 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
42 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
43 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
45 import android
.accounts
.Account
;
46 import android
.accounts
.AccountsException
;
47 import android
.app
.Notification
;
48 import android
.app
.NotificationManager
;
49 import android
.app
.PendingIntent
;
50 import android
.app
.Service
;
51 import android
.content
.Intent
;
52 import android
.os
.Binder
;
53 import android
.os
.Handler
;
54 import android
.os
.HandlerThread
;
55 import android
.os
.IBinder
;
56 import android
.os
.Looper
;
57 import android
.os
.Message
;
58 import android
.os
.Process
;
59 import android
.widget
.RemoteViews
;
61 import com
.owncloud
.android
.Log_OC
;
62 import com
.owncloud
.android
.R
;
63 import eu
.alefzero
.webdav
.WebdavClient
;
65 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
67 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
68 public static final String EXTRA_FILE
= "FILE";
70 public static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
71 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
72 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
73 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
74 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
75 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
77 private static final String TAG
= "FileDownloader";
79 private Looper mServiceLooper
;
80 private ServiceHandler mServiceHandler
;
81 private IBinder mBinder
;
82 private WebdavClient mDownloadClient
= null
;
83 private Account mLastAccount
= null
;
84 private FileDataStorageManager mStorageManager
;
86 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
87 private DownloadFileOperation mCurrentDownload
= null
;
89 private NotificationManager mNotificationManager
;
90 private Notification mNotification
;
91 private int mLastPercent
;
95 * Builds a key for mPendingDownloads from the account and file to download
97 * @param account Account where the file to download is stored
98 * @param file File to download
100 private String
buildRemoteName(Account account
, OCFile file
) {
101 return account
.name
+ file
.getRemotePath();
106 * Service initialization
109 public void onCreate() {
111 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
112 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
113 Process
.THREAD_PRIORITY_BACKGROUND
);
115 mServiceLooper
= thread
.getLooper();
116 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
117 mBinder
= new FileDownloaderBinder();
121 * Entry point to add one or several files to the queue of downloads.
123 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
124 * although the caller activity goes away.
127 public int onStartCommand(Intent intent
, int flags
, int startId
) {
128 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
129 !intent
.hasExtra(EXTRA_FILE
)
130 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
131 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
133 Log_OC
.e(TAG
, "Not enough information provided in intent");
134 return START_NOT_STICKY
;
136 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
137 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
139 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)
140 String downloadKey
= buildRemoteName(account
, file
);
142 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
143 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
144 newDownload
.addDatatransferProgressListener(this);
145 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
146 requestedDownloads
.add(downloadKey
);
147 sendBroadcastNewDownload(newDownload
);
149 } catch (IllegalArgumentException e
) {
150 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
151 return START_NOT_STICKY
;
154 if (requestedDownloads
.size() > 0) {
155 Message msg
= mServiceHandler
.obtainMessage();
157 msg
.obj
= requestedDownloads
;
158 mServiceHandler
.sendMessage(msg
);
161 return START_NOT_STICKY
;
166 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
168 * Implemented to perform cancellation, pause and resume of existing downloads.
171 public IBinder
onBind(Intent arg0
) {
177 * Called when ALL the bound clients were onbound.
180 public boolean onUnbind(Intent intent
) {
181 ((FileDownloaderBinder
)mBinder
).clearListeners();
182 return false
; // not accepting rebinding (default behaviour)
187 * Binder to let client components to perform operations on the queue of downloads.
189 * It provides by itself the available operations.
191 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
194 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
196 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
200 * Cancels a pending or current download of a remote file.
202 * @param account Owncloud account where the remote file is stored.
203 * @param file A file in the queue of pending downloads
205 public void cancel(Account account
, OCFile file
) {
206 DownloadFileOperation download
= null
;
207 synchronized (mPendingDownloads
) {
208 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
210 if (download
!= null
) {
216 public void clearListeners() {
217 mBoundListeners
.clear();
222 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
224 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
226 * @param account Owncloud account where the remote file is stored.
227 * @param file A file that could be in the queue of downloads.
229 public boolean isDownloading(Account account
, OCFile file
) {
230 if (account
== null
|| file
== null
) return false
;
231 String targetKey
= buildRemoteName(account
, file
);
232 synchronized (mPendingDownloads
) {
233 if (file
.isDirectory()) {
234 // this can be slow if there are many downloads :(
235 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
236 boolean found
= false
;
237 while (it
.hasNext() && !found
) {
238 found
= it
.next().startsWith(targetKey
);
242 return (mPendingDownloads
.containsKey(targetKey
));
249 * Adds a listener interested in the progress of the download for a concrete file.
251 * @param listener Object to notify about progress of transfer.
252 * @param account ownCloud account holding the file of interest.
253 * @param file {@link OCfile} of interest for listener.
255 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
256 if (account
== null
|| file
== null
|| listener
== null
) return;
257 String targetKey
= buildRemoteName(account
, file
);
258 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
);
328 * Core download method: requests a file to download and stores it.
330 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
332 private void downloadFile(String downloadKey
) {
334 synchronized(mPendingDownloads
) {
335 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
338 if (mCurrentDownload
!= null
) {
340 notifyDownloadStart(mCurrentDownload
);
342 RemoteOperationResult downloadResult
= null
;
344 /// prepare client object to send the request to the ownCloud server
345 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
346 mLastAccount
= mCurrentDownload
.getAccount();
347 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
348 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
351 /// perform the download
352 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
353 if (downloadResult
.isSuccess()) {
354 saveDownloadedFile();
357 } catch (AccountsException e
) {
358 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
359 downloadResult
= new RemoteOperationResult(e
);
360 } catch (IOException e
) {
361 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
362 downloadResult
= new RemoteOperationResult(e
);
365 synchronized(mPendingDownloads
) {
366 mPendingDownloads
.remove(downloadKey
);
372 notifyDownloadResult(mCurrentDownload
, downloadResult
);
374 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
380 * Updates the OC File after a successful download.
382 private void saveDownloadedFile() {
383 OCFile file
= mCurrentDownload
.getFile();
384 long syncDate
= System
.currentTimeMillis();
385 file
.setLastSyncDateForProperties(syncDate
);
386 file
.setLastSyncDateForData(syncDate
);
387 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
388 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
389 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
390 file
.setMimetype(mCurrentDownload
.getMimeType());
391 file
.setStoragePath(mCurrentDownload
.getSavePath());
392 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
393 mStorageManager
.saveFile(file
);
398 * Creates a status notification to show the download progress
400 * @param download Download operation starting.
402 private void notifyDownloadStart(DownloadFileOperation download
) {
403 /// create status notification with a progress bar
405 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
406 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
407 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
408 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
409 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
410 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
412 /// includes a pending intent in the notification showing the details view of the file
413 Intent showDetailsIntent
= null
;
414 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
415 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
417 showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
419 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
420 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
421 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
422 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
424 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
429 * Callback method to update the progress bar in the status notification.
432 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
433 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
434 if (percent
!= mLastPercent
) {
435 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
436 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
437 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
438 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
440 mLastPercent
= percent
;
445 * Callback method to update the progress bar in the status notification (old version)
448 public void onTransferProgress(long progressRate
) {
449 // NOTHING TO DO HERE ANYMORE
454 * Updates the status notification with the result of a download operation.
456 * @param downloadResult Result of the download operation.
457 * @param download Finished download operation
459 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
460 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
461 if (!downloadResult
.isCancelled()) {
462 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
463 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
464 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
465 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
466 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
);
467 if (needsToUpdateCredentials
) {
468 // let the user update credentials with one click
469 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
470 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
471 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
472 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
473 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
474 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
475 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
476 finalNotification
.setLatestEventInfo( getApplicationContext(),
478 String
.format(getString(contentId
), new File(download
.getSavePath()).getName()),
479 finalNotification
.contentIntent
);
480 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
483 Intent showDetailsIntent
= null
;
484 if (downloadResult
.isSuccess()) {
485 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
486 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
488 showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
490 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, download
.getFile());
491 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, download
.getAccount());
492 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
495 // TODO put something smart in showDetailsIntent
496 showDetailsIntent
= new Intent();
498 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
499 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
501 mNotificationManager
.notify(tickerId
, finalNotification
);
507 * Sends a broadcast when a download finishes in order to the interested activities can update their view
509 * @param download Finished download operation
510 * @param downloadResult Result of the download operation
512 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
513 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
514 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
515 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
516 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
517 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
518 sendStickyBroadcast(end
);
523 * Sends a broadcast when a new download is added to the queue.
525 * @param download Added download operation
527 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
528 Intent added
= new Intent(DOWNLOAD_ADDED_MESSAGE
);
529 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
530 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
531 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
532 sendStickyBroadcast(added
);