FileDownloader.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  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.
  8. *
  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.
  13. *
  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/>.
  16. *
  17. */
  18. package com.owncloud.android.files.services;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.util.AbstractList;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.Map;
  25. import java.util.Vector;
  26. import java.util.concurrent.ConcurrentHashMap;
  27. import java.util.concurrent.ConcurrentMap;
  28. import com.owncloud.android.R;
  29. import com.owncloud.android.authentication.AuthenticatorActivity;
  30. import com.owncloud.android.datamodel.FileDataStorageManager;
  31. import com.owncloud.android.datamodel.OCFile;
  32. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  33. import com.owncloud.android.lib.common.OwnCloudAccount;
  34. import com.owncloud.android.lib.common.OwnCloudClient;
  35. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  36. import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
  37. import com.owncloud.android.notifications.NotificationDelayer;
  38. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  39. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  40. import com.owncloud.android.lib.common.utils.Log_OC;
  41. import com.owncloud.android.lib.resources.files.FileUtils;
  42. import com.owncloud.android.operations.DownloadFileOperation;
  43. import com.owncloud.android.ui.activity.FileActivity;
  44. import com.owncloud.android.ui.activity.FileDisplayActivity;
  45. import com.owncloud.android.ui.preview.PreviewImageActivity;
  46. import com.owncloud.android.ui.preview.PreviewImageFragment;
  47. import com.owncloud.android.utils.ErrorMessageAdapter;
  48. import android.accounts.Account;
  49. import android.accounts.AccountsException;
  50. import android.app.NotificationManager;
  51. import android.app.PendingIntent;
  52. import android.app.Service;
  53. import android.content.Intent;
  54. import android.os.Binder;
  55. import android.os.Handler;
  56. import android.os.HandlerThread;
  57. import android.os.IBinder;
  58. import android.os.Looper;
  59. import android.os.Message;
  60. import android.os.Process;
  61. import android.support.v4.app.NotificationCompat;
  62. public class FileDownloader extends Service implements OnDatatransferProgressListener {
  63. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  64. public static final String EXTRA_FILE = "FILE";
  65. private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
  66. private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
  67. public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
  68. public static final String EXTRA_FILE_PATH = "FILE_PATH";
  69. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  70. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  71. private static final String TAG = "FileDownloader";
  72. private Looper mServiceLooper;
  73. private ServiceHandler mServiceHandler;
  74. private IBinder mBinder;
  75. private OwnCloudClient mDownloadClient = null;
  76. private Account mLastAccount = null;
  77. private FileDataStorageManager mStorageManager;
  78. private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
  79. private DownloadFileOperation mCurrentDownload = null;
  80. private NotificationManager mNotificationManager;
  81. private NotificationCompat.Builder mNotificationBuilder;
  82. private int mLastPercent;
  83. public static String getDownloadAddedMessage() {
  84. return FileDownloader.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE;
  85. }
  86. public static String getDownloadFinishMessage() {
  87. return FileDownloader.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE;
  88. }
  89. /**
  90. * Builds a key for mPendingDownloads from the account and file to download
  91. *
  92. * @param account Account where the file to download is stored
  93. * @param file File to download
  94. */
  95. private String buildRemoteName(Account account, OCFile file) {
  96. return account.name + file.getRemotePath();
  97. }
  98. /**
  99. * Service initialization
  100. */
  101. @Override
  102. public void onCreate() {
  103. super.onCreate();
  104. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  105. HandlerThread thread = new HandlerThread("FileDownloaderThread",
  106. Process.THREAD_PRIORITY_BACKGROUND);
  107. thread.start();
  108. mServiceLooper = thread.getLooper();
  109. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  110. mBinder = new FileDownloaderBinder();
  111. }
  112. /**
  113. * Entry point to add one or several files to the queue of downloads.
  114. *
  115. * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
  116. * although the caller activity goes away.
  117. */
  118. @Override
  119. public int onStartCommand(Intent intent, int flags, int startId) {
  120. if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
  121. !intent.hasExtra(EXTRA_FILE)
  122. /*!intent.hasExtra(EXTRA_FILE_PATH) ||
  123. !intent.hasExtra(EXTRA_REMOTE_PATH)*/
  124. ) {
  125. Log_OC.e(TAG, "Not enough information provided in intent");
  126. return START_NOT_STICKY;
  127. }
  128. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  129. OCFile file = intent.getParcelableExtra(EXTRA_FILE);
  130. 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)
  131. String downloadKey = buildRemoteName(account, file);
  132. try {
  133. DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
  134. mPendingDownloads.putIfAbsent(downloadKey, newDownload);
  135. newDownload.addDatatransferProgressListener(this);
  136. newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
  137. requestedDownloads.add(downloadKey);
  138. sendBroadcastNewDownload(newDownload);
  139. } catch (IllegalArgumentException e) {
  140. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  141. return START_NOT_STICKY;
  142. }
  143. if (requestedDownloads.size() > 0) {
  144. Message msg = mServiceHandler.obtainMessage();
  145. msg.arg1 = startId;
  146. msg.obj = requestedDownloads;
  147. mServiceHandler.sendMessage(msg);
  148. }
  149. return START_NOT_STICKY;
  150. }
  151. /**
  152. * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
  153. *
  154. * Implemented to perform cancellation, pause and resume of existing downloads.
  155. */
  156. @Override
  157. public IBinder onBind(Intent arg0) {
  158. return mBinder;
  159. }
  160. /**
  161. * Called when ALL the bound clients were onbound.
  162. */
  163. @Override
  164. public boolean onUnbind(Intent intent) {
  165. ((FileDownloaderBinder)mBinder).clearListeners();
  166. return false; // not accepting rebinding (default behaviour)
  167. }
  168. /**
  169. * Binder to let client components to perform operations on the queue of downloads.
  170. *
  171. * It provides by itself the available operations.
  172. */
  173. public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
  174. /**
  175. * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
  176. */
  177. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  178. /**
  179. * Cancels a pending or current download of a remote file.
  180. *
  181. * @param account Owncloud account where the remote file is stored.
  182. * @param file A file in the queue of pending downloads
  183. */
  184. public void cancel(Account account, OCFile file) {
  185. DownloadFileOperation download = null;
  186. synchronized (mPendingDownloads) {
  187. download = mPendingDownloads.remove(buildRemoteName(account, file));
  188. }
  189. if (download != null) {
  190. download.cancel();
  191. }
  192. }
  193. public void clearListeners() {
  194. mBoundListeners.clear();
  195. }
  196. /**
  197. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
  198. *
  199. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
  200. *
  201. * @param account Owncloud account where the remote file is stored.
  202. * @param file A file that could be in the queue of downloads.
  203. */
  204. public boolean isDownloading(Account account, OCFile file) {
  205. if (account == null || file == null) return false;
  206. String targetKey = buildRemoteName(account, file);
  207. synchronized (mPendingDownloads) {
  208. if (file.isFolder()) {
  209. // this can be slow if there are many downloads :(
  210. Iterator<String> it = mPendingDownloads.keySet().iterator();
  211. boolean found = false;
  212. while (it.hasNext() && !found) {
  213. found = it.next().startsWith(targetKey);
  214. }
  215. return found;
  216. } else {
  217. return (mPendingDownloads.containsKey(targetKey));
  218. }
  219. }
  220. }
  221. /**
  222. * Adds a listener interested in the progress of the download for a concrete file.
  223. *
  224. * @param listener Object to notify about progress of transfer.
  225. * @param account ownCloud account holding the file of interest.
  226. * @param file {@link OCfile} of interest for listener.
  227. */
  228. public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  229. if (account == null || file == null || listener == null) return;
  230. String targetKey = buildRemoteName(account, file);
  231. mBoundListeners.put(targetKey, listener);
  232. }
  233. /**
  234. * Removes a listener interested in the progress of the download for a concrete file.
  235. *
  236. * @param listener Object to notify about progress of transfer.
  237. * @param account ownCloud account holding the file of interest.
  238. * @param file {@link OCfile} of interest for listener.
  239. */
  240. public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  241. if (account == null || file == null || listener == null) return;
  242. String targetKey = buildRemoteName(account, file);
  243. if (mBoundListeners.get(targetKey) == listener) {
  244. mBoundListeners.remove(targetKey);
  245. }
  246. }
  247. @Override
  248. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  249. String fileName) {
  250. String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
  251. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  252. if (boundListener != null) {
  253. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
  254. }
  255. }
  256. }
  257. /**
  258. * Download worker. Performs the pending downloads in the order they were requested.
  259. *
  260. * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
  261. */
  262. private static class ServiceHandler extends Handler {
  263. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  264. FileDownloader mService;
  265. public ServiceHandler(Looper looper, FileDownloader service) {
  266. super(looper);
  267. if (service == null)
  268. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  269. mService = service;
  270. }
  271. @Override
  272. public void handleMessage(Message msg) {
  273. @SuppressWarnings("unchecked")
  274. AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
  275. if (msg.obj != null) {
  276. Iterator<String> it = requestedDownloads.iterator();
  277. while (it.hasNext()) {
  278. mService.downloadFile(it.next());
  279. }
  280. }
  281. mService.stopSelf(msg.arg1);
  282. }
  283. }
  284. /**
  285. * Core download method: requests a file to download and stores it.
  286. *
  287. * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
  288. */
  289. private void downloadFile(String downloadKey) {
  290. synchronized(mPendingDownloads) {
  291. mCurrentDownload = mPendingDownloads.get(downloadKey);
  292. }
  293. if (mCurrentDownload != null) {
  294. notifyDownloadStart(mCurrentDownload);
  295. RemoteOperationResult downloadResult = null;
  296. try {
  297. /// prepare client object to send the request to the ownCloud server
  298. if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
  299. mLastAccount = mCurrentDownload.getAccount();
  300. mStorageManager =
  301. new FileDataStorageManager(mLastAccount, getContentResolver());
  302. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
  303. mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  304. getClientFor(ocAccount, this);
  305. }
  306. /// perform the download
  307. downloadResult = mCurrentDownload.execute(mDownloadClient);
  308. if (downloadResult.isSuccess()) {
  309. saveDownloadedFile();
  310. }
  311. } catch (AccountsException e) {
  312. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  313. downloadResult = new RemoteOperationResult(e);
  314. } catch (IOException e) {
  315. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  316. downloadResult = new RemoteOperationResult(e);
  317. } finally {
  318. synchronized(mPendingDownloads) {
  319. mPendingDownloads.remove(downloadKey);
  320. }
  321. }
  322. /// notify result
  323. notifyDownloadResult(mCurrentDownload, downloadResult);
  324. sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
  325. }
  326. }
  327. /**
  328. * Updates the OC File after a successful download.
  329. */
  330. private void saveDownloadedFile() {
  331. OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
  332. long syncDate = System.currentTimeMillis();
  333. file.setLastSyncDateForProperties(syncDate);
  334. file.setLastSyncDateForData(syncDate);
  335. file.setNeedsUpdateThumbnail(true);
  336. file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
  337. file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
  338. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
  339. file.setMimetype(mCurrentDownload.getMimeType());
  340. file.setStoragePath(mCurrentDownload.getSavePath());
  341. file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
  342. mStorageManager.saveFile(file);
  343. }
  344. /**
  345. * Creates a status notification to show the download progress
  346. *
  347. * @param download Download operation starting.
  348. */
  349. private void notifyDownloadStart(DownloadFileOperation download) {
  350. /// create status notification with a progress bar
  351. mLastPercent = 0;
  352. mNotificationBuilder =
  353. NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  354. mNotificationBuilder
  355. .setSmallIcon(R.drawable.notification_icon)
  356. .setTicker(getString(R.string.downloader_download_in_progress_ticker))
  357. .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
  358. .setOngoing(true)
  359. .setProgress(100, 0, download.getSize() < 0)
  360. .setContentText(
  361. String.format(getString(R.string.downloader_download_in_progress_content), 0,
  362. new File(download.getSavePath()).getName())
  363. );
  364. /// includes a pending intent in the notification showing the details view of the file
  365. Intent showDetailsIntent = null;
  366. if (PreviewImageFragment.canBePreviewed(download.getFile())) {
  367. showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  368. } else {
  369. showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  370. }
  371. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
  372. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
  373. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  374. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  375. this, (int) System.currentTimeMillis(), showDetailsIntent, 0
  376. ));
  377. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
  378. }
  379. /**
  380. * Callback method to update the progress bar in the status notification.
  381. */
  382. @Override
  383. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
  384. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  385. if (percent != mLastPercent) {
  386. mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
  387. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  388. String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
  389. mNotificationBuilder.setContentText(text);
  390. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
  391. }
  392. mLastPercent = percent;
  393. }
  394. /**
  395. * Updates the status notification with the result of a download operation.
  396. *
  397. * @param downloadResult Result of the download operation.
  398. * @param download Finished download operation
  399. */
  400. private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  401. mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
  402. if (!downloadResult.isCancelled()) {
  403. int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
  404. R.string.downloader_download_failed_ticker;
  405. boolean needsToUpdateCredentials = (
  406. downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
  407. downloadResult.isIdPRedirection()
  408. );
  409. tickerId = (needsToUpdateCredentials) ?
  410. R.string.downloader_download_failed_credentials_error : tickerId;
  411. mNotificationBuilder
  412. .setTicker(getString(tickerId))
  413. .setContentTitle(getString(tickerId))
  414. .setAutoCancel(true)
  415. .setOngoing(false)
  416. .setProgress(0, 0, false);
  417. if (needsToUpdateCredentials) {
  418. // let the user update credentials with one click
  419. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  420. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
  421. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  422. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  423. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  424. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  425. mNotificationBuilder
  426. .setContentIntent(PendingIntent.getActivity(
  427. this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
  428. mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
  429. } else {
  430. // TODO put something smart in showDetailsIntent
  431. Intent showDetailsIntent = new Intent();
  432. mNotificationBuilder
  433. .setContentIntent(PendingIntent.getActivity(
  434. this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
  435. }
  436. mNotificationBuilder.setContentText(ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
  437. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  438. // Remove success notification
  439. if (downloadResult.isSuccess()) {
  440. // Sleep 2 seconds, so show the notification before remove it
  441. NotificationDelayer.cancelWithDelay(
  442. mNotificationManager,
  443. R.string.downloader_download_succeeded_ticker,
  444. 2000);
  445. }
  446. }
  447. }
  448. /**
  449. * Sends a broadcast when a download finishes in order to the interested activities can update their view
  450. *
  451. * @param download Finished download operation
  452. * @param downloadResult Result of the download operation
  453. */
  454. private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  455. Intent end = new Intent(getDownloadFinishMessage());
  456. end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
  457. end.putExtra(ACCOUNT_NAME, download.getAccount().name);
  458. end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  459. end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  460. sendStickyBroadcast(end);
  461. }
  462. /**
  463. * Sends a broadcast when a new download is added to the queue.
  464. *
  465. * @param download Added download operation
  466. */
  467. private void sendBroadcastNewDownload(DownloadFileOperation download) {
  468. Intent added = new Intent(getDownloadAddedMessage());
  469. added.putExtra(ACCOUNT_NAME, download.getAccount().name);
  470. added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  471. added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  472. sendStickyBroadcast(added);
  473. }
  474. }