File: download_bubble_ui_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 (439 lines) | stat: -rw-r--r-- 17,816 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
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
// Copyright 2022 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/bubble/download_bubble_ui_controller.h"

#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_index/content_index_provider_impl.h"
#include "chrome/browser/download/bubble/download_bubble_prefs.h"
#include "chrome/browser/download/bubble/download_bubble_update_service.h"
#include "chrome/browser/download/bubble/download_bubble_update_service_factory.h"
#include "chrome/browser/download/bubble/download_bubble_utils.h"
#include "chrome/browser/download/bubble/download_display_controller.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_item_warning_data.h"
#include "chrome/browser/download/download_item_web_app_data.h"
#include "chrome/browser/download/download_ui_model.h"
#include "chrome/browser/download/download_warning_desktop_hats_utils.h"
#include "chrome/browser/download/offline_item_model_manager.h"
#include "chrome/browser/download/offline_item_model_manager_factory.h"
#include "chrome/browser/download/offline_item_utils.h"
#include "chrome/browser/feature_engagement/tracker_factory.h"
#include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service_factory.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_stats.h"
#include "components/feature_engagement/public/tracker.h"
#include "components/offline_items_collection/core/offline_content_aggregator.h"
#include "components/safe_browsing/buildflags.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#endif

namespace {

using DownloadCreationType = ::download::DownloadItem::DownloadCreationType;
using DownloadUIModelPtr = DownloadUIModel::DownloadUIModelPtr;

// Don't show the partial view more than once per 15 seconds, as this pops up
// automatically and may be annoying to the user. The time is reset when the
// user clicks on the button to open the main view.
constexpr base::TimeDelta kShowPartialViewMinInterval = base::Seconds(15);

bool IsForDownload(Browser* browser, download::DownloadItem* item) {
  Profile* profile = Profile::FromBrowserContext(
      content::DownloadItemUtils::GetBrowserContext(item));
  // An off-the-record `profile` should match only the off-the-record browsers,
  // but a regular `profile` should match both the regular and off-the-record
  // browsers.
  if (browser->profile() != profile &&
      browser->profile()->GetOriginalProfile() != profile) {
    return false;
  }

  if (DownloadItemWebAppData* web_app_data = DownloadItemWebAppData::Get(item);
      web_app_data) {
    return web_app::AppBrowserController::IsForWebApp(browser,
                                                      web_app_data->id());
  } else {
    return !web_app::AppBrowserController::IsWebApp(browser);
  }
}

}  // namespace

// static
DownloadBubbleUIController* DownloadBubbleUIController::GetForDownload(
    download::DownloadItem* item) {
  for (Browser* browser : BrowserList::GetInstance()->OrderedByActivation()) {
    if (IsForDownload(browser, item) && browser->window() &&
        browser->window()->GetDownloadBubbleUIController()) {
      return browser->window()->GetDownloadBubbleUIController();
    }
  }
  return nullptr;
}

DownloadBubbleUIController::DownloadBubbleUIController(Browser* browser)
    : DownloadBubbleUIController(
          browser,
          DownloadBubbleUpdateServiceFactory::GetForProfile(
              browser->profile())) {}

DownloadBubbleUIController::DownloadBubbleUIController(
    Browser* browser,
    DownloadBubbleUpdateService* update_service)
    : browser_(browser),
      profile_(browser->profile()),
      update_service_(update_service),
      offline_manager_(
          OfflineItemModelManagerFactory::GetForBrowserContext(profile_)) {
  if (MaybeGetDownloadWarningHatsTrigger(
          DownloadWarningHatsType::kDownloadBubbleIgnore)) {
    delayed_hats_launcher_ =
        std::make_unique<DelayedDownloadWarningHatsLauncher>(
            profile_, GetIgnoreDownloadBubbleWarningDelay(),
            base::BindRepeating(&DownloadBubbleUIController::CompleteHatsPsd,
                                weak_factory_.GetWeakPtr()));
    browser_activity_watcher_ = std::make_unique<BrowserActivityWatcher>(
        base::BindRepeating(&DownloadBubbleUIController::OnBrowserActivity,
                            weak_factory_.GetWeakPtr()));
  }
}

