File: office_file_tasks.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 (715 lines) | stat: -rw-r--r-- 29,714 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// Copyright 2023 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/ash/file_manager/office_file_tasks.h"

#include <algorithm>
#include <initializer_list>
#include <string_view>

#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/strings/string_util.h"
#include "base/types/cxx23_to_underlying.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/ash/drive/drive_integration_service_factory.h"
#include "chrome/browser/ash/drive/file_system_util.h"
#include "chrome/browser/ash/file_manager/file_tasks.h"
#include "chrome/browser/ash/file_manager/virtual_file_tasks.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_open_metrics.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload_dialog.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload_util.h"
#include "chrome/browser/ui/webui/ash/office_fallback/office_fallback_ui.h"
#include "chrome/common/extensions/api/file_manager_private.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/file_manager/app_id.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/services/app_service/public/cpp/types_util.h"
#include "content/public/browser/network_service_instance.h"
#include "extensions/common/constants.h"

namespace file_manager::file_tasks {

namespace {

// The map with pairs Office file extensions with their corresponding
// `OfficeOpenExtensions` enum.
constexpr auto kExtensionToOfficeOpenExtensionsEnum =
    base::MakeFixedFlatMap<std::string_view, OfficeOpenExtensions>(
        {{".doc", OfficeOpenExtensions::kDoc},
         {".docm", OfficeOpenExtensions::kDocm},
         {".docx", OfficeOpenExtensions::kDocx},
         {".dotm", OfficeOpenExtensions::kDotm},
         {".dotx", OfficeOpenExtensions::kDotx},
         {".odp", OfficeOpenExtensions::kOdp},
         {".ods", OfficeOpenExtensions::kOds},
         {".odt", OfficeOpenExtensions::kOdt},
         {".pot", OfficeOpenExtensions::kPot},
         {".potm", OfficeOpenExtensions::kPotm},
         {".potx", OfficeOpenExtensions::kPotx},
         {".ppam", OfficeOpenExtensions::kPpam},
         {".pps", OfficeOpenExtensions::kPps},
         {".ppsm", OfficeOpenExtensions::kPpsm},
         {".ppsx", OfficeOpenExtensions::kPpsx},
         {".ppt", OfficeOpenExtensions::kPpt},
         {".pptm", OfficeOpenExtensions::kPptm},
         {".pptx", OfficeOpenExtensions::kPptx},
         {".xls", OfficeOpenExtensions::kXls},
         {".xlsb", OfficeOpenExtensions::kXlsb},
         {".xlsm", OfficeOpenExtensions::kXlsm},
         {".xlsx", OfficeOpenExtensions::kXlsx}});

OfficeOpenExtensions GetOfficeOpenExtension(const storage::FileSystemURL& url) {
  const std::string extension = base::ToLowerASCII(url.path().FinalExtension());
  auto itr = kExtensionToOfficeOpenExtensionsEnum.find(extension);
  if (itr != kExtensionToOfficeOpenExtensionsEnum.end()) {
    return itr->second;
  }
  return OfficeOpenExtensions::kOther;
}

std::optional<ash::office_fallback::FallbackReason>
DriveAvailabilityToFallbackReason(
    drive::util::DriveAvailability drive_availability) {
  switch (drive_availability) {
    case drive::util::DriveAvailability::
        kNotAvailableWhenDisableDrivePreferenceSet:
      return ash::office_fallback::FallbackReason::kDisableDrivePreferenceSet;
    case drive::util::DriveAvailability::kNotAvailableForAccountType:
      return ash::office_fallback::FallbackReason::kDriveDisabledForAccountType;
    case drive::util::DriveAvailability::
        kNotAvailableForUninitialisedLoginState:
    case drive::util::DriveAvailability::kNotAvailableInIncognito:
    case drive::util::DriveAvailability::kNotAvailableForTestImage:
      return ash::office_fallback::FallbackReason::kDriveDisabled;
    case drive::util::DriveAvailability::kAvailable:
      return std::nullopt;
  }
}

std::optional<ash::office_fallback::FallbackReason>
DriveConnectionStatusToFallbackReason(
    drive::util::ConnectionStatus drive_connection_status) {
  switch (drive_connection_status) {
    case drive::util::ConnectionStatus::kNoService:
      return ash::office_fallback::FallbackReason::kNoDriveService;
    case drive::util::ConnectionStatus::kNoNetwork:
      return ash::office_fallback::FallbackReason::kOffline;
    case drive::util::ConnectionStatus::kNotReady:
      return ash::office_fallback::FallbackReason::kDriveAuthenticationNotReady;
    case drive::util::ConnectionStatus::kMetered:
      return ash::office_fallback::FallbackReason::kMeteredConnection;
    case drive::util::ConnectionStatus::kConnected:
      return std::nullopt;
  }
}

bool AnyFileNeedsUploadToDrive(
    Profile* profile,
    const std::vector<storage::FileSystemURL>& file_urls) {
  return !std::ranges::all_of(file_urls, [profile](const auto& url) {
    return ash::cloud_upload::PathIsOnDriveFS(profile, url.path());
  });
}

}  // namespace

void RegisterOfficeProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(prefs::kOfficeFilesAlwaysMoveToDrive, false);
  registry->RegisterBooleanPref(prefs::kOfficeFilesAlwaysMoveToOneDrive, false);
  registry->RegisterBooleanPref(prefs::kOfficeMoveConfirmationShownForDrive,
                                false);
  registry->RegisterBooleanPref(prefs::kOfficeMoveConfirmationShownForOneDrive,
                                false);
  registry->RegisterBooleanPref(
      prefs::kOfficeMoveConfirmationShownForLocalToDrive, false);
  registry->RegisterBooleanPref(
      prefs::kOfficeMoveConfirmationShownForLocalToOneDrive, false);
  registry->RegisterBooleanPref(
      prefs::kOfficeMoveConfirmationShownForCloudToDrive, false);
  registry->RegisterBooleanPref(
      prefs::kOfficeMoveConfirmationShownForCloudToOneDrive, false);
  registry->RegisterTimePref(prefs::kOfficeFileMovedToOneDrive, base::Time());
  registry->RegisterTimePref(prefs::kOfficeFileMovedToGoogleDrive,
                             base::Time());
}

