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 Log_OC
.d(TAG
, "Creating service");
113 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
114 HandlerThread thread
= new HandlerThread("FileDownloaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
116 mServiceLooper
= thread
.getLooper();
117 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
118 mBinder
= new FileDownloaderBinder();
126 public void onDestroy() {
127 Log_OC
.v(TAG
, "Destroying service" );
129 mServiceHandler
= null
;
130 mServiceLooper
.quit();
131 mServiceLooper
= null
;
132 mNotificationManager
= null
;
138 * Entry point to add one or several files to the queue of downloads.
140 * New downloads are added calling to startService(), resulting in a call to this method.
141 * This ensures the service will keep on working although the caller activity goes away.
144 public int onStartCommand(Intent intent
, int flags
, int startId
) {
145 Log_OC
.d(TAG
, "Starting command with id " + startId
);
147 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
148 !intent
.hasExtra(EXTRA_FILE
)
150 Log_OC
.e(TAG
, "Not enough information provided in intent");
151 return START_NOT_STICKY
;
153 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
154 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
157 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
158 "Received request to download file"
161 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
163 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
164 newDownload
.addDatatransferProgressListener(this);
165 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
166 Pair
<String
, String
> putResult
= mPendingDownloads
.putIfAbsent(
167 account
, file
.getRemotePath(), newDownload
169 String downloadKey
= putResult
.first
;
170 requestedDownloads
.add(downloadKey
);
172 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
173 "Download on " + file.getRemotePath() + " added to queue"
176 // Store file on db with state 'downloading'
178 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
179 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
180 file.setDownloading(true);
181 storageManager.saveFile(file);
184 sendBroadcastNewDownload(newDownload
, putResult
.second
);
186 } catch (IllegalArgumentException e
) {
187 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
188 return START_NOT_STICKY
;
191 if (requestedDownloads
.size() > 0) {
192 Message msg
= mServiceHandler
.obtainMessage();
194 msg
.obj
= requestedDownloads
;
195 mServiceHandler
.sendMessage(msg
);
200 return START_NOT_STICKY
;
205 * Provides a binder object that clients can use to perform operations on the queue of downloads,
206 * excepting the addition of new files.
208 * Implemented to perform cancellation, pause and resume of existing downloads.
211 public IBinder
onBind(Intent arg0
) {
217 * Called when ALL the bound clients were onbound.
220 public boolean onUnbind(Intent intent
) {
221 ((FileDownloaderBinder
)mBinder
).clearListeners();
222 return false
; // not accepting rebinding (default behaviour)
227 * Binder to let client components to perform operations on the queue of downloads.
229 * It provides by itself the available operations.
231 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
234 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
237 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
238 new HashMap
<Long
, OnDatatransferProgressListener
>();
242 * Cancels a pending or current download of a remote file.
244 * @param account ownCloud account where the remote file is stored.
245 * @param file A file in the queue of pending downloads
247 public void cancel(Account account
, OCFile file
) {
249 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
250 "Received request to cancel download of " + file.getRemotePath()
252 Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
253 "Removing download of " + file.getRemotePath());*/
254 Pair
<DownloadFileOperation
, String
> removeResult
= mPendingDownloads
.remove(account
, file
.getRemotePath());
255 DownloadFileOperation download
= removeResult
.first
;
256 if (download
!= null
) {
257 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
258 "Canceling returned download of " + file.getRemotePath());*/
261 if (mCurrentDownload
!= null
&& mCurrentAccount
!= null
&&
262 mCurrentDownload
.getRemotePath().startsWith(file
.getRemotePath()) &&
263 account
.name
.equals(mCurrentAccount
.name
)) {
264 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
265 "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/
266 mCurrentDownload
.cancel();
272 public void clearListeners() {
273 mBoundListeners
.clear();
278 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
279 * waiting to download.
281 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
282 * waiting to download.
284 * @param account ownCloud account where the remote file is stored.
285 * @param file A file that could be in the queue of downloads.
287 public boolean isDownloading(Account account
, OCFile file
) {
288 if (account
== null
|| file
== null
) return false
;
289 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
294 * Adds a listener interested in the progress of the download for a concrete file.
296 * @param listener Object to notify about progress of transfer.
297 * @param account ownCloud account holding the file of interest.
298 * @param file {@link OCFile} of interest for listener.
300 public void addDatatransferProgressListener (
301 OnDatatransferProgressListener listener
, Account account
, OCFile file
303 if (account
== null
|| file
== null
|| listener
== null
) return;
304 //String targetKey = buildKey(account, file.getRemotePath());
305 mBoundListeners
.put(file
.getFileId(), listener
);
310 * Removes a listener interested in the progress of the download for a concrete file.
312 * @param listener Object to notify about progress of transfer.
313 * @param account ownCloud account holding the file of interest.
314 * @param file {@link OCFile} of interest for listener.
316 public void removeDatatransferProgressListener (
317 OnDatatransferProgressListener listener
, Account account
, OCFile file
319 if (account
== null
|| file
== null
|| listener
== null
) return;
320 //String targetKey = buildKey(account, file.getRemotePath());
321 Long fileId
= file
.getFileId();
322 if (mBoundListeners
.get(fileId
) == listener
) {
323 mBoundListeners
.remove(fileId
);
328 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
330 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
331 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
332 if (boundListener
!= null
) {
333 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
341 * Download worker. Performs the pending downloads in the order they were requested.
343 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
345 private static class ServiceHandler
extends Handler
{
346 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
347 FileDownloader mService
;
348 public ServiceHandler(Looper looper
, FileDownloader service
) {
351 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
356 public void handleMessage(Message msg
) {
357 @SuppressWarnings("unchecked")
358 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
359 if (msg
.obj
!= null
) {
360 Iterator
<String
> it
= requestedDownloads
.iterator();
361 while (it
.hasNext()) {
362 String next
= it
.next();
363 mService
.downloadFile(next
);
366 Log_OC
.d(TAG
, "Stopping after command with id " + msg
.arg1
);
367 mService
.stopSelf(msg
.arg1
);
373 * Core download method: requests a file to download and stores it.
375 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
377 private void downloadFile(String downloadKey
) {
379 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
380 "Getting download of " + downloadKey);*/
381 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
383 if (mCurrentDownload
!= null
) {
385 notifyDownloadStart(mCurrentDownload
);
387 RemoteOperationResult downloadResult
= null
;
389 /// prepare client object to send the request to the ownCloud server
390 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentDownload
.getAccount())) {
391 mCurrentAccount
= mCurrentDownload
.getAccount();
392 mStorageManager
= new FileDataStorageManager(
396 } // else, reuse storage manager from previous operation
398 // always get client from client manager, to get fresh credentials in case of update
399 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
400 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
401 getClientFor(ocAccount
, this);
404 /// perform the download
405 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
406 "Executing download of " + mCurrentDownload.getRemotePath());*/
407 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
408 if (downloadResult
.isSuccess()) {
409 saveDownloadedFile();
412 } catch (AccountsException e
) {
413 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
414 downloadResult
= new RemoteOperationResult(e
);
415 } catch (IOException e
) {
416 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
417 downloadResult
= new RemoteOperationResult(e
);
420 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
421 "Removing payload " + mCurrentDownload.getRemotePath());*/
423 Pair
<DownloadFileOperation
, String
> removeResult
=
424 mPendingDownloads
.removePayload(mCurrentAccount
, mCurrentDownload
.getRemotePath());
427 notifyDownloadResult(mCurrentDownload
, downloadResult
);
429 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
, removeResult
.second
);
437 * Updates the OC File after a successful download.
439 private void saveDownloadedFile() {
440 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
441 long syncDate
= System
.currentTimeMillis();
442 file
.setLastSyncDateForProperties(syncDate
);
443 file
.setLastSyncDateForData(syncDate
);
444 file
.setNeedsUpdateThumbnail(true
);
445 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
446 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
447 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
448 file
.setMimetype(mCurrentDownload
.getMimeType());
449 file
.setStoragePath(mCurrentDownload
.getSavePath());
450 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
451 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
452 mStorageManager
.saveFile(file
);
453 mStorageManager
.triggerMediaScan(file
.getStoragePath());
457 * Update the OC File after a unsuccessful download
459 private void updateUnsuccessfulDownloadedFile() {
460 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
461 file
.setDownloading(false
);
462 mStorageManager
.saveFile(file
);
467 * Creates a status notification to show the download progress
469 * @param download Download operation starting.
471 private void notifyDownloadStart(DownloadFileOperation download
) {
472 /// create status notification with a progress bar
474 mNotificationBuilder
=
475 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
477 .setSmallIcon(R
.drawable
.notification_icon
)
478 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
479 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
481 .setProgress(100, 0, download
.getSize() < 0)
483 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
484 new File(download
.getSavePath()).getName())
487 /// includes a pending intent in the notification showing the details view of the file
488 Intent showDetailsIntent
= null
;
489 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
490 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
492 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
494 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
495 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
496 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
498 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
499 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
502 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
507 * Callback method to update the progress bar in the status notification.
510 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
)
512 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
513 if (percent
!= mLastPercent
) {
514 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
515 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
516 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
517 mNotificationBuilder
.setContentText(text
);
518 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
520 mLastPercent
= percent
;
525 * Updates the status notification with the result of a download operation.
527 * @param downloadResult Result of the download operation.
528 * @param download Finished download operation
530 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
531 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
532 if (!downloadResult
.isCancelled()) {
533 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
534 R
.string
.downloader_download_failed_ticker
;
536 boolean needsToUpdateCredentials
= (
537 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
538 downloadResult
.isIdPRedirection()
540 tickerId
= (needsToUpdateCredentials
) ?
541 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
544 .setTicker(getString(tickerId
))
545 .setContentTitle(getString(tickerId
))
548 .setProgress(0, 0, false
);
550 if (needsToUpdateCredentials
) {
552 // let the user update credentials with one click
553 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
554 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
555 updateAccountCredentials
.putExtra(
556 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
558 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
559 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
560 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
562 .setContentIntent(PendingIntent
.getActivity(
563 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
566 // TODO put something smart in showDetailsIntent
567 Intent showDetailsIntent
= new Intent();
569 .setContentIntent(PendingIntent
.getActivity(
570 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
573 mNotificationBuilder
.setContentText(
574 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
576 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
578 // Remove success notification
579 if (downloadResult
.isSuccess()) {
580 // Sleep 2 seconds, so show the notification before remove it
581 NotificationDelayer
.cancelWithDelay(
582 mNotificationManager
,
583 R
.string
.downloader_download_succeeded_ticker
,
592 * Sends a broadcast when a download finishes in order to the interested activities can update their view
594 * @param download Finished download operation
595 * @param downloadResult Result of the download operation
596 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
598 private void sendBroadcastDownloadFinished(
599 DownloadFileOperation download
,
600 RemoteOperationResult downloadResult
,
601 String unlinkedFromRemotePath
) {
602 Intent end
= new Intent(getDownloadFinishMessage());
603 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
604 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
605 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
606 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
607 if (unlinkedFromRemotePath
!= null
) {
608 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
610 sendStickyBroadcast(end
);
615 * Sends a broadcast when a new download is added to the queue.
617 * @param download Added download operation
618 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
620 private void sendBroadcastNewDownload(DownloadFileOperation download
, String linkedToRemotePath
) {
621 Intent added
= new Intent(getDownloadAddedMessage());
622 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
623 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
624 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
625 added
.putExtra(EXTRA_LINKED_TO_PATH
, linkedToRemotePath
);
626 sendStickyBroadcast(added
);