summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/net/file_downloader.h
blob: 17bc38348fb76f515be689d6ab2d02eeb58b09aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_NET_FILE_DOWNLOADER_H_
#define CHROME_BROWSER_NET_FILE_DOWNLOADER_H_

#include <memory>

#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "net/traffic_annotation/network_traffic_annotation.h"

namespace network {
class SimpleURLLoader;
class SharedURLLoaderFactory;
}  // namespace network

class GURL;

// Helper class to download a file from a given URL and store it in a local
// file. If |overwrite| is true, any existing file will be overwritten;
// otherwise if the local file already exists, this will report success without
// downloading anything.
class FileDownloader {
 public:
  enum Result {
    // The file was successfully downloaded.
    DOWNLOADED,
    // A local file at the given path already existed and was kept.
    EXISTS,
    // Downloading failed.
    FAILED
  };
  using DownloadFinishedCallback = base::OnceCallback<void(Result)>;

  // Directly starts the download (if necessary) and runs |callback| when done.
  // If the instance is destroyed before it is finished, |callback| is not run.
  FileDownloader(
      const GURL& url,
      const base::FilePath& path,
      bool overwrite,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      DownloadFinishedCallback callback,
      const net::NetworkTrafficAnnotationTag& traffic_annotation);
  ~FileDownloader();

  static bool IsSuccess(Result result) { return result != FAILED; }

 private:
  void OnSimpleDownloadComplete(base::FilePath response_path);

  void OnFileExistsCheckDone(bool exists);

  void OnFileMoveDone(bool success);

  scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;

  DownloadFinishedCallback callback_;

  std::unique_ptr<network::SimpleURLLoader> simple_url_loader_;

  base::FilePath local_path_;

  base::WeakPtrFactory<FileDownloader> weak_ptr_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(FileDownloader);
};

#endif  // CHROME_BROWSER_NET_FILE_DOWNLOADER_H_