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
.R
;
32 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
33 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
34 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudClientFactory
;
38 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
39 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
40 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
43 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
44 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
45 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
46 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
47 import com
.owncloud
.android
.utils
.Log_OC
;
48 import com
.owncloud
.android
.utils
.NotificationBuilderWithProgressBar
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountsException
;
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
.support
.v4
.app
.NotificationCompat
;
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 OwnCloudClient 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 NotificationCompat
.Builder mNotificationBuilder
;
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
);
286 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
288 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
289 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
290 if (boundListener
!= null
) {
291 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
299 * Download worker. Performs the pending downloads in the order they were requested.
301 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
303 private static class ServiceHandler
extends Handler
{
304 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
305 FileDownloader mService
;
306 public ServiceHandler(Looper looper
, FileDownloader service
) {
309 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
314 public void handleMessage(Message msg
) {
315 @SuppressWarnings("unchecked")
316 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
317 if (msg
.obj
!= null
) {
318 Iterator
<String
> it
= requestedDownloads
.iterator();
319 while (it
.hasNext()) {
320 mService
.downloadFile(it
.next());
323 mService
.stopSelf(msg
.arg1
);
329 * Core download method: requests a file to download and stores it.
331 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
333 private void downloadFile(String downloadKey
) {
335 synchronized(mPendingDownloads
) {
336 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
339 if (mCurrentDownload
!= null
) {
341 notifyDownloadStart(mCurrentDownload
);
343 RemoteOperationResult downloadResult
= null
;
345 /// prepare client object to send the request to the ownCloud server
346 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
347 mLastAccount
= mCurrentDownload
.getAccount();
348 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
349 mDownloadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
352 /// perform the download
353 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
354 if (downloadResult
.isSuccess()) {
355 saveDownloadedFile();
358 } catch (AccountsException e
) {
359 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
360 downloadResult
= new RemoteOperationResult(e
);
361 } catch (IOException e
) {
362 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
363 downloadResult
= new RemoteOperationResult(e
);
366 synchronized(mPendingDownloads
) {
367 mPendingDownloads
.remove(downloadKey
);
373 notifyDownloadResult(mCurrentDownload
, downloadResult
);
375 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
381 * Updates the OC File after a successful download.
383 private void saveDownloadedFile() {
384 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
385 long syncDate
= System
.currentTimeMillis();
386 file
.setLastSyncDateForProperties(syncDate
);
387 file
.setLastSyncDateForData(syncDate
);
388 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
389 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
390 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
391 file
.setMimetype(mCurrentDownload
.getMimeType());
392 file
.setStoragePath(mCurrentDownload
.getSavePath());
393 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
394 mStorageManager
.saveFile(file
);
399 * Creates a status notification to show the download progress
401 * @param download Download operation starting.
403 private void notifyDownloadStart(DownloadFileOperation download
) {
404 /// create status notification with a progress bar
406 mNotificationBuilder
=
407 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
409 .setSmallIcon(R
.drawable
.notification_icon
)
410 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
411 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
413 .setProgress(100, 0, download
.getSize() < 0)
415 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
416 new File(download
.getSavePath()).getName())
419 /// includes a pending intent in the notification showing the details view of the file
420 Intent showDetailsIntent
= null
;
421 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
422 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
424 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
426 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
427 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
428 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
430 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
431 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
434 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
439 * Callback method to update the progress bar in the status notification.
442 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
443 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
444 if (percent
!= mLastPercent
) {
445 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
446 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
447 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
448 mNotificationBuilder
.setContentText(text
);
449 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
451 mLastPercent
= percent
;
456 * Updates the status notification with the result of a download operation.
458 * @param downloadResult Result of the download operation.
459 * @param download Finished download operation
461 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
462 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
463 if (!downloadResult
.isCancelled()) {
464 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
465 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
467 .setTicker(getString(tickerId
))
468 .setContentTitle(getString(tickerId
))
471 .setProgress(0, 0, false
);
472 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
473 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
474 (downloadResult
.isIdPRedirection()
475 && mDownloadClient
.getCredentials() == null
));
476 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
477 if (needsToUpdateCredentials
) {
478 // let the user update credentials with one click
479 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
480 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
481 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
482 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
483 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
484 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
486 .setContentIntent(PendingIntent
.getActivity(
487 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
489 .setContentText(String
.format(getString(contentId
), new File(download
.getSavePath()).getName()));
490 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
493 Intent showDetailsIntent
= null
;
494 if (downloadResult
.isSuccess()) {
495 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
496 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
498 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
500 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
501 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
502 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
505 // TODO put something smart in showDetailsIntent
506 showDetailsIntent
= new Intent();
509 .setContentIntent(PendingIntent
.getActivity(
510 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
512 .setContentText(String
.format(getString(contentId
), new File(download
.getSavePath()).getName()));
514 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
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
);