treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 1 | // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef CHROME_BROWSER_NET_FILE_DOWNLOADER_H_ |
| 6 | #define CHROME_BROWSER_NET_FILE_DOWNLOADER_H_ |
| 7 | |
| 8 | #include "base/callback.h" |
maybelle | fae2b70 | 2015-10-12 10:11:58 | [diff] [blame] | 9 | #include "base/files/file_path.h" |
avi | 6846aef | 2015-12-26 01:09:38 | [diff] [blame^] | 10 | #include "base/macros.h" |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 11 | #include "base/memory/scoped_ptr.h" |
| 12 | #include "base/memory/weak_ptr.h" |
| 13 | #include "net/url_request/url_fetcher_delegate.h" |
| 14 | |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 15 | namespace net { |
| 16 | class URLFetcher; |
| 17 | class URLRequestContextGetter; |
| 18 | } // namespace net |
| 19 | |
| 20 | class GURL; |
| 21 | |
| 22 | // Helper class to download a file from a given URL and store it in a local |
treib | f79ed40d | 2015-09-22 12:38:06 | [diff] [blame] | 23 | // file. If |overwrite| is true, any existing file will be overwritten; |
| 24 | // otherwise if the local file already exists, this will report success without |
| 25 | // downloading anything. |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 26 | class FileDownloader : public net::URLFetcherDelegate { |
| 27 | public: |
| 28 | typedef base::Callback<void(bool /* success */)> DownloadFinishedCallback; |
| 29 | |
| 30 | // Directly starts the download (if necessary) and runs |callback| when done. |
| 31 | // If the instance is destroyed before it is finished, |callback| is not run. |
| 32 | FileDownloader(const GURL& url, |
| 33 | const base::FilePath& path, |
treib | f79ed40d | 2015-09-22 12:38:06 | [diff] [blame] | 34 | bool overwrite, |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 35 | net::URLRequestContextGetter* request_context, |
| 36 | const DownloadFinishedCallback& callback); |
| 37 | ~FileDownloader() override; |
| 38 | |
| 39 | private: |
| 40 | // net::URLFetcherDelegate implementation. |
| 41 | void OnURLFetchComplete(const net::URLFetcher* source) override; |
| 42 | |
| 43 | void OnFileExistsCheckDone(bool exists); |
| 44 | |
maybelle | fae2b70 | 2015-10-12 10:11:58 | [diff] [blame] | 45 | void OnFileMoveDone(bool success); |
| 46 | |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 47 | DownloadFinishedCallback callback_; |
| 48 | |
| 49 | scoped_ptr<net::URLFetcher> fetcher_; |
| 50 | |
maybelle | fae2b70 | 2015-10-12 10:11:58 | [diff] [blame] | 51 | base::FilePath local_path_; |
| 52 | |
treib | cffa650 | 2015-08-06 09:12:27 | [diff] [blame] | 53 | base::WeakPtrFactory<FileDownloader> weak_ptr_factory_; |
| 54 | |
| 55 | DISALLOW_COPY_AND_ASSIGN(FileDownloader); |
| 56 | }; |
| 57 | |
| 58 | #endif // CHROME_BROWSER_NET_FILE_DOWNLOADER_H_ |