DownloadBubbleUIController::~DownloadBubbleUIController() = default;

void DownloadBubbleUIController::HideDownloadUi() {
  display_controller_->HideToolbarButton();
}

void DownloadBubbleUIController::HandleButtonPressed() {
  display_controller_->HandleButtonPressed();
}

void DownloadBubbleUIController::OnOfflineItemsAdded(
    const OfflineContentProvider::OfflineItemList& items) {
  display_controller_->OnNewItem(/*show_animation=*/false);
}

void DownloadBubbleUIController::OnDownloadItemAdded(
    download::DownloadItem* item,
    bool may_show_animation) {
  DownloadItemModel model(item);
  if (model.ShouldNotifyUI()) {
    model.SetActionedOn(false);
  }
  display_controller_->OnNewItem(may_show_animation &&
                                 model.ShouldShowDownloadStartedAnimation());
}

void DownloadBubbleUIController::OnOfflineItemRemoved(const ContentId& id) {
  if (OfflineItemUtils::IsDownload(id)) {
    return;
  }
  offline_manager_->RemoveOfflineItemModelData(id);
  display_controller_->OnRemovedItem(id);
}

void DownloadBubbleUIController::OnDownloadItemRemoved(
    download::DownloadItem* item) {
  std::make_unique<DownloadItemModel>(item)->SetActionedOn(true);
  const ContentId& id = OfflineItemUtils::GetContentIdForDownload(item);
  display_controller_->OnRemovedItem(id);
}

void DownloadBubbleUIController::OnOfflineItemUpdated(const OfflineItem& item) {
  OfflineItemModel model(offline_manager_, item);
  bool may_show_details =
      model.ShouldShowInBubble() &&
      (browser_ == chrome::FindLastActiveWithProfile(profile_.get()));
  // Consider dangerous in-progress downloads to be completed.
  bool is_done = model.IsDone() ||
                 (model.GetState() == download::DownloadItem::IN_PROGRESS &&
                  !IsModelInProgress(&model));
  display_controller_->OnUpdatedItem(is_done, may_show_details);
}

void DownloadBubbleUIController::OnDownloadItemUpdated(
    download::DownloadItem* item) {
  DownloadItemModel model(item);
  bool may_show_details =
      model.ShouldShowInBubble() &&
      (browser_ == chrome::FindLastActiveWithProfile(profile_.get()));
  // Consider dangerous in-progress downloads to be completed.
  bool is_done = item->IsDone() ||
                 (item->GetState() == download::DownloadItem::IN_PROGRESS &&
                  !IsItemInProgress(item));
  if (model.IsDangerous()) {
    RecordDangerousDownloadShownToUser(item);
  }
  display_controller_->OnUpdatedItem(is_done, may_show_details);
}

std::vector<DownloadUIModelPtr> DownloadBubbleUIController::GetDownloadUIModels(
    bool is_main_view) {
  std::vector<DownloadUIModelPtr> all_items;
  if (!update_service_->IsInitialized()) {
    return all_items;
  }
  update_service_->GetAllModelsToDisplay(
      all_items, GetWebAppIdForBrowser(browser_),
      /*force_backfill_download_items=*/true);
  std::vector<DownloadUIModelPtr> items_to_return;
  for (auto& model : all_items) {
    if (!is_main_view && model->WasActionedOn()) {
      continue;
    }
    // Partial view entries are removed if viewed on the main view after
    // completion.
    if (is_main_view && !IsModelInProgress(model.get())) {
      model->SetActionedOn(true);
    }
    items_to_return.push_back(std::move(model));
  }
  return items_to_return;
}

std::vector<DownloadUIModelPtr> DownloadBubbleUIController::GetMainView() {
  last_partial_view_shown_time_ = std::nullopt;
  last_primary_view_was_partial_ = false;
  std::vector<DownloadUIModelPtr> list =
      GetDownloadUIModels(/*is_main_view=*/true);
  base::UmaHistogramCounts100("Download.Bubble.FullViewSize", list.size());
  return list;
}

