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
.ArrayList
;
25 import java
.util
.HashMap
;
26 import java
.util
.Iterator
;
28 import java
.util
.Vector
;
29 import java
.util
.concurrent
.ConcurrentHashMap
;
30 import java
.util
.concurrent
.ConcurrentMap
;
32 import com
.owncloud
.android
.R
;
33 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
38 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
39 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
40 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
41 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
42 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
43 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
44 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
45 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
46 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
47 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
48 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
49 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
50 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
51 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
52 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
54 import android
.accounts
.Account
;
55 import android
.accounts
.AccountsException
;
56 import android
.app
.NotificationManager
;
57 import android
.app
.PendingIntent
;
58 import android
.app
.Service
;
59 import android
.content
.Intent
;
60 import android
.os
.Binder
;
61 import android
.os
.Handler
;
62 import android
.os
.HandlerThread
;
63 import android
.os
.IBinder
;
64 import android
.os
.Looper
;
65 import android
.os
.Message
;
66 import android
.os
.Process
;
67 import android
.support
.v4
.app
.NotificationCompat
;
69 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
71 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
72 public static final String EXTRA_FILE
= "FILE";
74 public static final String ACTION_CANCEL_FILE_DOWNLOAD
= "CANCEL_FILE_DOWNLOAD";
76 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
77 private static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
78 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
79 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
80 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
81 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
83 private static final String TAG
= "FileDownloader";
85 private Looper mServiceLooper
;
86 private ServiceHandler mServiceHandler
;
87 private IBinder mBinder
;
88 private OwnCloudClient mDownloadClient
= null
;
89 private Account mLastAccount
= null
;
90 private FileDataStorageManager mStorageManager
;
92 private ConcurrentMap
<String
, DownloadFileOperation
> mPendingDownloads
= new ConcurrentHashMap
<String
, DownloadFileOperation
>();
93 private DownloadFileOperation mCurrentDownload
= null
;
95 private NotificationManager mNotificationManager
;
96 private NotificationCompat
.Builder mNotificationBuilder
;
97 private int mLastPercent
;
100 public static String
getDownloadAddedMessage() {
101 return FileDownloader
.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE
;
104 public static String
getDownloadFinishMessage() {
105 return FileDownloader
.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE
;
109 * Builds a key for mPendingDownloads from the account and file to download
111 * @param account Account where the file to download is stored
112 * @param file File to download
114 private String
buildRemoteName(Account account
, OCFile file
) {
115 return account
.name
+ file
.getRemotePath();
120 * Service initialization
123 public void onCreate() {
125 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
126 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
127 Process
.THREAD_PRIORITY_BACKGROUND
);
129 mServiceLooper
= thread
.getLooper();
130 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
131 mBinder
= new FileDownloaderBinder();
135 * Entry point to add one or several files to the queue of downloads.
137 * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
138 * although the caller activity goes away.
141 public int onStartCommand(Intent intent
, int flags
, int startId
) {
142 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
143 !intent
.hasExtra(EXTRA_FILE
)
144 /*!intent.hasExtra(EXTRA_FILE_PATH) ||
145 !intent.hasExtra(EXTRA_REMOTE_PATH)*/
147 Log_OC
.e(TAG
, "Not enough information provided in intent");
148 return START_NOT_STICKY
;
150 Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
151 OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
153 if (ACTION_CANCEL_FILE_DOWNLOAD
.equals(intent
.getAction())) {
155 // Cancel the download
156 cancel(account
,file
);
160 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)
161 String downloadKey
= buildRemoteName(account
, file
);
163 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
164 mPendingDownloads
.putIfAbsent(downloadKey
, newDownload
);
165 newDownload
.addDatatransferProgressListener(this);
166 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
167 requestedDownloads
.add(downloadKey
);
168 sendBroadcastNewDownload(newDownload
);
170 } catch (IllegalArgumentException e
) {
171 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
172 return START_NOT_STICKY
;
175 if (requestedDownloads
.size() > 0) {
176 Message msg
= mServiceHandler
.obtainMessage();
178 msg
.obj
= requestedDownloads
;
179 mServiceHandler
.sendMessage(msg
);
184 return START_NOT_STICKY
;
189 * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
191 * Implemented to perform cancellation, pause and resume of existing downloads.
194 public IBinder
onBind(Intent arg0
) {
200 * Called when ALL the bound clients were onbound.
203 public boolean onUnbind(Intent intent
) {
204 ((FileDownloaderBinder
)mBinder
).clearListeners();
205 return false
; // not accepting rebinding (default behaviour)
210 * Binder to let client components to perform operations on the queue of downloads.
212 * It provides by itself the available operations.
214 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
217 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
219 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
223 * Cancels a pending or current download of a remote file.
225 * @param account Owncloud account where the remote file is stored.
226 * @param file A file in the queue of pending downloads
228 public void cancel(Account account
, OCFile file
) {
229 DownloadFileOperation download
= null
;
230 synchronized (mPendingDownloads
) {
231 download
= mPendingDownloads
.remove(buildRemoteName(account
, file
));
233 if (download
!= null
) {
239 public void clearListeners() {
240 mBoundListeners
.clear();
245 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
247 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
249 * @param account Owncloud account where the remote file is stored.
250 * @param file A file that could be in the queue of downloads.
252 public boolean isDownloading(Account account
, OCFile file
) {
253 if (account
== null
|| file
== null
) return false
;
254 String targetKey
= buildRemoteName(account
, file
);
255 synchronized (mPendingDownloads
) {
256 if (file
.isFolder()) {
257 // this can be slow if there are many downloads :(
258 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
259 boolean found
= false
;
260 while (it
.hasNext() && !found
) {
261 found
= it
.next().startsWith(targetKey
);
265 return (mPendingDownloads
.containsKey(targetKey
));
272 * Adds 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 addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
279 if (account
== null
|| file
== null
|| listener
== null
) return;
280 String targetKey
= buildRemoteName(account
, file
);
281 mBoundListeners
.put(targetKey
, listener
);
286 * Removes a listener interested in the progress of the download for a concrete file.
288 * @param listener Object to notify about progress of transfer.
289 * @param account ownCloud account holding the file of interest.
290 * @param file {@link OCfile} of interest for listener.
292 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
293 if (account
== null
|| file
== null
|| listener
== null
) return;
294 String targetKey
= buildRemoteName(account
, file
);
295 if (mBoundListeners
.get(targetKey
) == listener
) {
296 mBoundListeners
.remove(targetKey
);
301 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
303 String key
= buildRemoteName(mCurrentDownload
.getAccount(), mCurrentDownload
.getFile());
304 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
305 if (boundListener
!= null
) {
306 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
314 * Download worker. Performs the pending downloads in the order they were requested.
316 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
318 private static class ServiceHandler
extends Handler
{
319 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
320 FileDownloader mService
;
321 public ServiceHandler(Looper looper
, FileDownloader service
) {
324 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
329 public void handleMessage(Message msg
) {
330 @SuppressWarnings("unchecked")
331 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
332 if (msg
.obj
!= null
) {
333 Iterator
<String
> it
= requestedDownloads
.iterator();
334 while (it
.hasNext()) {
335 mService
.downloadFile(it
.next());
338 mService
.stopSelf(msg
.arg1
);
344 * Core download method: requests a file to download and stores it.
346 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
348 private void downloadFile(String downloadKey
) {
350 synchronized(mPendingDownloads
) {
351 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
354 if (mCurrentDownload
!= null
) {
356 notifyDownloadStart(mCurrentDownload
);
358 RemoteOperationResult downloadResult
= null
;
360 /// prepare client object to send the request to the ownCloud server
361 if (mDownloadClient
== null
|| !mLastAccount
.equals(mCurrentDownload
.getAccount())) {
362 mLastAccount
= mCurrentDownload
.getAccount();
364 new FileDataStorageManager(mLastAccount
, getContentResolver());
365 OwnCloudAccount ocAccount
= new OwnCloudAccount(mLastAccount
, this);
366 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
367 getClientFor(ocAccount
, this);
370 /// perform the download
371 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
372 if (downloadResult
.isSuccess()) {
373 saveDownloadedFile();
376 } catch (AccountsException e
) {
377 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
378 downloadResult
= new RemoteOperationResult(e
);
379 } catch (IOException e
) {
380 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
381 downloadResult
= new RemoteOperationResult(e
);
384 synchronized(mPendingDownloads
) {
385 mPendingDownloads
.remove(downloadKey
);
391 notifyDownloadResult(mCurrentDownload
, downloadResult
);
393 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
);
399 * Updates the OC File after a successful download.
401 private void saveDownloadedFile() {
402 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
403 long syncDate
= System
.currentTimeMillis();
404 file
.setLastSyncDateForProperties(syncDate
);
405 file
.setLastSyncDateForData(syncDate
);
406 file
.setNeedsUpdateThumbnail(true
);
407 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
408 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
409 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
410 file
.setMimetype(mCurrentDownload
.getMimeType());
411 file
.setStoragePath(mCurrentDownload
.getSavePath());
412 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
413 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
414 mStorageManager
.saveFile(file
);
415 mStorageManager
.triggerMediaScan(file
.getStoragePath());
420 * Creates a status notification to show the download progress
422 * @param download Download operation starting.
424 private void notifyDownloadStart(DownloadFileOperation download
) {
425 /// create status notification with a progress bar
427 mNotificationBuilder
=
428 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
430 .setSmallIcon(R
.drawable
.notification_icon
)
431 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
432 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
434 .setProgress(100, 0, download
.getSize() < 0)
436 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
437 new File(download
.getSavePath()).getName())
440 /// includes a pending intent in the notification showing the details view of the file
441 Intent showDetailsIntent
= null
;
442 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
443 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
445 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
447 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
448 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
449 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
451 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
452 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
455 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
460 * Callback method to update the progress bar in the status notification.
463 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
464 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
465 if (percent
!= mLastPercent
) {
466 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
467 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
468 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
469 mNotificationBuilder
.setContentText(text
);
470 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
472 mLastPercent
= percent
;
477 * Updates the status notification with the result of a download operation.
479 * @param downloadResult Result of the download operation.
480 * @param download Finished download operation
482 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
483 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
484 if (!downloadResult
.isCancelled()) {
485 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
486 R
.string
.downloader_download_failed_ticker
;
488 boolean needsToUpdateCredentials
= (
489 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
490 downloadResult
.isIdPRedirection()
492 tickerId
= (needsToUpdateCredentials
) ?
493 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
496 .setTicker(getString(tickerId
))
497 .setContentTitle(getString(tickerId
))
500 .setProgress(0, 0, false
);
502 if (needsToUpdateCredentials
) {
504 // let the user update credentials with one click
505 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
506 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
507 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
508 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
509 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
510 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
512 .setContentIntent(PendingIntent
.getActivity(
513 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
515 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
518 // TODO put something smart in showDetailsIntent
519 Intent showDetailsIntent
= new Intent();
521 .setContentIntent(PendingIntent
.getActivity(
522 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
525 mNotificationBuilder
.setContentText(ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources()));
526 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
528 // Remove success notification
529 if (downloadResult
.isSuccess()) {
530 // Sleep 2 seconds, so show the notification before remove it
531 NotificationDelayer
.cancelWithDelay(
532 mNotificationManager
,
533 R
.string
.downloader_download_succeeded_ticker
,
542 * Sends a broadcast when a download finishes in order to the interested activities can update their view
544 * @param download Finished download operation
545 * @param downloadResult Result of the download operation
547 private void sendBroadcastDownloadFinished(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
548 Intent end
= new Intent(getDownloadFinishMessage());
549 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
550 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
551 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
552 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
553 sendStickyBroadcast(end
);
558 * Sends a broadcast when a new download is added to the queue.
560 * @param download Added download operation
562 private void sendBroadcastNewDownload(DownloadFileOperation download
) {
563 Intent added
= new Intent(getDownloadAddedMessage());
564 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
565 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
566 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
567 sendStickyBroadcast(added
);
572 * @param account Owncloud account where the remote file is stored.
573 * @param file File OCFile
575 public void cancel(Account account
, OCFile file
){
576 if(Looper
.myLooper() == Looper
.getMainLooper()) {
577 Log_OC
.d(TAG
, "Current Thread is Main Thread.");
579 Log_OC
.d(TAG
, "Current Thread is NOT Main Thread.");
582 DownloadFileOperation download
= null
;
583 String targetKey
= buildRemoteName(account
, file
);
584 ArrayList
<String
> keyItems
= new ArrayList
<String
>();
585 synchronized (mPendingDownloads
) {
586 if (file
.isFolder()) {
587 Log_OC
.d(TAG
, "Folder download. Canceling pending downloads (from folder)");
588 Iterator
<String
> it
= mPendingDownloads
.keySet().iterator();
589 boolean found
= false
;
590 while (it
.hasNext()) {
591 String keyDownloadOperation
= it
.next();
592 found
= keyDownloadOperation
.startsWith(targetKey
);
594 keyItems
.add(keyDownloadOperation
);
598 Log_OC
.d(TAG
, "Canceling file download");
599 keyItems
.add(buildRemoteName(account
, file
));
602 for (String item
: keyItems
) {
603 download
= mPendingDownloads
.remove(item
);
604 Log_OC
.d(TAG
, "Key removed: " + item
);
606 if (download
!= null
) {