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
|
// 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 "chromeos/ash/components/growth/campaigns_matcher.h"
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/features.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/system/sys_info.h"
#include "base/time/time.h"
#include "base/version.h"
#include "base/version_info/channel.h"
#include "base/version_info/version_info.h"
#include "chromeos/ash/components/channel/channel_info.h"
#include "chromeos/ash/components/demo_mode/utils/dimensions_utils.h"
#include "chromeos/ash/components/growth/campaigns_logger.h"
#include "chromeos/ash/components/growth/campaigns_manager_client.h"
#include "chromeos/ash/components/growth/campaigns_model.h"
#include "chromeos/ash/components/growth/campaigns_utils.h"
#include "chromeos/ash/components/growth/growth_metrics.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/account_capabilities.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/tribool.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "components/version_info/version_info.h"
#include "google_apis/gaia/gaia_id.h"
#include "third_party/re2/src/re2/re2.h"
namespace growth {
namespace {
constexpr char kEventKey[] = "event_to_be_checked";
constexpr char kInternalLogLineSeparator[] = "--------------------------------";
inline constexpr char kBoards[] = "boards";
inline constexpr char kChannels[] = "channels";
base::Time GetDeviceCurrentTimeForScheduling() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(
ash::switches::kGrowthCampaignsCurrentTimeSecondsSinceUnixEpoch)) {
const auto& value = command_line->GetSwitchValueASCII(
ash::switches::kGrowthCampaignsCurrentTimeSecondsSinceUnixEpoch);
double seconds_since_epoch;
CHECK(base::StringToDouble(value, &seconds_since_epoch));
return base::Time::FromSecondsSinceUnixEpoch(seconds_since_epoch);
}
return base::Time::Now();
}
bool MatchPref(const base::Value::List* criterias,
std::string_view pref_path,
const PrefService* pref_service) {
if (!pref_service) {
CAMPAIGNS_LOG(ERROR) << "Matching pref before pref service is available";
RecordCampaignsManagerError(
CampaignsManagerError::kUserPrefUnavailableAtMatching);
return false;
}
if (!criterias) {
// No related targeting found in campaign targeting, returns true.
return true;
}
auto& value = pref_service->GetValue(pref_path);
// String list targeting.
if (criterias) {
return Contains(*criterias, value);
}
return false;
}
int GetMilestone() {
return version_info::GetMajorVersionNumberAsInt();
}
const base::Version& GetVersion() {
return version_info::GetVersion();
}
bool MatchTimeWindow(const base::Time& start_time,
const base::Time& end_time,
const base::Time& targeted_time) {
return start_time <= targeted_time && end_time >= targeted_time;
}
bool MatchTimeWindow(const TimeWindowTargeting& time_window_targeting,
const base::Time& targeted_time) {
return MatchTimeWindow(time_window_targeting.GetStartTime(),
time_window_targeting.GetEndTime(), targeted_time);
}
// Matched if any of the given `scheduling_targetings` is matched.
bool MatchSchedulings(const std::vector<std::unique_ptr<TimeWindowTargeting>>&
scheduling_targetings) {
if (scheduling_targetings.empty()) {
// Match campaign if there is no scheduling targeting criteria.
return true;
}
const auto now = GetDeviceCurrentTimeForScheduling();
for (const auto& scheduling_targeting : scheduling_targetings) {
if (MatchTimeWindow(*scheduling_targeting, now)) {
return true;
}
}
CAMPAIGNS_LOG(DEBUG) << "Schedulings is NOT matched.";
return false;
}
bool MatchExperimentTags(const base::Value::List* experiment_tags,
std::optional<const base::Feature*> feature) {
if (!ash::features::IsGrowthCampaignsExperimentTagTargetingEnabled()) {
// Campaign not match if experiment tag targeting is not enabled.
return false;
}
// TODO: b/344673533 - verify that valid experiment targeting should have
// both feature and experiment tag. Ignore the campaign if it is not the case.
if (!feature.has_value()) {
// Campaign matched if there is no targeted feature config.
return true;
}
const auto* targeted_feature = feature.value();
if (!targeted_feature) {
// Campaign not matched if feaure config is invalid.
CAMPAIGNS_LOG(DEBUG) << "Feature config is invalid.";
return false;
}
if (!experiment_tags || experiment_tags->empty()) {
// Campaign matched if there is no experiment tag targeting.
CAMPAIGNS_LOG(DEBUG) << "No targeted experiment tag.";
return true;
}
const auto exp_tag =
base::GetFieldTrialParamValueByFeature(*targeted_feature, "exp_tag");
if (exp_tag.empty()) {
// Campaign not match if no experiment tag exists.
CAMPAIGNS_LOG(DEBUG) << "No experiment tag exists.";
return false;
}
// Campaign is matched if the tag from field trail param matches any of the
// tag in the targeting criteria.
const bool exp_tag_matched = base::Contains(*experiment_tags, exp_tag);
if (!exp_tag_matched) {
CAMPAIGNS_LOG(DEBUG) << "ExperimentTags is NOT matched.";
}
return exp_tag_matched;
}
// Match if the target values and the user pref has any overlap entries.
bool HasOverlapEntries(const base::Value::List& pref_values,
const base::Value::List& target_values) {
for (auto& value : target_values) {
if (base::Contains(pref_values, value)) {
return true;
}
}
return false;
}
// Match if the values in the List and Vector has any overlap entries.
bool HasOverlapEntries(const base::Value::List& list_values,
const std::vector<std::string>& vector_values) {
for (const auto& value : vector_values) {
if (base::Contains(list_values, value)) {
return true;
}
}
return false;
}
// Match if any value in the target is found in user pref.
bool MatchUserPref(const PrefService& pref_service,
const std::string* pref_name,
const base::Value::List* target_values) {
if (!pref_name || pref_name->empty()) {
growth::RecordCampaignsManagerError(
growth::CampaignsManagerError::kTargetingUserPrefParsingFail);
CAMPAIGNS_LOG(ERROR) << "Targeting user pref name missing.";
return false;
}
if (!target_values || target_values->empty()) {
growth::RecordCampaignsManagerError(
growth::CampaignsManagerError::kTargetingUserPrefParsingFail);
CAMPAIGNS_LOG(ERROR) << "Targeting user pref value missing.";
return false;
}
auto* pref = pref_service.FindPreference(*pref_name);
if (!pref) {
growth::RecordCampaignsManagerError(
growth::CampaignsManagerError::kTargetingUserPrefNotFound);
CAMPAIGNS_LOG(ERROR) << "Targeting user pref not found: " << pref_name;
return false;
}
auto* pref_value = pref->GetValue();
CHECK(pref_value);
if (pref_value->is_none() || pref_value->is_dict()) {
CAMPAIGNS_LOG(ERROR) << "User pref type is not supported: " << pref_name;
return false;
}
// If the user pref is a list, match if any entry in target values is in user
// pref.
if (pref_value->is_list()) {
return HasOverlapEntries(pref_value->GetList(), *target_values);
}
// If the user pref is not a list, match if any entry in target values is the
// pref value.
return base::Contains(*target_values, *pref_value);
}
// TODO: b/354060160 - Add more data type to pref targeting.
// Match a user pref condition if any criterion matched.
// [ // These criteria are logic OR.
// {"name": "prefA", "value": ["A1", "A2"]},
// {"name": "prefB", "value": ["B1"]}
// ],
// conditions_met = A1 || A2 || B1
bool MatchUserPrefCriteria(const PrefService& pref_service,
const base::Value::List& criteria) {
for (auto& criterion : criteria) {
if (!criterion.is_dict()) {
growth::RecordCampaignsManagerError(
growth::CampaignsManagerError::kTargetingUserPrefParsingFail);
CAMPAIGNS_LOG(ERROR) << "Fail to parse user pref targeting.";
continue;
}
if (MatchUserPref(pref_service, criterion.GetDict().FindString("name"),
criterion.GetDict().FindList("value"))) {
return true;
}
}
return false;
}
// Match the user preference. The structure looks like:
// "userPrefs": [ // These two conditions are logic AND.
// [ // These criteria are logic OR.
// {"name": "prefA", "value": ["A1", "A2"]},
// {"name": "prefB", "value": ["B1"]}
// ],
// [
// {"name": "prefC", "value": ["C1"]}
// ]
// ]
// conditions_met = (A1 || A2 || B1) && C1;
bool MatchUserPrefs(const PrefService* pref_service,
const base::Value::List* user_pref_targetings) {
if (!user_pref_targetings || user_pref_targetings->empty()) {
return true;
}
if (!pref_service) {
RecordCampaignsManagerError(
CampaignsManagerError::kUserPrefUnavailableAtMatching);
CAMPAIGNS_LOG(ERROR)
<< "Matching user pref before user pref service is available";
return false;
}
// If all conditions are matched, the campaign will be selected.
for (auto& targeting : *user_pref_targetings) {
if (!targeting.is_list()) {
growth::RecordCampaignsManagerError(
growth::CampaignsManagerError::kTargetingUserPrefParsingFail);
CAMPAIGNS_LOG(ERROR) << "Invalid user pref targeting set.";
return false;
}
if (!MatchUserPrefCriteria(*pref_service, targeting.GetList())) {
CAMPAIGNS_LOG(DEBUG) << "UserPref is NOT matched.";
return false;
}
}
return true;
}
bool MatchVersion(const base::Version& current_version,
std::optional<base::Version> min_version,
std::optional<base::Version> max_version) {
if (!current_version.IsValid()) {
// Not match if current version is invalid.
return false;
}
if (min_version && min_version->CompareTo(current_version) == 1) {
return false;
}
if (max_version && max_version->CompareTo(current_version) == -1) {
return false;
}
return true;
}
bool MatchStringList(const StringListTargeting& string_list_targeting,
const std::string& value,
const std::string_view& target_name) {
const auto* includes = string_list_targeting.GetIncludes();
// If the `includes` is empty, then it will not match.
if (includes && !Contains(*includes, value)) {
CAMPAIGNS_LOG(DEBUG) << "Value is not in the includes list of "
<< target_name;
return false;
}
const auto* excludes = string_list_targeting.GetExcludes();
if (excludes && Contains(*excludes, value)) {
CAMPAIGNS_LOG(DEBUG) << "Value is in the excludes list of " << target_name;
return false;
}
return true;
}
bool IsCampaignValid(const Campaign* campaign) {
if (!GetCampaignId(campaign)) {
CAMPAIGNS_LOG(ERROR) << "Invalid campaign: missing campaign ID.";
RecordCampaignsManagerError(CampaignsManagerError::kMissingCampaignId);
return false;
}
return true;
}
} // namespace
CampaignsMatcher::CampaignsMatcher(CampaignsManagerClient* client,
PrefService* local_state)
: client_(client), local_state_(local_state) {}
CampaignsMatcher::~CampaignsMatcher() = default;
void CampaignsMatcher::FilterAndSetCampaigns(CampaignsPerSlot* campaigns) {
// Filter campaigns that doesn't pass pre-match.
for (int slot = 0; slot <= static_cast<int>(Slot::kMaxValue); slot++) {
auto* targeted_campaigns =
GetMutableCampaignsBySlot(campaigns, static_cast<Slot>(slot));
if (!targeted_campaigns) {
continue;
}
auto campaign_iter = targeted_campaigns->begin();
while (campaign_iter != targeted_campaigns->end()) {
if (IsCampaignMatched(campaign_iter->GetIfDict(),
/*is_prematch=*/true)) {
++campaign_iter;
} else {
campaign_iter = targeted_campaigns->erase(campaign_iter);
}
}
}
campaigns_ = campaigns;
}
void CampaignsMatcher::SetOpenedApp(std::string app_id) {
opened_app_id_ = std::move(app_id);
}
void CampaignsMatcher::SetActiveUrl(const GURL& url) {
active_url_ = url;
}
void CampaignsMatcher::SetOobeCompleteTime(base::Time time) {
oobe_compelete_time_ = time;
}
void CampaignsMatcher::SetIsUserOwner(bool is_user_owner) {
is_user_owner_ = is_user_owner;
}
void CampaignsMatcher::SetTrigger(const Trigger&& trigger) {
trigger_ = std::move(trigger);
}
void CampaignsMatcher::SetPrefs(PrefService* prefs) {
prefs_ = prefs;
}
const Campaign* CampaignsMatcher::GetCampaignBySlot(Slot slot) const {
auto* targeted_campaigns = GetCampaignsBySlot(campaigns_, slot);
if (!targeted_campaigns) {
return nullptr;
}
for (auto& campaign_value : *targeted_campaigns) {
const auto* campaign = campaign_value.GetIfDict();
if (IsCampaignMatched(campaign, /*is_prematch=*/false)) {
return campaign;
}
}
return nullptr;
}
void CampaignsMatcher::SetMantaCapabilityForTesting(signin::Tribool value) {
manta_capability_for_testing_ = value;
}
void CampaignsMatcher::SetBoardForTesting(std::optional<std::string> board) {
board_for_testing_ = board;
}
bool CampaignsMatcher::IsCampaignMatched(const Campaign* campaign,
bool is_prematch) const {
if (!campaign || !IsCampaignValid(campaign)) {
CAMPAIGNS_LOG(ERROR) << "Invalid campaign.";
RecordCampaignsManagerError(CampaignsManagerError::kInvalidCampaign);
return false;
}
const auto* targetings = GetTargetings(campaign);
const auto campaign_id = GetCampaignId(campaign).value();
CAMPAIGNS_LOG(DEBUG) << kInternalLogLineSeparator;
CAMPAIGNS_LOG(DEBUG) << "Evaluating campaign: " << campaign_id
<< ". In prematch: " << ToString(is_prematch);
const bool is_matched = Matched(targetings, campaign_id,
GetCampaignGroupId(campaign), is_prematch);
CAMPAIGNS_LOG(DEBUG) << "Campaign: " << campaign_id
<< " is matched: " << ToString(is_matched)
<< ". In prematch: " << ToString(is_prematch);
CAMPAIGNS_LOG(DEBUG) << kInternalLogLineSeparator;
return is_matched;
}
bool CampaignsMatcher::MatchDemoModeTier(
const DemoModeTargeting& targeting) const {
const auto is_cloud_gaming = targeting.TargetCloudGamingDevice();
if (is_cloud_gaming.has_value()) {
if (is_cloud_gaming != client_->IsCloudGamingDevice()) {
return false;
}
}
const auto is_feature_aware_device = targeting.TargetFeatureAwareDevice();
if (is_feature_aware_device.has_value()) {
if (is_feature_aware_device != client_->IsFeatureAwareDevice()) {
return false;
}
}
return true;
}
bool CampaignsMatcher::MatchRetailers(
const base::Value::List* retailers) const {
if (!retailers) {
return true;
}
base::Value::List canonicalized_retailers;
for (auto& retailer : *retailers) {
if (retailer.is_string()) {
canonicalized_retailers.Append(
ash::demo_mode::CanonicalizeDimension(retailer.GetString()));
}
}
return MatchPref(&canonicalized_retailers, ash::prefs::kDemoModeRetailerId,
local_state_);
}
bool CampaignsMatcher::MatchDemoModeAppVersion(
const DemoModeTargeting& targeting) const {
const auto max_version = targeting.GetAppMaxVersion();
const auto min_version = targeting.GetAppMinVersion();
if (!max_version && !min_version) {
return true;
}
return MatchVersion(client_->GetDemoModeAppVersion(),
targeting.GetAppMinVersion(),
targeting.GetAppMaxVersion());
}
bool CampaignsMatcher::MaybeMatchDemoModeTargeting(
const DemoModeTargeting& targeting) const {
if (!targeting.IsValid()) {
// Campaigns matched if there is no demo mode targeting.
return true;
}
if (!client_->IsDeviceInDemoMode()) {
// Return early if it is not in demo mode while the campaign is targeting
// demo mode.
CAMPAIGNS_LOG(DEBUG) << "Not in Demo Mode.";
return false;
}
if (!MatchDemoModeAppVersion(targeting)) {
CAMPAIGNS_LOG(DEBUG) << "Demo Mode app version is NOT matched.";
return false;
}
if (!MatchDemoModeTier(targeting)) {
CAMPAIGNS_LOG(DEBUG) << "Demo Mode tier is NOT matched.";
return false;
}
if (!MatchRetailers(targeting.GetRetailers())) {
CAMPAIGNS_LOG(DEBUG) << "Demo Mode retailers are NOT matched.";
return false;
}
if (!MatchPref(targeting.GetStoreIds(), ash::prefs::kDemoModeStoreId,
local_state_)) {
CAMPAIGNS_LOG(DEBUG) << "Demo Mode store IDs are NOT matched.";
return false;
}
if (!MatchPref(targeting.GetCountries(), ash::prefs::kDemoModeCountry,
local_state_)) {
CAMPAIGNS_LOG(DEBUG) << "Demo Mode store countries are NOT matched.";
return false;
}
return true;
}
bool CampaignsMatcher::MatchMilestone(const DeviceTargeting& targeting) const {
const auto milestone = GetMilestone();
auto min_milestone = targeting.GetMinMilestone();
if (min_milestone && milestone < min_milestone) {
return false;
}
auto max_milestone = targeting.GetMaxMilestone();
if (max_milestone && milestone > max_milestone) {
return false;
}
return true;
}
bool CampaignsMatcher::MatchMilestoneVersion(
const DeviceTargeting& targeting) const {
return MatchVersion(GetVersion(), targeting.GetMinVersion(),
targeting.GetMaxVersion());
}
bool CampaignsMatcher::MatchDeviceTargeting(
const DeviceTargeting& targeting) const {
if (!targeting.IsValid()) {
// Campaigns matched if there is no device targeting.
return true;
}
const auto boards = targeting.GetBoards();
if (!MatchBoard(boards.get())) {
return false;
}
auto target_feature_aware_device = targeting.GetFeatureAwareDevice();
if (target_feature_aware_device &&
target_feature_aware_device.value() !=
ash::features::IsFeatureManagementGrowthFrameworkEnabled()) {
return false;
}
const auto* targeting_locales = targeting.GetLocales();
if (targeting_locales &&
!Contains(*targeting_locales, client_->GetApplicationLocale())) {
return false;
}
const auto* user_locales = targeting.GetUserLocales();
if (user_locales && !Contains(*user_locales, client_->GetUserLocale())) {
return false;
}
const auto registered_time_targeting = targeting.GetRegisteredTime();
if (!MatchRegisteredTime(registered_time_targeting)) {
return false;
}
const auto device_age_in_hours = targeting.GetDeviceAge();
if (!MatchDeviceAge(device_age_in_hours)) {
return false;
}
const auto* included_countries = targeting.GetIncludedCountries();
if (included_countries &&
!Contains(*included_countries, client_->GetCountryCode())) {
return false;
}
const auto* excluded_countries = targeting.GetExcludedCountries();
if (excluded_countries &&
Contains(*excluded_countries, client_->GetCountryCode())) {
return false;
}
return MatchChannel(targeting.GetChannels().get()) &&
MatchMilestone(targeting) && MatchMilestoneVersion(targeting);
}
bool CampaignsMatcher::MatchRegisteredTime(
const std::unique_ptr<TimeWindowTargeting>& registered_time_targeting)
const {
if (!registered_time_targeting) {
// Match campaign if there is no registered date targeting.
return true;
}
// TODO: b/333458177 - The `oobe_complete_time_` is not available when testing
// in x11 emulator. Add support make it testable in x11 emulator.
return MatchTimeWindow(*registered_time_targeting, oobe_compelete_time_);
}
bool CampaignsMatcher::MatchBoard(
const StringListTargeting* boards_targeting) const {
if (!boards_targeting) {
// Match campaign if there is no boards targeting.
return true;
}
std::string board;
if (board_for_testing_.has_value()) {
board = board_for_testing_.value();
} else {
// Refer to comment describing base::SysInfo::GetLsbReleaseBoard for why
// splitting the Lsb Release Board string is needed.
std::vector<std::string> board_info =
base::SplitString(base::SysInfo::GetLsbReleaseBoard(), "-",
base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (board_info.empty()) {
// If no board info is available, return false.
RecordCampaignsManagerError(CampaignsManagerError::kNoBoardInfo);
CAMPAIGNS_LOG(ERROR) << "Board info is not available.";
return false;
}
board = board_info[0];
}
return MatchStringList(*boards_targeting, board, kBoards);
}
bool CampaignsMatcher::MatchChannel(
const StringListTargeting* channels_targeting) const {
if (!channels_targeting) {
// Match campaign if there is no channel targeting.
return true;
}
auto channel = version_info::GetChannelString(ash::GetChannel());
return MatchStringList(*channels_targeting, std::string(channel), kChannels);
}
bool CampaignsMatcher::MatchDeviceAge(
const std::unique_ptr<NumberRangeTargeting>& device_age_in_hours) const {
if (!device_age_in_hours) {
// Match campaign if there is no device age targeting.
return true;
}
// TODO: b/333458177 - The `oobe_complete_time_` is not available when testing
// in x11 emulator. Add support make it testable in x11 emulator.
auto start_time = base::Time::Min();
const auto device_age_start = device_age_in_hours->GetStart();
if (device_age_start) {
start_time = oobe_compelete_time_ + base::Hours(device_age_start.value());
}
auto end_time = base::Time::Max();
const auto device_age_end = device_age_in_hours->GetEnd();
if (device_age_end) {
end_time = oobe_compelete_time_ + base::Hours(device_age_end.value());
}
return MatchTimeWindow(start_time, end_time,
/*target=*/base::Time::Now());
}
bool CampaignsMatcher::MatchTriggerTargeting(
const std::vector<std::unique_ptr<TriggerTargeting>>& trigger_targetings)
const {
if (trigger_targetings.empty()) {
// Campaigns matched if `trigger_targetings` is empty.
return true;
}
for (const auto& trigger : trigger_targetings) {
auto trigger_type = trigger->GetTriggerType();
if (!trigger_type) {
// Ignore if trigger type is missing from the targeting.
// TODO: b/341374525 - Record the error when the trigger type is missing.
continue;
}
// TODO: b/330931877 - Add bounds check for casting to enum from value in
// campaign.
if (trigger_.type != static_cast<TriggerType>(trigger_type.value())) {
continue;
}
// Only `kEvent` trigger needs to check event name, so other trigger type
// is matched at this point.
if (trigger_.type != TriggerType::kEvent) {
return true;
}
const base::Value::List* trigger_events = trigger->GetTriggerEvents();
if (!trigger_events) {
// If the trigger type is `kEvent`, but the `trigger_events` is not valid,
// does not match.
// TODO: b/341164013 - Add new specific error type for this case.
RecordCampaignsManagerError(CampaignsManagerError::kInvalidTrigger);
CAMPAIGNS_LOG(ERROR)
<< "Invalid trigger events, requires a list of strings.";
continue;
}
if (HasOverlapEntries(*trigger_events, trigger_.events)) {
return true;
}
}
CAMPAIGNS_LOG(DEBUG) << "TriggerTargeting is NOT matched.";
return false;
}
bool CampaignsMatcher::MatchOpenedApp(
const std::vector<std::unique_ptr<AppTargeting>>& apps_opened_targeting)
const {
if (apps_opened_targeting.empty()) {
// Campaigns matched if apps opened targeting is empty.
return true;
}
for (const auto& app : apps_opened_targeting) {
auto* app_id = app->GetAppId();
if (!app_id) {
// Ignore if app id is missing from the targeting.
continue;
}
if (*app_id == opened_app_id_) {
return true;
}
}
CAMPAIGNS_LOG(DEBUG) << "OpenedApp is NOT matched.";
return false;
}
bool CampaignsMatcher::ReachCap(base::cstring_view campaign_type,
int id,
base::cstring_view event_type,
std::optional<int> cap) const {
if (!cap) {
// There is no cap, return false.
return false;
}
std::map<std::string, std::string> conditions_params =
CreateBasicConditionParams();
// Event can be put in any key starting with `event_`.
// Please see `components/feature_engagement/README.md#featureconfig`.
conditions_params[kEventKey] =
CreateConditionParamForCap(campaign_type, id, event_type, cap.value());
const bool reach_cap = !client_->WouldTriggerHelpUI(conditions_params);
if (reach_cap) {
CAMPAIGNS_LOG(DEBUG) << "Events are NOT matched. Campaign: " << id
<< " reached cap for " << campaign_type << " "
<< event_type;
}
return reach_cap;
}
bool CampaignsMatcher::MatchActiveUrlRegexes(
const std::vector<std::string>& active_url_regrexes) const {
if (active_url_regrexes.empty()) {
// Campaigns matched if active URL targeting is empty.
return true;
}
if (active_url_.is_empty()) {
// Campaigns matched if no active URL is set. Active URL is used for
// targeting web app and PWA. When active URL is empty, it is likely not
// triggered by opening web app or PWA. In this case, defer to other
// targeting to match campaign.
// An example is G1 nudge is triggered by a group of app opened (PWA, Web
// App and ARC app), the active URL targeting is used for PWA and Web App
// while doesn't apply for ARC app.
return true;
}
for (const auto& url_regrex : active_url_regrexes) {
if (RE2::FullMatch(active_url_.spec(), url_regrex)) {
return true;
}
}
CAMPAIGNS_LOG(DEBUG) << "ActiveUrlRegexes is NOT matched.";
return false;
}
bool CampaignsMatcher::MatchHotseatAppIcon(
std::unique_ptr<AppTargeting> app) const {
if (!app) {
return true;
}
auto* app_id = app->GetAppId();
if (!app_id) {
// Ignore if app id is missing from the targeting.
return true;
}
const bool is_matched = client_->IsAppIconOnShelf(*app_id);
if (!is_matched) {
CAMPAIGNS_LOG(DEBUG) << "Hotseat app icon targeting is NOT matched.";
}
return is_matched;
}
bool CampaignsMatcher::MatchEvents(std::unique_ptr<EventsTargeting> config,
int campaign_id,
std::optional<int> group_id) const {
if (!config) {
// Campaign is matched if there is no events targeting.
return true;
}
// Check group impression cap and dismissal cap.
if (group_id && (ReachCap("Group", group_id.value(), "Impression",
config->GetGroupImpressionCap()) ||
ReachCap("Group", group_id.value(), "Dismissed",
config->GetGroupDismissalCap()))) {
// Reached group impression cap or dismissal cap.
CAMPAIGNS_LOG(DEBUG)
<< "Events are NOT matched. Reached group impression/dismissal caps.";
return false;
}
// Check campaign impression cap and dismissal cap.
if (ReachCap("Campaign", campaign_id, "Impression",
config->GetImpressionCap()) ||
ReachCap("Campaign", campaign_id, "Dismissed",
config->GetDismissalCap())) {
CAMPAIGNS_LOG(DEBUG) << "Events are NOT matched. Reached campaign "
"impression/dismissal caps.";
return false;
}
std::map<std::string, std::string> conditions_params =
CreateBasicConditionParams();
// Here is to handle custom events targeting conditions.
// The outer loop is AND logic and the inner loop is OR logic.
const base::Value::List* conditions = config->GetEventsConditions();
if (!conditions) {
// Campaign is matched if there is no custom events targeting conditions.
return true;
}
for (const auto& condition : *conditions) {
if (!condition.is_list()) {
RecordCampaignsManagerError(
CampaignsManagerError::kInvalidEventTargetingCondition);
CAMPAIGNS_LOG(ERROR)
<< "Events are NOT matched. Invalid events targeting conditions.";
return false;
}
bool any_event_matched = false;
for (const auto& param : condition.GetList()) {
if (!param.is_string()) {
RecordCampaignsManagerError(
CampaignsManagerError::kInvalidEventTargetingConditionParam);
CAMPAIGNS_LOG(ERROR)
<< "Events are NOT matched. Invalid events targeting condition.";
return false;
}
std::string param_str = param.GetString();
conditions_params[kEventKey] = param_str;
if (client_->WouldTriggerHelpUI(conditions_params)) {
any_event_matched = true;
// Can break the loop if any condition is met.
break;
}
}
if (!any_event_matched) {
// Can return if no condition is met.
CAMPAIGNS_LOG(DEBUG)
<< "Events are NOT matched. Not meet custom events conditions.";
return false;
}
}
return true;
}
// Returns true if the users' minor mode status (e.g. under age of 18 or not)
// matches the `minor_user_targeting` capaiblity. The minor mode status is read
// from account capabilities. We assume user is in minor mode if capability
// value is unknown.
bool CampaignsMatcher::MatchMinorUser(
std::optional<bool> minor_user_targeting) const {
if (!minor_user_targeting) {
// Campaign matched if it does no include minor targeting.
return true;
}
signin::Tribool capability;
if (manta_capability_for_testing_) {
capability = manta_capability_for_testing_.value();
} else {
auto* identity_manager = client_->GetIdentityManager();
if (!identity_manager) {
// Identity manager is not available (e.g:guest mode). In that case,
// a campaign with minor user targeting shouldn't be triggered.
CAMPAIGNS_LOG(ERROR) << "IdentityManager is null.";
return false;
}
GaiaId gaia_id = user_manager::UserManager::Get()
->GetActiveUser()
->GetAccountId()
.GetGaiaId();
const AccountInfo account_info =
identity_manager->FindExtendedAccountInfoByGaiaId(gaia_id);
// TODO: b/333896450 - find a better signal for minor mode.
capability = account_info.capabilities.can_use_manta_service();
}
if (capability == signin::Tribool::kUnknown) {
// Records metrics when minor user state is unknown. This could be caused
// by the delay of getting minor users state. We would like to log metric
// to understand the impact while matching on the conservative side by
// considering unknown as minor users.
RecordCampaignsManagerError(CampaignsManagerError::kUnknownMinorUserState);
return false;
}
const bool isMinor = capability == signin::Tribool::kFalse;
const bool is_matched = isMinor == minor_user_targeting.value();
if (!is_matched) {
CAMPAIGNS_LOG(DEBUG) << "Please check MinorUser targeting.";
}
return is_matched;
}
bool CampaignsMatcher::MatchOwner(std::optional<bool> is_owner) const {
if (!is_owner) {
// Campaigns matched if there is no owner targeting.
return true;
}
const bool is_matched = is_owner.value() == is_user_owner_;
if (!is_matched) {
CAMPAIGNS_LOG(DEBUG) << "Owner targeting is NOT matched.";
}
return is_matched;
}
bool CampaignsMatcher::MatchSessionTargeting(
const SessionTargeting& targeting) const {
if (!targeting.IsValid()) {
// Campaigns matched if there is no session targeting.
return true;
}
bool is_matched = false;
is_matched = MatchExperimentTags(targeting.GetExperimentTags(),
targeting.GetFeature());
if (!is_matched) {
return false;
}
is_matched = MatchMinorUser(targeting.GetMinorUser());
if (!is_matched) {
return false;
}
is_matched = MatchOwner(targeting.GetIsOwner());
if (!is_matched) {
return false;
}
return true;
}
bool CampaignsMatcher::MatchRuntimeTargeting(
const RuntimeTargeting& targeting,
int campaign_id,
std::optional<int> group_id) const {
if (!targeting.IsValid()) {
// Campaigns matched if there is no runtime targeting.
return true;
}
bool is_matched = false;
is_matched = MatchSchedulings(targeting.GetSchedulings());
if (!is_matched) {
return false;
}
is_matched = MatchHotseatAppIcon(targeting.GetHotseatAppIcon());
if (!is_matched) {
return false;
}
is_matched = MatchOpenedApp(targeting.GetAppsOpened());
if (!is_matched) {
return false;
}
is_matched = MatchActiveUrlRegexes(targeting.GetActiveUrlRegexes());
if (!is_matched) {
return false;
}
is_matched =
MatchEvents(targeting.GetEventsTargeting(), campaign_id, group_id);
if (!is_matched) {
return false;
}
is_matched = MatchUserPrefs(prefs_, targeting.GetUserPrefTargetings());
if (!is_matched) {
return false;
}
return true;
}
bool CampaignsMatcher::Matched(const Targeting* targeting,
int campaign_id,
std::optional<int> group_id,
bool is_prematch) const {
if (!targeting) {
// Targeting is invalid. Skip the current campaign.
CAMPAIGNS_LOG(ERROR) << "Invalid targeting.";
RecordCampaignsManagerError(CampaignsManagerError::kInvalidTargeting);
return false;
}
if (is_prematch) {
// TOOD(369188855): Re-enable demo mode prematch.
return MatchDeviceTargeting(DeviceTargeting(targeting));
}
bool is_matched = MaybeMatchDemoModeTargeting(DemoModeTargeting(targeting));
if (!is_matched) {
return false;
}
// Skip other matchings if the trigger type doesn't match, which contributes
// to the majority of the mismatch as we added event based triggering.
RuntimeTargeting runtime_targeting = RuntimeTargeting(targeting);
if (runtime_targeting.IsValid()) {
is_matched = MatchTriggerTargeting(runtime_targeting.GetTriggers());
if (!is_matched) {
return false;
}
}
is_matched = MatchSessionTargeting(SessionTargeting(targeting));
if (!is_matched) {
CAMPAIGNS_LOG(DEBUG) << "Campaign: " << campaign_id
<< " Session targeting is NOT matched.";
return false;
}
is_matched =
MatchRuntimeTargeting(RuntimeTargeting(targeting), campaign_id, group_id);
if (!is_matched) {
CAMPAIGNS_LOG(DEBUG) << "Campaign: " << campaign_id
<< " Runtime targeting is NOT matched.";
return false;
}
return true;
}
bool CampaignsMatcher::Matched(const Targetings* targetings,
int campaign_id,
std::optional<int> group_id,
bool is_prematch) const {
if (!targetings || targetings->empty()) {
return true;
}
for (const auto& targeting : *targetings) {
if (Matched(targeting.GetIfDict(), campaign_id, group_id, is_prematch)) {
return true;
}
}
return false;
}
} // namespace growth
|