std::vector<DownloadUIModelPtr> DownloadBubbleUIController::GetPartialView() {
  base::Time now = base::Time::Now();
  if (last_partial_view_shown_time_.has_value() &&
      now - *last_partial_view_shown_time_ < kShowPartialViewMinInterval) {
    return {};
  }
  if (!download::IsDownloadBubblePartialViewEnabled(profile_)) {
    return {};
  }
  std::vector<DownloadUIModelPtr> list =
      GetDownloadUIModels(/*is_main_view=*/false);
  if (!list.empty()) {
    last_primary_view_was_partial_ = true;
    last_partial_view_shown_time_ = std::make_optional(now);
  }
  base::UmaHistogramCounts100("Download.Bubble.PartialViewSize", list.size());
  return list;
}

void DownloadBubbleUIController::ProcessDownloadButtonPress(
    base::WeakPtr<DownloadUIModel> model,
    DownloadCommands::Command command,
    bool is_main_view) {
  if (!model) {
    return;
  }
  download::DownloadItem* item = model->GetDownloadItem();
  DownloadCommands commands(model);
  base::UmaHistogramEnumeration("Download.Bubble.ProcessedCommand2", command);
  DownloadItemWarningData::WarningSurface warning_surface =
      is_main_view ? DownloadItemWarningData::WarningSurface::BUBBLE_MAINPAGE
                   : DownloadItemWarningData::WarningSurface::BUBBLE_SUBPAGE;
  DownloadItemWarningData::WarningAction warning_action =
      command == DownloadCommands::KEEP
          ? DownloadItemWarningData::WarningAction::PROCEED
          : DownloadItemWarningData::WarningAction::DISCARD;
  switch (command) {
    case DownloadCommands::KEEP:
    case DownloadCommands::DISCARD: {
      if (safe_browsing::IsSafeBrowsingSurveysEnabled(*profile_->GetPrefs())) {
        TrustSafetySentimentService* trust_safety_sentiment_service =
            TrustSafetySentimentServiceFactory::GetForProfile(profile_);
        if (trust_safety_sentiment_service) {
          trust_safety_sentiment_service->InteractedWithDownloadWarningUI(
              warning_surface, warning_action);
        }
      }
      DownloadItemWarningData::AddWarningActionEvent(item, warning_surface,
                                                     warning_action);
      // Launch a HaTS survey. Note this needs to come before the command is
      // executed, as that may change the state of the DownloadItem.
      if (item && CanShowDownloadWarningHatsSurvey(item)) {
        DownloadWarningHatsType survey_type =
            command == DownloadCommands::KEEP
                ? DownloadWarningHatsType::kDownloadBubbleBypass
                : DownloadWarningHatsType::kDownloadBubbleHeed;
        auto psd =
            DownloadWarningHatsProductSpecificData::Create(survey_type, item);
        CompleteHatsPsd(psd);
        MaybeLaunchDownloadWarningHatsSurvey(profile_, psd);
      }
      commands.ExecuteCommand(command);
      break;
    }
    case DownloadCommands::REVIEW:
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
      model->ReviewScanningVerdict(
          browser_->tab_strip_model()->GetActiveWebContents());
#endif
      break;
    case DownloadCommands::RETRY:
      RetryDownload(model.get(), command);
      break;
    case DownloadCommands::CANCEL:
      model->SetActionedOn(true);
      commands.ExecuteCommand(command);
      break;
    case DownloadCommands::BYPASS_DEEP_SCANNING: {
      DownloadItemWarningData::AddWarningActionEvent(
          item, warning_surface,
          DownloadItemWarningData::WarningAction::PROCEED_DEEP_SCAN);
      // Launch a HaTS survey. Note this needs to come before the command is
      // executed, as that may change the state of the DownloadItem.
      if (item && CanShowDownloadWarningHatsSurvey(item)) {
        auto psd = DownloadWarningHatsProductSpecificData::Create(
            DownloadWarningHatsType::kDownloadBubbleBypass, item);
        CompleteHatsPsd(psd);
        MaybeLaunchDownloadWarningHatsSurvey(profile_, psd);
      }
      commands.ExecuteCommand(command);
      break;
    }
    case DownloadCommands::LEARN_MORE_SCANNING:
    case DownloadCommands::LEARN_MORE_DOWNLOAD_BLOCKED:
      DownloadItemWarningData::AddWarningActionEvent(
          model->GetDownloadItem(), warning_surface,
          DownloadItemWarningData::WarningAction::OPEN_LEARN_MORE_LINK);
      commands.ExecuteCommand(command);
      break;
    case DownloadCommands::DEEP_SCAN:
    case DownloadCommands::RESUME:
    case DownloadCommands::PAUSE:
    case DownloadCommands::OPEN_WHEN_COMPLETE:
    case DownloadCommands::SHOW_IN_FOLDER:
    case DownloadCommands::ALWAYS_OPEN_TYPE:
    case DownloadCommands::CANCEL_DEEP_SCAN:
    case DownloadCommands::OPEN_SAFE_BROWSING_SETTING:
      commands.ExecuteCommand(command);
      break;
    default:
      NOTREACHED() << "Unexpected button pressed on download bubble: "
                   << command;
  }
}

