File: product_specifications_entry_point_controller.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 (464 lines) | stat: -rw-r--r-- 18,165 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// 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/commerce/product_specifications_entry_point_controller.h"

#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/commerce/shopping_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/views/commerce/product_specifications_button.h"
#include "chrome/browser/ui/webui/commerce/product_specifications_disclosure_dialog.h"
#include "components/commerce/core/commerce_constants.h"
#include "components/commerce/core/commerce_feature_list.h"
#include "components/commerce/core/commerce_types.h"
#include "components/commerce/core/commerce_utils.h"
#include "components/commerce/core/feature_utils.h"
#include "components/commerce/core/mojom/product_specifications.mojom.h"
#include "components/commerce/core/mojom/shopping_service.mojom.h"
#include "components/commerce/core/pref_names.h"
#include "components/commerce/core/shopping_service.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "ui/base/l10n/l10n_util.h"

namespace {

// Number of URLs of the same cluster that a window needs to contain in order
// for the entry point to stay valid.
constexpr int kEligibleWindowUrlCountForValidation = 2;
// Number of URLs of the same cluster that a window needs to contain in order
// for the entry point to trigger for navigation.
constexpr int kEligibleWindowUrlCountForNavigationTriggering = 3;
// The maximum length of the entry point title.
constexpr int kEntryPointTitleMaxLength = 24;

bool CheckWindowContainsEntryPointURLs(
    TabStripModel* tab_strip_model,
    commerce::EntryPointInfo entry_point_info,
    size_t threshold) {
  std::map<GURL, uint64_t> similar_products =
      entry_point_info.similar_candidate_products;
  if (similar_products.size() < threshold) {
    return false;
  }
  std::set<uint64_t> similar_product_ids;
  for (int i = 0; i < tab_strip_model->count(); i++) {
    GURL tab_url = tab_strip_model->GetWebContentsAt(i)->GetLastCommittedURL();
    if (similar_products.find(tab_url) != similar_products.end()) {
      similar_product_ids.insert(similar_products[tab_url]);
      if (similar_product_ids.size() >= threshold) {
        return true;
      }
    }
  }
  return similar_product_ids.size() >= threshold;
}

bool IsWindowValidForEntryPoint(TabStripModel* tab_strip_model,
                                commerce::EntryPointInfo entry_point_info) {
  return CheckWindowContainsEntryPointURLs(
      tab_strip_model, entry_point_info, kEligibleWindowUrlCountForValidation);
}

bool IsNavigationEligibleForEntryPoint(
    TabStripModel* tab_strip_model,
    commerce::EntryPointInfo entry_point_info) {
  return CheckWindowContainsEntryPointURLs(
      tab_strip_model, entry_point_info,
      kEligibleWindowUrlCountForNavigationTriggering);
}

void LogClusterUKM(const TabStripModel* tab_strip_model,
                   std::vector<GURL> urls,
                   std::optional<commerce::EntryPointInfo> entry_point_info) {
  // If there's no active index, it's likely that the tabstrip is in startup or
  // shutdown.
  if (!tab_strip_model ||
      tab_strip_model->active_index() == TabStripModel::kNoTab) {
    return;
  }
  // Create an event id to tie the UKM rows together.
  base::Time event_time = base::Time::Now();
  int64_t tab_strip_event_id =
      event_time.ToDeltaSinceWindowsEpoch().InMicroseconds();

  for (int tab_index = 0; tab_index < tab_strip_model->count(); tab_index++) {
    content::WebContents* contents =
        tab_strip_model->GetWebContentsAt(tab_index);
    const GURL& current_url = contents->GetLastCommittedURL();
    if (!base::Contains(urls, current_url)) {
      continue;
    }
    bool comparable_by_server =
        entry_point_info.has_value() &&
        base::Contains(entry_point_info->similar_candidate_products,
                       current_url);
    ukm::builders::Shopping_Compare_ClusterIdenfitiedByClient(
        contents->GetPrimaryMainFrame()->GetPageUkmSourceId())
        .SetCompareEventID(tab_strip_event_id)
        .SetComparableByServer(comparable_by_server)
        .Record(ukm::UkmRecorder::Get());
  }
}

}  // namespace

