FileDownloader.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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.io.IOException;
  21. import java.util.AbstractList;
  22. import java.util.Iterator;
  23. import java.util.Vector;
  24. import java.util.concurrent.ConcurrentHashMap;
  25. import java.util.concurrent.ConcurrentMap;
  26. import com.owncloud.android.datamodel.FileDataStorageManager;
  27. import com.owncloud.android.datamodel.OCFile;
  28. import eu.alefzero.webdav.OnDatatransferProgressListener;
  29. import com.owncloud.android.network.OwnCloudClientUtils;
  30. import com.owncloud.android.operations.DownloadFileOperation;
  31. import com.owncloud.android.operations.RemoteOperationResult;
  32. import com.owncloud.android.ui.activity.FileDetailActivity;
  33. import com.owncloud.android.ui.fragment.FileDetailFragment;
  34. import android.accounts.Account;
  35. import android.accounts.AccountsException;
  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. requestedDownloads.add(downloadKey);
  121. sendBroadcastNewDownload(newDownload);
  122. } catch (IllegalArgumentException e) {
  123. Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  124. return START_NOT_STICKY;
  125. }
  126. if (requestedDownloads.size() > 0) {
  127. Message msg = mServiceHandler.obtainMessage();
  128. msg.arg1 = startId;
  129. msg.obj = requestedDownloads;
  130. mServiceHandler.sendMessage(msg);
  131. }
  132. return START_NOT_STICKY;
  133. }
  134. /**
  135. * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
  136. *
  137. * Implemented to perform cancellation, pause and resume of existing downloads.
  138. */
  139. @Override
  140. public IBinder onBind(Intent arg0) {
  141. return mBinder;
  142. }
  143. /**
  144. * Binder to let client components to perform operations on the queue of downloads.
  145. *
  146. * It provides by itself the available operations.
  147. */
  148. public class FileDownloaderBinder extends Binder {
  149. /**
  150. * Cancels a pending or current download of a remote file.
  151. *
  152. * @param account Owncloud account where the remote file is stored.
  153. * @param file A file in the queue of pending downloads
  154. */
  155. public void cancel(Account account, OCFile file) {
  156. DownloadFileOperation download = null;
  157. synchronized (mPendingDownloads) {
  158. download = mPendingDownloads.remove(buildRemoteName(account, file));
  159. }
  160. if (download != null) {
  161. download.cancel();
  162. }
  163. }
  164. /**
  165. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
  166. *
  167. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
  168. *
  169. * @param account Owncloud account where the remote file is stored.
  170. * @param file A file that could be in the queue of downloads.
  171. */
  172. public boolean isDownloading(Account account, OCFile file) {
  173. String targetKey = buildRemoteName(account, file);
  174. synchronized (mPendingDownloads) {
  175. if (file.isDirectory()) {
  176. // this can be slow if there are many downloads :(
  177. Iterator<String> it = mPendingDownloads.keySet().iterator();
  178. boolean found = false;
  179. while (it.hasNext() && !found) {
  180. found = it.next().startsWith(targetKey);
  181. }
  182. return found;
  183. } else {
  184. return (mPendingDownloads.containsKey(targetKey));
  185. }
  186. }
  187. }
  188. }
  189. /**
  190. * Download worker. Performs the pending downloads in the order they were requested.
  191. *
  192. * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
  193. */
  194. private static class ServiceHandler extends Handler {
  195. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  196. FileDownloader mService;
  197. public ServiceHandler(Looper looper, FileDownloader service) {
  198. super(looper);
  199. if (service == null)
  200. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  201. mService = service;
  202. }
  203. @Override
  204. public void handleMessage(Message msg) {
  205. @SuppressWarnings("unchecked")
  206. AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
  207. if (msg.obj != null) {
  208. Iterator<String> it = requestedDownloads.iterator();
  209. while (it.hasNext()) {
  210. mService.downloadFile(it.next());
  211. }
  212. }
  213. mService.stopSelf(msg.arg1);
  214. }
  215. }
  216. /**
  217. * Core download method: requests a file to download and stores it.
  218. *
  219. * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
  220. */
  221. private void downloadFile(String downloadKey) {
  222. synchronized(mPendingDownloads) {
  223. mCurrentDownload = mPendingDownloads.get(downloadKey);
  224. }
  225. if (mCurrentDownload != null) {
  226. notifyDownloadStart(mCurrentDownload);
  227. RemoteOperationResult downloadResult = null;
  228. try {
  229. /// prepare client object to send the request to the ownCloud server
  230. if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
  231. mLastAccount = mCurrentDownload.getAccount();
  232. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  233. mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, this);
  234. }
  235. /// perform the download
  236. if (downloadResult == null) {
  237. downloadResult = mCurrentDownload.execute(mDownloadClient);
  238. }
  239. if (downloadResult.isSuccess()) {
  240. saveDownloadedFile();
  241. }
  242. } catch (AccountsException e) {
  243. Log.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  244. downloadResult = new RemoteOperationResult(e);
  245. } catch (IOException e) {
  246. Log.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  247. downloadResult = new RemoteOperationResult(e);
  248. } finally {
  249. synchronized(mPendingDownloads) {
  250. mPendingDownloads.remove(downloadKey);
  251. }
  252. }
  253. /// notify result
  254. notifyDownloadResult(mCurrentDownload, downloadResult);
  255. sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
  256. }
  257. }
  258. /**
  259. * Updates the OC File after a successful download.
  260. */
  261. private void saveDownloadedFile() {
  262. OCFile file = mCurrentDownload.getFile();
  263. long syncDate = System.currentTimeMillis();
  264. file.setLastSyncDateForProperties(syncDate);
  265. file.setLastSyncDateForData(syncDate);
  266. file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
  267. file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
  268. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
  269. file.setMimetype(mCurrentDownload.getMimeType());
  270. file.setStoragePath(mCurrentDownload.getSavePath());
  271. file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
  272. mStorageManager.saveFile(file);
  273. }
  274. /**
  275. * Creates a status notification to show the download progress
  276. *
  277. * @param download Download operation starting.
  278. */
  279. private void notifyDownloadStart(DownloadFileOperation download) {
  280. /// create status notification with a progress bar
  281. mLastPercent = 0;
  282. mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
  283. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  284. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
  285. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
  286. mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
  287. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  288. /// includes a pending intent in the notification showing the details view of the file
  289. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  290. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
  291. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
  292. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  293. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
  294. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  295. }
  296. /**
  297. * Callback method to update the progress bar in the status notification.
  298. */
  299. @Override
  300. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  301. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  302. if (percent != mLastPercent) {
  303. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
  304. String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
  305. mNotification.contentView.setTextViewText(R.id.status_text, text);
  306. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  307. }
  308. mLastPercent = percent;
  309. }
  310. /**
  311. * Callback method to update the progress bar in the status notification (old version)
  312. */
  313. @Override
  314. public void onTransferProgress(long progressRate) {
  315. // NOTHING TO DO HERE ANYMORE
  316. }
  317. /**
  318. * Updates the status notification with the result of a download operation.
  319. *
  320. * @param downloadResult Result of the download operation.
  321. * @param download Finished download operation
  322. */
  323. private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  324. mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
  325. if (!downloadResult.isCancelled()) {
  326. int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
  327. int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
  328. Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
  329. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  330. // TODO put something smart in the contentIntent below
  331. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  332. finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
  333. mNotificationManager.notify(tickerId, finalNotification);
  334. }
  335. }
  336. /**
  337. * Sends a broadcast when a download finishes in order to the interested activities can update their view
  338. *
  339. * @param download Finished download operation
  340. * @param downloadResult Result of the download operation
  341. */
  342. private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  343. Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
  344. end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
  345. end.putExtra(ACCOUNT_NAME, download.getAccount().name);
  346. end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  347. end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  348. sendStickyBroadcast(end);
  349. }
  350. /**
  351. * Sends a broadcast when a new download is added to the queue.
  352. *
  353. * @param download Added download operation
  354. */
  355. private void sendBroadcastNewDownload(DownloadFileOperation download) {
  356. Intent added = new Intent(DOWNLOAD_ADDED_MESSAGE);
  357. /*added.putExtra(ACCOUNT_NAME, download.getAccount().name);
  358. added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
  359. added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  360. sendStickyBroadcast(added);
  361. }
  362. }