void RecordOfficeOpenExtensionDriveMetric(
    const storage::FileSystemURL& file_url) {
  UMA_HISTOGRAM_ENUMERATION(
      file_manager::file_tasks::kOfficeOpenExtensionDriveMetricName,
      GetOfficeOpenExtension(file_url));
}

void RecordOfficeOpenExtensionOneDriveMetric(
    const storage::FileSystemURL& file_url) {
  UMA_HISTOGRAM_ENUMERATION(
      file_manager::file_tasks::kOfficeOpenExtensionOneDriveMetricName,
      GetOfficeOpenExtension(file_url));
}

bool ExecuteWebDriveOfficeTask(
    Profile* profile,
    const TaskDescriptor& task,
    const std::vector<storage::FileSystemURL>& file_urls,
    std::unique_ptr<ash::cloud_upload::CloudOpenMetrics> cloud_open_metrics) {
  const drive::util::DriveAvailability drive_availability =
      drive::util::CheckDriveEnabledAndDriveAvailabilityForProfile(profile);
  std::optional<ash::office_fallback::FallbackReason> fallback_reason_opt =
      DriveAvailabilityToFallbackReason(drive_availability);
  if (fallback_reason_opt) {
    ash::office_fallback::FallbackReason fallback_reason =
        fallback_reason_opt.value();
    return GetUserFallbackChoice(
        profile, task, file_urls, fallback_reason,
        base::BindOnce(&OnDialogChoiceReceived, profile, task, file_urls,
                       fallback_reason, std::move(cloud_open_metrics)));
  }

  const drive::util::ConnectionStatus drive_connection_status =
      drive::util::GetDriveConnectionStatus(profile);
  fallback_reason_opt =
      DriveConnectionStatusToFallbackReason(drive_connection_status);
  if (fallback_reason_opt &&
      (fallback_reason_opt !=
           ash::office_fallback::FallbackReason::kMeteredConnection ||
       AnyFileNeedsUploadToDrive(profile, file_urls))) {
    ash::office_fallback::FallbackReason fallback_reason =
        fallback_reason_opt.value();
    return GetUserFallbackChoice(
        profile, task, file_urls, fallback_reason,
        base::BindOnce(&OnDialogChoiceReceived, profile, task, file_urls,
                       fallback_reason, std::move(cloud_open_metrics)));
  }

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(profile);
  if (!integration_service || !integration_service->IsMounted() ||
      !integration_service->GetDriveFsInterface()) {
    ash::office_fallback::FallbackReason fallback_reason =
        ash::office_fallback::FallbackReason::kDriveFsInterfaceError;
    return GetUserFallbackChoice(
        profile, task, file_urls, fallback_reason,
        base::BindOnce(&OnDialogChoiceReceived, profile, task, file_urls,
                       fallback_reason, std::move(cloud_open_metrics)));
  }

  return ash::cloud_upload::CloudOpenTask::Execute(
      profile, file_urls, task, ash::cloud_upload::CloudProvider::kGoogleDrive,
      std::move(cloud_open_metrics));
}