void DownloadBubbleUIController::RetryDownload(
    DownloadUIModel* model,
    DownloadCommands::Command command) {
  DCHECK(command == DownloadCommands::RETRY);
  display_controller_->HideBubble();
  content::DownloadManager* download_manager = profile_->GetDownloadManager();
  if (!download_manager) {
    return;
  }
  RecordDownloadRetry(
      OfflineItemUtils::ConvertFailStateToDownloadInterruptReason(
          model->GetLastFailState()));

  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("download_bubble_retry_download", R"(
        semantics {
          sender: "The download bubble"
          description: "Kick off retrying an interrupted download."
          trigger:
            "The user selects the retry button for an interrupted download on "
            "the downloads bubble."
          data: "None"
          destination: WEBSITE
        }
        policy {
          cookies_allowed: YES
          cookies_store: "user"
          setting:
            "This feature cannot be disabled by settings, but it's only "
            "triggered by user request."
          policy_exception_justification: "Not implemented."
        })");

  // Use the last URL in the chain like resumption does.
  auto download_url_params = std::make_unique<download::DownloadUrlParameters>(
      model->GetURL(), traffic_annotation);
  // Set to false because user interaction is needed.
  download_url_params->set_content_initiated(false);
  download_url_params->set_download_source(
      download::DownloadSource::RETRY_FROM_BUBBLE);

  download_manager->DownloadUrl(std::move(download_url_params));
}

void DownloadBubbleUIController::ScheduleCancelForEphemeralWarning(
    const std::string& guid) {
  // Schedule hiding the item from the download bubble.
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&DownloadBubbleUpdateService::OnEphemeralWarningExpired,
                     update_service_->GetWeakPtr(), guid),
      DownloadItemModel::kEphemeralWarningLifetimeOnBubble);

  // Schedule cancelling the download altogether.
  DownloadCoreService* download_core_service =
      DownloadCoreServiceFactory::GetForBrowserContext(profile_);
  if (!download_core_service) {
    return;
  }
  ChromeDownloadManagerDelegate* delegate =
      download_core_service->GetDownloadManagerDelegate();
  if (delegate) {
    delegate->ScheduleCancelForEphemeralWarning(guid);
  }
}

void DownloadBubbleUIController::CompleteHatsPsd(
    DownloadWarningHatsProductSpecificData& psd) {
  psd.AddPartialViewInteraction(last_primary_view_was_partial());
}

void DownloadBubbleUIController::OnBrowserActivity() {
  CHECK(browser_activity_watcher_);
  CHECK(delayed_hats_launcher_);
  delayed_hats_launcher_->RecordBrowserActivity();
}

void DownloadBubbleUIController::RecordDangerousDownloadShownToUser(
    download::DownloadItem* download) {
  feature_engagement::Tracker* tracker =
      feature_engagement::TrackerFactory::GetForBrowserContext(
          browser_->profile());
  tracker->NotifyEvent("download_bubble_dangerous_download_detected");

  // Schedule a survey to be shown if the user ignores the survey for the whole
  // delay period, but is otherwise actively using the browser.
  if (CanShowDownloadWarningHatsSurvey(download) && delayed_hats_launcher_) {
    delayed_hats_launcher_->TryScheduleTask(
        DownloadWarningHatsType::kDownloadBubbleIgnore, download);
  }
}

base::WeakPtr<DownloadBubbleUIController>
DownloadBubbleUIController::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}