FileDownloader.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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.Iterator;
  22. import java.util.Vector;
  23. import java.util.concurrent.ConcurrentHashMap;
  24. import java.util.concurrent.ConcurrentMap;
  25. import com.owncloud.android.datamodel.OCFile;
  26. import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
  27. import eu.alefzero.webdav.OnDatatransferProgressListener;
  28. import com.owncloud.android.network.OwnCloudClientUtils;
  29. import com.owncloud.android.operations.DownloadFileOperation;
  30. import com.owncloud.android.operations.RemoteOperationResult;
  31. import com.owncloud.android.ui.activity.FileDetailActivity;
  32. import com.owncloud.android.ui.fragment.FileDetailFragment;
  33. import android.accounts.Account;
  34. import android.app.Notification;
  35. import android.app.NotificationManager;
  36. import android.app.PendingIntent;
  37. import android.app.Service;
  38. import android.content.ContentValues;
  39. import android.content.Intent;
  40. import android.net.Uri;
  41. import android.os.Binder;
  42. import android.os.Environment;
  43. import android.os.Handler;
  44. import android.os.HandlerThread;
  45. import android.os.IBinder;
  46. import android.os.Looper;
  47. import android.os.Message;
  48. import android.os.Process;
  49. import android.util.Log;
  50. import android.widget.RemoteViews;
  51. import com.owncloud.android.R;
  52. import eu.alefzero.webdav.WebdavClient;
  53. public class FileDownloader extends Service implements OnDatatransferProgressListener {
  54. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  55. public static final String EXTRA_FILE = "FILE";
  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 ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
  68. private DownloadFileOperation mCurrentDownload = null;
  69. private NotificationManager mNotificationManager;
  70. private Notification mNotification;
  71. private int mLastPercent;
  72. /**
  73. * Builds a key for mPendingDownloads from the account and file to download
  74. *
  75. * @param account Account where the file to download is stored
  76. * @param file File to download
  77. */
  78. private String buildRemoteName(Account account, OCFile file) {
  79. return account.name + file.getRemotePath();
  80. }
  81. public static final String getSavePath(String accountName) {
  82. File sdCard = Environment.getExternalStorageDirectory();
  83. return sdCard.getAbsolutePath() + "/owncloud/" + Uri.encode(accountName, "@");
  84. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
  85. }
  86. public static final String getTemporalPath(String accountName) {
  87. File sdCard = Environment.getExternalStorageDirectory();
  88. return sdCard.getAbsolutePath() + "/owncloud/tmp/" + Uri.encode(accountName, "@");
  89. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
  90. }
  91. /**
  92. * Service initialization
  93. */
  94. @Override
  95. public void onCreate() {
  96. super.onCreate();
  97. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  98. HandlerThread thread = new HandlerThread("FileDownloaderThread",
  99. Process.THREAD_PRIORITY_BACKGROUND);
  100. thread.start();
  101. mServiceLooper = thread.getLooper();
  102. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  103. mBinder = new FileDownloaderBinder();
  104. }
  105. /**
  106. * Entry point to add one or several files to the queue of downloads.
  107. *
  108. * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
  109. * although the caller activity goes away.
  110. */
  111. @Override
  112. public int onStartCommand(Intent intent, int flags, int startId) {
  113. if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
  114. !intent.hasExtra(EXTRA_FILE)
  115. /*!intent.hasExtra(EXTRA_FILE_PATH) ||
  116. !intent.hasExtra(EXTRA_REMOTE_PATH)*/
  117. ) {
  118. Log.e(TAG, "Not enough information provided in intent");
  119. return START_NOT_STICKY;
  120. }
  121. Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
  122. OCFile file = intent.getParcelableExtra(EXTRA_FILE);
  123. 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)
  124. String downloadKey = buildRemoteName(account, file);
  125. try {
  126. DownloadFileOperation newDownload = new DownloadFileOperation(account, file);
  127. mPendingDownloads.putIfAbsent(downloadKey, newDownload);
  128. newDownload.addDatatransferProgressListener(this);
  129. requestedDownloads.add(downloadKey);
  130. } catch (IllegalArgumentException e) {
  131. Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  132. return START_NOT_STICKY;
  133. }
  134. if (requestedDownloads.size() > 0) {
  135. Message msg = mServiceHandler.obtainMessage();
  136. msg.arg1 = startId;
  137. msg.obj = requestedDownloads;
  138. mServiceHandler.sendMessage(msg);
  139. }
  140. return START_NOT_STICKY;
  141. }
  142. /**
  143. * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
  144. *
  145. * Implemented to perform cancellation, pause and resume of existing downloads.
  146. */
  147. @Override
  148. public IBinder onBind(Intent arg0) {
  149. return mBinder;
  150. }
  151. /**
  152. * Binder to let client components to perform operations on the queue of downloads.
  153. *
  154. * It provides by itself the available operations.
  155. */
  156. public class FileDownloaderBinder extends Binder {
  157. /**
  158. * Cancels a pending or current download of a remote file.
  159. *
  160. * @param account Owncloud account where the remote file is stored.
  161. * @param file A file in the queue of pending downloads
  162. */
  163. public void cancel(Account account, OCFile file) {
  164. DownloadFileOperation download = null;
  165. synchronized (mPendingDownloads) {
  166. download = mPendingDownloads.remove(buildRemoteName(account, file));
  167. }
  168. if (download != null) {
  169. download.cancel();
  170. }
  171. }
  172. /**
  173. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download
  174. *
  175. * @param account Owncloud account where the remote file is stored.
  176. * @param file A file that could be in the queue of downloads.
  177. */
  178. public boolean isDownloading(Account account, OCFile file) {
  179. synchronized (mPendingDownloads) {
  180. return (mPendingDownloads.containsKey(buildRemoteName(account, file)));
  181. }
  182. }
  183. }
  184. /**
  185. * Download worker. Performs the pending downloads in the order they were requested.
  186. *
  187. * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
  188. */
  189. private static class ServiceHandler extends Handler {
  190. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  191. FileDownloader mService;
  192. public ServiceHandler(Looper looper, FileDownloader service) {
  193. super(looper);
  194. if (service == null)
  195. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  196. mService = service;
  197. }
  198. @Override
  199. public void handleMessage(Message msg) {
  200. @SuppressWarnings("unchecked")
  201. AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
  202. if (msg.obj != null) {
  203. Iterator<String> it = requestedDownloads.iterator();
  204. while (it.hasNext()) {
  205. mService.downloadFile(it.next());
  206. }
  207. }
  208. mService.stopSelf(msg.arg1);
  209. }
  210. }
  211. /**
  212. * Core download method: requests a file to download and stores it.
  213. *
  214. * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
  215. */
  216. private void downloadFile(String downloadKey) {
  217. synchronized(mPendingDownloads) {
  218. mCurrentDownload = mPendingDownloads.get(downloadKey);
  219. }
  220. if (mCurrentDownload != null) {
  221. notifyDownloadStart(mCurrentDownload);
  222. /// prepare client object to send the request to the ownCloud server
  223. if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
  224. mLastAccount = mCurrentDownload.getAccount();
  225. mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
  226. }
  227. /// perform the download
  228. RemoteOperationResult downloadResult = null;
  229. try {
  230. downloadResult = mCurrentDownload.execute(mDownloadClient);
  231. if (downloadResult.isSuccess()) {
  232. ContentValues cv = new ContentValues();
  233. cv.put(ProviderTableMeta.FILE_STORAGE_PATH, mCurrentDownload.getSavePath());
  234. getContentResolver().update(
  235. ProviderTableMeta.CONTENT_URI,
  236. cv,
  237. ProviderTableMeta.FILE_NAME + "=? AND "
  238. + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
  239. new String[] {
  240. mCurrentDownload.getSavePath().substring(mCurrentDownload.getSavePath().lastIndexOf('/') + 1),
  241. mLastAccount.name });
  242. }
  243. } finally {
  244. synchronized(mPendingDownloads) {
  245. mPendingDownloads.remove(downloadKey);
  246. }
  247. }
  248. /// notify result
  249. notifyDownloadResult(mCurrentDownload, downloadResult);
  250. sendFinalBroadcast(mCurrentDownload, downloadResult);
  251. }
  252. }
  253. /**
  254. * Creates a status notification to show the download progress
  255. *
  256. * @param download Download operation starting.
  257. */
  258. private void notifyDownloadStart(DownloadFileOperation download) {
  259. /// create status notification with a progress bar
  260. mLastPercent = 0;
  261. mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
  262. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  263. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
  264. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);
  265. mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));
  266. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  267. /// includes a pending intent in the notification showing the details view of the file
  268. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  269. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, download.getFile());
  270. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, download.getAccount());
  271. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  272. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
  273. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  274. }
  275. /**
  276. * Callback method to update the progress bar in the status notification.
  277. */
  278. @Override
  279. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  280. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  281. if (percent != mLastPercent) {
  282. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);
  283. String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
  284. mNotification.contentView.setTextViewText(R.id.status_text, text);
  285. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);
  286. }
  287. mLastPercent = percent;
  288. }
  289. /**
  290. * Callback method to update the progress bar in the status notification (old version)
  291. */
  292. @Override
  293. public void onTransferProgress(long progressRate) {
  294. // NOTHING TO DO HERE ANYMORE
  295. }
  296. /**
  297. * Updates the status notification with the result of a download operation.
  298. *
  299. * @param downloadResult Result of the download operation.
  300. * @param download Finished download operation
  301. */
  302. private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  303. mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
  304. if (!downloadResult.isCancelled()) {
  305. int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
  306. int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
  307. Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
  308. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  309. // TODO put something smart in the contentIntent below
  310. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  311. finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);
  312. mNotificationManager.notify(tickerId, finalNotification);
  313. }
  314. }
  315. /**
  316. * Sends a broadcast in order to the interested activities can update their view
  317. *
  318. * @param download Finished download operation
  319. * @param downloadResult Result of the download operation
  320. */
  321. private void sendFinalBroadcast(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  322. Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
  323. end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
  324. end.putExtra(ACCOUNT_NAME, download.getAccount().name);
  325. end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  326. if (downloadResult.isSuccess()) {
  327. end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  328. }
  329. sendBroadcast(end);
  330. }
  331. }