1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2015 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
;
29 import com
.owncloud
.android
.R
;
30 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
31 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
32 import com
.owncloud
.android
.datamodel
.OCFile
;
34 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
35 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
36 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
38 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
39 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
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
.common
.utils
.Log_OC
;
43 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
44 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
45 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
46 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
47 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
48 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
49 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
51 import android
.accounts
.Account
;
52 import android
.accounts
.AccountsException
;
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
.support
.v4
.app
.NotificationCompat
;
65 import android
.util
.Pair
;
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 EXTRA_LINKED_TO_PATH
= "LINKED_TO";
78 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
80 private static final String TAG
= "FileDownloader";
82 private Looper mServiceLooper
;
83 private ServiceHandler mServiceHandler
;
84 private IBinder mBinder
;
85 private OwnCloudClient mDownloadClient
= null
;
86 private Account mCurrentAccount
= null
;
87 private FileDataStorageManager mStorageManager
;
89 private IndexedForest
<DownloadFileOperation
> mPendingDownloads
= new IndexedForest
<DownloadFileOperation
>();
91 private DownloadFileOperation mCurrentDownload
= null
;
93 private NotificationManager mNotificationManager
;
94 private NotificationCompat
.Builder mNotificationBuilder
;
95 private int mLastPercent
;
98 public static String
getDownloadAddedMessage() {
99 return FileDownloader
.class.getName() + DOWNLOAD_ADDED_MESSAGE
;
102 public static String
getDownloadFinishMessage() {
103 return FileDownloader
.class.getName() + DOWNLOAD_FINISH_MESSAGE
;
107 * Service initialization
110 public void onCreate() {
112 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
113 HandlerThread thread
= new HandlerThread("FileDownloaderThread",
114 Process
.THREAD_PRIORITY_BACKGROUND
);
116 mServiceLooper
= thread
.getLooper();
117 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
118 mBinder
= new FileDownloaderBinder();
122 * Entry point to add one or several files to the queue of downloads.
124 * New downloads are added calling to startService(), resulting in a call to this method.
125 * This ensures the service will keep on working although the caller activity goes away.
128 public int onStartCommand(Intent intent
, int flags
, int startId
) {
129 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
130 !intent
.hasExtra(EXTRA_FILE
)
132 Log_OC
.e(TAG
, "Not enough information provided in intent");
133 return START_NOT_STICKY
;
135 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
136 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
139 if (ACTION_CANCEL_FILE_DOWNLOAD.equals(intent.getAction())) {
141 new Thread(new Runnable() {
143 // Cancel the download
144 cancel(account, file);
151 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
153 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
154 newDownload
.addDatatransferProgressListener(this);
155 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
156 Pair
<String
, String
> putResult
= mPendingDownloads
.putIfAbsent(
157 account
, file
.getRemotePath(), newDownload
159 String downloadKey
= putResult
.first
;
160 requestedDownloads
.add(downloadKey
);
162 // Store file on db with state 'downloading'
164 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
165 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
166 file.setDownloading(true);
167 storageManager.saveFile(file);
170 sendBroadcastNewDownload(newDownload
, putResult
.second
);
172 } catch (IllegalArgumentException e
) {
173 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
174 return START_NOT_STICKY
;
177 if (requestedDownloads
.size() > 0) {
178 Message msg
= mServiceHandler
.obtainMessage();
180 msg
.obj
= requestedDownloads
;
181 mServiceHandler
.sendMessage(msg
);
186 return START_NOT_STICKY
;
191 * Provides a binder object that clients can use to perform operations on the queue of downloads,
192 * excepting the addition of new files.
194 * Implemented to perform cancellation, pause and resume of existing downloads.
197 public IBinder
onBind(Intent arg0
) {
203 * Called when ALL the bound clients were onbound.
206 public boolean onUnbind(Intent intent
) {
207 ((FileDownloaderBinder
)mBinder
).clearListeners();
208 return false
; // not accepting rebinding (default behaviour)
213 * Binder to let client components to perform operations on the queue of downloads.
215 * It provides by itself the available operations.
217 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
220 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
223 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
224 new HashMap
<Long
, OnDatatransferProgressListener
>();
228 * Cancels a pending or current download of a remote file.
230 * @param account ownCloud account where the remote file is stored.
231 * @param file A file in the queue of pending downloads
233 public void cancel(Account account
, OCFile file
) {
234 Pair
<DownloadFileOperation
, String
> removeResult
= mPendingDownloads
.remove(account
, file
.getRemotePath());
235 DownloadFileOperation download
= removeResult
.first
;
236 if (download
!= null
) {
239 if (mCurrentDownload
!= null
&& mCurrentAccount
!= null
&&
240 mCurrentDownload
.getRemotePath().startsWith(file
.getRemotePath()) &&
241 account
.name
.equals(mCurrentAccount
.name
)) {
242 mCurrentDownload
.cancel();
248 public void clearListeners() {
249 mBoundListeners
.clear();
254 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
255 * waiting to download.
257 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
258 * waiting to download.
260 * @param account ownCloud account where the remote file is stored.
261 * @param file A file that could be in the queue of downloads.
263 public boolean isDownloading(Account account
, OCFile file
) {
264 if (account
== null
|| file
== null
) return false
;
265 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
270 * Adds a listener interested in the progress of the download for a concrete file.
272 * @param listener Object to notify about progress of transfer.
273 * @param account ownCloud account holding the file of interest.
274 * @param file {@link OCFile} of interest for listener.
276 public void addDatatransferProgressListener (
277 OnDatatransferProgressListener listener
, Account account
, OCFile file
279 if (account
== null
|| file
== null
|| listener
== null
) return;
280 //String targetKey = buildKey(account, file.getRemotePath());
281 mBoundListeners
.put(file
.getFileId(), 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 (
293 OnDatatransferProgressListener listener
, Account account
, OCFile file
295 if (account
== null
|| file
== null
|| listener
== null
) return;
296 //String targetKey = buildKey(account, file.getRemotePath());
297 Long fileId
= file
.getFileId();
298 if (mBoundListeners
.get(fileId
) == listener
) {
299 mBoundListeners
.remove(fileId
);
304 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
306 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
307 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
308 if (boundListener
!= null
) {
309 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
317 * Download worker. Performs the pending downloads in the order they were requested.
319 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
321 private static class ServiceHandler
extends Handler
{
322 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
323 FileDownloader mService
;
324 public ServiceHandler(Looper looper
, FileDownloader service
) {
327 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
332 public void handleMessage(Message msg
) {
333 @SuppressWarnings("unchecked")
334 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
335 if (msg
.obj
!= null
) {
336 Iterator
<String
> it
= requestedDownloads
.iterator();
337 while (it
.hasNext()) {
338 mService
.downloadFile(it
.next());
341 mService
.stopSelf(msg
.arg1
);
347 * Core download method: requests a file to download and stores it.
349 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
351 private void downloadFile(String downloadKey
) {
353 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
355 if (mCurrentDownload
!= null
) {
357 notifyDownloadStart(mCurrentDownload
);
359 RemoteOperationResult downloadResult
= null
;
361 /// prepare client object to send the request to the ownCloud server
362 if (mDownloadClient
== null
|| !mCurrentAccount
.equals(mCurrentDownload
.getAccount())) {
363 mCurrentAccount
= mCurrentDownload
.getAccount();
365 new FileDataStorageManager(mCurrentAccount
, getContentResolver());
366 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
367 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
368 getClientFor(ocAccount
, this);
371 /// perform the download
372 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
373 if (downloadResult
.isSuccess()) {
374 saveDownloadedFile();
376 updateUnsuccessfulDownloadedFile();
380 } catch (AccountsException e
) {
381 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
382 downloadResult
= new RemoteOperationResult(e
);
383 } catch (IOException e
) {
384 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
385 downloadResult
= new RemoteOperationResult(e
);
388 Pair
<DownloadFileOperation
, String
> removeResult
=
389 mPendingDownloads
.removePayload(mCurrentAccount
, mCurrentDownload
.getRemotePath());
392 notifyDownloadResult(mCurrentDownload
, downloadResult
);
394 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
, removeResult
.second
);
402 * Updates the OC File after a successful download.
404 private void saveDownloadedFile() {
405 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
406 long syncDate
= System
.currentTimeMillis();
407 file
.setLastSyncDateForProperties(syncDate
);
408 file
.setLastSyncDateForData(syncDate
);
409 file
.setNeedsUpdateThumbnail(true
);
410 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
411 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
412 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
413 file
.setMimetype(mCurrentDownload
.getMimeType());
414 file
.setStoragePath(mCurrentDownload
.getSavePath());
415 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
416 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
417 //file.setDownloading(false);
418 mStorageManager
.saveFile(file
);
419 mStorageManager
.triggerMediaScan(file
.getStoragePath());
423 * Update the OC File after a unsuccessful download
425 private void updateUnsuccessfulDownloadedFile() {
426 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
427 file
.setDownloading(false
);
428 mStorageManager
.saveFile(file
);
433 * Creates a status notification to show the download progress
435 * @param download Download operation starting.
437 private void notifyDownloadStart(DownloadFileOperation download
) {
438 /// create status notification with a progress bar
440 mNotificationBuilder
=
441 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
443 .setSmallIcon(R
.drawable
.notification_icon
)
444 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
445 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
447 .setProgress(100, 0, download
.getSize() < 0)
449 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
450 new File(download
.getSavePath()).getName())
453 /// includes a pending intent in the notification showing the details view of the file
454 Intent showDetailsIntent
= null
;
455 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
456 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
458 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
460 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
461 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
462 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
464 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
465 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
468 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
473 * Callback method to update the progress bar in the status notification.
476 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
)
478 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
479 if (percent
!= mLastPercent
) {
480 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
481 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
482 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
483 mNotificationBuilder
.setContentText(text
);
484 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
486 mLastPercent
= percent
;
491 * Updates the status notification with the result of a download operation.
493 * @param downloadResult Result of the download operation.
494 * @param download Finished download operation
496 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
497 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
498 if (!downloadResult
.isCancelled()) {
499 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
500 R
.string
.downloader_download_failed_ticker
;
502 boolean needsToUpdateCredentials
= (
503 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
504 downloadResult
.isIdPRedirection()
506 tickerId
= (needsToUpdateCredentials
) ?
507 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
510 .setTicker(getString(tickerId
))
511 .setContentTitle(getString(tickerId
))
514 .setProgress(0, 0, false
);
516 if (needsToUpdateCredentials
) {
518 // let the user update credentials with one click
519 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
520 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
521 updateAccountCredentials
.putExtra(
522 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
524 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
525 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
526 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
528 .setContentIntent(PendingIntent
.getActivity(
529 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
531 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
534 // TODO put something smart in showDetailsIntent
535 Intent showDetailsIntent
= new Intent();
537 .setContentIntent(PendingIntent
.getActivity(
538 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
541 mNotificationBuilder
.setContentText(
542 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
544 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
546 // Remove success notification
547 if (downloadResult
.isSuccess()) {
548 // Sleep 2 seconds, so show the notification before remove it
549 NotificationDelayer
.cancelWithDelay(
550 mNotificationManager
,
551 R
.string
.downloader_download_succeeded_ticker
,
560 * Sends a broadcast when a download finishes in order to the interested activities can update their view
562 * @param download Finished download operation
563 * @param downloadResult Result of the download operation
564 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
566 private void sendBroadcastDownloadFinished(
567 DownloadFileOperation download
,
568 RemoteOperationResult downloadResult
,
569 String unlinkedFromRemotePath
) {
570 Intent end
= new Intent(getDownloadFinishMessage());
571 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
572 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
573 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
574 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
575 if (unlinkedFromRemotePath
!= null
) {
576 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
578 sendStickyBroadcast(end
);
583 * Sends a broadcast when a new download is added to the queue.
585 * @param download Added download operation
586 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
588 private void sendBroadcastNewDownload(DownloadFileOperation download
, String linkedToRemotePath
) {
589 Intent added
= new Intent(getDownloadAddedMessage());
590 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
591 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
592 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
593 added
.putExtra(EXTRA_LINKED_TO_PATH
, linkedToRemotePath
);
594 sendStickyBroadcast(added
);
599 * @param account ownCloud account where the remote file is stored.
600 * @param file File OCFile
602 public void cancel(Account account, OCFile file){
603 DownloadFileOperation download = null;
604 //String targetKey = buildKey(account, file.getRemotePath());
605 ArrayList<String> keyItems = new ArrayList<String>();
606 if (file.isFolder()) {
607 Log_OC.d(TAG, "Folder download. Canceling pending downloads (from folder)");
611 Iterator<String> it = mPendingDownloads.keySet().iterator();
612 boolean found = false;
613 while (it.hasNext()) {
614 String keyDownloadOperation = it.next();
615 found = keyDownloadOperation.startsWith(targetKey);
617 keyItems.add(keyDownloadOperation);
621 for (String item: keyItems) {
622 download = mPendingDownloads.remove(item);
623 Log_OC.d(TAG, "Key removed: " + item);
625 if (download != null) {
633 // this is not really expected...
634 Log_OC.d(TAG, "Canceling file download");
635 download = mPendingDownloads.remove(account, file.getRemotePath());
636 if (download != null) {