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 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
|
// 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/ui/webui/ash/cloud_upload/cloud_upload_dialog.h"
#include "ash/constants/web_app_id_constants.h"
#include "ash/public/cpp/new_window_delegate.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "base/containers/enum_set.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/strings/escape.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.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/arc/fileapi/arc_documents_provider_util.h"
#include "chrome/browser/ash/browser_delegate/browser_controller.h"
#include "chrome/browser/ash/browser_delegate/browser_delegate.h"
#include "chrome/browser/ash/extensions/file_manager/event_router_factory.h"
#include "chrome/browser/ash/file_manager/file_tasks.h"
#include "chrome/browser/ash/file_manager/io_task.h"
#include "chrome/browser/ash/file_manager/office_file_tasks.h"
#include "chrome/browser/ash/file_manager/open_util.h"
#include "chrome/browser/ash/file_manager/open_with_browser.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/file_system_provider/mount_path_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/upload_office_to_cloud/upload_office_to_cloud.h"
#include "chrome/browser/notifications/notification_display_service.h"
#include "chrome/browser/ui/ash/system_web_apps/system_web_app_ui_utils.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload.mojom-forward.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload.mojom-shared.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload.mojom.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload_ui.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/cloud_upload_util.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/drive_upload_handler.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/hats_office_trigger.h"
#include "chrome/browser/ui/webui/ash/cloud_upload/one_drive_upload_handler.h"
#include "chrome/browser/ui/webui/ash/office_fallback/office_fallback_ui.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "chromeos/constants/chromeos_features.h"
#include "components/user_manager/user_manager.h"
#include "extensions/browser/api/file_handlers/mime_util.h"
#include "extensions/browser/entry_info.h"
#include "extensions/common/constants.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "net/base/url_util.h"
#include "storage/browser/file_system/file_system_url.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/mojom/ui_base_types.mojom-shared.h"
#include "ui/chromeos/strings/grit/ui_chromeos_strings.h"
#include "ui/gfx/geometry/size.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/message_center/public/cpp/notification_delegate.h"
namespace ash::cloud_upload {
namespace {
namespace fm_tasks = file_manager::file_tasks;
using ash::file_system_provider::ProvidedFileSystemInfo;
using ash::file_system_provider::ProviderId;
using ash::file_system_provider::Service;
constexpr char kAndroidOneDriveAuthority[] =
"com.microsoft.skydrive.content.StorageAccessProvider";
constexpr char kNotificationId[] = "cloud_upload_open_failure";
constexpr char kFileHandlerSelectionMetricName[] =
"FileBrowser.OfficeFiles.Setup.FileHandlerSelection";
constexpr char kFirstTimeMicrosoft365AvailabilityMetric[] =
"FileBrowser.OfficeFiles.Setup.FirstTimeMicrosoft365Availability";
// Records the file handler selected on the first page of Office setup.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class OfficeSetupFileHandler {
kGoogleDocs = 0,
kGoogleSheets = 1,
kGoogleSlides = 2,
kMicrosoft365 = 3,
kOtherLocalHandler = 4,
kQuickOffice = 5,
kMaxValue = kQuickOffice,
};
// Represents (as a bitmask) whether or not Microsoft 365 PWA and ODFS are set
// up. Used to record this state when setup is launched.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class Microsoft365Availability {
kPWA = 0,
kODFS = 1,
kMinValue = kPWA,
kMaxValue = kODFS,
};
// Handle system error notification "Sign in" click.
void HandleSignInClick(Profile* profile, std::optional<int> button_index) {
// If the "Sign in" button was pressed, rather than a click to somewhere
// else in the notification.
if (button_index) {
// TODO(b/282619291) decide what callback should be.
// Request an ODFS mount which will trigger reauthentication.
RequestODFSMount(profile, base::DoNothing());
}
NotificationDisplayService* notification_service =
NotificationDisplayServiceFactory::GetForProfile(profile);
notification_service->Close(NotificationHandler::Type::TRANSIENT,
kNotificationId);
}
// TODO(b/288038136): Use a notification manager to handle error notifications.
// TODO(b/242685536) Use "files" in the title for multi-files when support for
// multi-files is added.
// Show system notification to communicate that their file can't be opened. If
// the user needs to reauthenticate to OneDrive, prompt the user to
// reauthenticate to ODFS via a "Sign in" button.
void ShowUnableToOpenNotification(
Profile* profile,
std::string message = GetGenericErrorMessage(),
std::string title =
l10n_util::GetPluralStringFUTF8(IDS_OFFICE_UPLOAD_ERROR_CANT_OPEN_FILE,
1),
message_center::SystemNotificationWarningLevel warning_level =
message_center::SystemNotificationWarningLevel::WARNING) {
std::vector<message_center::ButtonInfo> notification_buttons;
if (message == GetReauthenticationRequiredMessage()) {
// Special case of |FILE_ERROR_ACCESS_DENIED| where the user needs to
// reauthenticate to OneDrive.
// Add "Sign in" button.
notification_buttons.emplace_back(
l10n_util::GetStringUTF16(IDS_OFFICE_NOTIFICATION_SIGN_IN_BUTTON));
}
auto notification = ash::CreateSystemNotificationPtr(
/*type=*/message_center::NOTIFICATION_TYPE_SIMPLE,
/*id=*/kNotificationId,
/*title*/ base::UTF8ToUTF16(title),
/*message=*/base::UTF8ToUTF16(message),
/*display_source=*/
l10n_util::GetStringUTF16(IDS_ASH_MESSAGE_CENTER_SYSTEM_APP_NAME_FILES),
/*origin_url=*/GURL(),
/*notifier_id=*/message_center::NotifierId(),
/*optional_fields=*/{},
/*delegate=*/
base::MakeRefCounted<message_center::HandleNotificationClickDelegate>(
base::BindRepeating(&HandleSignInClick, profile)),
/*small_image=*/ash::kFolderIcon, warning_level);
notification->set_buttons(notification_buttons);
// Set never_timeout with the highest priority, SYSTEM_PRIORITY, so that the
// notification never times out.
notification->set_never_timeout(true);
notification->SetSystemPriority();
NotificationDisplayService* notification_service =
NotificationDisplayServiceFactory::GetForProfile(profile);
notification_service->Display(NotificationHandler::Type::TRANSIENT,
*notification,
/*metadata=*/nullptr);
}
// Check if reauthentication to OneDrive is required from the ODFS metadata
// and show the reuathentication is required notification if true. Otherwise
// show the generic access error notification.
void OnGetReauthenticationRequired(
Profile* profile,
base::OnceCallback<void(OfficeOneDriveOpenErrors)> callback,
base::expected<ODFSMetadata, base::File::Error> metadata) {
bool reauthentication_required = false;
if (metadata.has_value()) {
// TODO(b/330786891): Only query account_state once
// reauthentication_required is no longer needed for backwards compatibility
// with ODFS.
reauthentication_required =
metadata->reauthentication_required ||
(metadata->account_state.has_value() &&
metadata->account_state.value() ==
OdfsAccountState::kReauthenticationRequired);
} else {
LOG(ERROR) << "Failed to get reauthentication required state: "
<< metadata.error();
}
if (reauthentication_required) {
ShowUnableToOpenNotification(profile, GetReauthenticationRequiredMessage());
std::move(callback).Run(
OfficeOneDriveOpenErrors::kGetActionsReauthRequired);
return;
}
ShowUnableToOpenNotification(profile);
std::move(callback).Run(OfficeOneDriveOpenErrors::kGetActionsAccessDenied);
}
// Open file with |file_path| from ODFS |file_system|. Open in the OneDrive PWA
// without link capturing.
void OpenFileFromODFS(
Profile* profile,
file_system_provider::ProvidedFileSystemInterface* file_system,
const base::FilePath& file_path,
base::OnceCallback<void(OfficeOneDriveOpenErrors)> callback) {
GetODFSEntryMetadata(
file_system, file_path,
base::BindOnce(
[](Profile* profile,
file_system_provider::ProvidedFileSystemInterface* file_system,
base::OnceCallback<void(OfficeOneDriveOpenErrors)> callback,
base::expected<ODFSEntryMetadata, base::File::Error> metadata) {
if (!metadata.has_value()) {
switch (metadata.error()) {
case base::File::Error::FILE_ERROR_ACCESS_DENIED:
// Query authentication state to determine which error message
// to show.
GetODFSMetadata(file_system,
base::BindOnce(&OnGetReauthenticationRequired,
profile, std::move(callback)));
break;
default:
ShowUnableToOpenNotification(profile);
std::move(callback).Run(
OfficeOneDriveOpenErrors::kGetActionsGenericError);
break;
}
return;
}
if (!metadata->url) {
ShowUnableToOpenNotification(profile);
std::move(callback).Run(
OfficeOneDriveOpenErrors::kGetActionsNoUrl);
return;
}
GURL url(*metadata->url);
if (!url.is_valid()) {
ShowUnableToOpenNotification(profile);
std::move(callback).Run(
OfficeOneDriveOpenErrors::kGetActionsInvalidUrl);
return;
}
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile);
if (!proxy->AppRegistryCache().IsAppInstalled(
ash::kMicrosoft365AppId)) {
LOG(ERROR) << "MS365 with app ID " << ash::kMicrosoft365AppId
<< " is not installed";
ShowUnableToOpenNotification(profile);
std::move(callback).Run(
OfficeOneDriveOpenErrors::kMS365NotInstalled);
return;
}
proxy->LaunchAppWithUrl(
ash::kMicrosoft365AppId,
/*event_flags=*/ui::EF_NONE, url,
apps::LaunchSource::kFromFileManager,
/*window_info=*/nullptr,
base::BindOnce(
[](Profile* profile,
base::OnceCallback<void(OfficeOneDriveOpenErrors)>
callback,
apps::LaunchResult&& launch_result) {
OfficeOneDriveOpenErrors open;
switch (launch_result.state) {
case apps::LaunchResult::State::kSuccess:
open = OfficeOneDriveOpenErrors::kSuccess;
break;
default:
LOG(ERROR) << "Failed to launch URL";
ShowUnableToOpenNotification(profile);
open = OfficeOneDriveOpenErrors::kFailedToLaunch;
break;
}
std::move(callback).Run(open);
},
profile, std::move(callback)));
if (base::FeatureList::IsEnabled(
::features::kHappinessTrackingOffice)) {
ash::cloud_upload::HatsOfficeTrigger::Get()
.ShowSurveyAfterAppInactive(
ash::kMicrosoft365AppId,
ash::cloud_upload::HatsOfficeLaunchingApp::kMS365);
}
},
profile, file_system, std::move(callback)));
}
// Open office file using the ODFS |url|.
void OpenODFSUrl(Profile* profile,
const storage::FileSystemURL& url,
base::OnceCallback<void(OfficeOneDriveOpenErrors)> callback) {
if (!url.is_valid()) {
LOG(ERROR) << "Invalid uploaded file URL";
std::move(callback).Run(OfficeOneDriveOpenErrors::kNoFileSystemURL);
return;
}
ash::file_system_provider::util::FileSystemURLParser parser(url);
if (!parser.Parse()) {
LOG(ERROR) << "Path not in FSP";
std::move(callback).Run(OfficeOneDriveOpenErrors::kInvalidFileSystemURL);
return;
}
OpenFileFromODFS(profile, parser.file_system(), parser.file_path(),
std::move(callback));
}
bool HasFileWithExtensionFromSet(
const std::vector<storage::FileSystemURL>& file_urls,
const std::set<std::string>& extensions) {
return std::ranges::any_of(file_urls, [&extensions](const auto& file_url) {
return std::ranges::any_of(extensions, [&file_url](const auto& extension) {
return file_url.path().MatchesExtension(extension);
});
});
}
bool HasWordFile(const std::vector<storage::FileSystemURL>& file_urls) {
return HasFileWithExtensionFromSet(file_urls,
fm_tasks::WordGroupExtensions());
}
bool HasExcelFile(const std::vector<storage::FileSystemURL>& file_urls) {
return HasFileWithExtensionFromSet(file_urls,
fm_tasks::ExcelGroupExtensions());
}
bool HasPowerPointFile(const std::vector<storage::FileSystemURL>& file_urls) {
return HasFileWithExtensionFromSet(file_urls,
fm_tasks::PowerPointGroupExtensions());
}
// This indicates we ran Office setup and set a preference, or the user had a
// pre-existing preference for these file types.
bool HaveExplicitFileHandlers(
Profile* profile,
const std::vector<storage::FileSystemURL>& file_urls) {
return std::ranges::all_of(file_urls, [profile](const auto& url) {
return fm_tasks::HasExplicitDefaultFileHandler(profile,
url.path().FinalExtension());
});
}
// This indicates we ran Office setup and set a preference, or the user had a
// pre-existing preference for these file types.
bool HaveExplicitFileHandlers(Profile* profile,
const std::set<std::string>& extensions) {
return std::ranges::all_of(extensions, [profile](const auto& extension) {
return fm_tasks::HasExplicitDefaultFileHandler(profile, extension);
});
}
void RecordMicrosoft365Availability(const char* metric, Profile* profile) {
base::EnumSet<Microsoft365Availability, Microsoft365Availability::kMinValue,
Microsoft365Availability::kMaxValue>
ms365_state;
if (IsOfficeWebAppInstalled(profile)) {
ms365_state.Put(Microsoft365Availability::kPWA);
}
if (IsODFSMounted(profile)) {
ms365_state.Put(Microsoft365Availability::kODFS);
}
base::UmaHistogramExactLinear(
metric, ms365_state.ToEnumBitmask(),
decltype(ms365_state)::All().ToEnumBitmask() + 1);
}
mojom::OperationType UploadTypeToOperationType(UploadType upload_type) {
switch (upload_type) {
case UploadType::kMove:
return mojom::OperationType::kMove;
case UploadType::kCopy:
return mojom::OperationType::kCopy;
}
}
void OnWaitingForAndroidUnsupportedPathFallbackChoiceReceived(
Profile* profile,
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.
fm_tasks::LogOneDriveMetricsAfterFallback(
fallback_reason,
ash::cloud_upload::OfficeTaskResult::kCannotGetFallbackChoiceAfterOpen,
std::move(cloud_open_metrics));
return;
}
if (choice.value() == ash::office_fallback::kDialogChoiceQuickOffice) {
fm_tasks::LogOneDriveMetricsAfterFallback(
fallback_reason,
ash::cloud_upload::OfficeTaskResult::kFallbackQuickOfficeAfterOpen,
std::move(cloud_open_metrics));
fm_tasks::LaunchQuickOffice(profile, file_urls);
} else if (choice.value() == ash::office_fallback::kDialogChoiceTryAgain) {
LOG(ERROR) << "Unexpected response: " << choice.value();
} else if (choice.value() == ash::office_fallback::kDialogChoiceCancel) {
fm_tasks::LogOneDriveMetricsAfterFallback(
fallback_reason,
ash::cloud_upload::OfficeTaskResult::kCancelledAtFallbackAfterOpen,
std::move(cloud_open_metrics));
} else if (choice.value() == ash::office_fallback::kDialogChoiceOk) {
fm_tasks::LogOneDriveMetricsAfterFallback(
fallback_reason,
ash::cloud_upload::OfficeTaskResult::kOkAtFallbackAfterOpen,
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";
fm_tasks::LogOneDriveMetricsAfterFallback(
fallback_reason,
ash::cloud_upload::OfficeTaskResult::kCancelledAtFallbackAfterOpen,
std::move(cloud_open_metrics));
}
}
bool BringDialogToFrontIfItExists(const std::string& id) {
SystemWebDialogDelegate* existing_dialog =
SystemWebDialogDelegate::FindInstance(id);
if (!existing_dialog) {
return false;
}
existing_dialog->StackAtTop();
return true;
}
} // namespace
// static
// Creates an instance of CloudOpenTask that effectively owns itself by keeping
// a reference alive in the TaskFinished callback.
bool CloudOpenTask::Execute(
Profile* profile,
const std::vector<storage::FileSystemURL>& file_urls,
const fm_tasks::TaskDescriptor& task,
const CloudProvider cloud_provider,
std::unique_ptr<CloudOpenMetrics> cloud_open_metrics) {
DCHECK(!file_urls.empty());
auto* event_router = file_manager::EventRouterFactory::GetForProfile(profile);
// TODO(b/242685536) add support for multiple files.
if (event_router) {
if (!event_router->AddCloudOpenTask(file_urls.front())) {
LOG(ERROR) << "File already being opened";
// If a cloud upload dialog already exists, bring it to the front to
// prompt the user to keep going.
BringDialogToFrontIfItExists(chrome::kChromeUICloudUploadURL);
// Notify the user that a file is already being opened. Nothing is wrong
// when the file is already being opened, so use a normal level
// notification
ShowUnableToOpenNotification(
profile, GetAlreadyBeingOpenedMessage(), GetAlreadyBeingOpenedTitle(),
/*warning_level=*/
message_center::SystemNotificationWarningLevel::NORMAL);
cloud_open_metrics->LogTaskResult(
OfficeTaskResult::kFileAlreadyBeingOpened);
return false;
}
} else {
LOG(ERROR) << "Cannot get EventRouter";
}
std::optional<SourceType> source_type =
GetSourceType(profile, file_urls.front());
if (!source_type.has_value()) {
LOG(ERROR) << "Cannot get source type";
cloud_open_metrics->LogTaskResult(OfficeTaskResult::kCannotGetSourceType);
return false;
}
scoped_refptr<CloudOpenTask> upload_task = WrapRefCounted(
new CloudOpenTask(profile, file_urls, task, source_type.value(),
cloud_provider, std::move(cloud_open_metrics)));
// Keep `upload_task` alive until `TaskFinished` executes.
bool status = upload_task->ExecuteInternal();
return status;
}
CloudOpenTask::CloudOpenTask(
Profile* profile,
std::vector<storage::FileSystemURL> file_urls,
const fm_tasks::TaskDescriptor& task,
const SourceType source_type,
const CloudProvider cloud_provider,
std::unique_ptr<CloudOpenMetrics> cloud_open_metrics)
: profile_(profile),
file_urls_(file_urls),
task_(task),
source_type_(source_type),
cloud_provider_(cloud_provider),
cloud_open_metrics_(std::move(cloud_open_metrics)) {
BrowserList::AddObserver(this);
}
CloudOpenTask::~CloudOpenTask() {
auto* event_router =
file_manager::EventRouterFactory::GetForProfile(profile_);
DCHECK(!file_urls_.empty());
if (event_router) {
event_router->RemoveCloudOpenTask(file_urls_.front());
} else {
LOG(ERROR) << "Cannot get EventRouter";
}
BrowserList::RemoveObserver(this);
}
// Runs setup if it's never been completed. Runs the fixup version of setup if
// there are any issues, e.g. ODFS is not mounted. Otherwise, attempts to move
// files to the correct cloud or open the files if they are already there.
bool CloudOpenTask::ExecuteInternal() {
if (file_urls_.empty()) {
LOG(ERROR) << "No files to open";
cloud_open_metrics_->LogTaskResult(OfficeTaskResult::kNoFilesToOpen);
return false;
}
// Run the setup flow if we don't have explicit default file handlers set for
// these files in preferences. This indicates we haven't run setup, because
// setup sets default handlers at the end. If the user has a default set for
// another, non-office handler, then we won't get here except via the 'Open
// With' menu. In that case we might need to run fixup or just open/move the
// file, but without changing stored user file handler preferences.
if (!HaveExplicitFileHandlers(profile_, file_urls_)) {
RecordMicrosoft365Availability(kFirstTimeMicrosoft365AvailabilityMetric,
profile_);
return InitAndShowSetupOrMoveDialog(
SetupOrMoveDialogPage::kFileHandlerDialog);
}
return MaybeRunFixupFlow();
}
// Runs the fixup version of setup if there are any issues, e.g. ODFS is not
// mounted. Otherwise, attempts to move files to the correct cloud or open the
// files if they are already there.
bool CloudOpenTask::MaybeRunFixupFlow() {
if (ShouldFixUpOffice(profile_, cloud_provider_)) {
// TODO(cassycc): Use page specifically for fix up.
return InitAndShowSetupOrMoveDialog(SetupOrMoveDialogPage::kOneDriveSetup);
}
return OpenOrMoveFiles();
}
// Opens office files if they are in the correct cloud already. Otherwise moves
// the files before opening.
bool CloudOpenTask::OpenOrMoveFiles() {
// Record the source volume type of the opened file.
OfficeFilesSourceVolume source_volume;
if (UrlIsOnODFS(file_urls_.front())) {
source_volume = OfficeFilesSourceVolume::kMicrosoftOneDrive;
} else if (UrlIsOnAndroidOneDrive(profile_, file_urls_.front())) {
source_volume = OfficeFilesSourceVolume::kAndroidOneDriveDocumentsProvider;
} else {
auto* volume_manager = file_manager::VolumeManager::Get(profile_);
base::WeakPtr<file_manager::Volume> source =
volume_manager->FindVolumeFromPath(file_urls_.front().path());
if (source) {
source_volume = VolumeTypeToSourceVolume(source->type());
} else {
source_volume = OfficeFilesSourceVolume::kUnknown;
}
}
cloud_open_metrics_->LogSourceVolume(source_volume);
std::string ext = file_urls_.front().path().Extension();
if (cloud_provider_ == CloudProvider::kGoogleDrive &&
PathIsOnDriveFS(profile_, file_urls_.front().path())) {
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Opening a " << ext << " file from Google Drive";
// The files are on Drive already.
transfer_required_ = OfficeFilesTransferRequired::kNotRequired;
cloud_open_metrics_->LogTransferRequired(
OfficeFilesTransferRequired::kNotRequired);
OpenAlreadyHostedDriveUrls();
return true;
}
if (cloud_provider_ == CloudProvider::kOneDrive &&
source_volume == OfficeFilesSourceVolume::kMicrosoftOneDrive) {
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Opening a " << ext << " file from OneDrive";
// The files are on OneDrive already, selected from ODFS.
transfer_required_ = OfficeFilesTransferRequired::kNotRequired;
cloud_open_metrics_->LogTransferRequired(
OfficeFilesTransferRequired::kNotRequired);
OpenODFSUrls(OfficeTaskResult::kOpened);
return true;
}
if (cloud_provider_ == CloudProvider::kOneDrive &&
source_volume ==
OfficeFilesSourceVolume::kAndroidOneDriveDocumentsProvider) {
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Opening a " << ext << " file from Android OneDrive";
// The files are on OneDrive already, selected from Android OneDrive.
transfer_required_ = OfficeFilesTransferRequired::kNotRequired;
cloud_open_metrics_->LogTransferRequired(
OfficeFilesTransferRequired::kNotRequired);
// Get ODFS email address, compare against Android OneDrive's email address
// and open URLs.
GetODFSMetadata(
GetODFS(profile_),
base::BindOnce(&CloudOpenTask::CheckEmailAndOpenAndroidOneDriveURLs,
this));
return true;
}
// The files need to be moved.
auto operation = SourceTypeToUploadType(source_type_) == UploadType::kCopy
? OfficeFilesTransferRequired::kCopy
: OfficeFilesTransferRequired::kMove;
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << (operation == OfficeFilesTransferRequired::kCopy ? "Copy"
: "Mov")
<< "ing a " << ext << " file to "
<< (cloud_provider_ == CloudProvider::kGoogleDrive
? "Google Drive"
: "OneDrive");
transfer_required_ = operation;
cloud_open_metrics_->LogTransferRequired(operation);
return ConfirmMoveOrStartUpload();
}
void CloudOpenTask::OpenAlreadyHostedDriveUrls() {
drive::DriveIntegrationService* integration_service =
drive::DriveIntegrationServiceFactory::FindForProfile(profile_);
base::FilePath relative_path;
for (const auto& file_url : file_urls_) {
if (!integration_service->GetRelativeDrivePath(file_url.path(),
&relative_path)) {
LOG(ERROR) << "Unexpected error obtaining the relative path";
LogGoogleDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeDriveOpenErrors::kCannotGetRelativePath);
} else if (!integration_service->GetDriveFsInterface()) {
LOG(ERROR) << "DriveFs interface not available";
LogGoogleDriveOpenResultUMA(OfficeTaskResult::kOpened,
OfficeDriveOpenErrors::kDriveFsInterface);
} else {
integration_service->GetDriveFsInterface()->GetMetadata(
relative_path,
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
base::BindOnce(&CloudOpenTask::OnGoogleDriveGetMetadata, this),
drive::FILE_ERROR_SERVICE_UNAVAILABLE, nullptr));
}
}
}
// Open an already hosted MS Office file e.g. .docx, from a url hosted in
// DriveFS. Check there was no error retrieving the file's metadata.
void CloudOpenTask::OnGoogleDriveGetMetadata(
drive::FileError error,
drivefs::mojom::FileMetadataPtr metadata) {
OfficeDriveOpenErrors open_result = OfficeDriveOpenErrors::kSuccess;
if (error == drive::FILE_ERROR_SERVICE_UNAVAILABLE) {
LOG(ERROR) << "DriveFs is unavailable";
open_result = OfficeDriveOpenErrors::kDriveFsUnavailable;
} else if (error != drive::FILE_ERROR_OK) {
LOG(ERROR) << "Drive metadata error: " << error;
open_result = OfficeDriveOpenErrors::kNoMetadata;
} else if (metadata.is_null()) {
LOG(ERROR) << "Drive metadata is null";
open_result = OfficeDriveOpenErrors::kNoMetadata;
} else {
GURL hosted_url(metadata->alternate_url);
if (hosted_url.is_empty() &&
metadata->item_id.value_or("").starts_with("local-")) {
LOG(ERROR) << "Local item id, the file hasn't been uploaded";
open_result = OfficeDriveOpenErrors::kWaitingForUpload;
GetUserFallbackChoice(
profile_, task_, file_urls_,
ash::office_fallback::FallbackReason::kWaitingForUpload,
base::DoNothing());
} else if (hosted_url.is_empty()) {
LOG(ERROR) << "Empty URL";
open_result = OfficeDriveOpenErrors::kEmptyAlternateUrl;
} else if (!hosted_url.is_valid()) {
LOG(ERROR) << "Invalid URL";
open_result = OfficeDriveOpenErrors::kInvalidAlternateUrl;
} else if (hosted_url.host() == "drive.google.com") {
LOG(ERROR) << "URL was from drive.google.com";
open_result = OfficeDriveOpenErrors::kDriveAlternateUrl;
} else if (hosted_url.host() != "docs.google.com") {
LOG(ERROR) << "URL was not from docs.google.com";
open_result = OfficeDriveOpenErrors::kUnexpectedAlternateUrl;
} else {
// TODO(crbug.com/242685536) add support for multiple files.
::file_manager::util::OpenHostedFileInNewTabOrApp(
profile_, file_urls_.front().path(), base::DoNothing(),
net::AppendOrReplaceQueryParameter(hosted_url, "cros_files", "true"));
}
}
LogGoogleDriveOpenResultUMA(OfficeTaskResult::kOpened, open_result);
}
// Open a hosted MS Office file e.g. .docx, from a url hosted in
// DriveFS. Check the file was successfully uploaded to DriveFS.
void CloudOpenTask::OpenUploadedDriveUrl(const GURL& url,
const OfficeTaskResult task_result) {
// TODO(b/242685536) add support for multiple files.
::file_manager::util::OpenHostedFileInNewTabOrApp(
profile_, file_urls_.front().path(), base::DoNothing(),
net::AppendOrReplaceQueryParameter(url, "cros_files", "true"));
// TODO(b/296950967): This function logs both open result and task result (but
// only if open fails) metrics internally, pull them up to a higher level so
// all the metrics are logged in one place.
LogGoogleDriveOpenResultUMA(task_result, OfficeDriveOpenErrors::kSuccess);
}
void CloudOpenTask::OpenODFSUrls(const OfficeTaskResult task_result_uma) {
for (const auto& file_url : file_urls_) {
OpenODFSUrl(profile_, file_url,
base::BindOnce(&CloudOpenTask::LogOneDriveOpenResultUMA, this,
task_result_uma));
}
}
// Returns True if the confirmation dialog should be shown before uploading a
// file to a cloud location and opening it.
bool CloudOpenTask::ShouldShowConfirmationDialog() {
bool force_show_confirmation_dialog = false;
if (cloud_provider_ == CloudProvider::kGoogleDrive) {
switch (source_type_) {
case SourceType::READ_ONLY:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForLocalToDrive(
profile_) &&
!fm_tasks::GetOfficeMoveConfirmationShownForCloudToDrive(profile_);
break;
case SourceType::LOCAL:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForLocalToDrive(profile_);
break;
case SourceType::CLOUD:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForCloudToDrive(profile_);
break;
}
return force_show_confirmation_dialog ||
!fm_tasks::GetAlwaysMoveOfficeFilesToDrive(profile_);
} else if (cloud_provider_ == CloudProvider::kOneDrive) {
switch (source_type_) {
case SourceType::READ_ONLY:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForLocalToOneDrive(
profile_) &&
!fm_tasks::GetOfficeMoveConfirmationShownForCloudToOneDrive(
profile_);
break;
case SourceType::LOCAL:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForLocalToOneDrive(
profile_);
break;
case SourceType::CLOUD:
force_show_confirmation_dialog =
!fm_tasks::GetOfficeMoveConfirmationShownForCloudToOneDrive(
profile_);
break;
}
return force_show_confirmation_dialog ||
!fm_tasks::GetAlwaysMoveOfficeFilesToOneDrive(profile_);
}
NOTREACHED();
}
bool CloudOpenTask::ConfirmMoveOrStartUpload() {
bool show_confirmation_dialog = ShouldShowConfirmationDialog();
if (show_confirmation_dialog) {
SetupOrMoveDialogPage dialog_page =
cloud_provider_ == CloudProvider::kGoogleDrive
? SetupOrMoveDialogPage::kMoveConfirmationGoogleDrive
: SetupOrMoveDialogPage::kMoveConfirmationOneDrive;
return InitAndShowSetupOrMoveDialog(dialog_page);
}
StartUpload();
return true;
}
bool ShouldFixUpOffice(Profile* profile, const CloudProvider cloud_provider) {
return cloud_provider == CloudProvider::kOneDrive &&
!(IsODFSMounted(profile) && IsOfficeWebAppInstalled(profile));
}
bool UrlIsOnAndroidOneDrive(Profile* profile, const FileSystemURL& url) {
std::string authority;
std::string root_id;
base::FilePath path;
return arc::ParseDocumentsProviderUrl(url, &authority, &root_id, &path) &&
authority == kAndroidOneDriveAuthority;
}
void CloudOpenTask::CheckEmailAndOpenAndroidOneDriveURLs(
base::expected<ODFSMetadata, base::File::Error> metadata_or_error) {
if (!metadata_or_error.has_value()) {
LOG(ERROR) << "Failed to get user email: " << metadata_or_error.error();
LogOneDriveOpenResultUMA(OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kGetActionsGenericError);
return;
}
if (metadata_or_error->user_email.empty()) {
LOG(ERROR) << "User email is empty";
LogOneDriveOpenResultUMA(OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kGetActionsNoEmail);
return;
}
// In Android OneDrive, the DocumentsProvider uses the email account
// associated with it as the root_id.
std::string authority;
std::string android_onedrive_email;
base::FilePath path;
if (!arc::ParseDocumentsProviderUrl(file_urls_.front(), &authority,
&android_onedrive_email, &path)) {
LogOneDriveOpenResultUMA(OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kInvalidFileSystemURL);
return;
}
// Proceed only if the Android OneDrive and ODFS email addresses match.
if (base::ToLowerASCII(android_onedrive_email) !=
base::ToLowerASCII(metadata_or_error->user_email)) {
LOG(ERROR) << "Email accounts associated with ODFS and "
"Android OneDrive don't match.";
LogOneDriveOpenResultUMA(OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kEmailsDoNotMatch);
return;
}
// TODO(b/242685536) add support for multiple files.
OpenAndroidOneDriveUrl(file_urls_[0]);
}
// Open office file, originally selected from Android OneDrive, from ODFS. First
// convert the |android_onedrive_urls| to ODFS file paths, then open them from
// ODFS in the MS 365 PWA.
void CloudOpenTask::OpenAndroidOneDriveUrl(
const FileSystemURL& android_onedrive_file_url) {
// TODO(b/269364287): Handle when Android OneDrive file can't be opened.
if (!UrlIsOnAndroidOneDrive(profile_, android_onedrive_file_url)) {
LOG(ERROR) << "File not on Android OneDrive";
LogOneDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kConversionToODFSUrlError);
return;
}
// Get the ODFS mount path.
std::optional<ProvidedFileSystemInfo> odfs_file_system_info =
GetODFSInfo(profile_);
if (!odfs_file_system_info.has_value()) {
LOG(ERROR) << "ODFS not found";
LogOneDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kConversionToODFSUrlError);
return;
}
base::FilePath odfs_path = odfs_file_system_info->mount_path();
// Find the relative path from Android OneDrive Url.
std::string authority;
std::string root_id;
base::FilePath path;
if (!arc::ParseDocumentsProviderUrl(android_onedrive_file_url, &authority,
&root_id, &path)) {
LOG(ERROR) << "Could not parse Android OneDrive Url";
LogOneDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kConversionToODFSUrlError);
return;
}
// Format for Android OneDrive documents provider `path` is:
// Files/<rel_path>
std::vector<base::FilePath::StringType> components =
base::FilePath(path.value()).GetComponents();
if (components.size() < 2) {
LOG(ERROR)
<< "Android OneDrive documents provider path is not as expected.";
LogOneDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kAndroidOneDriveInvalidUrl);
return;
}
if (components[0] != "Files") {
ash::office_fallback::FallbackReason fallback_reason = ash::
office_fallback::FallbackReason::kAndroidOneDriveUnsupportedLocation;
// `cloud_open_metrics_` can be safely moved since CloudUploadTask is
// expected to be destructed straight after.
GetUserFallbackChoice(
profile_, task_, file_urls_, fallback_reason,
base::BindOnce(
&OnWaitingForAndroidUnsupportedPathFallbackChoiceReceived, profile_,
file_urls_, fallback_reason, std::move(cloud_open_metrics_)));
return;
}
// Append relative path from Android OneDrive Url.
for (size_t i = 1; i < components.size(); i++) {
odfs_path = odfs_path.Append(components[i]);
}
ash::file_system_provider::util::LocalPathParser parser(profile_, odfs_path);
if (!parser.Parse()) {
LOG(ERROR) << "Path not in FSP";
LogOneDriveOpenResultUMA(
OfficeTaskResult::kOpened,
OfficeOneDriveOpenErrors::kConversionToODFSUrlError);
return;
}
OpenFileFromODFS(profile_, parser.file_system(), parser.file_path(),
base::BindOnce(&CloudOpenTask::LogOneDriveOpenResultUMA,
this, OfficeTaskResult::kOpened));
return;
}
void CloudOpenTask::StartUpload() {
DCHECK_EQ(file_urls_idx_, 0UL);
upload_timer_ = base::ElapsedTimer();
// CloudOpenTask is the only owner of the `CloudOpenMetrics` object and will
// still be alive after the upload handler completes. Thus, pass a `SafeRef`
// of `CloudOpenMetrics` to the upload handler.
if (cloud_provider_ == CloudProvider::kGoogleDrive) {
StartNextGoogleDriveUpload();
} else if (cloud_provider_ == CloudProvider::kOneDrive) {
StartNextOneDriveUpload();
}
}
void CloudOpenTask::StartNextGoogleDriveUpload() {
DCHECK_LT(file_urls_idx_, file_urls_.size());
drive_upload_handler_ = std::make_unique<DriveUploadHandler>(
profile_, file_urls_[file_urls_idx_],
SourceTypeToUploadType(source_type_),
base::BindOnce(&CloudOpenTask::FinishedDriveUpload, this),
cloud_open_metrics_->GetSafeRef());
drive_upload_handler_->Run();
}
void CloudOpenTask::StartNextOneDriveUpload() {
DCHECK_LT(file_urls_idx_, file_urls_.size());
one_drive_upload_handler_ = std::make_unique<OneDriveUploadHandler>(
profile_, file_urls_[file_urls_idx_],
SourceTypeToUploadType(source_type_),
base::BindOnce(&CloudOpenTask::FinishedOneDriveUpload, this,
profile_->GetWeakPtr()),
cloud_open_metrics_->GetSafeRef());
one_drive_upload_handler_->Run();
}
void CloudOpenTask::FinishedDriveUpload(OfficeTaskResult task_result,
std::optional<GURL> url,
int64_t size) {
DCHECK_LT(file_urls_idx_, file_urls_.size());
if (url.has_value()) {
upload_total_size_ += size;
fm_tasks::SetOfficeFileMovedToGoogleDrive(profile_, base::Time::Now());
// Log TaskResult after open is tried.
OpenUploadedDriveUrl(url.value(), task_result);
} else {
cloud_open_metrics_->LogTaskResult(task_result);
has_upload_errors_ = has_upload_errors_ ||
(task_result == OfficeTaskResult::kFailedToUpload);
}
file_urls_idx_++;
if (file_urls_idx_ < file_urls_.size()) {
StartNextGoogleDriveUpload();
return;
}
if (!has_upload_errors_) {
RecordUploadLatencyUMA();
}
}
void CloudOpenTask::FinishedOneDriveUpload(
base::WeakPtr<Profile> profile_weak_ptr,
OfficeTaskResult task_result,
std::optional<storage::FileSystemURL> url,
int64_t size) {
DCHECK_LT(file_urls_idx_, file_urls_.size());
if (url.has_value()) {
upload_total_size_ += size;
Profile* profile = profile_weak_ptr.get();
if (!profile) {
// TODO(b/296950967): metric to log here?
return;
}
fm_tasks::SetOfficeFileMovedToOneDrive(profile, base::Time::Now());
// Log TaskResult after open is tried.
OpenODFSUrl(profile, url.value(),
base::BindOnce(&CloudOpenTask::LogOneDriveOpenResultUMA, this,
task_result));
} else {
cloud_open_metrics_->LogTaskResult(task_result);
has_upload_errors_ = has_upload_errors_ ||
(task_result == OfficeTaskResult::kFailedToUpload);
}
file_urls_idx_++;
if (file_urls_idx_ < file_urls_.size()) {
StartNextOneDriveUpload();
return;
}
if (!has_upload_errors_) {
RecordUploadLatencyUMA();
}
}
// Logs UMA when the Drive task ends with an attempt to open a file.
void CloudOpenTask::LogGoogleDriveOpenResultUMA(
OfficeTaskResult success_task_result,
OfficeDriveOpenErrors open_result) {
cloud_open_metrics_->LogGoogleDriveOpenError(open_result);
cloud_open_metrics_->LogTaskResult(open_result ==
OfficeDriveOpenErrors::kSuccess
? success_task_result
: OfficeTaskResult::kFailedToOpen);
}
// Logs UMA when the OneDrive task ends with an attempt to open a file.
void CloudOpenTask::LogOneDriveOpenResultUMA(
OfficeTaskResult success_task_result,
OfficeOneDriveOpenErrors open_result) {
cloud_open_metrics_->LogOneDriveOpenError(open_result);
cloud_open_metrics_->LogTaskResult(open_result ==
OfficeOneDriveOpenErrors::kSuccess
? success_task_result
: OfficeTaskResult::kFailedToOpen);
}
void CloudOpenTask::RecordUploadLatencyUMA() {
constexpr int64_t kMegabyte = 1000 * 1000;
std::string uma_size;
if (upload_total_size_ > 1000 * kMegabyte) {
uma_size = "1000MB-and-above";
} else if (upload_total_size_ > 100 * kMegabyte) {
uma_size = "0100MB-to-1GB";
} else if (upload_total_size_ > 10 * kMegabyte) {
uma_size = "0010MB-to-100MB";
} else if (upload_total_size_ > 1 * kMegabyte) {
uma_size = "0001MB-to-10MB";
} else if (upload_total_size_ <= 1 * kMegabyte) {
uma_size = "0000MB-to-1MB";
}
auto* transfer =
(transfer_required_ == OfficeFilesTransferRequired::kCopy ? "Copy"
: "Move");
auto* provider =
(cloud_provider_ == CloudProvider::kGoogleDrive ? "GoogleDrive"
: "OneDrive");
const auto metric = base::StrCat({"FileBrowser.OfficeFiles.FileOpen.Time.",
transfer, ".", uma_size, ".To.", provider});
base::UmaHistogramMediumTimes(metric, upload_timer_.Elapsed());
}
// Create the arguments necessary for showing the dialog. We first need to
// collect local file tasks, if we are trying to show the kFileHandlerDialog
// page.
bool CloudOpenTask::InitAndShowSetupOrMoveDialog(
SetupOrMoveDialogPage dialog_page) {
// Allow no more than one upload dialog at a time. If one already exists,
// bring it to the front to prompt the user to keep going. In the case of
// multiple upload requests, they should either be handled simultaneously or
// queued.
if (BringDialogToFrontIfItExists(chrome::kChromeUICloudUploadURL)) {
LOG(WARNING) << "Another cloud upload dialog is already being shown";
if (dialog_page == SetupOrMoveDialogPage::kMoveConfirmationGoogleDrive ||
dialog_page == SetupOrMoveDialogPage::kMoveConfirmationOneDrive) {
cloud_open_metrics_->LogTaskResult(
OfficeTaskResult::kCannotShowMoveConfirmation);
} else {
cloud_open_metrics_->LogTaskResult(
OfficeTaskResult::kCannotShowSetupDialog);
}
return false;
}
mojom::DialogArgsPtr args = CreateDialogArgs(dialog_page);
// Display local file handlers (tasks) only for the file handler dialog.
if (dialog_page == SetupOrMoveDialogPage::kFileHandlerDialog) {
// Callback to show the dialog after the tasks have been found.
fm_tasks::FindTasksCallback find_all_types_of_tasks_callback =
base::BindOnce(&CloudOpenTask::ShowDialog, this, dialog_page,
std::move(args));
// Find the file tasks that can open the `file_urls_` and then run
// `ShowDialog`.
FindTasksForDialog(std::move(find_all_types_of_tasks_callback));
} else {
ShowDialog(dialog_page, std::move(args), nullptr);
}
return true;
}
mojom::DialogArgsPtr CloudOpenTask::CreateDialogArgs(
SetupOrMoveDialogPage dialog_page) {
mojom::DialogArgsPtr args = mojom::DialogArgs::New();
for (const auto& file_url : file_urls_) {
args->file_names.push_back(file_url.path().BaseName().value());
}
switch (dialog_page) {
case SetupOrMoveDialogPage::kFileHandlerDialog: {
auto file_handler_dialog_args = mojom::FileHandlerDialogArgs::New();
file_handler_dialog_args->show_google_workspace_task =
chromeos::cloud_upload::IsGoogleWorkspaceCloudUploadAllowed(profile_);
file_handler_dialog_args->show_microsoft_office_task =
chromeos::cloud_upload::IsMicrosoftOfficeCloudUploadAllowed(profile_);
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewFileHandlerDialogArgs(
std::move(file_handler_dialog_args));
break;
}
case SetupOrMoveDialogPage::kOneDriveSetup: {
auto one_drive_setup_dialog_args = mojom::OneDriveSetupDialogArgs::New();
one_drive_setup_dialog_args->set_office_as_default_handler =
!HaveExplicitFileHandlers(profile_, file_urls_);
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewOneDriveSetupDialogArgs(
std::move(one_drive_setup_dialog_args));
break;
}
case SetupOrMoveDialogPage::kMoveConfirmationOneDrive: {
auto move_confirmation_one_drive_dialog_args =
mojom::MoveConfirmationOneDriveDialogArgs::New();
move_confirmation_one_drive_dialog_args->operation_type =
UploadTypeToOperationType(SourceTypeToUploadType(source_type_));
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewMoveConfirmationOneDriveDialogArgs(
std::move(move_confirmation_one_drive_dialog_args));
break;
}
case SetupOrMoveDialogPage::kMoveConfirmationGoogleDrive: {
auto move_confirmation_google_drive_dialog_args =
mojom::MoveConfirmationGoogleDriveDialogArgs::New();
move_confirmation_google_drive_dialog_args->operation_type =
UploadTypeToOperationType(SourceTypeToUploadType(source_type_));
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewMoveConfirmationGoogleDriveDialogArgs(
std::move(move_confirmation_google_drive_dialog_args));
break;
}
}
return args;
}
// Creates and shows a new dialog for the cloud upload workflow. If there are
// local file tasks from `resulting_tasks`, include them in the dialog
// arguments. These tasks are can be selected by the user to open the files
// instead of using a cloud provider. If there is no Files app window currently
// open to use as a modal parent for the dialog, first launches a new Files app
// window, which we listen for in OnBrowserAdded().
void CloudOpenTask::ShowDialog(
SetupOrMoveDialogPage dialog_page,
mojom::DialogArgsPtr args,
std::unique_ptr<fm_tasks::ResultingTasks> resulting_tasks) {
if (resulting_tasks) {
SetTaskArgs(args, std::move(resulting_tasks));
if (chromeos::features::IsUploadOfficeToCloudForEnterpriseEnabled()) {
const auto& file_handler_dialog_args =
args->dialog_specific_args->get_file_handler_dialog_args();
// When there is only one possible task (Microsoft or Google) and no
// further local tasks, skip the file handler page and either show the
// OneDrive setup if necessary, or go straight to opening/moving the
// files.
if ((!file_handler_dialog_args->show_microsoft_office_task ||
!file_handler_dialog_args->show_google_workspace_task) &&
local_tasks_.empty()) {
// Validate that `cloud_provider_` differs from the disabled task.
CHECK(!(cloud_provider_ == CloudProvider::kOneDrive &&
!file_handler_dialog_args->show_microsoft_office_task));
CHECK(!(cloud_provider_ == CloudProvider::kGoogleDrive &&
!file_handler_dialog_args->show_google_workspace_task));
MaybeRunFixupFlow();
return;
}
}
}
bool office_move_confirmation_shown =
cloud_provider_ == CloudProvider::kGoogleDrive
? fm_tasks::GetOfficeMoveConfirmationShownForDrive(profile_)
: fm_tasks::GetOfficeMoveConfirmationShownForOneDrive(profile_);
base::OnceCallback<void(const std::string&)> dialog_callback;
switch (dialog_page) {
case SetupOrMoveDialogPage::kFileHandlerDialog:
case SetupOrMoveDialogPage::kOneDriveSetup:
dialog_callback =
base::BindOnce(&CloudOpenTask::OnSetupDialogComplete, this);
break;
case SetupOrMoveDialogPage::kMoveConfirmationOneDrive:
case SetupOrMoveDialogPage::kMoveConfirmationGoogleDrive:
dialog_callback =
base::BindOnce(&CloudOpenTask::OnMoveConfirmationComplete, this);
break;
}
// This CloudUploadDialog pointer is managed by an instance of
// `views::WebDialogView` and deleted in
// `SystemWebDialogDelegate::OnDialogClosed`.
CloudUploadDialog* dialog =
new CloudUploadDialog(std::move(args), std::move(dialog_callback),
office_move_confirmation_shown);
// Get Files App window, if it exists.
files_app_browser_ = FindSystemWebAppBrowser(
profile_, ash::SystemWebAppType::FILE_MANAGER, ash::BrowserType::kApp);
gfx::NativeWindow modal_parent =
files_app_browser_ ? files_app_browser_->GetNativeWindow() : nullptr;
if (!modal_parent) {
need_new_files_app_ = true;
DCHECK(!pending_dialog_);
pending_dialog_ = dialog;
// Create a files app window and use it as the modal parent. CloudOpenTask
// is kept alive by the callback passed to CloudUploadDialog above. We
// expect this to trigger OnBrowserAdded, which then shows the dialog.
file_manager::util::ShowItemInFolder(profile_, file_urls_.at(0).path(),
base::DoNothing());
} else {
dialog->ShowSystemDialog(modal_parent);
}
}
// Stores constructed tasks into
// `args->dialog_specific_args->file_handler_dialog_args->local_tasks` and
// `local_tasks_`.
void CloudOpenTask::SetTaskArgs(
mojom::DialogArgsPtr& args,
std::unique_ptr<fm_tasks::ResultingTasks> resulting_tasks) {
int nextPosition = 0;
auto& file_handler_dialog_args =
args->dialog_specific_args->get_file_handler_dialog_args();
for (fm_tasks::FullTaskDescriptor& task : resulting_tasks->tasks) {
// Ignore Google Docs and MS Office tasks as they are already
// set up to show in the dialog.
if (fm_tasks::IsWebDriveOfficeTask(task.task_descriptor) ||
fm_tasks::IsOpenInOfficeTask(task.task_descriptor)) {
continue;
}
mojom::DialogTaskPtr dialog_task = mojom::DialogTask::New();
// The (unique and positive) `position` of the task in the `tasks` vector.
// If the user responds with the `position`, the task will be launched via
// `LaunchLocalFileTask()`.
dialog_task->position = nextPosition++;
dialog_task->title = task.task_title;
dialog_task->icon_url = task.icon_url.spec();
dialog_task->app_id = task.task_descriptor.app_id;
file_handler_dialog_args->local_tasks.push_back(std::move(dialog_task));
local_tasks_.push_back(std::move(task.task_descriptor));
}
}
void CloudOpenTask::OnBrowserAdded(Browser* browser) {
if (!need_new_files_app_) {
return;
}
// TODO(petermarshall): Add a timeout. If Files app never launches for some
// reason, then we will never show the dialog.
DCHECK(pending_dialog_);
if (!IsBrowserForSystemWebApp(browser, SystemWebAppType::FILE_MANAGER)) {
// Wait for Files app to launch.
LOG(WARNING) << "Browser did not match Files app";
return;
}
need_new_files_app_ = false;
files_app_browser_ = BrowserController::GetInstance()->GetDelegate(browser);
pending_dialog_->ShowSystemDialog(files_app_browser_->GetNativeWindow());
// The dialog is deleted in `SystemWebDialogDelegate::OnDialogClosed`.
pending_dialog_ = nullptr;
}
void CloudOpenTask::OnBrowserClosing(Browser* browser) {
if (BrowserController::GetInstance()->GetDelegate(browser) ==
files_app_browser_) {
// The Files app that the dialog is modal to is closed. This will close the
// dialog with an empty user response.
files_app_closed_ = true;
}
}
// Receive user's setup dialog response and acts accordingly. `user_response` is
// either a particular ash::cloud_upload::mojom::UserAction or the id (position)
// of the task in `local_tasks_` to launch. We never use the return value but
// it's necessary to make sure that we delete CloudOpenTask when we're done.
void CloudOpenTask::OnSetupDialogComplete(const std::string& user_response) {
if (user_response == kUserActionConfirmOrUploadToGoogleDrive) {
cloud_provider_ = CloudProvider::kGoogleDrive;
cloud_open_metrics_->set_cloud_provider(cloud_provider_);
// Because we treat Docs/Sheets/Slides as three separate apps, only set
// the default handler for the types that we are dealing with.
// We don't currently check MIME types, which could mean we get into edge
// cases if the MIME type doesn't match the file extension.
if (HasWordFile(file_urls_)) {
UMA_HISTOGRAM_ENUMERATION(kFileHandlerSelectionMetricName,
OfficeSetupFileHandler::kGoogleDocs);
fm_tasks::SetWordFileHandlerToFilesSWA(
profile_, fm_tasks::kActionIdWebDriveOfficeWord);
}
if (HasExcelFile(file_urls_)) {
UMA_HISTOGRAM_ENUMERATION(kFileHandlerSelectionMetricName,
OfficeSetupFileHandler::kGoogleSheets);
fm_tasks::SetExcelFileHandlerToFilesSWA(
profile_, fm_tasks::kActionIdWebDriveOfficeExcel);
}
if (HasPowerPointFile(file_urls_)) {
UMA_HISTOGRAM_ENUMERATION(kFileHandlerSelectionMetricName,
OfficeSetupFileHandler::kGoogleSlides);
fm_tasks::SetPowerPointFileHandlerToFilesSWA(
profile_, fm_tasks::kActionIdWebDriveOfficePowerPoint);
}
OpenOrMoveFiles();
} else if (user_response == kUserActionConfirmOrUploadToOneDrive) {
// Default handlers have already been set by this point for
// Office/OneDrive.
OpenOrMoveFiles();
} else if (user_response == kUserActionSetUpOneDrive) {
UMA_HISTOGRAM_ENUMERATION(kFileHandlerSelectionMetricName,
OfficeSetupFileHandler::kMicrosoft365);
cloud_provider_ = CloudProvider::kOneDrive;
cloud_open_metrics_->set_cloud_provider(cloud_provider_);
InitAndShowSetupOrMoveDialog(SetupOrMoveDialogPage::kOneDriveSetup);
} else if (user_response == kUserActionCancel) {
cloud_open_metrics_->LogTaskResult(OfficeTaskResult::kCancelledAtSetup);
// Do nothing.
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Cancelled setup";
} else if (!user_response.empty()) {
cloud_open_metrics_->LogTaskResult(OfficeTaskResult::kLocalFileTask);
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Chose local file task";
LaunchLocalFileTask(user_response);
} else {
// Always map an empty user response to a Cancel user response. This can
// occur when the Files app the dialog was modal to is closed.
if (!files_app_closed_) {
// This can also 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 not due to the files app closing";
}
cloud_open_metrics_->LogTaskResult(OfficeTaskResult::kCancelledAtSetup);
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Cancelled setup";
}
}
// Receive user's move confirmation response and acts accordingly.
// `user_response` is a particular ash::cloud_upload::mojom::UserAction. We
// never use the return value but it's necessary to make sure that we delete
// CloudOpenTask when we're done.
void CloudOpenTask::OnMoveConfirmationComplete(
const std::string& user_response) {
// TODO(petermarshall): Don't need separate actions for drive/onedrive now
// (and for StartUpload?).
if (user_response == kUserActionUploadToGoogleDrive) {
fm_tasks::SetOfficeMoveConfirmationShownForDrive(profile_, true);
switch (source_type_) {
case SourceType::LOCAL:
fm_tasks::SetOfficeMoveConfirmationShownForLocalToDrive(profile_, true);
break;
case SourceType::CLOUD:
fm_tasks::SetOfficeMoveConfirmationShownForCloudToDrive(profile_, true);
break;
case SourceType::READ_ONLY:
// TODO (jboulic): Clarify UX.
break;
}
StartUpload();
} else if (user_response == kUserActionUploadToOneDrive) {
fm_tasks::SetOfficeMoveConfirmationShownForOneDrive(profile_, true);
switch (source_type_) {
case SourceType::LOCAL:
fm_tasks::SetOfficeMoveConfirmationShownForLocalToOneDrive(profile_,
true);
break;
case SourceType::CLOUD:
fm_tasks::SetOfficeMoveConfirmationShownForCloudToOneDrive(profile_,
true);
break;
case SourceType::READ_ONLY:
// TODO (jboulic): Clarify UX.
break;
}
StartUpload();
} else if (user_response == kUserActionCancelGoogleDrive ||
user_response == kUserActionCancelOneDrive) {
cloud_open_metrics_->LogTaskResult(
OfficeTaskResult::kCancelledAtConfirmation);
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Cancelled move";
} else if (!user_response.empty()) {
LOG(ERROR) << "Unhandled response: " << user_response;
} else {
// Always map an empty user response to a Cancel user response. This can
// occur when the Files app the dialog was modal to is closed.
if (!files_app_closed_) {
// This can also 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 not due to the files app closing";
}
cloud_open_metrics_->LogTaskResult(
OfficeTaskResult::kCancelledAtConfirmation);
// Set as WARNING as INFO is not allowed.
LOG(WARNING) << "Cancelled move";
}
}
// Launch the local file task in `local_tasks_` with the position specified by
// `string_task_position`.
void CloudOpenTask::LaunchLocalFileTask(
const std::string& string_task_position) {
// Convert the `string_task_position` - the string of the task position in
// `local_tasks_` - to an int. Ensure that it is within the range of
// `local_tasks_`.
int task_position;
if (!base::StringToInt(string_task_position, &task_position) ||
task_position < 0 ||
static_cast<size_t>(task_position) >= local_tasks_.size()) {
LOG(ERROR) << "Position for local file task is unexpectedly unable to be "
"retrieved. Retrieved position: "
<< string_task_position
<< " from user response: " << string_task_position;
return;
}
// Launch the task.
fm_tasks::TaskDescriptor& task = local_tasks_[task_position];
UMA_HISTOGRAM_ENUMERATION(kFileHandlerSelectionMetricName,
extension_misc::IsQuickOfficeExtension(task.app_id)
? OfficeSetupFileHandler::kQuickOffice
: OfficeSetupFileHandler::kOtherLocalHandler);
fm_tasks::ExecuteFileTask(
profile_, task, file_urls_,
base::BindOnce(&CloudOpenTask::LocalTaskExecuted, this, task));
}
// We never use the return value but it's necessary to make sure that we delete
// CloudOpenTask when we're done.
void CloudOpenTask::LocalTaskExecuted(
const fm_tasks::TaskDescriptor& task,
extensions::api::file_manager_private::TaskResult result,
std::string error_message) {
if (!error_message.empty()) {
LOG(ERROR) << "Execution of local file task with app id " << task.app_id
<< " to open office files. Led to error message: "
<< error_message
<< " and result: " << base::to_underlying(result);
return;
}
if (HasWordFile(file_urls_)) {
fm_tasks::SetWordFileHandler(profile_, task);
}
if (HasExcelFile(file_urls_)) {
fm_tasks::SetExcelFileHandler(profile_, task);
}
if (HasPowerPointFile(file_urls_)) {
fm_tasks::SetPowerPointFileHandler(profile_, task);
}
}
// Find the file tasks that can open the `file_urls` and pass them to the
// `find_all_types_of_tasks_callback`.
void CloudOpenTask::FindTasksForDialog(
fm_tasks::FindTasksCallback find_all_types_of_tasks_callback) {
using extensions::app_file_handler_util::MimeTypeCollector;
// Get the file info for finding the tasks.
std::vector<base::FilePath> local_paths;
std::vector<GURL> gurls;
for (const auto& file_url : file_urls_) {
local_paths.push_back(file_url.path());
gurls.push_back(file_url.ToGURL());
}
// Get the mime types of the files and then pass them to the callback to
// get the entries.
std::unique_ptr<MimeTypeCollector> mime_collector =
std::make_unique<MimeTypeCollector>(profile_);
auto* mime_collector_ptr = mime_collector.get();
mime_collector_ptr->CollectForLocalPaths(
local_paths,
base::BindOnce(&CloudOpenTask::ConstructEntriesAndFindTasks, this,
local_paths, gurls, std::move(mime_collector),
std::move(find_all_types_of_tasks_callback)));
}
void CloudOpenTask::ConstructEntriesAndFindTasks(
const std::vector<base::FilePath>& file_paths,
const std::vector<GURL>& gurls,
std::unique_ptr<extensions::app_file_handler_util::MimeTypeCollector>
mime_collector,
fm_tasks::FindTasksCallback find_all_types_of_tasks_callback,
std::unique_ptr<std::vector<std::string>> mime_types) {
std::vector<extensions::EntryInfo> entries;
DCHECK_EQ(file_paths.size(), mime_types->size());
for (size_t i = 0; i < file_paths.size(); ++i) {
entries.emplace_back(file_paths[i], (*mime_types)[i], false);
}
const std::vector<std::string> dlp_source_urls(entries.size(), "");
fm_tasks::FindAllTypesOfTasks(profile_, entries, gurls, dlp_source_urls,
std::move(find_all_types_of_tasks_callback));
}
void CloudOpenTask::SetTasksForTest(
const std::vector<fm_tasks::TaskDescriptor>& tasks) {
local_tasks_ = tasks;
}
void CloudUploadDialog::OnDialogShown(content::WebUI* webui) {
CHECK(dialog_args_);
SystemWebDialogDelegate::OnDialogShown(webui);
static_cast<CloudUploadUI*>(webui->GetController())
->SetDialogArgs(dialog_args_.Clone());
}
void CloudUploadDialog::OnDialogClosed(const std::string& json_retval) {
UploadRequestCallback callback = std::move(callback_);
// Deletes this, so we store the `callback` first.
SystemWebDialogDelegate::OnDialogClosed(json_retval);
// The callback can create a new dialog. It must be called last because we
// can only have one of these dialogs at a time.
if (callback) {
std::move(callback).Run(json_retval);
}
}
CloudUploadDialog::CloudUploadDialog(mojom::DialogArgsPtr args,
UploadRequestCallback callback,
bool office_move_confirmation_shown)
: SystemWebDialogDelegate(GURL(chrome::kChromeUICloudUploadURL),
std::u16string() /* title */),
dialog_args_(std::move(args)),
callback_(std::move(callback)),
office_move_confirmation_shown_(office_move_confirmation_shown) {}
CloudUploadDialog::~CloudUploadDialog() = default;
ui::mojom::ModalType CloudUploadDialog::GetDialogModalType() const {
return ui::mojom::ModalType::kWindow;
}
bool CloudUploadDialog::ShouldCloseDialogOnEscape() const {
// All the dialogs handle an Escape keydown.
return false;
}
bool CloudUploadDialog::ShouldShowCloseButton() const {
return false;
}
namespace {
constexpr int kDialogWidthForOneDriveSetup = 512;
constexpr int kDialogHeightForOneDriveSetup = 556;
constexpr int kDialogWidthForFileHandlerDialog = 512;
constexpr int kDialogHeightForFileHandlerDialog = 379;
constexpr int kDialogHeightForFileHandlerDialogNoLocalApp = 315;
constexpr int kDialogHeightForFileHandlerDialogOneHandlerMissing = 295;
constexpr int kDialogWidthForMoveConfirmation = 512;
constexpr int kDialogHeightForMoveConfirmationWithCheckbox = 524;
constexpr int kDialogHeightForMoveConfirmationWithoutCheckbox = 472;
constexpr int kDialogWidthForConnectToOneDrive = 512;
constexpr int kDialogHeightForConnectToOneDrive = 556;
} // namespace
void CloudUploadDialog::GetDialogSize(gfx::Size* size) const {
const auto& dialog_specific_args = dialog_args_->dialog_specific_args;
if (dialog_specific_args->is_file_handler_dialog_args()) {
const auto& file_handler_dialog_args =
dialog_specific_args->get_file_handler_dialog_args();
const bool has_local_tasks = !file_handler_dialog_args->local_tasks.empty();
const bool is_microsoft_office_or_google_workspace_disabled_by_policy =
!file_handler_dialog_args->show_microsoft_office_task ||
!file_handler_dialog_args->show_google_workspace_task;
size->set_width(kDialogWidthForFileHandlerDialog);
if (is_microsoft_office_or_google_workspace_disabled_by_policy) {
CHECK(has_local_tasks);
size->set_height(kDialogHeightForFileHandlerDialogOneHandlerMissing);
} else {
size->set_height(has_local_tasks
? kDialogHeightForFileHandlerDialog
: kDialogHeightForFileHandlerDialogNoLocalApp);
}
} else if (dialog_specific_args->is_one_drive_setup_dialog_args()) {
size->set_width(kDialogWidthForOneDriveSetup);
size->set_height(kDialogHeightForOneDriveSetup);
} else if (dialog_specific_args
->is_move_confirmation_google_drive_dialog_args() ||
dialog_specific_args
->is_move_confirmation_one_drive_dialog_args()) {
size->set_width(kDialogWidthForMoveConfirmation);
if (office_move_confirmation_shown_) {
size->set_height(kDialogHeightForMoveConfirmationWithCheckbox);
} else {
size->set_height(kDialogHeightForMoveConfirmationWithoutCheckbox);
}
} else if (dialog_specific_args->is_connect_to_one_drive_dialog_args()) {
size->set_width(kDialogWidthForConnectToOneDrive);
size->set_height(kDialogHeightForConnectToOneDrive);
} else {
NOTREACHED();
}
}
bool ShowConnectOneDriveDialog(gfx::NativeWindow modal_parent) {
// Allow no more than one upload dialog at a time. If one already exists,
// bring it to the front to prompt the user to keep going. Only one of either
// this dialog, or CloudOpenTask can be shown at a time because they use the
// same WebUI for dialogs.
if (BringDialogToFrontIfItExists(chrome::kChromeUICloudUploadURL)) {
LOG(WARNING) << "Another cloud upload dialog is already being shown";
return false;
}
mojom::DialogArgsPtr args = mojom::DialogArgs::New();
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewConnectToOneDriveDialogArgs(
mojom::ConnectToOneDriveDialogArgs::New());
// This CloudUploadDialog pointer is managed by an instance of
// `views::WebDialogView` and deleted in
// `SystemWebDialogDelegate::OnDialogClosed`.
CloudUploadDialog* dialog =
new CloudUploadDialog(std::move(args), base::DoNothing(),
/*office_move_confirmation_shown=*/false);
dialog->ShowSystemDialog(modal_parent);
return true;
}
void LaunchMicrosoft365Setup(Profile* profile, gfx::NativeWindow modal_parent) {
mojom::DialogArgsPtr args = mojom::DialogArgs::New();
auto one_drive_setup_dialog_args = mojom::OneDriveSetupDialogArgs::New();
// If `set_office_as_default_handler` is false, it indicates that we already
// ran the Office setup and set file handler preferences for all handled
// Office file types, or that the user has pre-existing preferences for these
// file types.
one_drive_setup_dialog_args->set_office_as_default_handler =
!HaveExplicitFileHandlers(profile, fm_tasks::WordGroupExtensions()) ||
!HaveExplicitFileHandlers(profile, fm_tasks::ExcelGroupExtensions()) ||
!HaveExplicitFileHandlers(profile, fm_tasks::PowerPointGroupExtensions());
args->dialog_specific_args =
mojom::DialogSpecificArgs::NewOneDriveSetupDialogArgs(
std::move(one_drive_setup_dialog_args));
// This CloudUploadDialog pointer is managed by an instance of
// `views::WebDialogView` and deleted in
// `SystemWebDialogDelegate::OnDialogClosed`.
CloudUploadDialog* dialog =
new CloudUploadDialog(std::move(args), base::DoNothing(),
/*office_move_confirmation_shown=*/false);
dialog->ShowSystemDialog(modal_parent);
}
} // namespace ash::cloud_upload
|