blob: 79f631124d9b98155baf0e22a35488a5fa58a01a [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
dcheng4e7c0422016-04-14 00:59:058#include <memory>
9
treibcffa6502015-08-06 09:12:2710#include "base/callback.h"
maybellefae2b702015-10-12 10:11:5811#include "base/files/file_path.h"
avi6846aef2015-12-26 01:09:3812#include "base/macros.h"
treibcffa6502015-08-06 09:12:2713#include "base/memory/weak_ptr.h"
14#include "net/url_request/url_fetcher_delegate.h"
15
treibcffa6502015-08-06 09:12:2716namespace net {
17class URLFetcher;
18class URLRequestContextGetter;
19} // namespace net
20
21class GURL;
22
23// Helper class to download a file from a given URL and store it in a local
treibf79ed40d2015-09-22 12:38:0624// file. If |overwrite| is true, any existing file will be overwritten;
25// otherwise if the local file already exists, this will report success without
26// downloading anything.
treibcffa6502015-08-06 09:12:2727class FileDownloader : public net::URLFetcherDelegate {
28 public:
treibf38cc252016-04-07 14:44:1129 enum Result {
30 // The file was successfully downloaded.
31 DOWNLOADED,
32 // A local file at the given path already existed and was kept.
33 EXISTS,
34 // Downloading failed.
35 FAILED
36 };
37 using DownloadFinishedCallback = base::Callback<void(Result)>;
treibcffa6502015-08-06 09:12:2738
39 // Directly starts the download (if necessary) and runs |callback| when done.
40 // If the instance is destroyed before it is finished, |callback| is not run.
41 FileDownloader(const GURL& url,
42 const base::FilePath& path,
treibf79ed40d2015-09-22 12:38:0643 bool overwrite,
treibcffa6502015-08-06 09:12:2744 net::URLRequestContextGetter* request_context,
45 const DownloadFinishedCallback& callback);
46 ~FileDownloader() override;
47
treibf38cc252016-04-07 14:44:1148 static bool IsSuccess(Result result) { return result != FAILED; }
49
treibcffa6502015-08-06 09:12:2750 private:
51 // net::URLFetcherDelegate implementation.
52 void OnURLFetchComplete(const net::URLFetcher* source) override;
53
54 void OnFileExistsCheckDone(bool exists);
55
maybellefae2b702015-10-12 10:11:5856 void OnFileMoveDone(bool success);
57
treibcffa6502015-08-06 09:12:2758 DownloadFinishedCallback callback_;
59
dcheng4e7c0422016-04-14 00:59:0560 std::unique_ptr<net::URLFetcher> fetcher_;
treibcffa6502015-08-06 09:12:2761
maybellefae2b702015-10-12 10:11:5862 base::FilePath local_path_;
63
treibcffa6502015-08-06 09:12:2764 base::WeakPtrFactory<FileDownloader> weak_ptr_factory_;
65
66 DISALLOW_COPY_AND_ASSIGN(FileDownloader);
67};
68
69#endif // CHROME_BROWSER_NET_FILE_DOWNLOADER_H_