bool ExecuteOpenInOfficeTask(
    Profile* profile,
    const TaskDescriptor& task,
    const std::vector<storage::FileSystemURL>& file_urls,
    std::unique_ptr<ash::cloud_upload::CloudOpenMetrics> cloud_open_metrics) {
  if (content::GetNetworkConnectionTracker()->IsOffline()) {
    ash::office_fallback::FallbackReason fallback_reason =
        ash::office_fallback::FallbackReason::kOffline;
    return GetUserFallbackChoice(
        profile, task, file_urls, fallback_reason,
        base::BindOnce(&OnDialogChoiceReceived, profile, task, file_urls,
                       fallback_reason, std::move(cloud_open_metrics)));
  }

  return ash::cloud_upload::CloudOpenTask::Execute(
      profile, file_urls, task, ash::cloud_upload::CloudProvider::kOneDrive,
      std::move(cloud_open_metrics));
}

void LaunchQuickOffice(Profile* profile,
                       const std::vector<storage::FileSystemURL>& file_urls) {
  const TaskDescriptor quick_office_task(
      extension_misc::kQuickOfficeComponentExtensionId, TASK_TYPE_FILE_HANDLER,
      kActionIdQuickOffice);

  ExecuteFileTask(
      profile, quick_office_task, file_urls,
      base::BindOnce(
          [](extensions::api::file_manager_private::TaskResult result,
             std::string error_message) {
            if (!error_message.empty()) {
              LOG(ERROR) << "Fallback to QuickOffice for opening office file "
                            "with error message: "
                         << error_message
                         << " and result: " << base::to_underlying(result);
            }
          }));

  return;
}

void LogOneDriveMetricsAfterFallback(
    ash::office_fallback::FallbackReason fallback_reason,
    ash::cloud_upload::OfficeTaskResult task_result,
    std::unique_ptr<ash::cloud_upload::CloudOpenMetrics> cloud_open_metrics) {
  switch (fallback_reason) {
    case ash::office_fallback::FallbackReason::kOffline:
      cloud_open_metrics->LogOneDriveOpenError(
          ash::cloud_upload::OfficeOneDriveOpenErrors::kOffline);
      break;
    case ash::office_fallback::FallbackReason::
        kAndroidOneDriveUnsupportedLocation:
      cloud_open_metrics->LogOneDriveOpenError(
          ash::cloud_upload::OfficeOneDriveOpenErrors::
              kAndroidOneDriveUnsupportedLocation);
      break;
    case ash::office_fallback::FallbackReason::kDriveDisabled:
    case ash::office_fallback::FallbackReason::kNoDriveService:
    case ash::office_fallback::FallbackReason::kDriveAuthenticationNotReady:
    case ash::office_fallback::FallbackReason::kDriveFsInterfaceError:
    case ash::office_fallback::FallbackReason::kMeteredConnection:
    case ash::office_fallback::FallbackReason::kDisableDrivePreferenceSet:
    case ash::office_fallback::FallbackReason::kDriveDisabledForAccountType:
    case ash::office_fallback::FallbackReason::kWaitingForUpload:
      NOTREACHED();
  }
  cloud_open_metrics->LogTaskResult(task_result);
}

