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
.Log_OC
;
32 import com
.owncloud
.android
.MainApp
;
33 import com
.owncloud
.android
.R
;
34 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
35 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
36 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
38 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
40 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
41 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
42 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
43 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
44 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
46 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
49 import android
.accounts
.Account
;
50 import android
.accounts
.AccountsException
;
51 import android
.app
.Notification
;
52 import android
.app
.NotificationManager
;
53 import android
.app
.PendingIntent
;
54 import android
.app
.Service
;
55 import android
.content
.Intent
;
56 import android
.os
.Binder
;
57 import android
.os
.Handler
;
58 import android
.os
.HandlerThread
;
59 import android
.os
.IBinder
;
60 import android
.os
.Looper
;
61 import android
.os
.Message
;
62 import android
.os
.Process
;
63 import android
.widget
.RemoteViews
;
65 import eu
.alefzero
.webdav
.WebdavClient
;
67 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
69 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
70 public static final String EXTRA_FILE
= "FILE";
72 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
73 private static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
74 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
75 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
76 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
77 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
79 private static final String TAG
= "FileDownloader";
81 private Looper mServiceLooper
;
82 private ServiceHandler mServiceHandler
;
83 private IBinder mBinder
;
84 private WebdavClient mDownloadClient
= null
;
85 private Account mLastAccount
= null
;
86 private FileDataStorageManager mStorageManager
;
88 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
89 private DownloadFileOperation mCurrentDownload
= null
;
91 private NotificationManager mNotificationManager
;
92 private Notification mNotification
;
93 private int mLastPercent
;
96 public static String
getDownloadAddedMessage() {
97 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
100 public static String
getDownloadFinishMessage() {
101 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
105 * Builds a key for mPendingDownloads from the account and file to download
107 * @param account Account where the file to download is stored
108 * @param file File to download
110 private String
buildRemoteName(Account account
, OCFile file
) {
111 return account
.name
+ file
.getRemotePath();
116 * Service initialization
119 public void onCreate() {
121 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
122 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
123 Process
.THREAD_PRIORITY_BACKGROUND
);
125 mServiceLooper
= thread
.getLooper();
126 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
127 mBinder
= new FileDownloaderBinder();
131 * Entry point to add one or several files to the queue of downloads.
133 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
134 * although the caller activity goes away.
137 public int onStartCommand(Intent intent
, int flags
, int startId
) {
138 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
139 !intent
.hasExtra(EXTRA_FILE
)
140 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
141 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
143 Log_OC
.e(TAG
, "Not enough information provided in intent");
144 return START_NOT_STICKY
;
146 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
147 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
149 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)
150 String downloadKey
= buildRemoteName(account
, file
);
152 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
153 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
154 newDownload
.addDatatransferProgressListener(this);
155 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
156 requestedDownloads
.add(downloadKey
);
157 sendBroadcastNewDownload(newDownload
);
159 } catch (IllegalArgumentException e
) {
160 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
161 return START_NOT_STICKY
;
164 if (requestedDownloads
.size() > 0) {
165 Message msg
= mServiceHandler
.obtainMessage();
167 msg
.obj
= requestedDownloads
;
168 mServiceHandler
.sendMessage(msg
);
171 return START_NOT_STICKY
;
176 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
178 * Implemented to perform cancellation, pause and resume of existing downloads.
181 public IBinder
onBind(Intent arg0
) {
187 * Called when ALL the bound clients were onbound.
190 public boolean onUnbind(Intent intent
) {
191 ((FileDownloaderBinder
)mBinder
).clearListeners();
192 return false
; // not accepting rebinding (default behaviour)
197 * Binder to let client components to perform operations on the queue of downloads.
199 * It provides by itself the available operations.
201 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
204 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
206 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
210 * Cancels a pending or current download of a remote file.
212 * @param account Owncloud account where the remote file is stored.
213 * @param file A file in the queue of pending downloads
215 public void cancel(Account account
, OCFile file
) {
216 DownloadFileOperation download
= null
;
217 synchronized (mPendingDownloads
) {
218 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
220 if (download
!= null
) {
226 public void clearListeners() {
227 mBoundListeners
.clear();
232 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
234 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
236 * @param account Owncloud account where the remote file is stored.
237 * @param file A file that could be in the queue of downloads.
239 public boolean isDownloading(Account account
, OCFile file
) {
240 if (account
== null
|| file
== null
) return false
;
241 String targetKey
= buildRemoteName(account
, file
);
242 synchronized (mPendingDownloads
) {
243 if (file
.isDirectory()) {
244 // this can be slow if there are many downloads :(
245 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
246 boolean found
= false
;
247 while (it
.hasNext() && !found
) {
248 found
= it
.next().startsWith(targetKey
);
252 return (mPendingDownloads
.containsKey(targetKey
));
259 * Adds a listener interested in the progress of the download for a concrete file.
261 * @param listener Object to notify about progress of transfer.
262 * @param account ownCloud account holding the file of interest.
263 * @param file {@link OCfile} of interest for listener.
265 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
266 if (account
== null
|| file
== null
|| listener
== null
) return;
267 String targetKey
= buildRemoteName(account
, file
);
268 mBoundListeners
.put(targetKey
, listener
);
273 * Removes a listener interested in the progress of the download for a concrete file.
275 * @param listener Object to notify about progress of transfer.
276 * @param account ownCloud account holding the file of interest.
277 * @param file {@link OCfile} of interest for listener.
279 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
280 if (account
== null
|| file
== null
|| listener
== null
) return;
281 String targetKey
= buildRemoteName(account
, file
);
282 if (mBoundListeners
.get(targetKey
) == listener
) {
283 mBoundListeners
.remove(targetKey
);
289 public void onTransferProgress(long progressRate
) {
290 // old way, should not be in use any more
295 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
297 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
298 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
299 if (boundListener
!= null
) {
300 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
308 * Download worker. Performs the pending downloads in the order they were requested.
310 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
312 private static class ServiceHandler
extends Handler
{
313 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
314 FileDownloader mService
;
315 public ServiceHandler(Looper looper
, FileDownloader service
) {
318 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
323 public void handleMessage(Message msg
) {
324 @SuppressWarnings("unchecked")
325 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
326 if (msg
.obj
!= null
) {
327 Iterator
<String
> it
= requestedDownloads
.iterator();
328 while (it
.hasNext()) {
329 mService
.downloadFile(it
.next());
332 mService
.stopSelf(msg
.arg1
);
338 * Core download method: requests a file to download and stores it.
340 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
342 private void downloadFile(String downloadKey
) {
344 synchronized(mPendingDownloads
) {
345 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
348 if (mCurrentDownload
!= null
) {
350 notifyDownloadStart(mCurrentDownload
);
352 RemoteOperationResult downloadResult
= null
;
354 /// prepare client object to send the request to the ownCloud server
355 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
356 mLastAccount
= mCurrentDownload
.getAccount();
357 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
358 mDownloadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
361 /// perform the download
362 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
363 if (downloadResult
.isSuccess()) {
364 saveDownloadedFile();
367 } catch (AccountsException e
) {
368 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
369 downloadResult
= new RemoteOperationResult(e
);
370 } catch (IOException e
) {
371 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
372 downloadResult
= new RemoteOperationResult(e
);
375 synchronized(mPendingDownloads
) {
376 mPendingDownloads
.remove(downloadKey
);
382 notifyDownloadResult(mCurrentDownload
, downloadResult
);
384 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
390 * Updates the OC File after a successful download.
392 private void saveDownloadedFile() {
393 OCFile file
= mCurrentDownload
.getFile();
394 long syncDate
= System
.currentTimeMillis();
395 file
.setLastSyncDateForProperties(syncDate
);
396 file
.setLastSyncDateForData(syncDate
);
397 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
398 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
399 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
400 file
.setMimetype(mCurrentDownload
.getMimeType());
401 file
.setStoragePath(mCurrentDownload
.getSavePath());
402 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
403 mStorageManager
.saveFile(file
);
408 * Creates a status notification to show the download progress
410 * @param download Download operation starting.
412 private void notifyDownloadStart(DownloadFileOperation download
) {
413 /// create status notification with a progress bar
415 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
416 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
417 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
418 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
419 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
420 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
422 /// includes a pending intent in the notification showing the details view of the file
423 Intent showDetailsIntent
= null
;
424 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
425 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
427 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
429 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
430 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
431 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
432 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
434 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
439 * Callback method to update the progress bar in the status notification.
442 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
443 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
444 if (percent
!= mLastPercent
) {
445 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
446 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
447 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
448 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
450 mLastPercent
= percent
;
455 * Callback method to update the progress bar in the status notification (old version)
458 public void onTransferProgress(long progressRate
) {
459 // NOTHING TO DO HERE ANYMORE
464 * Updates the status notification with the result of a download operation.
466 * @param downloadResult Result of the download operation.
467 * @param download Finished download operation
469 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
470 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
471 if (!downloadResult
.isCancelled()) {
472 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
473 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
474 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
475 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
476 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
477 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
478 (downloadResult
.isIdPRedirection()
479 && MainApp
.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient
.getAuthTokenType())));
480 if (needsToUpdateCredentials
) {
481 // let the user update credentials with one click
482 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
483 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
484 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
485 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
486 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
487 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
488 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
489 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
490 finalNotification
.setLatestEventInfo( getApplicationContext(),
492 String
.format(getString(contentId
), new File(download
.getSavePath()).getName()),
493 finalNotification
.contentIntent
);
494 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
497 Intent showDetailsIntent
= null
;
498 if (downloadResult
.isSuccess()) {
499 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
500 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
502 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
504 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
505 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
506 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
509 // TODO put something smart in showDetailsIntent
510 showDetailsIntent
= new Intent();
512 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
513 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
515 mNotificationManager
.notify(tickerId
, finalNotification
);
521 * Sends a broadcast when a download finishes in order to the interested activities can update their view
523 * @param download Finished download operation
524 * @param downloadResult Result of the download operation
526 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
527 Intent end
= new Intent(getDownloadFinishMessage());
528 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
529 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
530 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
531 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
532 sendStickyBroadcast(end
);
537 * Sends a broadcast when a new download is added to the queue.
539 * @param download Added download operation
541 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
542 Intent added
= new Intent(getDownloadAddedMessage());
543 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
544 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
545 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
546 sendStickyBroadcast(added
);