1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/engagement/site_engagement_service.h"
10 #include "base/command_line.h"
11 #include "base/time/clock.h"
12 #include "chrome/browser/engagement/site_engagement_helper.h"
13 #include "chrome/browser/engagement/site_engagement_service_factory.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/common/chrome_switches.h"
18 const double SiteEngagementScore::kMaxPoints
= 100;
19 const double SiteEngagementScore::kMaxPointsPerDay
= 5;
20 const double SiteEngagementScore::kNavigationPoints
= 1;
21 const int SiteEngagementScore::kDecayPeriodInDays
= 7;
22 const double SiteEngagementScore::kDecayPoints
= 5;
24 SiteEngagementScore::SiteEngagementScore() : SiteEngagementScore(nullptr) {
27 SiteEngagementScore::SiteEngagementScore(base::Clock
* clock
)
28 : clock_(clock
), raw_score_(0), added_today_(0), last_engagement_() {
31 SiteEngagementScore::~SiteEngagementScore() {
34 double SiteEngagementScore::Score() const {
35 return DecayedScore();
38 void SiteEngagementScore::AddPoints(double points
) {
39 // As the score is about to be updated, commit any decay that has happened
40 // since the last update.
41 raw_score_
= DecayedScore();
43 base::Time now
= Now();
44 if (!last_engagement_
.is_null() &&
45 now
.LocalMidnight() != last_engagement_
.LocalMidnight()) {
50 std::min(kMaxPoints
- raw_score_
, kMaxPointsPerDay
- added_today_
);
51 to_add
= std::min(to_add
, points
);
53 added_today_
+= to_add
;
56 last_engagement_
= now
;
59 double SiteEngagementScore::DecayedScore() const {
60 // Note that users can change their clock, so from this system's perspective
61 // time can go backwards. If that does happen and the system detects that the
62 // current day is earlier than the last engagement, no decay (or growth) is
64 int days_since_engagement
= (Now() - last_engagement_
).InDays();
65 if (days_since_engagement
< 0)
68 int periods
= days_since_engagement
/ kDecayPeriodInDays
;
69 double decayed_score
= raw_score_
- periods
* kDecayPoints
;
70 return std::max(0.0, decayed_score
);
73 base::Time
SiteEngagementScore::Now() const {
77 return base::Time::Now();
81 SiteEngagementService
* SiteEngagementService::Get(Profile
* profile
) {
82 return SiteEngagementServiceFactory::GetForProfile(profile
);
86 bool SiteEngagementService::IsEnabled() {
87 return base::CommandLine::ForCurrentProcess()->HasSwitch(
88 switches::kEnableSiteEngagementService
);
91 SiteEngagementService::SiteEngagementService(Profile
* profile
)
95 SiteEngagementService::~SiteEngagementService() {
98 void SiteEngagementService::HandleNavigation(const GURL
& url
) {
99 GURL origin
= url
.GetOrigin();
100 scores_
[origin
].AddPoints(SiteEngagementScore::kNavigationPoints
);
103 int SiteEngagementService::GetScore(const GURL
& url
) {
104 return scores_
[url
.GetOrigin()].Score();