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 <memory>
9 
10 #include "base/callback.h"
11 #include "base/files/file_path.h"
12 #include "base/macros.h"
13 #include "base/memory/weak_ptr.h"
14 #include "net/traffic_annotation/network_traffic_annotation.h"
15 
16 namespace network {
17 class SimpleURLLoader;
18 class SharedURLLoaderFactory;
19 }  // namespace network
20 
21 class GURL;
22 
23 // Helper class to download a file from a given URL and store it in a local
24 // 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.
27 class FileDownloader {
28  public:
29   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::OnceCallback<void(Result)>;
38 
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(
42       const GURL& url,
43       const base::FilePath& path,
44       bool overwrite,
45       scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
46       DownloadFinishedCallback callback,
47       const net::NetworkTrafficAnnotationTag& traffic_annotation);
48   ~FileDownloader();
49 
IsSuccess(Result result)50   static bool IsSuccess(Result result) { return result != FAILED; }
51 
52  private:
53   void OnSimpleDownloadComplete(base::FilePath response_path);
54 
55   void OnFileExistsCheckDone(bool exists);
56 
57   void OnFileMoveDone(bool success);
58 
59   scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
60 
61   DownloadFinishedCallback callback_;
62 
63   std::unique_ptr<network::SimpleURLLoader> simple_url_loader_;
64 
65   base::FilePath local_path_;
66 
67   base::WeakPtrFactory<FileDownloader> weak_ptr_factory_{this};
68 
69   DISALLOW_COPY_AND_ASSIGN(FileDownloader);
70 };
71 
72 #endif  // CHROME_BROWSER_NET_FILE_DOWNLOADER_H_
73