void LogGoogleDriveMetricsAfterFallback(
    ash::office_fallback::FallbackReason fallback_reason,
    ash::cloud_upload::OfficeTaskResult task_result,
    std::unique_ptr<ash::cloud_upload::CloudOpenMetrics> cloud_open_metrics) {
  switch (fallback_reason) {
    case ash::office_fallback::FallbackReason::kOffline:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kOffline);
      break;
    case ash::office_fallback::FallbackReason::kDriveDisabled:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kDriveDisabled);
      break;
    case ash::office_fallback::FallbackReason::kNoDriveService:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kNoDriveService);
      break;
    case ash::office_fallback::FallbackReason::kDriveAuthenticationNotReady:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::
              kDriveAuthenticationNotReady);
      break;
    case ash::office_fallback::FallbackReason::kDriveFsInterfaceError:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kDriveFsInterface);
      break;
    case ash::office_fallback::FallbackReason::kMeteredConnection:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kMeteredConnection);
      break;
    case ash::office_fallback::FallbackReason::kDisableDrivePreferenceSet:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::kDisableDrivePreferenceSet);
      break;
    case ash::office_fallback::FallbackReason::kDriveDisabledForAccountType:
      cloud_open_metrics->LogGoogleDriveOpenError(
          ash::cloud_upload::OfficeDriveOpenErrors::
              kDriveDisabledForAccountType);
      break;
    case ash::office_fallback::FallbackReason::kWaitingForUpload:
    case ash::office_fallback::FallbackReason::
        kAndroidOneDriveUnsupportedLocation:
      NOTREACHED();
  }
  cloud_open_metrics->LogTaskResult(task_result);
}

void OnDialogChoiceReceived(
    Profile* profile,
    const TaskDescriptor& task,
    const std::vector<storage::FileSystemURL>& file_urls,
    ash::office_fallback::FallbackReason fallback_reason,
    std::unique_ptr<ash::cloud_upload::CloudOpenMetrics> cloud_open_metrics,
    std::optional<const std::string> choice) {
  if (!choice.has_value()) {
    // The user's choice was unable to be retrieved.
    if (IsWebDriveOfficeTask(task)) {
      LogGoogleDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCannotGetFallbackChoice,
          std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      LogOneDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCannotGetFallbackChoice,
          std::move(cloud_open_metrics));
    }
    return;
  }

  if (choice.value() == ash::office_fallback::kDialogChoiceQuickOffice) {
    if (IsWebDriveOfficeTask(task)) {
      LogGoogleDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kFallbackQuickOffice,
          std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      LogOneDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kFallbackQuickOffice,
          std::move(cloud_open_metrics));
    }
    LaunchQuickOffice(profile, file_urls);
  } else if (choice.value() == ash::office_fallback::kDialogChoiceTryAgain) {
    // When retrying, the original open result is thrown away, so that
    // (likely the same) result codes from repeated retries are not counted.
    // Only the last open result is recorded: when the user either selects
    // QO or cancels.
    if (IsWebDriveOfficeTask(task)) {
      ExecuteWebDriveOfficeTask(profile, task, file_urls,
                                std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      ExecuteOpenInOfficeTask(profile, task, file_urls,
                              std::move(cloud_open_metrics));
    }
  } else if (choice.value() == ash::office_fallback::kDialogChoiceCancel) {
    if (IsWebDriveOfficeTask(task)) {
      LogGoogleDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCancelledAtFallback,
          std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      LogOneDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCancelledAtFallback,
          std::move(cloud_open_metrics));
    }
  } else if (choice.value() == ash::office_fallback::kDialogChoiceOk) {
    if (IsWebDriveOfficeTask(task)) {
      LogGoogleDriveMetricsAfterFallback(
          fallback_reason, ash::cloud_upload::OfficeTaskResult::kOkAtFallback,
          std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      LogOneDriveMetricsAfterFallback(
          fallback_reason, ash::cloud_upload::OfficeTaskResult::kOkAtFallback,
          std::move(cloud_open_metrics));
    }
  } else if (!choice.value().empty()) {
    LOG(ERROR) << "Unhandled response: " << choice.value();
  } else {
    // Always map an empty user response to a Cancel user response.
    // This can occur when the user logs out of the session. However,
    // since there could be other unknown causes, leave a log.
    LOG(ERROR) << "Empty user response";
    if (IsWebDriveOfficeTask(task)) {
      LogGoogleDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCancelledAtFallback,
          std::move(cloud_open_metrics));
    } else if (IsOpenInOfficeTask(task)) {
      LogOneDriveMetricsAfterFallback(
          fallback_reason,
          ash::cloud_upload::OfficeTaskResult::kCancelledAtFallback,
          std::move(cloud_open_metrics));
    }
  }
}

