FileDownloader.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  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.util.AbstractList;
  21. import java.util.HashMap;
  22. import java.util.Iterator;
  23. import java.util.Map;
  24. import java.util.Vector;
  25. import java.util.concurrent.ConcurrentHashMap;
  26. import java.util.concurrent.ConcurrentMap;
  27. import com.owncloud.android.datamodel.FileDataStorageManager;
  28. import com.owncloud.android.datamodel.OCFile;
  29. import eu.alefzero.webdav.OnDatatransferProgressListener;
  30. import com.owncloud.android.network.OwnCloudClientUtils;
  31. import com.owncloud.android.operations.DownloadFileOperation;
  32. import com.owncloud.android.operations.RemoteOperationResult;
  33. import com.owncloud.android.ui.activity.FileDetailActivity;
  34. import com.owncloud.android.ui.fragment.FileDetailFragment;
  35. import android.accounts.Account;
  36. import android.app.Notification;
  37. import android.app.NotificationManager;
  38. import android.app.PendingIntent;
  39. import android.app.Service;
  40. import android.content.Intent;
  41. import android.os.Binder;
  42. import android.os.Handler;
  43. import android.os.HandlerThread;
  44. import android.os.IBinder;
  45. import android.os.Looper;
  46. import android.os.Message;
  47. import android.os.Process;
  48. import android.util.Log;
  49. import android.widget.RemoteViews;
  50. import com.owncloud.android.R;
  51. import eu.alefzero.webdav.WebdavClient;
  52. public class FileDownloader extends Service implements OnDatatransferProgressListener {
  53. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  54. public static final String EXTRA_FILE = "FILE";
  55. public static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
  56. public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
  57. public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
  58. public static final String EXTRA_FILE_PATH = "FILE_PATH";
  59. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  60. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  61. private static final String TAG = "FileDownloader";
  62. private Looper mServiceLooper;
  63. private ServiceHandler mServiceHandler;
  64. private IBinder mBinder;
  65. private WebdavClient mDownloadClient = null;
  66. private Account mLastAccount = null;
  67. private FileDataStorageManager mStorageManager;
  68. private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
  69. private DownloadFileOperation mCurrentDownload = null;
  70. private NotificationManager mNotificationManager;
  71. private Notification mNotification;
  72. private int mLastPercent;
  73. /**
  74. * Builds a key for mPendingDownloads from the account and file to download
  75. *
  76. * @param account Account where the file to download is stored
  77. * @param file File to download
  78. */
  79. private String buildRemoteName(Account account, OCFile file) {
  80. return account.name + file.getRemotePath();
  81. }
  82. /**
  83. * Service initialization
  84. */
  85. @Override
  86. public void onCreate() {
  87. super.onCreate();
  88. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  89. HandlerThread thread = new HandlerThread("FileDownloaderThread",
  90. Process.THREAD_PRIORITY_BACKGROUND);
  91. thread.start();
  92. mServiceLooper = thread.getLooper();
  93. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  94. mBinder = new FileDownloaderBinder();
  95. }
  96. /**
  97. * Entry point to add one or several files to the queue of downloads.
  98. *
  99. * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
  100. * although the caller activity goes away.
  101. */
  102. @Override
  103. public int onStartCommand(Intent intent, int flags, int startId) {
  104. if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
  105. !intent.hasExtra(EXTRA_FILE)
  106. /*!intent.hasExtra(EXTRA_FILE_PATH) ||
  107. !intent.hasExtra(EXTRA_REMOTE_PATH)*/
  108. ) {
  109. Log.e(TAG, "Not enough information provided in intent");
  110. return START_NOT_STICKY;
  111. }
  112. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  113. OCFile file = intent.getParcelableExtra(EXTRA_FILE);
  114. 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)
  115. String downloadKey = buildRemoteName(account, file);
  116. try {
  117. DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
  118. mPendingDownloads.putIfAbsent(downloadKey, newDownload);
  119. newDownload.addDatatransferProgressListener(this);
  120. newDownload.addDatatransferProgressListener((FileDownloaderBinder)mBinder);
  121. requestedDownloads.add(downloadKey);
  122. sendBroadcastNewDownload(newDownload);
  123. } catch (IllegalArgumentException e) {
  124. Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  125. return START_NOT_STICKY;
  126. }
  127. if (requestedDownloads.size() > 0) {
  128. Message msg = mServiceHandler.obtainMessage();
  129. msg.arg1 = startId;
  130. msg.obj = requestedDownloads;
  131. mServiceHandler.sendMessage(msg);
  132. }
  133. return START_NOT_STICKY;
  134. }
  135. /**
  136. * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
  137. *
  138. * Implemented to perform cancellation, pause and resume of existing downloads.
  139. */
  140. @Override
  141. public IBinder onBind(Intent arg0) {
  142. return mBinder;
  143. }
  144. /**
  145. * Called when ALL the bound clients were onbound.
  146. */
  147. @Override
  148. public boolean onUnbind(Intent intent) {
  149. ((FileDownloaderBinder)mBinder).clearListeners();
  150. return false; // not accepting rebinding (default behaviour)
  151. }
  152. /**
  153. * Binder to let client components to perform operations on the queue of downloads.
  154. *
  155. * It provides by itself the available operations.
  156. */
  157. public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
  158. /**
  159. * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
  160. */
  161. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  162. /**
  163. * Cancels a pending or current download of a remote file.
  164. *
  165. * @param account Owncloud account where the remote file is stored.
  166. * @param file A file in the queue of pending downloads
  167. */
  168. public void cancel(Account account, OCFile file) {
  169. DownloadFileOperation download = null;
  170. synchronized (mPendingDownloads) {
  171. download = mPendingDownloads.remove(buildRemoteName(account, file));
  172. }
  173. if (download != null) {
  174. download.cancel();
  175. }
  176. }
  177. public void clearListeners() {
  178. mBoundListeners.clear();
  179. }
  180. /**
  181. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
  182. *
  183. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
  184. *
  185. * @param account Owncloud account where the remote file is stored.
  186. * @param file A file that could be in the queue of downloads.
  187. */
  188. public boolean isDownloading(Account account, OCFile file) {
  189. if (account == null || file == null) return false;
  190. String targetKey = buildRemoteName(account, file);
  191. synchronized (mPendingDownloads) {
  192. if (file.isDirectory()) {
  193. // this can be slow if there are many downloads :(
  194. Iterator<String> it = mPendingDownloads.keySet().iterator();
  195. boolean found = false;
  196. while (it.hasNext() && !found) {
  197. found = it.next().startsWith(targetKey);
  198. }
  199. return found;
  200. } else {
  201. return (mPendingDownloads.containsKey(targetKey));
  202. }
  203. }
  204. }
  205. /**
  206. * Adds a listener interested in the progress of the download for a concrete file.
  207. *
  208. * @param listener Object to notify about progress of transfer.
  209. * @param account ownCloud account holding the file of interest.
  210. * @param file {@link OCfile} of interest for listener.
  211. */
  212. public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  213. if (account == null || file == null || listener == null) return;
  214. String targetKey = buildRemoteName(account, file);
  215. mBoundListeners.put(targetKey, listener);
  216. }
  217. /**
  218. * Removes a listener interested in the progress of the download for a concrete file.
  219. *
  220. * @param listener Object to notify about progress of transfer.
  221. * @param account ownCloud account holding the file of interest.
  222. * @param file {@link OCfile} of interest for listener.
  223. */
  224. public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  225. if (account == null || file == null || listener == null) return;
  226. String targetKey = buildRemoteName(account, file);
  227. if (mBoundListeners.get(targetKey) == listener) {
  228. mBoundListeners.remove(targetKey);
  229. }
  230. }
  231. @Override
  232. public void onTransferProgress(long progressRate) {
  233. // old way, should not be in use any more
  234. }
  235. @Override
  236. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  237. String fileName) {
  238. String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
  239. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  240. if (boundListener != null) {
  241. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
  242. }
  243. }
  244. }
  245. /**
  246. * Download worker. Performs the pending downloads in the order they were requested.
  247. *
  248. * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
  249. */
  250. private static class ServiceHandler extends Handler {
  251. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  252. FileDownloader mService;
  253. public ServiceHandler(Looper looper, FileDownloader service) {
  254. super(looper);
  255. if (service == null)
  256. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  257. mService = service;
  258. }
  259. @Override
  260. public void handleMessage(Message msg) {
  261. @SuppressWarnings("unchecked")
  262. AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
  263. if (msg.obj != null) {
  264. Iterator<String> it = requestedDownloads.iterator();
  265. while (it.hasNext()) {
  266. mService.downloadFile(it.next());
  267. }
  268. }
  269. mService.stopSelf(msg.arg1);
  270. }
  271. }
  272. /**
  273. * Core download method: requests a file to download and stores it.
  274. *
  275. * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
  276. */
  277. private void downloadFile(String downloadKey) {
  278. synchronized(mPendingDownloads) {
  279. mCurrentDownload = mPendingDownloads.get(downloadKey);
  280. }
  281. if (mCurrentDownload != null) {
  282. notifyDownloadStart(mCurrentDownload);
  283. /// prepare client object to send the request to the ownCloud server
  284. if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
  285. mLastAccount = mCurrentDownload.getAccount();
  286. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  287. mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
  288. }
  289. /// perform the download
  290. RemoteOperationResult downloadResult = null;
  291. try {
  292. downloadResult = mCurrentDownload.execute(mDownloadClient);
  293. if (downloadResult.isSuccess()) {
  294. saveDownloadedFile();
  295. }
  296. } finally {
  297. synchronized(mPendingDownloads) {
  298. mPendingDownloads.remove(downloadKey);
  299. }
  300. }
  301. /// notify result
  302. notifyDownloadResult(mCurrentDownload, downloadResult);
  303. sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
  304. }
  305. }
  306. /**
  307. * Updates the OC File after a successful download.
  308. */
  309. private void saveDownloadedFile() {
  310. OCFile file = mCurrentDownload.getFile();
  311. long syncDate = System.currentTimeMillis();
  312. file.setLastSyncDateForProperties(syncDate);
  313. file.setLastSyncDateForData(syncDate);
  314. file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
  315. file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
  316. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
  317. file.setMimetype(mCurrentDownload.getMimeType());
  318. file.setStoragePath(mCurrentDownload.getSavePath());
  319. file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
  320. mStorageManager.saveFile(file);
  321. }
  322. /**
  323. * Creates a status notification to show the download progress
  324. *
  325. * @param download Download operation starting.
  326. */
  327. private void notifyDownloadStart(DownloadFileOperation download) {
  328. /// create status notification with a progress bar
  329. mLastPercent = 0;
  330. mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
  331. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  332. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
  333. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
  334. mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
  335. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  336. /// includes a pending intent in the notification showing the details view of the file
  337. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  338. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
  339. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
  340. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  341. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
  342. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  343. }
  344. /**
  345. * Callback method to update the progress bar in the status notification.
  346. */
  347. @Override
  348. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  349. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  350. if (percent != mLastPercent) {
  351. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
  352. String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
  353. mNotification.contentView.setTextViewText(R.id.status_text, text);
  354. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  355. }
  356. mLastPercent = percent;
  357. }
  358. /**
  359. * Callback method to update the progress bar in the status notification (old version)
  360. */
  361. @Override
  362. public void onTransferProgress(long progressRate) {
  363. // NOTHING TO DO HERE ANYMORE
  364. }
  365. /**
  366. * Updates the status notification with the result of a download operation.
  367. *
  368. * @param downloadResult Result of the download operation.
  369. * @param download Finished download operation
  370. */
  371. private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  372. mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
  373. if (!downloadResult.isCancelled()) {
  374. int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
  375. int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
  376. Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
  377. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  378. // TODO put something smart in the contentIntent below
  379. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  380. finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
  381. mNotificationManager.notify(tickerId, finalNotification);
  382. }
  383. }
  384. /**
  385. * Sends a broadcast when a download finishes in order to the interested activities can update their view
  386. *
  387. * @param download Finished download operation
  388. * @param downloadResult Result of the download operation
  389. */
  390. private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  391. Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
  392. end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
  393. end.putExtra(ACCOUNT_NAME, download.getAccount().name);
  394. end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  395. end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  396. sendStickyBroadcast(end);
  397. }
  398. /**
  399. * Sends a broadcast when a new download is added to the queue.
  400. *
  401. * @param download Added download operation
  402. */
  403. private void sendBroadcastNewDownload(DownloadFileOperation download) {
  404. Intent added = new Intent(DOWNLOAD_ADDED_MESSAGE);
  405. /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
  406. added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
  407. added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  408. sendStickyBroadcast(added);
  409. }
  410. }