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 "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
140 "Received request to download file"
144 if (ACTION_CANCEL_FILE_DOWNLOAD.equals(intent.getAction())) {
146 new Thread(new Runnable() {
148 // Cancel the download
149 cancel(account, file);
156 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
158 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
159 newDownload
.addDatatransferProgressListener(this);
160 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
161 Pair
<String
, String
> putResult
= mPendingDownloads
.putIfAbsent(
162 account
, file
.getRemotePath(), newDownload
164 String downloadKey
= putResult
.first
;
165 requestedDownloads
.add(downloadKey
);
167 "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
168 "Download on " + file
.getRemotePath() + " added to queue"
171 // Store file on db with state 'downloading'
173 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
174 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
175 file.setDownloading(true);
176 storageManager.saveFile(file);
179 sendBroadcastNewDownload(newDownload
, putResult
.second
);
181 } catch (IllegalArgumentException e
) {
182 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
183 return START_NOT_STICKY
;
186 if (requestedDownloads
.size() > 0) {
187 Message msg
= mServiceHandler
.obtainMessage();
189 msg
.obj
= requestedDownloads
;
190 mServiceHandler
.sendMessage(msg
);
195 return START_NOT_STICKY
;
200 * Provides a binder object that clients can use to perform operations on the queue of downloads,
201 * excepting the addition of new files.
203 * Implemented to perform cancellation, pause and resume of existing downloads.
206 public IBinder
onBind(Intent arg0
) {
212 * Called when ALL the bound clients were onbound.
215 public boolean onUnbind(Intent intent
) {
216 ((FileDownloaderBinder
)mBinder
).clearListeners();
217 return false
; // not accepting rebinding (default behaviour)
222 * Binder to let client components to perform operations on the queue of downloads.
224 * It provides by itself the available operations.
226 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
229 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
232 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
233 new HashMap
<Long
, OnDatatransferProgressListener
>();
237 * Cancels a pending or current download of a remote file.
239 * @param account ownCloud account where the remote file is stored.
240 * @param file A file in the queue of pending downloads
242 public void cancel(Account account
, OCFile file
) {
244 "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
245 "Received request to cancel download of " + file
.getRemotePath()
247 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
248 "Removing download of " + file
.getRemotePath());
249 Pair
<DownloadFileOperation
, String
> removeResult
= mPendingDownloads
.remove(account
, file
.getRemotePath());
250 DownloadFileOperation download
= removeResult
.first
;
251 if (download
!= null
) {
252 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
253 "Canceling returned download of " + file
.getRemotePath());
256 if (mCurrentDownload
!= null
&& mCurrentAccount
!= null
&&
257 mCurrentDownload
.getRemotePath().startsWith(file
.getRemotePath()) &&
258 account
.name
.equals(mCurrentAccount
.name
)) {
259 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
260 "Canceling current sync as descendant: " + mCurrentDownload
.getRemotePath());
261 mCurrentDownload
.cancel();
267 public void clearListeners() {
268 mBoundListeners
.clear();
273 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
274 * waiting to download.
276 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
277 * waiting to download.
279 * @param account ownCloud account where the remote file is stored.
280 * @param file A file that could be in the queue of downloads.
282 public boolean isDownloading(Account account
, OCFile file
) {
283 if (account
== null
|| file
== null
) return false
;
284 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
289 * Adds a listener interested in the progress of the download for a concrete file.
291 * @param listener Object to notify about progress of transfer.
292 * @param account ownCloud account holding the file of interest.
293 * @param file {@link OCFile} of interest for listener.
295 public void addDatatransferProgressListener (
296 OnDatatransferProgressListener listener
, Account account
, OCFile file
298 if (account
== null
|| file
== null
|| listener
== null
) return;
299 //String targetKey = buildKey(account, file.getRemotePath());
300 mBoundListeners
.put(file
.getFileId(), listener
);
305 * Removes a listener interested in the progress of the download for a concrete file.
307 * @param listener Object to notify about progress of transfer.
308 * @param account ownCloud account holding the file of interest.
309 * @param file {@link OCFile} of interest for listener.
311 public void removeDatatransferProgressListener (
312 OnDatatransferProgressListener listener
, Account account
, OCFile file
314 if (account
== null
|| file
== null
|| listener
== null
) return;
315 //String targetKey = buildKey(account, file.getRemotePath());
316 Long fileId
= file
.getFileId();
317 if (mBoundListeners
.get(fileId
) == listener
) {
318 mBoundListeners
.remove(fileId
);
323 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
325 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
326 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
327 if (boundListener
!= null
) {
328 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
336 * Download worker. Performs the pending downloads in the order they were requested.
338 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
340 private static class ServiceHandler
extends Handler
{
341 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
342 FileDownloader mService
;
343 public ServiceHandler(Looper looper
, FileDownloader service
) {
346 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
351 public void handleMessage(Message msg
) {
352 @SuppressWarnings("unchecked")
353 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
354 if (msg
.obj
!= null
) {
355 Iterator
<String
> it
= requestedDownloads
.iterator();
356 while (it
.hasNext()) {
357 String next
= it
.next();
358 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
359 "Handling download file " + next
);
360 mService
.downloadFile(next
);
363 mService
.stopSelf(msg
.arg1
);
369 * Core download method: requests a file to download and stores it.
371 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
373 private void downloadFile(String downloadKey
) {
375 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
376 "Getting download of " + downloadKey
);
377 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
379 if (mCurrentDownload
!= null
) {
381 notifyDownloadStart(mCurrentDownload
);
383 RemoteOperationResult downloadResult
= null
;
385 /// prepare client object to send the request to the ownCloud server
386 if (mDownloadClient
== null
|| !mCurrentAccount
.equals(mCurrentDownload
.getAccount())) {
387 mCurrentAccount
= mCurrentDownload
.getAccount();
389 new FileDataStorageManager(mCurrentAccount
, getContentResolver());
390 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
391 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
392 getClientFor(ocAccount
, this);
395 /// perform the download
396 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
397 "Executing download of " + mCurrentDownload
.getRemotePath());
398 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
399 if (downloadResult
.isSuccess()) {
400 saveDownloadedFile();
402 updateUnsuccessfulDownloadedFile();
406 } catch (AccountsException e
) {
407 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
408 downloadResult
= new RemoteOperationResult(e
);
409 } catch (IOException e
) {
410 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
411 downloadResult
= new RemoteOperationResult(e
);
414 Log_OC
.v( "NOW " + TAG
+ ", thread " + Thread
.currentThread().getName(),
415 "Removing payload " + mCurrentDownload
.getRemotePath());
417 Pair
<DownloadFileOperation
, String
> removeResult
=
418 mPendingDownloads
.removePayload(mCurrentAccount
, mCurrentDownload
.getRemotePath());
421 notifyDownloadResult(mCurrentDownload
, downloadResult
);
423 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
, removeResult
.second
);
431 * Updates the OC File after a successful download.
433 private void saveDownloadedFile() {
434 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
435 long syncDate
= System
.currentTimeMillis();
436 file
.setLastSyncDateForProperties(syncDate
);
437 file
.setLastSyncDateForData(syncDate
);
438 file
.setNeedsUpdateThumbnail(true
);
439 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
440 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
441 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
442 file
.setMimetype(mCurrentDownload
.getMimeType());
443 file
.setStoragePath(mCurrentDownload
.getSavePath());
444 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
445 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
446 //file.setDownloading(false);
447 mStorageManager
.saveFile(file
);
448 mStorageManager
.triggerMediaScan(file
.getStoragePath());
452 * Update the OC File after a unsuccessful download
454 private void updateUnsuccessfulDownloadedFile() {
455 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
456 file
.setDownloading(false
);
457 mStorageManager
.saveFile(file
);
462 * Creates a status notification to show the download progress
464 * @param download Download operation starting.
466 private void notifyDownloadStart(DownloadFileOperation download
) {
467 /// create status notification with a progress bar
469 mNotificationBuilder
=
470 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
472 .setSmallIcon(R
.drawable
.notification_icon
)
473 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
474 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
476 .setProgress(100, 0, download
.getSize() < 0)
478 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
479 new File(download
.getSavePath()).getName())
482 /// includes a pending intent in the notification showing the details view of the file
483 Intent showDetailsIntent
= null
;
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
);
493 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
494 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
497 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
502 * Callback method to update the progress bar in the status notification.
505 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
)
507 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
508 if (percent
!= mLastPercent
) {
509 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
510 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
511 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
512 mNotificationBuilder
.setContentText(text
);
513 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
515 mLastPercent
= percent
;
520 * Updates the status notification with the result of a download operation.
522 * @param downloadResult Result of the download operation.
523 * @param download Finished download operation
525 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
526 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
527 if (!downloadResult
.isCancelled()) {
528 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
529 R
.string
.downloader_download_failed_ticker
;
531 boolean needsToUpdateCredentials
= (
532 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
533 downloadResult
.isIdPRedirection()
535 tickerId
= (needsToUpdateCredentials
) ?
536 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
539 .setTicker(getString(tickerId
))
540 .setContentTitle(getString(tickerId
))
543 .setProgress(0, 0, false
);
545 if (needsToUpdateCredentials
) {
547 // let the user update credentials with one click
548 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
549 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
550 updateAccountCredentials
.putExtra(
551 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
553 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
554 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
555 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
557 .setContentIntent(PendingIntent
.getActivity(
558 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
560 mDownloadClient
= null
; // grant that future retries on the same account will get the fresh credentials
563 // TODO put something smart in showDetailsIntent
564 Intent showDetailsIntent
= new Intent();
566 .setContentIntent(PendingIntent
.getActivity(
567 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
570 mNotificationBuilder
.setContentText(
571 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
573 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
575 // Remove success notification
576 if (downloadResult
.isSuccess()) {
577 // Sleep 2 seconds, so show the notification before remove it
578 NotificationDelayer
.cancelWithDelay(
579 mNotificationManager
,
580 R
.string
.downloader_download_succeeded_ticker
,
589 * Sends a broadcast when a download finishes in order to the interested activities can update their view
591 * @param download Finished download operation
592 * @param downloadResult Result of the download operation
593 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
595 private void sendBroadcastDownloadFinished(
596 DownloadFileOperation download
,
597 RemoteOperationResult downloadResult
,
598 String unlinkedFromRemotePath
) {
599 Intent end
= new Intent(getDownloadFinishMessage());
600 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
601 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
602 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
603 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
604 if (unlinkedFromRemotePath
!= null
) {
605 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
607 sendStickyBroadcast(end
);
612 * Sends a broadcast when a new download is added to the queue.
614 * @param download Added download operation
615 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
617 private void sendBroadcastNewDownload(DownloadFileOperation download
, String linkedToRemotePath
) {
618 Intent added
= new Intent(getDownloadAddedMessage());
619 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
620 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
621 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
622 added
.putExtra(EXTRA_LINKED_TO_PATH
, linkedToRemotePath
);
623 sendStickyBroadcast(added
);