bool GetUserFallbackChoice(
    Profile* profile,
    const TaskDescriptor& task,
    const std::vector<storage::FileSystemURL>& file_urls,
    ash::office_fallback::FallbackReason fallback_reason,
    ash::office_fallback::DialogChoiceCallback callback) {
  // TODO(b/242685536) Add support for multi-file
  // selection so the OfficeFallbackDialog can display multiple file names and
  // `OnDialogChoiceReceived()` can open multiple files.
  std::vector<storage::FileSystemURL> first_url{file_urls.front()};

  // If QuickOffice is not installed, don't launch dialog.
  if (!IsQuickOfficeInstalled(profile)) {
    LOG(ERROR) << "Cannot fallback to QuickOffice when it is not installed";
    std::move(callback).Run(std::nullopt);
    return false;
  }

  std::string task_title;
  VirtualTask* virtual_task = FindVirtualTask(task);
  if (virtual_task) {
    task_title = virtual_task->title();
  }

  return ash::office_fallback::OfficeFallbackDialog::Show(
      first_url, fallback_reason, task_title, std::move(callback));
}

bool IsWebDriveOfficeTask(const TaskDescriptor& task) {
  const std::string action_id = ParseFilesAppActionId(task.action_id);
  bool is_web_drive_office_action_id =
      action_id == kActionIdWebDriveOfficeWord ||
      action_id == kActionIdWebDriveOfficeExcel ||
      action_id == kActionIdWebDriveOfficePowerPoint;
  return IsVirtualTask(task) && is_web_drive_office_action_id;
}

bool IsOpenInOfficeTask(const TaskDescriptor& task) {
  const std::string action_id = ParseFilesAppActionId(task.action_id);
  return IsVirtualTask(task) && action_id == kActionIdOpenInOffice;
}

bool IsQuickOfficeInstalled(Profile* profile) {
  apps::AppServiceProxy* proxy =
      apps::AppServiceProxyFactory::GetForProfile(profile);
  if (!proxy) {
    return false;
  }
  // The AppRegistryCache will contain the QuickOffice extension on Ash.
  bool installed = false;
  proxy->AppRegistryCache().ForOneApp(
      extension_misc::kQuickOfficeComponentExtensionId,
      [&installed](const apps::AppUpdate& update) {
        installed = apps_util::IsInstalled(update.Readiness());
      });
  return installed;
}

bool IsOfficeFile(const base::FilePath& path) {
  std::vector<std::set<std::string>> groups = {WordGroupExtensions(),
                                               ExcelGroupExtensions(),
                                               PowerPointGroupExtensions()};

  for (const std::set<std::string>& group : groups) {
    for (const std::string& extension : group) {
      if (path.MatchesExtension(extension)) {
        return true;
      }
    }
  }
  return false;
}

