File: background_download_service_factory.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (243 lines) | stat: -rw-r--r-- 9,698 bytes parent folder | download | duplicates (6)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/download/background_download_service_factory.h"

#include <memory>
#include <utility>

#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/browser/download/deferred_client_wrapper.h"
#include "chrome/browser/download/download_manager_utils.h"
#include "chrome/browser/download/simple_download_manager_coordinator_factory.h"
#include "chrome/browser/optimization_guide/prediction/prediction_model_download_client.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/transition_manager/full_browser_transition_manager.h"
#include "chrome/common/chrome_constants.h"
#include "components/background_fetch/download_client.h"
#include "components/download/content/factory/download_service_factory_helper.h"
#include "components/download/content/factory/navigation_monitor_factory.h"
#include "components/download/public/background_service/background_download_service.h"
#include "components/download/public/background_service/basic_task_scheduler.h"
#include "components/download/public/background_service/blob_context_getter_factory.h"
#include "components/download/public/background_service/clients.h"
#include "components/download/public/background_service/features.h"
#include "components/download/public/background_service/url_loader_factory_getter.h"
#include "components/download/public/common/simple_download_manager_coordinator.h"
#include "components/keyed_service/core/simple_dependency_manager.h"
#include "components/leveldb_proto/public/proto_database_provider.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/download/android/service/download_task_scheduler.h"
#endif

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/plugin_vm/plugin_vm_image_download_client.h"
#endif

