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
.DisplayUtils
;
48 import com
.owncloud
.android
.utils
.Log_OC
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountsException
;
52 import android
.app
.Notification
;
53 import android
.app
.NotificationManager
;
54 import android
.app
.PendingIntent
;
55 import android
.app
.Service
;
56 import android
.content
.Intent
;
57 import android
.os
.Binder
;
58 import android
.os
.Handler
;
59 import android
.os
.HandlerThread
;
60 import android
.os
.IBinder
;
61 import android
.os
.Looper
;
62 import android
.os
.Message
;
63 import android
.os
.Process
;
64 import android
.widget
.RemoteViews
;
66 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
68 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
69 public static final String EXTRA_FILE
= "FILE";
71 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
72 private static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
73 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
74 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
75 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
76 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
78 private static final String TAG
= "FileDownloader";
80 private Looper mServiceLooper
;
81 private ServiceHandler mServiceHandler
;
82 private IBinder mBinder
;
83 private OwnCloudClient mDownloadClient
= null
;
84 private Account mLastAccount
= null
;
85 private FileDataStorageManager mStorageManager
;
87 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
88 private DownloadFileOperation mCurrentDownload
= null
;
90 private NotificationManager mNotificationManager
;
91 private Notification mNotification
;
92 private int mLastPercent
;
95 public static String
getDownloadAddedMessage() {
96 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
99 public static String
getDownloadFinishMessage() {
100 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
104 * Builds a key for mPendingDownloads from the account and file to download
106 * @param account Account where the file to download is stored
107 * @param file File to download
109 private String
buildRemoteName(Account account
, OCFile file
) {
110 return account
.name
+ file
.getRemotePath();
115 * Service initialization
118 public void onCreate() {
120 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
121 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
122 Process
.THREAD_PRIORITY_BACKGROUND
);
124 mServiceLooper
= thread
.getLooper();
125 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
126 mBinder
= new FileDownloaderBinder();
130 * Entry point to add one or several files to the queue of downloads.
132 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
133 * although the caller activity goes away.
136 public int onStartCommand(Intent intent
, int flags
, int startId
) {
137 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
138 !intent
.hasExtra(EXTRA_FILE
)
139 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
140 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
142 Log_OC
.e(TAG
, "Not enough information provided in intent");
143 return START_NOT_STICKY
;
145 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
146 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
148 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)
149 String downloadKey
= buildRemoteName(account
, file
);
151 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
152 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
153 newDownload
.addDatatransferProgressListener(this);
154 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
)mBinder
);
155 requestedDownloads
.add(downloadKey
);
156 sendBroadcastNewDownload(newDownload
);
158 } catch (IllegalArgumentException e
) {
159 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
160 return START_NOT_STICKY
;
163 if (requestedDownloads
.size() > 0) {
164 Message msg
= mServiceHandler
.obtainMessage();
166 msg
.obj
= requestedDownloads
;
167 mServiceHandler
.sendMessage(msg
);
170 return START_NOT_STICKY
;
175 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
177 * Implemented to perform cancellation, pause and resume of existing downloads.
180 public IBinder
onBind(Intent arg0
) {
186 * Called when ALL the bound clients were onbound.
189 public boolean onUnbind(Intent intent
) {
190 ((FileDownloaderBinder
)mBinder
).clearListeners();
191 return false
; // not accepting rebinding (default behaviour)
196 * Binder to let client components to perform operations on the queue of downloads.
198 * It provides by itself the available operations.
200 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
203 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
205 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
209 * Cancels a pending or current download of a remote file.
211 * @param account Owncloud account where the remote file is stored.
212 * @param file A file in the queue of pending downloads
214 public void cancel(Account account
, OCFile file
) {
215 DownloadFileOperation download
= null
;
216 synchronized (mPendingDownloads
) {
217 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
219 if (download
!= null
) {
225 public void clearListeners() {
226 mBoundListeners
.clear();
231 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
233 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
235 * @param account Owncloud account where the remote file is stored.
236 * @param file A file that could be in the queue of downloads.
238 public boolean isDownloading(Account account
, OCFile file
) {
239 if (account
== null
|| file
== null
) return false
;
240 String targetKey
= buildRemoteName(account
, file
);
241 synchronized (mPendingDownloads
) {
242 if (file
.isFolder()) {
243 // this can be slow if there are many downloads :(
244 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
245 boolean found
= false
;
246 while (it
.hasNext() && !found
) {
247 found
= it
.next().startsWith(targetKey
);
251 return (mPendingDownloads
.containsKey(targetKey
));
258 * Adds a listener interested in the progress of the download for a concrete file.
260 * @param listener Object to notify about progress of transfer.
261 * @param account ownCloud account holding the file of interest.
262 * @param file {@link OCfile} of interest for listener.
264 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
265 if (account
== null
|| file
== null
|| listener
== null
) return;
266 String targetKey
= buildRemoteName(account
, file
);
267 mBoundListeners
.put(targetKey
, listener
);
272 * Removes a listener interested in the progress of the download for a concrete file.
274 * @param listener Object to notify about progress of transfer.
275 * @param account ownCloud account holding the file of interest.
276 * @param file {@link OCfile} of interest for listener.
278 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
279 if (account
== null
|| file
== null
|| listener
== null
) return;
280 String targetKey
= buildRemoteName(account
, file
);
281 if (mBoundListeners
.get(targetKey
) == listener
) {
282 mBoundListeners
.remove(targetKey
);
287 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
289 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
290 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
291 if (boundListener
!= null
) {
292 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
300 * Download worker. Performs the pending downloads in the order they were requested.
302 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
304 private static class ServiceHandler
extends Handler
{
305 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
306 FileDownloader mService
;
307 public ServiceHandler(Looper looper
, FileDownloader service
) {
310 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
315 public void handleMessage(Message msg
) {
316 @SuppressWarnings("unchecked")
317 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
318 if (msg
.obj
!= null
) {
319 Iterator
<String
> it
= requestedDownloads
.iterator();
320 while (it
.hasNext()) {
321 mService
.downloadFile(it
.next());
324 mService
.stopSelf(msg
.arg1
);
330 * Core download method: requests a file to download and stores it.
332 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
334 private void downloadFile(String downloadKey
) {
336 synchronized(mPendingDownloads
) {
337 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
340 if (mCurrentDownload
!= null
) {
342 notifyDownloadStart(mCurrentDownload
);
344 RemoteOperationResult downloadResult
= null
;
346 /// prepare client object to send the request to the ownCloud server
347 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
348 mLastAccount
= mCurrentDownload
.getAccount();
349 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
350 mDownloadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
353 /// perform the download
354 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
355 if (downloadResult
.isSuccess()) {
356 saveDownloadedFile();
359 } catch (AccountsException e
) {
360 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
361 downloadResult
= new RemoteOperationResult(e
);
362 } catch (IOException e
) {
363 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
364 downloadResult
= new RemoteOperationResult(e
);
367 synchronized(mPendingDownloads
) {
368 mPendingDownloads
.remove(downloadKey
);
374 notifyDownloadResult(mCurrentDownload
, downloadResult
);
376 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
382 * Updates the OC File after a successful download.
384 private void saveDownloadedFile() {
385 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
386 long syncDate
= System
.currentTimeMillis();
387 file
.setLastSyncDateForProperties(syncDate
);
388 file
.setLastSyncDateForData(syncDate
);
389 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
390 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
391 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
392 file
.setMimetype(mCurrentDownload
.getMimeType());
393 file
.setStoragePath(mCurrentDownload
.getSavePath());
394 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
395 mStorageManager
.saveFile(file
);
400 * Creates a status notification to show the download progress
402 * @param download Download operation starting.
404 private void notifyDownloadStart(DownloadFileOperation download
) {
405 /// create status notification with a progress bar
407 mNotification
= new Notification(DisplayUtils
.getSeasonalIconId(), getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
408 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
409 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
410 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, download
.getSize() < 0);
411 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, new File(download
.getSavePath()).getName()));
412 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, DisplayUtils
.getSeasonalIconId());
414 /// includes a pending intent in the notification showing the details view of the file
415 Intent showDetailsIntent
= null
;
416 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
417 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
419 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
421 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
422 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
423 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
424 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
426 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
431 * Callback method to update the progress bar in the status notification.
434 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
435 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
436 if (percent
!= mLastPercent
) {
437 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, totalToTransfer
< 0);
438 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
439 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
440 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
441 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
443 mLastPercent
= percent
;
448 * Updates the status notification with the result of a download operation.
450 * @param downloadResult Result of the download operation.
451 * @param download Finished download operation
453 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
454 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
455 if (!downloadResult
.isCancelled()) {
456 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
457 int contentId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
458 Notification finalNotification
= new Notification(DisplayUtils
.getSeasonalIconId(), getString(tickerId
), System
.currentTimeMillis());
459 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
460 boolean needsToUpdateCredentials
= (downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
461 // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
462 (downloadResult
.isIdPRedirection()
463 && mDownloadClient
.getCredentials() == null
));
464 //&& MainApp.getAuthTokenTypeSamlSessionCookie().equals(mDownloadClient.getAuthTokenType())));
465 if (needsToUpdateCredentials
) {
466 // let the user update credentials with one click
467 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
468 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
469 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
470 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
471 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
472 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
473 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
474 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
475 finalNotification
.setLatestEventInfo( getApplicationContext(),
477 String
.format(getString(contentId
), new File(download
.getSavePath()).getName()),
478 finalNotification
.contentIntent
);
479 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
482 Intent showDetailsIntent
= null
;
483 if (downloadResult
.isSuccess()) {
484 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
485 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
487 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
489 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
490 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
491 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
494 // TODO put something smart in showDetailsIntent
495 showDetailsIntent
= new Intent();
497 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
498 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), new File(download
.getSavePath()).getName()), finalNotification
.contentIntent
);
500 mNotificationManager
.notify(tickerId
, finalNotification
);
506 * Sends a broadcast when a download finishes in order to the interested activities can update their view
508 * @param download Finished download operation
509 * @param downloadResult Result of the download operation
511 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
512 Intent end
= new Intent(getDownloadFinishMessage());
513 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
514 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
515 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
516 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
517 sendStickyBroadcast(end
);
522 * Sends a broadcast when a new download is added to the queue.
524 * @param download Added download operation
526 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
527 Intent added
= new Intent(getDownloadAddedMessage());
528 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
529 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
530 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
531 sendStickyBroadcast(added
);