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
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/web_resource/notification_promo.h"
#include <cmath>
#include <vector>
#include "base/bind.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/web_resource/promo_resource_service.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "content/public/browser/user_metrics.h"
#include "net/base/url_util.h"
#include "ui/base/device_form_factor.h"
#include "url/gurl.h"
using base::UserMetricsAction;
namespace {
const int kDefaultGroupSize = 100;
const char promo_server_url[] = "https://clients3.google.com/crsignal/client";
// The name of the preference that stores the promotion object.
const char kPrefPromoObject[] = "promo";
// Keys in the kPrefPromoObject dictionary; used only here.
const char kPrefPromoText[] = "text";
const char kPrefPromoPayload[] = "payload";
const char kPrefPromoStart[] = "start";
const char kPrefPromoEnd[] = "end";
const char kPrefPromoNumGroups[] = "num_groups";
const char kPrefPromoSegment[] = "segment";
const char kPrefPromoIncrement[] = "increment";
const char kPrefPromoIncrementFrequency[] = "increment_frequency";
const char kPrefPromoIncrementMax[] = "increment_max";
const char kPrefPromoMaxViews[] = "max_views";
const char kPrefPromoMaxSeconds[] = "max_seconds";
const char kPrefPromoFirstViewTime[] = "first_view_time";
const char kPrefPromoGroup[] = "group";
const char kPrefPromoViews[] = "views";
const char kPrefPromoClosed[] = "closed";
// Returns a string suitable for the Promo Server URL 'osname' value.
std::string PlatformString() {
#if defined(OS_WIN)
return "win";
#elif defined(OS_ANDROID)
ui::DeviceFormFactor form_factor = ui::GetDeviceFormFactor();
return std::string("android-") +
(form_factor == ui::DEVICE_FORM_FACTOR_TABLET ? "tablet" : "phone");
#elif defined(OS_IOS)
ui::DeviceFormFactor form_factor = ui::GetDeviceFormFactor();
return std::string("ios-") +
(form_factor == ui::DEVICE_FORM_FACTOR_TABLET ? "tablet" : "phone");
#elif defined(OS_MACOSX)
return "mac";
#elif defined(OS_CHROMEOS)
return "chromeos";
#elif defined(OS_LINUX)
return "linux";
#else
return "none";
#endif
}
// Returns a string suitable for the Promo Server URL 'dist' value.
const char* ChannelString() {
#if defined (OS_WIN)
// GetChannel hits the registry on Windows. See http://crbug.com/70898.
// TODO(achuith): Move NotificationPromo::PromoServerURL to the blocking pool.
base::ThreadRestrictions::ScopedAllowIO allow_io;
#endif
const chrome::VersionInfo::Channel channel =
chrome::VersionInfo::GetChannel();
switch (channel) {
case chrome::VersionInfo::CHANNEL_CANARY:
return "canary";
case chrome::VersionInfo::CHANNEL_DEV:
return "dev";
case chrome::VersionInfo::CHANNEL_BETA:
return "beta";
case chrome::VersionInfo::CHANNEL_STABLE:
return "stable";
default:
return "none";
}
}
struct PromoMapEntry {
NotificationPromo::PromoType promo_type;
const char* promo_type_str;
};
const PromoMapEntry kPromoMap[] = {
{ NotificationPromo::NO_PROMO, "" },
{ NotificationPromo::NTP_NOTIFICATION_PROMO, "ntp_notification_promo" },
{ NotificationPromo::NTP_BUBBLE_PROMO, "ntp_bubble_promo" },
{ NotificationPromo::MOBILE_NTP_SYNC_PROMO, "mobile_ntp_sync_promo" },
{ NotificationPromo::MOBILE_NTP_WHATS_NEW_PROMO,
"mobile_ntp_whats_new_promo" },
};
// Convert PromoType to appropriate string.
const char* PromoTypeToString(NotificationPromo::PromoType promo_type) {
for (size_t i = 0; i < arraysize(kPromoMap); ++i) {
if (kPromoMap[i].promo_type == promo_type)
return kPromoMap[i].promo_type_str;
}
NOTREACHED();
return "";
}
// Deep-copies a node, replacing any "value" that is a key
// into "strings" dictionary with its value from "strings".
// E.g. for
// {promo_action_args:['MSG_SHORT']} + strings:{MSG_SHORT:'yes'}
// it will return
// {promo_action_args:['yes']}
// |node| - a value to be deep copied and resolved.
// |strings| - a dictionary of strings to be used for resolution.
// Returns a _new_ object that is a deep copy with replacements.
// TODO(aruslan): http://crbug.com/144320 Consider moving it to values.cc/h.
base::Value* DeepCopyAndResolveStrings(
const base::Value* node,
const base::DictionaryValue* strings) {
switch (node->GetType()) {
case base::Value::TYPE_LIST: {
const base::ListValue* list = static_cast<const base::ListValue*>(node);
base::ListValue* copy = new base::ListValue;
for (base::ListValue::const_iterator it = list->begin();
it != list->end();
++it) {
base::Value* child_copy = DeepCopyAndResolveStrings(*it, strings);
copy->Append(child_copy);
}
return copy;
}
case base::Value::TYPE_DICTIONARY: {
const base::DictionaryValue* dict =
static_cast<const base::DictionaryValue*>(node);
base::DictionaryValue* copy = new base::DictionaryValue;
for (base::DictionaryValue::Iterator it(*dict);
!it.IsAtEnd();
it.Advance()) {
base::Value* child_copy = DeepCopyAndResolveStrings(&it.value(),
strings);
copy->SetWithoutPathExpansion(it.key(), child_copy);
}
return copy;
}
case base::Value::TYPE_STRING: {
std::string value;
bool rv = node->GetAsString(&value);
DCHECK(rv);
std::string actual_value;
if (!strings || !strings->GetString(value, &actual_value))
actual_value = value;
return new base::StringValue(actual_value);
}
default:
// For everything else, just make a copy.
return node->DeepCopy();
}
}
void AppendQueryParameter(GURL* url,
const std::string& param,
const std::string& value) {
*url = net::AppendQueryParameter(*url, param, value);
}
} // namespace
NotificationPromo::NotificationPromo()
: prefs_(g_browser_process->local_state()),
promo_type_(NO_PROMO),
promo_payload_(new base::DictionaryValue()),
start_(0.0),
end_(0.0),
num_groups_(kDefaultGroupSize),
initial_segment_(0),
increment_(1),
time_slice_(0),
max_group_(0),
max_views_(0),
max_seconds_(0),
first_view_time_(0),
group_(0),
views_(0),
closed_(false),
new_notification_(false) {
DCHECK(prefs_);
}
NotificationPromo::~NotificationPromo() {}
void NotificationPromo::InitFromJson(const base::DictionaryValue& json,
PromoType promo_type) {
promo_type_ = promo_type;
const base::ListValue* promo_list = NULL;
DVLOG(1) << "InitFromJson " << PromoTypeToString(promo_type_);
if (!json.GetList(PromoTypeToString(promo_type_), &promo_list))
return;
// No support for multiple promos yet. Only consider the first one.
const base::DictionaryValue* promo = NULL;
if (!promo_list->GetDictionary(0, &promo))
return;
// Date.
const base::ListValue* date_list = NULL;
if (promo->GetList("date", &date_list)) {
const base::DictionaryValue* date;
if (date_list->GetDictionary(0, &date)) {
std::string time_str;
base::Time time;
if (date->GetString("start", &time_str) &&
base::Time::FromString(time_str.c_str(), &time)) {
start_ = time.ToDoubleT();
DVLOG(1) << "start str=" << time_str
<< ", start_="<< base::DoubleToString(start_);
}
if (date->GetString("end", &time_str) &&
base::Time::FromString(time_str.c_str(), &time)) {
end_ = time.ToDoubleT();
DVLOG(1) << "end str =" << time_str
<< ", end_=" << base::DoubleToString(end_);
}
}
}
// Grouping.
const base::DictionaryValue* grouping = NULL;
if (promo->GetDictionary("grouping", &grouping)) {
grouping->GetInteger("buckets", &num_groups_);
grouping->GetInteger("segment", &initial_segment_);
grouping->GetInteger("increment", &increment_);
grouping->GetInteger("increment_frequency", &time_slice_);
grouping->GetInteger("increment_max", &max_group_);
DVLOG(1) << "num_groups_ = " << num_groups_
<< ", initial_segment_ = " << initial_segment_
<< ", increment_ = " << increment_
<< ", time_slice_ = " << time_slice_
<< ", max_group_ = " << max_group_;
}
// Strings.
const base::DictionaryValue* strings = NULL;
promo->GetDictionary("strings", &strings);
// Payload.
const base::DictionaryValue* payload = NULL;
if (promo->GetDictionary("payload", &payload)) {
base::Value* ppcopy = DeepCopyAndResolveStrings(payload, strings);
DCHECK(ppcopy && ppcopy->IsType(base::Value::TYPE_DICTIONARY));
promo_payload_.reset(static_cast<base::DictionaryValue*>(ppcopy));
}
if (!promo_payload_->GetString("promo_message_short", &promo_text_) &&
strings) {
// For compatibility with the legacy desktop version,
// if no |payload.promo_message_short| is specified,
// the first string in |strings| is used.
base::DictionaryValue::Iterator iter(*strings);
iter.value().GetAsString(&promo_text_);
}
DVLOG(1) << "promo_text_=" << promo_text_;
promo->GetInteger("max_views", &max_views_);
DVLOG(1) << "max_views_ " << max_views_;
promo->GetInteger("max_seconds", &max_seconds_);
DVLOG(1) << "max_seconds_ " << max_seconds_;
CheckForNewNotification();
}
void NotificationPromo::CheckForNewNotification() {
NotificationPromo old_promo;
old_promo.InitFromPrefs(promo_type_);
const double old_start = old_promo.start_;
const double old_end = old_promo.end_;
const std::string old_promo_text = old_promo.promo_text_;
new_notification_ =
old_start != start_ || old_end != end_ || old_promo_text != promo_text_;
if (new_notification_)
OnNewNotification();
}
void NotificationPromo::OnNewNotification() {
DVLOG(1) << "OnNewNotification";
// Create a new promo group.
group_ = base::RandInt(0, num_groups_ - 1);
WritePrefs();
}
// static
void NotificationPromo::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(kPrefPromoObject);
}
// static
void NotificationPromo::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
// TODO(dbeam): Registered only for migration. Remove in M28 when
// we're reasonably sure all prefs are gone.
// http://crbug.com/168887
registry->RegisterDictionaryPref(
kPrefPromoObject, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
void NotificationPromo::MigrateUserPrefs(PrefService* user_prefs) {
user_prefs->ClearPref(kPrefPromoObject);
}
void NotificationPromo::WritePrefs() {
base::DictionaryValue* ntp_promo = new base::DictionaryValue;
ntp_promo->SetString(kPrefPromoText, promo_text_);
ntp_promo->Set(kPrefPromoPayload, promo_payload_->DeepCopy());
ntp_promo->SetDouble(kPrefPromoStart, start_);
ntp_promo->SetDouble(kPrefPromoEnd, end_);
ntp_promo->SetInteger(kPrefPromoNumGroups, num_groups_);
ntp_promo->SetInteger(kPrefPromoSegment, initial_segment_);
ntp_promo->SetInteger(kPrefPromoIncrement, increment_);
ntp_promo->SetInteger(kPrefPromoIncrementFrequency, time_slice_);
ntp_promo->SetInteger(kPrefPromoIncrementMax, max_group_);
ntp_promo->SetInteger(kPrefPromoMaxViews, max_views_);
ntp_promo->SetInteger(kPrefPromoMaxSeconds, max_seconds_);
ntp_promo->SetDouble(kPrefPromoFirstViewTime, first_view_time_);
ntp_promo->SetInteger(kPrefPromoGroup, group_);
ntp_promo->SetInteger(kPrefPromoViews, views_);
ntp_promo->SetBoolean(kPrefPromoClosed, closed_);
base::ListValue* promo_list = new base::ListValue;
promo_list->Set(0, ntp_promo); // Only support 1 promo for now.
base::DictionaryValue promo_dict;
promo_dict.MergeDictionary(prefs_->GetDictionary(kPrefPromoObject));
promo_dict.Set(PromoTypeToString(promo_type_), promo_list);
prefs_->Set(kPrefPromoObject, promo_dict);
DVLOG(1) << "WritePrefs " << promo_dict;
}
void NotificationPromo::InitFromPrefs(PromoType promo_type) {
promo_type_ = promo_type;
const base::DictionaryValue* promo_dict =
prefs_->GetDictionary(kPrefPromoObject);
if (!promo_dict)
return;
const base::ListValue* promo_list = NULL;
promo_dict->GetList(PromoTypeToString(promo_type_), &promo_list);
if (!promo_list)
return;
const base::DictionaryValue* ntp_promo = NULL;
promo_list->GetDictionary(0, &ntp_promo);
if (!ntp_promo)
return;
ntp_promo->GetString(kPrefPromoText, &promo_text_);
const base::DictionaryValue* promo_payload = NULL;
if (ntp_promo->GetDictionary(kPrefPromoPayload, &promo_payload))
promo_payload_.reset(promo_payload->DeepCopy());
ntp_promo->GetDouble(kPrefPromoStart, &start_);
ntp_promo->GetDouble(kPrefPromoEnd, &end_);
ntp_promo->GetInteger(kPrefPromoNumGroups, &num_groups_);
ntp_promo->GetInteger(kPrefPromoSegment, &initial_segment_);
ntp_promo->GetInteger(kPrefPromoIncrement, &increment_);
ntp_promo->GetInteger(kPrefPromoIncrementFrequency, &time_slice_);
ntp_promo->GetInteger(kPrefPromoIncrementMax, &max_group_);
ntp_promo->GetInteger(kPrefPromoMaxViews, &max_views_);
ntp_promo->GetInteger(kPrefPromoMaxSeconds, &max_seconds_);
ntp_promo->GetDouble(kPrefPromoFirstViewTime, &first_view_time_);
ntp_promo->GetInteger(kPrefPromoGroup, &group_);
ntp_promo->GetInteger(kPrefPromoViews, &views_);
ntp_promo->GetBoolean(kPrefPromoClosed, &closed_);
}
bool NotificationPromo::CheckAppLauncher() const {
#if !defined(ENABLE_APP_LIST)
return true;
#else
bool is_app_launcher_promo = false;
if (!promo_payload_->GetBoolean("is_app_launcher_promo",
&is_app_launcher_promo))
return true;
return !is_app_launcher_promo ||
!prefs_->GetBoolean(prefs::kAppLauncherIsEnabled);
#endif // !defined(ENABLE_APP_LIST)
}
bool NotificationPromo::CanShow() const {
return !closed_ &&
!promo_text_.empty() &&
!ExceedsMaxGroup() &&
!ExceedsMaxViews() &&
!ExceedsMaxSeconds() &&
CheckAppLauncher() &&
base::Time::FromDoubleT(StartTimeForGroup()) < base::Time::Now() &&
base::Time::FromDoubleT(EndTime()) > base::Time::Now();
}
// static
void NotificationPromo::HandleClosed(PromoType promo_type) {
content::RecordAction(UserMetricsAction("NTPPromoClosed"));
NotificationPromo promo;
promo.InitFromPrefs(promo_type);
if (!promo.closed_) {
promo.closed_ = true;
promo.WritePrefs();
}
}
// static
bool NotificationPromo::HandleViewed(PromoType promo_type) {
content::RecordAction(UserMetricsAction("NTPPromoShown"));
NotificationPromo promo;
promo.InitFromPrefs(promo_type);
++promo.views_;
if (promo.first_view_time_ == 0) {
promo.first_view_time_ = base::Time::Now().ToDoubleT();
}
promo.WritePrefs();
return promo.ExceedsMaxViews() || promo.ExceedsMaxSeconds();
}
bool NotificationPromo::ExceedsMaxGroup() const {
return (max_group_ == 0) ? false : group_ >= max_group_;
}
bool NotificationPromo::ExceedsMaxViews() const {
return (max_views_ == 0) ? false : views_ >= max_views_;
}
bool NotificationPromo::ExceedsMaxSeconds() const {
if (max_seconds_ == 0 || first_view_time_ == 0)
return false;
const base::Time last_view_time = base::Time::FromDoubleT(first_view_time_) +
base::TimeDelta::FromSeconds(max_seconds_);
return last_view_time < base::Time::Now();
}
// static
GURL NotificationPromo::PromoServerURL() {
GURL url(promo_server_url);
AppendQueryParameter(&url, "dist", ChannelString());
AppendQueryParameter(&url, "osname", PlatformString());
AppendQueryParameter(&url, "branding", chrome::VersionInfo().Version());
AppendQueryParameter(&url, "osver", base::SysInfo::OperatingSystemVersion());
DVLOG(1) << "PromoServerURL=" << url.spec();
// Note that locale param is added by WebResourceService.
return url;
}
double NotificationPromo::StartTimeForGroup() const {
if (group_ < initial_segment_)
return start_;
return start_ +
std::ceil(static_cast<float>(group_ - initial_segment_ + 1) / increment_)
* time_slice_;
}
double NotificationPromo::EndTime() const {
return end_;
}
|