File: whats_new_fetcher.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (257 lines) | stat: -rw-r--r-- 8,864 bytes parent folder | download | duplicates (3)
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright 2024 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/ui/webui/whats_new/whats_new_fetcher.h"

#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/global_features.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/webui/whats_new/whats_new_util.h"
#include "chrome/common/chrome_version.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/reduce_accept_language_controller_delegate.h"
#include "net/base/url_util.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h"

namespace whats_new {
const char kChromeWhatsNewV2URL[] =
    "https://www.google.com/chrome/v2/whats-new/";
const char kChromeWhatsNewV2StagingURL[] =
    "https://chrome-staging.corp.google.com/chrome/v2/whats-new/";

const int64_t kMaxDownloadBytes = 1024 * 1024;

GURL GetV2ServerURL(bool is_staging) {
  const GURL base_url = is_staging ? GURL(kChromeWhatsNewV2StagingURL)
                                   : GURL(kChromeWhatsNewV2URL);
  return net::AppendQueryParameter(base_url, "version",
                                   base::NumberToString(CHROME_VERSION_MAJOR));
}

GURL GetV2ServerURLForRender(const WhatsNewRegistry& whats_new_registry,
                             bool is_staging) {
  GURL url = GetV2ServerURL(is_staging);
  const auto active_features = whats_new_registry.GetActiveFeatureNames();
  if (!active_features.empty()) {
    url = net::AppendQueryParameter(
        url, "enabled", base::JoinString(active_features, std::string(",")));
  }

  const auto rolled_features = whats_new_registry.GetRolledFeatureNames();
  if (!rolled_features.empty()) {
    url = net::AppendQueryParameter(
        url, "rolled", base::JoinString(rolled_features, std::string(",")));
  }

  const auto customizations = whats_new_registry.GetCustomizations();
  if (!customizations.empty()) {
    url = net::AppendQueryParameter(
        url, "customization",
        base::JoinString(customizations, std::string(",")));
  }

  return net::AppendQueryParameter(url, "internal", "true");
}

namespace {

class WhatsNewFetcher : public BrowserListObserver {
 public:
  explicit WhatsNewFetcher(Browser* browser) : browser_(browser) {
    BrowserList::AddObserver(this);

    GURL server_url = GetV2ServerURL();
    startup_url_ = GetWebUIStartupURL();

    if (IsRemoteContentDisabled()) {
      // Don't fetch network content if this is the case, just pretend the tab
      // was retrieved successfully. Do so asynchronously to simulate the
      // production code better.
      base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, base::BindOnce(&WhatsNewFetcher::OpenWhatsNewTabForTest,
                                    base::Unretained(this)));
      return;
    }

    LogLoadEvent(LoadEvent::kLoadStart);
    auto traffic_annotation =
        net::DefineNetworkTrafficAnnotation("whats_new_fetcher", R"(
          semantics {
            sender: "What's New Page"
            description: "Attempts to fetch the content for the What's New "
              "page to ensure it loads successfully."
            trigger:
              "Restarting Chrome after an update. Desktop only."
            data:
              "No data sent, other than URL of What's New. "
              "Data does not contain PII."
            destination: GOOGLE_OWNED_SERVICE
            internal {
              contacts {
                email: "frizzle-team@google.com"
              }
            }
            user_data {
              type: NONE
            }
            last_reviewed: "2024-05-22"
          }
          policy {
            cookies_allowed: NO
            setting:
              "None"
            chrome_policy {
              PromotionalTabsEnabled {
                PromotionalTabsEnabled: false
              }
            }
          })");
    network::mojom::URLLoaderFactory* loader_factory =
        g_browser_process->system_network_context_manager()
            ->GetURLLoaderFactory();
    auto request = std::make_unique<network::ResourceRequest>();

    // Inform the server of the top browser language via the
    // Accept-Language header.
    if (auto* profile = browser->profile()) {
      if (auto* delegate =
              profile->GetReduceAcceptLanguageControllerDelegate()) {
        auto languages = delegate->GetUserAcceptLanguages();
        if (!languages.empty()) {
          request->headers.SetHeader(request->headers.kAcceptLanguage,
                                     languages.front());
        }
      }
    }

    // Don't allow redirects when checking if the page is valid for the current
    // milestone.
    request->url = server_url;
    simple_loader_ = network::SimpleURLLoader::Create(std::move(request),
                                                      traffic_annotation);
    // base::Unretained is safe here because only OnResponseLoaded deletes
    // |this|.
    simple_loader_->DownloadToString(
        loader_factory,
        base::BindOnce(&WhatsNewFetcher::OnResponseLoaded,
                       base::Unretained(this)),
        kMaxDownloadBytes);
  }

  ~WhatsNewFetcher() override { BrowserList::RemoveObserver(this); }

  // BrowserListObserver:
  void OnBrowserRemoved(Browser* browser) override {
    if (browser != browser_) {
      return;
    }

    browser_closed_or_inactive_ = true;
    BrowserList::RemoveObserver(this);
    browser_ = nullptr;
  }

  void OnBrowserNoLongerActive(Browser* browser) override {
    if (browser == browser_) {
      browser_closed_or_inactive_ = true;
    }
  }

  void OnBrowserSetLastActive(Browser* browser) override {
    if (browser == browser_) {
      browser_closed_or_inactive_ = false;
    }
  }

 private:
  void AddWhatsNewTab(Browser* browser) {
    chrome::AddTabAt(browser, startup_url_, 0, true);
    browser->tab_strip_model()->ActivateTabAt(
        browser->tab_strip_model()->IndexOfFirstNonPinnedTab());
  }

  static void LogLoadEvent(LoadEvent event) {
    base::UmaHistogramEnumeration("WhatsNew.LoadEvent", event);
  }

  void OpenWhatsNewTabForTest() {
    if (browser_closed_or_inactive_) {
      return;
    }

    AddWhatsNewTab(browser_);
    delete this;
  }

  void OnResponseLoaded(std::unique_ptr<std::string> body) {
    int error_or_response_code = simple_loader_->NetError();
    const auto& headers = simple_loader_->ResponseInfo()
                              ? simple_loader_->ResponseInfo()->headers
                              : nullptr;
    bool success = error_or_response_code == net::OK && headers;
    if (headers) {
      error_or_response_code =
          net::HttpUtil::MapStatusCodeForHistogram(headers->response_code());
    }

    base::UmaHistogramSparse("WhatsNew.LoadResponseCode",
                             error_or_response_code);

    // The server may respond with a 302 to indicate the requested
    // page version does not exist but a suitable page has been found.
    // This should not result in an error since the auto-opened page
    // can still access a relevant resource.
    success = success && error_or_response_code >= 200 &&
              error_or_response_code <= 302 && body;

    // If the browser was closed or moved to the background while What's New was
    // loading, return early before recording that the user saw the page.
    if (browser_closed_or_inactive_) {
      LogLoadEvent(LoadEvent::kLoadAbort);
      return;
    }

    DCHECK(browser_);

    LogLoadEvent(success ? LoadEvent::kLoadSuccess
                         : LoadEvent::kLoadFailAndDoNotShow);

    if (success) {
      AddWhatsNewTab(browser_);
    }
    delete this;
  }

  std::unique_ptr<network::SimpleURLLoader> simple_loader_;
  raw_ptr<Browser> browser_;
  bool browser_closed_or_inactive_ = false;
  GURL startup_url_;
};

}  // namespace

void StartWhatsNewFetch(Browser* browser) {
  new WhatsNewFetcher(browser);
}

}  // namespace whats_new