FileDownloader.java 24 KB

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