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
;
35 import com
.owncloud
.android
.oc_framework
.network
.webdav
.OnDatatransferProgressListener
;
36 import com
.owncloud
.android
.oc_framework
.network
.webdav
.OwnCloudClientFactory
;
37 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavClient
;
38 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
39 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
40 import com
.owncloud
.android
.oc_framework
.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 android
.accounts
.Account
;
47 import android
.accounts
.AccountsException
;
48 import android
.app
.Notification
;
49 import android
.app
.NotificationManager
;
50 import android
.app
.PendingIntent
;
51 import android
.app
.Service
;
52 import android
.content
.Intent
;
53 import android
.os
.Binder
;
54 import android
.os
.Handler
;
55 import android
.os
.HandlerThread
;
56 import android
.os
.IBinder
;
57 import android
.os
.Looper
;
58 import android
.os
.Message
;
59 import android
.os
.Process
;
60 import android
.widget
.RemoteViews
;
62 import com
.owncloud
.android
.Log_OC
;
63 import com
.owncloud
.android
.R
;
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 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
71 private 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
;
94 public static String
getDownloadAddedMessage() {
95 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
98 public static String
getDownloadFinishMessage() {
99 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
103 * Builds a key for mPendingDownloads from the account and file to download
105 * @param account Account where the file to download is stored
106 * @param file File to download
108 private String
buildRemoteName(Account account
, OCFile file
) {
109 return account
.name
+ file
.getRemotePath();
114 * Service initialization
117 public void onCreate() {
119 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
120 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
121 Process
.THREAD_PRIORITY_BACKGROUND
);
123 mServiceLooper
= thread
.getLooper();
124 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
125 mBinder
= new FileDownloaderBinder();
129 * Entry point to add one or several files to the queue of downloads.
131 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
132 * although the caller activity goes away.
135 public int onStartCommand(Intent intent
, int flags
, int startId
) {
136 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
137 !intent
.hasExtra(EXTRA_FILE
)
138 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
139 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
141 Log_OC
.e(TAG
, "Not enough information provided in intent");
142 return START_NOT_STICKY
;
144 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
145 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
147 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)
148 String downloadKey
= buildRemoteName(account
, file
);
150 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
151 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
152 newDownload
.addDatatransferProgressListener(this);
153 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
154 requestedDownloads
.add(downloadKey
);
155 sendBroadcastNewDownload(newDownload
);
157 } catch (IllegalArgumentException e
) {
158 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
159 return START_NOT_STICKY
;
162 if (requestedDownloads
.size() > 0) {
163 Message msg
= mServiceHandler
.obtainMessage();
165 msg
.obj
= requestedDownloads
;
166 mServiceHandler
.sendMessage(msg
);
169 return START_NOT_STICKY
;
174 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
176 * Implemented to perform cancellation, pause and resume of existing downloads.
179 public IBinder
onBind(Intent arg0
) {
185 * Called when ALL the bound clients were onbound.
188 public boolean onUnbind(Intent intent
) {
189 ((FileDownloaderBinder
)mBinder
).clearListeners();
190 return false
; // not accepting rebinding (default behaviour)
195 * Binder to let client components to perform operations on the queue of downloads.
197 * It provides by itself the available operations.
199 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
202 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
204 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
208 * Cancels a pending or current download of a remote file.
210 * @param account Owncloud account where the remote file is stored.
211 * @param file A file in the queue of pending downloads
213 public void cancel(Account account
, OCFile file
) {
214 DownloadFileOperation download
= null
;
215 synchronized (mPendingDownloads
) {
216 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
218 if (download
!= null
) {
224 public void clearListeners() {
225 mBoundListeners
.clear();
230 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
232 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
234 * @param account Owncloud account where the remote file is stored.
235 * @param file A file that could be in the queue of downloads.
237 public boolean isDownloading(Account account
, OCFile file
) {
238 if (account
== null
|| file
== null
) return false
;
239 String targetKey
= buildRemoteName(account
, file
);
240 synchronized (mPendingDownloads
) {
241 if (file
.isFolder()) {
242 // this can be slow if there are many downloads :(
243 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
244 boolean found
= false
;
245 while (it
.hasNext() && !found
) {
246 found
= it
.next().startsWith(targetKey
);
250 return (mPendingDownloads
.containsKey(targetKey
));
257 * Adds a listener interested in the progress of the download for a concrete file.
259 * @param listener Object to notify about progress of transfer.
260 * @param account ownCloud account holding the file of interest.
261 * @param file {@link OCfile} of interest for listener.
263 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
264 if (account
== null
|| file
== null
|| listener
== null
) return;
265 String targetKey
= buildRemoteName(account
, file
);
266 mBoundListeners
.put(targetKey
, listener
);
271 * Removes a listener interested in the progress of the download for a concrete file.
273 * @param listener Object to notify about progress of transfer.
274 * @param account ownCloud account holding the file of interest.
275 * @param file {@link OCfile} of interest for listener.
277 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
278 if (account
== null
|| file
== null
|| listener
== null
) return;
279 String targetKey
= buildRemoteName(account
, file
);
280 if (mBoundListeners
.get(targetKey
) == listener
) {
281 mBoundListeners
.remove(targetKey
);
287 public void onTransferProgress(long progressRate
) {
288 // old way, should not be in use any more
293 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
295 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
296 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
297 if (boundListener
!= null
) {
298 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
306 * Download worker. Performs the pending downloads in the order they were requested.
308 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
310 private static class ServiceHandler
extends Handler
{
311 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
312 FileDownloader mService
;
313 public ServiceHandler(Looper looper
, FileDownloader service
) {
316 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
321 public void handleMessage(Message msg
) {
322 @SuppressWarnings("unchecked")
323 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
324 if (msg
.obj
!= null
) {
325 Iterator
<String
> it
= requestedDownloads
.iterator();
326 while (it
.hasNext()) {
327 mService
.downloadFile(it
.next());
330 mService
.stopSelf(msg
.arg1
);
336 * Core download method: requests a file to download and stores it.
338 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
340 private void downloadFile(String downloadKey
) {
342 synchronized(mPendingDownloads
) {
343 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
346 if (mCurrentDownload
!= null
) {
348 notifyDownloadStart(mCurrentDownload
);
350 RemoteOperationResult downloadResult
= null
;
352 /// prepare client object to send the request to the ownCloud server
353 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
354 mLastAccount
= mCurrentDownload
.getAccount();
355 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
356 mDownloadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
359 /// perform the download
360 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
361 if (downloadResult
.isSuccess()) {
362 saveDownloadedFile();
365 } catch (AccountsException e
) {
366 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
367 downloadResult
= new RemoteOperationResult(e
);
368 } catch (IOException e
) {
369 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
370 downloadResult
= new RemoteOperationResult(e
);
373 synchronized(mPendingDownloads
) {
374 mPendingDownloads
.remove(downloadKey
);
380 notifyDownloadResult(mCurrentDownload
, downloadResult
);
382 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
388 * Updates the OC File after a successful download.
390 private void saveDownloadedFile() {
391 OCFile file
= mCurrentDownload
.getFile();
392 long syncDate
= System
.currentTimeMillis();
393 file
.setLastSyncDateForProperties(syncDate
);
394 file
.setLastSyncDateForData(syncDate
);
395 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
396 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
397 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
398 file
.setMimetype(mCurrentDownload
.getMimeType());
399 file
.setStoragePath(mCurrentDownload
.getSavePath());
400 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
401 mStorageManager
.saveFile(file
);
406 * Creates a status notification to show the download progress
408 * @param download Download operation starting.
410 private void notifyDownloadStart(DownloadFileOperation download
) {
411 /// create status notification with a progress bar
413 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
414 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
415 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
416 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
417 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
418 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
420 /// includes a pending intent in the notification showing the details view of the file
421 Intent showDetailsIntent
= null
;
422 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
423 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
425 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
427 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
428 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
429 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
430 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
432 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
437 * Callback method to update the progress bar in the status notification.
440 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
441 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
442 if (percent
!= mLastPercent
) {
443 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
444 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
445 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
446 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
448 mLastPercent
= percent
;
453 * Callback method to update the progress bar in the status notification (old version)
456 public void onTransferProgress(long progressRate
) {
457 // NOTHING TO DO HERE ANYMORE
462 * Updates the status notification with the result of a download operation.
464 * @param downloadResult Result of the download operation.
465 * @param download Finished download operation
467 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
468 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
469 if (!downloadResult
.isCancelled()) {
470 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
471 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
472 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
473 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
474 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
475 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
476 (downloadResult
.isIdPRedirection()
477 && mDownloadClient
.getCredentials() == null
));
478 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
479 if (needsToUpdateCredentials
) {
480 // let the user update credentials with one click
481 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
482 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
483 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
484 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
485 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
486 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
487 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
488 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
489 finalNotification
.setLatestEventInfo( getApplicationContext(),
491 String
.format(getString(contentId
), new File(download
.getSavePath()).getName()),
492 finalNotification
.contentIntent
);
493 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
496 Intent showDetailsIntent
= null
;
497 if (downloadResult
.isSuccess()) {
498 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
499 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
501 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
503 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
504 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
505 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
508 // TODO put something smart in showDetailsIntent
509 showDetailsIntent
= new Intent();
511 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
512 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
514 mNotificationManager
.notify(tickerId
, finalNotification
);
520 * Sends a broadcast when a download finishes in order to the interested activities can update their view
522 * @param download Finished download operation
523 * @param downloadResult Result of the download operation
525 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
526 Intent end
= new Intent(getDownloadFinishMessage());
527 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
528 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
529 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
530 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
531 sendStickyBroadcast(end
);
536 * Sends a broadcast when a new download is added to the queue.
538 * @param download Added download operation
540 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
541 Intent added
= new Intent(getDownloadAddedMessage());
542 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
543 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
544 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
545 sendStickyBroadcast(added
);