blob: d6383188464f3af04f6a66d801c3785c61c02636 [file] [log] [blame]
treibcffa6502015-08-06 09:12:271// 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"
maybellefae2b702015-10-12 10:11:589#include "base/files/file_path.h"
avi6846aef2015-12-26 01:09:3810#include "base/macros.h"
treibcffa6502015-08-06 09:12:2711#include "base/memory/scoped_ptr.h"
12#include "base/memory/weak_ptr.h"
13#include "net/url_request/url_fetcher_delegate.h"
14
treibcffa6502015-08-06 09:12:2715namespace net {
16class URLFetcher;
17class URLRequestContextGetter;
18} // namespace net
19
20class GURL;
21
22// Helper class to download a file from a given URL and store it in a local
treibf79ed40d2015-09-22 12:38:0623// 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.
treibcffa6502015-08-06 09:12:2726class 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,
treibf79ed40d2015-09-22 12:38:0634 bool overwrite,
treibcffa6502015-08-06 09:12:2735 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
maybellefae2b702015-10-12 10:11:5845 void OnFileMoveDone(bool success);
46
treibcffa6502015-08-06 09:12:2747 DownloadFinishedCallback callback_;
48
49 scoped_ptr<net::URLFetcher> fetcher_;
50
maybellefae2b702015-10-12 10:11:5851 base::FilePath local_path_;
52
treibcffa6502015-08-06 09:12:2753 base::WeakPtrFactory<FileDownloader> weak_ptr_factory_;
54
55 DISALLOW_COPY_AND_ASSIGN(FileDownloader);
56};
57
58#endif // CHROME_BROWSER_NET_FILE_DOWNLOADER_H_