bool IsOfficeFileMimeType(const std::string& mime_type) {
  std::vector<std::set<std::string>> groups = {
      WordGroupMimeTypes(), ExcelGroupMimeTypes(), PowerPointGroupMimeTypes()};

  for (const std::set<std::string>& group : groups) {
    for (const std::string& office_mime_type : group) {
      if (mime_type == office_mime_type) {
        return true;
      }
    }
  }
  return false;
}

std::set<std::string> WordGroupExtensions() {
  static const base::NoDestructor<std::set<std::string>> extensions(
      std::initializer_list<std::string>({".doc", ".docx"}));
  return *extensions;
}

std::set<std::string> WordGroupMimeTypes() {
  static const base::NoDestructor<std::set<std::string>> mime_types(
      std::initializer_list<std::string>(
          {"application/msword",
           "application/"
           "vnd.openxmlformats-officedocument.wordprocessingml.document"}));
  return *mime_types;
}

bool HasExplicitDefaultFileHandler(Profile* profile,
                                   const std::string& extension) {
  std::string lower_extension = base::ToLowerASCII(extension);
  const base::Value::Dict& extension_task_prefs =
      profile->GetPrefs()->GetDict(prefs::kDefaultTasksBySuffix);
  return extension_task_prefs.contains(lower_extension);
}

void SetWordFileHandler(Profile* profile,
                        const TaskDescriptor& task,
                        bool replace_existing) {
  UpdateDefaultTask(profile, task, WordGroupExtensions(), WordGroupMimeTypes(),
                    replace_existing);
}

void SetWordFileHandlerToFilesSWA(Profile* profile,
                                  const std::string& action_id,
                                  bool replace_existing) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  SetWordFileHandler(profile, task, replace_existing);
}

std::set<std::string> ExcelGroupExtensions() {
  static const base::NoDestructor<std::set<std::string>> extensions(
      std::initializer_list<std::string>({".xls", ".xlsm", ".xlsx"}));
  return *extensions;
}

std::set<std::string> ExcelGroupMimeTypes() {
  static const base::NoDestructor<std::set<std::string>> mime_types(
      std::initializer_list<std::string>(
          {"application/vnd.ms-excel",
           "application/vnd.ms-excel.sheet.macroEnabled.12",
           "application/"
           "vnd.openxmlformats-officedocument.spreadsheetml.sheet"}));
  return *mime_types;
}

void SetExcelFileHandler(Profile* profile,
                         const TaskDescriptor& task,
                         bool replace_existing) {
  UpdateDefaultTask(profile, task, ExcelGroupExtensions(),
                    ExcelGroupMimeTypes(), replace_existing);
}

void SetExcelFileHandlerToFilesSWA(Profile* profile,
                                   const std::string& action_id,
                                   bool replace_existing) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  SetExcelFileHandler(profile, task, replace_existing);
}

std::set<std::string> PowerPointGroupExtensions() {
  static const base::NoDestructor<std::set<std::string>> extensions(
      std::initializer_list<std::string>({".ppt", ".pptx"}));
  return *extensions;
}

std::set<std::string> PowerPointGroupMimeTypes() {
  static const base::NoDestructor<std::set<std::string>> mime_types(
      std::initializer_list<std::string>(
          {"application/vnd.ms-powerpoint",
           "application/"
           "vnd.openxmlformats-officedocument.presentationml.presentation"}));
  return *mime_types;
}

void SetPowerPointFileHandler(Profile* profile,
                              const TaskDescriptor& task,
                              bool replace_existing) {
  UpdateDefaultTask(profile, task, PowerPointGroupExtensions(),
                    PowerPointGroupMimeTypes(), replace_existing);
}

void SetPowerPointFileHandlerToFilesSWA(Profile* profile,
                                        const std::string& action_id,
                                        bool replace_existing) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  SetPowerPointFileHandler(profile, task, replace_existing);
}
void SetAlwaysMoveOfficeFilesToDrive(Profile* profile, bool always_move) {
  profile->GetPrefs()->SetBoolean(prefs::kOfficeFilesAlwaysMoveToDrive,
                                  always_move);
}

bool GetAlwaysMoveOfficeFilesToDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(prefs::kOfficeFilesAlwaysMoveToDrive);
}

void SetAlwaysMoveOfficeFilesToOneDrive(Profile* profile, bool always_move) {
  profile->GetPrefs()->SetBoolean(prefs::kOfficeFilesAlwaysMoveToOneDrive,
                                  always_move);
}

bool GetAlwaysMoveOfficeFilesToOneDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeFilesAlwaysMoveToOneDrive);
}

void SetOfficeMoveConfirmationShownForDrive(Profile* profile, bool complete) {
  profile->GetPrefs()->SetBoolean(prefs::kOfficeMoveConfirmationShownForDrive,
                                  complete);
}

bool GetOfficeMoveConfirmationShownForDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForDrive);
}

void SetOfficeMoveConfirmationShownForOneDrive(Profile* profile,
                                               bool complete) {
  profile->GetPrefs()->SetBoolean(
      prefs::kOfficeMoveConfirmationShownForOneDrive, complete);
}

bool GetOfficeMoveConfirmationShownForOneDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForOneDrive);
}

void SetOfficeMoveConfirmationShownForLocalToDrive(Profile* profile,
                                                   bool shown) {
  profile->GetPrefs()->SetBoolean(
      prefs::kOfficeMoveConfirmationShownForLocalToDrive, shown);
}

bool GetOfficeMoveConfirmationShownForLocalToDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForLocalToDrive);
}

void SetOfficeMoveConfirmationShownForLocalToOneDrive(Profile* profile,
                                                      bool shown) {
  profile->GetPrefs()->SetBoolean(
      prefs::kOfficeMoveConfirmationShownForLocalToOneDrive, shown);
}

bool GetOfficeMoveConfirmationShownForLocalToOneDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForLocalToOneDrive);
}

void SetOfficeMoveConfirmationShownForCloudToDrive(Profile* profile,
                                                   bool shown) {
  profile->GetPrefs()->SetBoolean(
      prefs::kOfficeMoveConfirmationShownForCloudToDrive, shown);
}

bool GetOfficeMoveConfirmationShownForCloudToDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForCloudToDrive);
}

void SetOfficeMoveConfirmationShownForCloudToOneDrive(Profile* profile,
                                                      bool shown) {
  profile->GetPrefs()->SetBoolean(
      prefs::kOfficeMoveConfirmationShownForCloudToOneDrive, shown);
}

bool GetOfficeMoveConfirmationShownForCloudToOneDrive(Profile* profile) {
  return profile->GetPrefs()->GetBoolean(
      prefs::kOfficeMoveConfirmationShownForCloudToOneDrive);
}

void SetOfficeFileMovedToOneDrive(Profile* profile, base::Time moved) {
  profile->GetPrefs()->SetTime(prefs::kOfficeFileMovedToOneDrive, moved);
}

void SetOfficeFileMovedToGoogleDrive(Profile* profile, base::Time moved) {
  profile->GetPrefs()->SetTime(prefs::kOfficeFileMovedToGoogleDrive, moved);
}

void RemoveFilesSWAWordFileHandler(Profile* profile,
                                   const std::string& action_id) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  RemoveDefaultTask(profile, task, WordGroupExtensions(), WordGroupMimeTypes());
}

void RemoveFilesSWAExcelFileHandler(Profile* profile,
                                    const std::string& action_id) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  RemoveDefaultTask(profile, task, ExcelGroupExtensions(),
                    ExcelGroupMimeTypes());
}

void RemoveFilesSWAPowerPointFileHandler(Profile* profile,
                                         const std::string& action_id) {
  TaskDescriptor task(kFileManagerSwaAppId, TaskType::TASK_TYPE_WEB_APP,
                      ToSwaActionId(action_id));
  RemoveDefaultTask(profile, task, PowerPointGroupExtensions(),
                    PowerPointGroupMimeTypes());
}

}  // namespace file_manager::file_tasks