namespace commerce {

// TODO(b/340252809): No need to have browser as a dependency.
ProductSpecificationsEntryPointController::
    ProductSpecificationsEntryPointController(BrowserWindowInterface* browser)
    : browser_(browser),
      scoped_data_holder_(browser->GetUnownedUserDataHost(), this) {
  CHECK(browser_);
  browser_->GetTabStripModel()->AddObserver(this);
  shopping_service_ =
      ShoppingServiceFactory::GetForBrowserContext(browser_->GetProfile());
  if (shopping_service_) {
    product_specifications_service_ =
        shopping_service_->GetProductSpecificationsService();
    cluster_manager_ = shopping_service_->GetClusterManager();
    if (cluster_manager_) {
      cluster_manager_observations_.Observe(cluster_manager_);
    }
  }
}

ProductSpecificationsEntryPointController::
    ~ProductSpecificationsEntryPointController() = default;

// static
ProductSpecificationsEntryPointController*
ProductSpecificationsEntryPointController::From(
    BrowserWindowInterface* browser_window_interface) {
  return ScopedUnownedUserData<ProductSpecificationsEntryPointController>::Get(
      browser_window_interface->GetUnownedUserDataHost());
}

void ProductSpecificationsEntryPointController::OnTabStripModelChanged(
    TabStripModel* tab_strip_model,
    const TabStripModelChange& change,
    const TabStripSelectionChange& selection) {
  if (selection.active_tab_changed() &&
      ProductSpecificationsDisclosureDialog::CloseDialog()) {
    // Don't try to re-trigger the entry point when the dialog is closed due
    // to this tab model change.
    return;
  }

  if (change.type() == TabStripModelChange::Type::kRemoved) {
    MaybeHideEntryPoint();
  }
  // Filter out non-tab-selection events.
  if (change.type() != TabStripModelChange::Type::kSelectionOnly ||
      !selection.active_tab_changed() || !selection.old_contents ||
      !selection.new_contents || !cluster_manager_) {
    return;
  }
  const GURL old_url = selection.old_contents->GetLastCommittedURL();
  const GURL new_url = selection.new_contents->GetLastCommittedURL();

  cluster_manager_->GetEntryPointInfoForSelection(
      old_url, new_url,
      base::BindOnce(&ProductSpecificationsEntryPointController::
                         CheckEntryPointInfoForSelection,
                     weak_ptr_factory_.GetWeakPtr(), old_url, new_url));
}

void ProductSpecificationsEntryPointController::AddObserver(
    Observer* observer) {
  observers_.AddObserver(observer);
}

void ProductSpecificationsEntryPointController::RemoveObserver(
    Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ProductSpecificationsEntryPointController::OnEntryPointExecuted() {
  if (!current_entry_point_info_.has_value()) {
    return;
  }
  std::set<GURL> urls;
  auto candidate_products =
      current_entry_point_info_->similar_candidate_products;
  for (const auto& url_info :
       shopping_service_->GetUrlInfosForActiveWebWrappers()) {
    if (base::Contains(candidate_products, url_info.url)) {
      urls.insert(url_info.url);
    }
  }
  std::vector<GURL> urls_in_set(urls.begin(), urls.end());
  auto* prefs = browser_->GetProfile()->GetPrefs();
  if (!prefs) {
    return;
  }
  // If user has not accepted the latest disclosure, show the disclosure dialog
  // first.
  if (prefs->GetInteger(kProductSpecificationsAcceptedDisclosureVersion) !=
      static_cast<int>(product_specifications::mojom::DisclosureVersion::kV1)) {
    DialogArgs dialog_args(urls_in_set, current_entry_point_info_->title,
                           /*set_id=*/"",
                           /*in_new_tab=*/true);
    ProductSpecificationsDisclosureDialog::ShowDialog(
        browser_->GetProfile(),
        browser_->GetTabStripModel()->GetActiveWebContents(),
        std::move(dialog_args));
    return;
  }
  // Reset entry point show gap time.
  browser_->GetProfile()->GetPrefs()->SetInteger(
      commerce::kProductSpecificationsEntryPointShowIntervalInDays, 0);
  std::vector<commerce::UrlInfo> url_infos;
  for (const auto& url : urls_in_set) {
    url_infos.emplace_back(url, std::u16string());
  }
  const std::optional<ProductSpecificationsSet> set =
      product_specifications_service_->AddProductSpecificationsSet(
          current_entry_point_info_->title, std::move(url_infos));
  if (set.has_value()) {
    // TODO(https://issues.chromium.org/issues/365046217)
    // Have to downcast here to get this to work. Migration from Browser* to
    // BrowserWindowInterface* in progress.
    chrome::AddTabAt(static_cast<Browser*>(browser_),
                     commerce::GetProductSpecsTabUrlForID(set->uuid()),
                     browser_->GetTabStripModel()->count(), true, std::nullopt);
  }
}

void ProductSpecificationsEntryPointController::OnEntryPointDismissed() {
  DCHECK(current_entry_point_info_.has_value());
  current_entry_point_info_.reset();

  auto* prefs = browser_->GetProfile()->GetPrefs();
  int current_gap_time_days = prefs->GetInteger(
      commerce::kProductSpecificationsEntryPointShowIntervalInDays);
  // Double the gap time for every dismiss, starting from one day.
  if (current_gap_time_days == 0) {
    current_gap_time_days = 1;
  } else {
    current_gap_time_days = std::min(
        2 * current_gap_time_days, kProductSpecMaxEntryPointTriggeringInterval);
  }
  base::UmaHistogramCounts100("Commerce.Compare.ProactiveBackoffDuration",
                              current_gap_time_days);
  prefs->SetInteger(
      commerce::kProductSpecificationsEntryPointShowIntervalInDays,
      current_gap_time_days);
  prefs->SetTime(commerce::kProductSpecificationsEntryPointLastDismissedTime,
                 base::Time::Now());
}

void ProductSpecificationsEntryPointController::OnEntryPointHidden() {
  DCHECK(current_entry_point_info_.has_value());
  current_entry_point_info_.reset();
}

bool ProductSpecificationsEntryPointController::ShouldExecuteEntryPointShow() {
  DCHECK(current_entry_point_info_.has_value());
  GURL current_url = browser_->GetTabStripModel()
                         ->GetActiveWebContents()
                         ->GetLastCommittedURL();
  std::map<GURL, uint64_t> candidate_products =
      current_entry_point_info_->similar_candidate_products;
  return base::Contains(candidate_products, current_url);
}

void ProductSpecificationsEntryPointController::OnClusterFinishedForNavigation(
    const GURL& url) {
  // Cluster finished for a navigation that didn't happen in this window.
  bool in_window = false;
  for (int i = 0; i < browser_->GetTabStripModel()->count(); i++) {
    if (browser_->GetTabStripModel()
            ->GetWebContentsAt(i)
            ->GetLastCommittedURL() == url) {
      in_window = true;
      break;
    }
  }
  if (!in_window) {
    return;
  }

  cluster_manager_->GetEntryPointInfoForNavigation(
      url, base::BindOnce(&ProductSpecificationsEntryPointController::
                              CheckEntryPointInfoForNavigation,
                          weak_ptr_factory_.GetWeakPtr()));
}

void ProductSpecificationsEntryPointController::DidFinishNavigation(
    content::WebContents* contents) {
  // TODO(b/343109556): Instead of hiding, sometimes we'll need to update
  // the showing entry point.
  MaybeHideEntryPoint();
  if (contents == browser_->GetTabStripModel()->GetActiveWebContents()) {
    ProductSpecificationsDisclosureDialog::CloseDialog();
  }
}

void ProductSpecificationsEntryPointController::CheckEntryPointInfoForSelection(
    const GURL old_url,
    const GURL new_url,
    std::optional<EntryPointInfo> entry_point_info) {
  if (!entry_point_info.has_value()) {
    return;
  }

  std::map<GURL, uint64_t> similar_products =
      entry_point_info->similar_candidate_products;
  if (similar_products.find(old_url) == similar_products.end() ||
      similar_products.find(new_url) == similar_products.end()) {
    return;
  }
  if (similar_products[old_url] == similar_products[new_url]) {
    return;
  }
  base::UmaHistogramEnumeration("Commerce.Compare.CandidateClusterIdentified",
                                CompareEntryPointTrigger::FROM_SELECTION);
  // Skip server-side check unless specified by feature param.
  if (kProductSpecificationsUseServerClustering.Get()) {
    // TODO(qinmin): we should check whether tabstrips have changed while
    // waiting for the callback.
    cluster_manager_->GetComparableProducts(
        entry_point_info.value(),
        base::BindOnce(&ProductSpecificationsEntryPointController::
                           ShowEntryPointWithTitleForSelection,
                       weak_ptr_factory_.GetWeakPtr(), old_url, new_url));
  } else {
    ShowEntryPointWithTitle(std::move(entry_point_info));
  }
}

void ProductSpecificationsEntryPointController::
    ShowEntryPointWithTitleForSelection(
        const GURL old_url,
        const GURL new_url,
        std::optional<EntryPointInfo> entry_point_info) {
  LogClusterUKM(browser_->GetTabStripModel(), {old_url, new_url},
                entry_point_info);
  if (!entry_point_info.has_value()) {
    base::RecordAction(
        base::UserMetricsAction("Commerce.Compare.CandidateClusterRejected"));
    return;
  }

  std::map<GURL, uint64_t> similar_products =
      entry_point_info->similar_candidate_products;
  if (similar_products.find(old_url) == similar_products.end() ||
      similar_products.find(new_url) == similar_products.end()) {
    base::RecordAction(
        base::UserMetricsAction("Commerce.Compare.CandidateClusterRejected"));
    return;
  }
  ShowEntryPointWithTitle(std::move(entry_point_info));
}

void ProductSpecificationsEntryPointController::
    CheckEntryPointInfoForNavigation(
        std::optional<EntryPointInfo> entry_point_info) {
  if (!entry_point_info.has_value()) {
    return;
  }

  if (!IsNavigationEligibleForEntryPoint(browser_->GetTabStripModel(),
                                         entry_point_info.value())) {
    return;
  }
  base::UmaHistogramEnumeration("Commerce.Compare.CandidateClusterIdentified",
                                CompareEntryPointTrigger::FROM_NAVIGATION);
  // Skip server-side check unless specified by feature param.
  if (kProductSpecificationsUseServerClustering.Get()) {
    // TODO(qinmin): we should check whether tabstrips have changed while
    // waiting for the callback.
    std::vector<GURL> cluster_urls;
    for (const auto& pair : entry_point_info->similar_candidate_products) {
      cluster_urls.push_back(pair.first);
    }
    cluster_manager_->GetComparableProducts(
        entry_point_info.value(),
        base::BindOnce(&ProductSpecificationsEntryPointController::
                           ShowEntryPointWithTitleForNavigation,
                       weak_ptr_factory_.GetWeakPtr(), cluster_urls));
  } else {
    ShowEntryPointWithTitle(std::move(entry_point_info));
  }
}

void ProductSpecificationsEntryPointController::
    ShowEntryPointWithTitleForNavigation(
        std::vector<GURL> urls,
        std::optional<EntryPointInfo> entry_point_info) {
  LogClusterUKM(browser_->GetTabStripModel(), urls, entry_point_info);
  if (!entry_point_info.has_value()) {
    base::RecordAction(
        base::UserMetricsAction("Commerce.Compare.CandidateClusterRejected"));
    return;
  }

  if (!IsNavigationEligibleForEntryPoint(browser_->GetTabStripModel(),
                                         entry_point_info.value())) {
    base::RecordAction(
        base::UserMetricsAction("Commerce.Compare.CandidateClusterRejected"));
    return;
  }
  ShowEntryPointWithTitle(std::move(entry_point_info));
}

void ProductSpecificationsEntryPointController::ShowEntryPointWithTitle(
    std::optional<EntryPointInfo> entry_point_info) {
  // Using the entry point UI will initiate a data fetch for the product
  // specifications feature. If we're not allowed to fetch this data, don't
  // offer the entry point.
  if (!CanFetchProductSpecificationsData(
          shopping_service_->GetAccountChecker())) {
    return;
  }

  auto* prefs = browser_->GetProfile()->GetPrefs();
  int current_gap_time = prefs->GetInteger(
      commerce::kProductSpecificationsEntryPointShowIntervalInDays);
  // Back off triggering if gap time is not finished yet.
  if (base::Time::Now() -
          prefs->GetTime(
              commerce::kProductSpecificationsEntryPointLastDismissedTime) <=
      base::Days(current_gap_time)) {
    return;
  }
  current_entry_point_info_ = entry_point_info;
  // Show the default title if the set title is too long.
  std::u16string title =
      entry_point_info->title.size() > kEntryPointTitleMaxLength
          ? l10n_util::GetStringUTF16(IDS_COMPARE_ENTRY_POINT_DEFAULT)
          : l10n_util::GetStringFUTF16(
                IDS_COMPARE_ENTRY_POINT,
                base::UTF8ToUTF16(entry_point_info->title));
  base::UmaHistogramCounts100(
      "Commerce.Compare.CandidateClusterSizeWhenShown",
      entry_point_info->similar_candidate_products.size());
  for (auto& observer : observers_) {
    observer.ShowEntryPointWithTitle(title);
  }
}

void ProductSpecificationsEntryPointController::MaybeHideEntryPoint() {
  if (!current_entry_point_info_.has_value() ||
      IsWindowValidForEntryPoint(browser_->GetTabStripModel(),
                                 current_entry_point_info_.value())) {
    return;
  }
  for (auto& observer : observers_) {
    observer.HideEntryPoint();
  }
}
}  // namespace commerce