namespace {

std::unique_ptr<download::Client> CreateBackgroundFetchDownloadClient(
    Profile* profile) {
  return std::make_unique<background_fetch::DownloadClient>(profile);
}

#if BUILDFLAG(IS_CHROMEOS)
std::unique_ptr<download::Client> CreatePluginVmImageDownloadClient(
    Profile* profile) {
  return std::make_unique<plugin_vm::PluginVmImageDownloadClient>(profile);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

std::unique_ptr<download::Client>
CreateOptimizationGuidePredictionModelDownloadClient(Profile* profile) {
  return std::make_unique<optimization_guide::PredictionModelDownloadClient>(
      profile);
}

// Called on profile created to retrieve the BlobStorageContextGetter.
void DownloadOnProfileCreated(download::BlobContextGetterCallback callback,
                              Profile* profile) {
  auto blob_context_getter = profile->GetBlobStorageContext();
  DCHECK(callback);
  std::move(callback).Run(blob_context_getter);
}

// Provides BlobContextGetter from Chrome asynchronously.
class DownloadBlobContextGetterFactory
    : public download::BlobContextGetterFactory {
 public:
  explicit DownloadBlobContextGetterFactory(SimpleFactoryKey* key) : key_(key) {
    DCHECK(key_);
  }

  DownloadBlobContextGetterFactory(const DownloadBlobContextGetterFactory&) =
      delete;
  DownloadBlobContextGetterFactory& operator=(
      const DownloadBlobContextGetterFactory&) = delete;

  ~DownloadBlobContextGetterFactory() override = default;

 private:
  // download::BlobContextGetterFactory implementation.
  void RetrieveBlobContextGetter(
      download::BlobContextGetterCallback callback) override {
    FullBrowserTransitionManager::Get()->RegisterCallbackOnProfileCreation(
        key_, base::BindOnce(&DownloadOnProfileCreated, std::move(callback)));
  }

  raw_ptr<SimpleFactoryKey> key_;
};

void OnProfileCreated(download::URLLoaderFactoryGetterCallback callback,
                      Profile* profile) {
  DCHECK(callback);
  std::move(callback).Run(profile->GetURLLoaderFactory());
}

class URLLoaderFactoryGetter : public download::URLLoaderFactoryGetter {
 public:
  explicit URLLoaderFactoryGetter(SimpleFactoryKey* key) : key_(key) {
    DCHECK(key_);
  }

  URLLoaderFactoryGetter(const URLLoaderFactoryGetter&) = delete;
  URLLoaderFactoryGetter& operator=(const URLLoaderFactoryGetter&) = delete;

  ~URLLoaderFactoryGetter() override = default;

 private:
  void RetrieveURLLoaderFactory(
      download::URLLoaderFactoryGetterCallback callback) override {
    FullBrowserTransitionManager::Get()->RegisterCallbackOnProfileCreation(
        key_, base::BindOnce(&OnProfileCreated, std::move(callback)));
  }

  raw_ptr<SimpleFactoryKey> key_;
};

}  // namespace

// static
BackgroundDownloadServiceFactory*
BackgroundDownloadServiceFactory::GetInstance() {
  static base::NoDestructor<BackgroundDownloadServiceFactory> instance;
  return instance.get();
}

// static
download::BackgroundDownloadService*
BackgroundDownloadServiceFactory::GetForKey(SimpleFactoryKey* key) {
  return static_cast<download::BackgroundDownloadService*>(
      GetInstance()->GetServiceForKey(key, true));
}

BackgroundDownloadServiceFactory::BackgroundDownloadServiceFactory()
    : SimpleKeyedServiceFactory("download::BackgroundDownloadService",
                                SimpleDependencyManager::GetInstance()) {
  DependsOn(SimpleDownloadManagerCoordinatorFactory::GetInstance());
  DependsOn(download::NavigationMonitorFactory::GetInstance());
}

BackgroundDownloadServiceFactory::~BackgroundDownloadServiceFactory() = default;

std::unique_ptr<KeyedService>
BackgroundDownloadServiceFactory::BuildServiceInstanceFor(
    SimpleFactoryKey* key) const {
  auto clients = std::make_unique<download::DownloadClientMap>();
  ProfileKey* profile_key = ProfileKey::FromSimpleFactoryKey(key);

  clients->insert(std::make_pair(
      download::DownloadClient::BACKGROUND_FETCH,
      std::make_unique<download::DeferredClientWrapper>(
          base::BindOnce(&CreateBackgroundFetchDownloadClient), key)));

#if BUILDFLAG(IS_CHROMEOS)
  if (!key->IsOffTheRecord()) {
    clients->insert(std::make_pair(
        download::DownloadClient::PLUGIN_VM_IMAGE,
        std::make_unique<download::DeferredClientWrapper>(
            base::BindOnce(&CreatePluginVmImageDownloadClient), key)));
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

  if (optimization_guide::features::IsModelDownloadingEnabled() &&
      !key->IsOffTheRecord()) {
    clients->insert(std::make_pair(
        download::DownloadClient::OPTIMIZATION_GUIDE_PREDICTION_MODELS,
        std::make_unique<download::DeferredClientWrapper>(
            base::BindOnce(
                &CreateOptimizationGuidePredictionModelDownloadClient),
            key)));
  }

  // Build in memory download service for incognito profile.
  if (key->IsOffTheRecord()) {
    auto blob_context_getter_factory =
        std::make_unique<DownloadBlobContextGetterFactory>(key);
    scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
        content::GetIOThreadTaskRunner({});

    return download::BuildInMemoryDownloadService(
        key, std::move(clients), content::GetNetworkConnectionTracker(),
        base::FilePath(), std::move(blob_context_getter_factory),
        io_task_runner, std::make_unique<::URLLoaderFactoryGetter>(key));
  } else {
    // Build download service for normal profile.
    base::FilePath storage_dir;
    if (!key->IsOffTheRecord() && !key->GetPath().empty()) {
      storage_dir =
          key->GetPath().Append(chrome::kDownloadServiceStorageDirname);
    }
    scoped_refptr<base::SequencedTaskRunner> background_task_runner =
        base::ThreadPool::CreateSequencedTaskRunner(
            {base::MayBlock(), base::TaskPriority::BEST_EFFORT});

    std::unique_ptr<download::TaskScheduler> task_scheduler;
#if BUILDFLAG(IS_ANDROID)
    task_scheduler =
        std::make_unique<download::android::DownloadTaskScheduler>();
#else
    task_scheduler =
        std::make_unique<download::BasicTaskScheduler>(base::BindRepeating(
            [](SimpleFactoryKey* key) {
              return BackgroundDownloadServiceFactory::GetForKey(key);
            },
            key));
#endif
    // Some tests doesn't initialize DownloadManager when profile is created,
    // and cause the download service to fail. Call
    // InitializeSimpleDownloadManager() to initialize the DownloadManager
    // whenever profile becomes available.
    DownloadManagerUtils::InitializeSimpleDownloadManager(profile_key);
    leveldb_proto::ProtoDatabaseProvider* proto_db_provider =
        profile_key->GetProtoDatabaseProvider();
    return download::BuildDownloadService(
        key, std::move(clients), content::GetNetworkConnectionTracker(),
        storage_dir, SimpleDownloadManagerCoordinatorFactory::GetForKey(key),
        proto_db_provider, background_task_runner, std::move(task_scheduler));
  }
}

SimpleFactoryKey* BackgroundDownloadServiceFactory::GetKeyToUse(
    SimpleFactoryKey* key) const {
  return key;
}