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"
143 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
145 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
146 newDownload
.addDatatransferProgressListener(this);
147 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
148 Pair
<String
, String
> putResult
= mPendingDownloads
.putIfAbsent(
149 account
, file
.getRemotePath(), newDownload
151 String downloadKey
= putResult
.first
;
152 requestedDownloads
.add(downloadKey
);
154 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
155 "Download on " + file.getRemotePath() + " added to queue"
158 // Store file on db with state 'downloading'
160 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
161 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
162 file.setDownloading(true);
163 storageManager.saveFile(file);
166 sendBroadcastNewDownload(newDownload
, putResult
.second
);
168 } catch (IllegalArgumentException e
) {
169 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
170 return START_NOT_STICKY
;
173 if (requestedDownloads
.size() > 0) {
174 Message msg
= mServiceHandler
.obtainMessage();
176 msg
.obj
= requestedDownloads
;
177 mServiceHandler
.sendMessage(msg
);
182 return START_NOT_STICKY
;
187 * Provides a binder object that clients can use to perform operations on the queue of downloads,
188 * excepting the addition of new files.
190 * Implemented to perform cancellation, pause and resume of existing downloads.
193 public IBinder
onBind(Intent arg0
) {
199 * Called when ALL the bound clients were onbound.
202 public boolean onUnbind(Intent intent
) {
203 ((FileDownloaderBinder
)mBinder
).clearListeners();
204 return false
; // not accepting rebinding (default behaviour)
209 * Binder to let client components to perform operations on the queue of downloads.
211 * It provides by itself the available operations.
213 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
216 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
219 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
220 new HashMap
<Long
, OnDatatransferProgressListener
>();
224 * Cancels a pending or current download of a remote file.
226 * @param account ownCloud account where the remote file is stored.
227 * @param file A file in the queue of pending downloads
229 public void cancel(Account account
, OCFile file
) {
231 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
232 "Received request to cancel download of " + file.getRemotePath()
234 Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
235 "Removing download of " + file.getRemotePath());*/
236 Pair
<DownloadFileOperation
, String
> removeResult
= mPendingDownloads
.remove(account
, file
.getRemotePath());
237 DownloadFileOperation download
= removeResult
.first
;
238 if (download
!= null
) {
239 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
240 "Canceling returned download of " + file.getRemotePath());*/
243 if (mCurrentDownload
!= null
&& mCurrentAccount
!= null
&&
244 mCurrentDownload
.getRemotePath().startsWith(file
.getRemotePath()) &&
245 account
.name
.equals(mCurrentAccount
.name
)) {
246 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
247 "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/
248 mCurrentDownload
.cancel();
254 public void clearListeners() {
255 mBoundListeners
.clear();
260 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
261 * waiting to download.
263 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
264 * waiting to download.
266 * @param account ownCloud account where the remote file is stored.
267 * @param file A file that could be in the queue of downloads.
269 public boolean isDownloading(Account account
, OCFile file
) {
270 if (account
== null
|| file
== null
) return false
;
271 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
276 * Adds a listener interested in the progress of the download for a concrete file.
278 * @param listener Object to notify about progress of transfer.
279 * @param account ownCloud account holding the file of interest.
280 * @param file {@link OCFile} of interest for listener.
282 public void addDatatransferProgressListener (
283 OnDatatransferProgressListener listener
, Account account
, OCFile file
285 if (account
== null
|| file
== null
|| listener
== null
) return;
286 //String targetKey = buildKey(account, file.getRemotePath());
287 mBoundListeners
.put(file
.getFileId(), listener
);
292 * Removes a listener interested in the progress of the download for a concrete file.
294 * @param listener Object to notify about progress of transfer.
295 * @param account ownCloud account holding the file of interest.
296 * @param file {@link OCFile} of interest for listener.
298 public void removeDatatransferProgressListener (
299 OnDatatransferProgressListener listener
, Account account
, OCFile file
301 if (account
== null
|| file
== null
|| listener
== null
) return;
302 //String targetKey = buildKey(account, file.getRemotePath());
303 Long fileId
= file
.getFileId();
304 if (mBoundListeners
.get(fileId
) == listener
) {
305 mBoundListeners
.remove(fileId
);
310 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
312 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
313 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
314 if (boundListener
!= null
) {
315 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
323 * Download worker. Performs the pending downloads in the order they were requested.
325 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
327 private static class ServiceHandler
extends Handler
{
328 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
329 FileDownloader mService
;
330 public ServiceHandler(Looper looper
, FileDownloader service
) {
333 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
338 public void handleMessage(Message msg
) {
339 @SuppressWarnings("unchecked")
340 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
341 if (msg
.obj
!= null
) {
342 Iterator
<String
> it
= requestedDownloads
.iterator();
343 while (it
.hasNext()) {
344 String next
= it
.next();
345 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
346 "Handling download file " + next);*/
347 mService
.downloadFile(next
);
350 mService
.stopSelf(msg
.arg1
);
356 * Core download method: requests a file to download and stores it.
358 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
360 private void downloadFile(String downloadKey
) {
362 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
363 "Getting download of " + downloadKey);*/
364 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
366 if (mCurrentDownload
!= null
) {
368 notifyDownloadStart(mCurrentDownload
);
370 RemoteOperationResult downloadResult
= null
;
372 /// prepare client object to send the request to the ownCloud server
373 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentDownload
.getAccount())) {
374 mCurrentAccount
= mCurrentDownload
.getAccount();
375 mStorageManager
= new FileDataStorageManager(
379 } // else, reuse storage manager from previous operation
381 // always get client from client manager, to get fresh credentials in case of update
382 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
383 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
384 getClientFor(ocAccount
, this);
387 /// perform the download
388 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
389 "Executing download of " + mCurrentDownload.getRemotePath());*/
390 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
391 if (downloadResult
.isSuccess()) {
392 saveDownloadedFile();
395 } catch (AccountsException e
) {
396 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
397 downloadResult
= new RemoteOperationResult(e
);
398 } catch (IOException e
) {
399 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
400 downloadResult
= new RemoteOperationResult(e
);
403 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
404 "Removing payload " + mCurrentDownload.getRemotePath());*/
406 Pair
<DownloadFileOperation
, String
> removeResult
=
407 mPendingDownloads
.removePayload(mCurrentAccount
, mCurrentDownload
.getRemotePath());
410 notifyDownloadResult(mCurrentDownload
, downloadResult
);
412 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
, removeResult
.second
);
420 * Updates the OC File after a successful download.
422 private void saveDownloadedFile() {
423 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
424 long syncDate
= System
.currentTimeMillis();
425 file
.setLastSyncDateForProperties(syncDate
);
426 file
.setLastSyncDateForData(syncDate
);
427 file
.setNeedsUpdateThumbnail(true
);
428 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
429 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
430 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
431 file
.setMimetype(mCurrentDownload
.getMimeType());
432 file
.setStoragePath(mCurrentDownload
.getSavePath());
433 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
434 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
435 mStorageManager
.saveFile(file
);
436 mStorageManager
.triggerMediaScan(file
.getStoragePath());
440 * Update the OC File after a unsuccessful download
442 private void updateUnsuccessfulDownloadedFile() {
443 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
444 file
.setDownloading(false
);
445 mStorageManager
.saveFile(file
);
450 * Creates a status notification to show the download progress
452 * @param download Download operation starting.
454 private void notifyDownloadStart(DownloadFileOperation download
) {
455 /// create status notification with a progress bar
457 mNotificationBuilder
=
458 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
460 .setSmallIcon(R
.drawable
.notification_icon
)
461 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
462 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
464 .setProgress(100, 0, download
.getSize() < 0)
466 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
467 new File(download
.getSavePath()).getName())
470 /// includes a pending intent in the notification showing the details view of the file
471 Intent showDetailsIntent
= null
;
472 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
473 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
475 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
477 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
478 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
479 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
481 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
482 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
485 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
490 * Callback method to update the progress bar in the status notification.
493 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
)
495 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
496 if (percent
!= mLastPercent
) {
497 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
498 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
499 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
500 mNotificationBuilder
.setContentText(text
);
501 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
503 mLastPercent
= percent
;
508 * Updates the status notification with the result of a download operation.
510 * @param downloadResult Result of the download operation.
511 * @param download Finished download operation
513 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
514 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
515 if (!downloadResult
.isCancelled()) {
516 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
517 R
.string
.downloader_download_failed_ticker
;
519 boolean needsToUpdateCredentials
= (
520 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
521 downloadResult
.isIdPRedirection()
523 tickerId
= (needsToUpdateCredentials
) ?
524 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
527 .setTicker(getString(tickerId
))
528 .setContentTitle(getString(tickerId
))
531 .setProgress(0, 0, false
);
533 if (needsToUpdateCredentials
) {
535 // let the user update credentials with one click
536 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
537 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
538 updateAccountCredentials
.putExtra(
539 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
541 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
542 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
543 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
545 .setContentIntent(PendingIntent
.getActivity(
546 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
549 // TODO put something smart in showDetailsIntent
550 Intent showDetailsIntent
= new Intent();
552 .setContentIntent(PendingIntent
.getActivity(
553 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
556 mNotificationBuilder
.setContentText(
557 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
559 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
561 // Remove success notification
562 if (downloadResult
.isSuccess()) {
563 // Sleep 2 seconds, so show the notification before remove it
564 NotificationDelayer
.cancelWithDelay(
565 mNotificationManager
,
566 R
.string
.downloader_download_succeeded_ticker
,
575 * Sends a broadcast when a download finishes in order to the interested activities can update their view
577 * @param download Finished download operation
578 * @param downloadResult Result of the download operation
579 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
581 private void sendBroadcastDownloadFinished(
582 DownloadFileOperation download
,
583 RemoteOperationResult downloadResult
,
584 String unlinkedFromRemotePath
) {
585 Intent end
= new Intent(getDownloadFinishMessage());
586 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
587 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
588 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
589 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
590 if (unlinkedFromRemotePath
!= null
) {
591 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
593 sendStickyBroadcast(end
);
598 * Sends a broadcast when a new download is added to the queue.
600 * @param download Added download operation
601 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
603 private void sendBroadcastNewDownload(DownloadFileOperation download
, String linkedToRemotePath
) {
604 Intent added
= new Intent(getDownloadAddedMessage());
605 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
606 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
607 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
608 added
.putExtra(EXTRA_LINKED_TO_PATH
, linkedToRemotePath
);
609 sendStickyBroadcast(added
);