summaryrefslogtreecommitdiff
path: root/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc
blob: 9770ca51ec0e4ff6abff5ac4828ebd30b8686338 (plain)
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
// Copyright 2017 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 "components/ntp_snippets/breaking_news/subscription_manager_impl.h"

#include "base/bind.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/stringprintf.h"
#include "components/ntp_snippets/breaking_news/breaking_news_metrics.h"
#include "components/ntp_snippets/breaking_news/subscription_json_request.h"
#include "components/ntp_snippets/features.h"
#include "components/ntp_snippets/ntp_snippets_constants.h"
#include "components/ntp_snippets/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/variations/service/variations_service.h"
#include "net/base/url_util.h"
#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"

namespace ntp_snippets {

using internal::SubscriptionJsonRequest;

namespace {

const char kApiKeyParamName[] = "key";
const char kAuthorizationRequestHeaderFormat[] = "Bearer %s";

}  // namespace

SubscriptionManagerImpl::SubscriptionManagerImpl(
    scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
    PrefService* pref_service,
    variations::VariationsService* variations_service,
    identity::IdentityManager* identity_manager,
    const std::string& locale,
    const std::string& api_key,
    const GURL& subscribe_url,
    const GURL& unsubscribe_url)
    : url_request_context_getter_(std::move(url_request_context_getter)),
      pref_service_(pref_service),
      variations_service_(variations_service),
      identity_manager_(identity_manager),
      locale_(locale),
      api_key_(api_key),
      subscribe_url_(subscribe_url),
      unsubscribe_url_(unsubscribe_url) {
  identity_manager_->AddObserver(this);
}

SubscriptionManagerImpl::~SubscriptionManagerImpl() {
  identity_manager_->RemoveObserver(this);
}

void SubscriptionManagerImpl::Subscribe(const std::string& subscription_token) {
  // If there is a request in flight, cancel it.
  if (request_) {
    request_ = nullptr;
  }
  if (identity_manager_->HasPrimaryAccount()) {
    StartAccessTokenRequest(subscription_token);
  } else {
    SubscribeInternal(subscription_token, /*access_token=*/std::string());
  }
}

void SubscriptionManagerImpl::SubscribeInternal(
    const std::string& subscription_token,
    const std::string& access_token) {
  SubscriptionJsonRequest::Builder builder;
  builder.SetToken(subscription_token)
      .SetUrlRequestContextGetter(url_request_context_getter_);

  if (!access_token.empty()) {
    builder.SetUrl(subscribe_url_);
    builder.SetAuthenticationHeader(base::StringPrintf(
        kAuthorizationRequestHeaderFormat, access_token.c_str()));
  } else {
    // When not providing OAuth token, we need to pass the Google API key.
    builder.SetUrl(
        net::AppendQueryParameter(subscribe_url_, kApiKeyParamName, api_key_));
  }

  builder.SetLocale(locale_);
  builder.SetCountryCode(variations_service_
                             ? variations_service_->GetStoredPermanentCountry()
                             : "");

  request_ = builder.Build();
  request_->Start(base::BindOnce(&SubscriptionManagerImpl::DidSubscribe,
                                 base::Unretained(this), subscription_token,
                                 /*is_authenticated=*/!access_token.empty()));
}

void SubscriptionManagerImpl::StartAccessTokenRequest(
    const std::string& subscription_token) {
  // If there is already an ongoing token request, destroy it.
  if (access_token_fetcher_) {
    access_token_fetcher_ = nullptr;
  }

  OAuth2TokenService::ScopeSet scopes = {kContentSuggestionsApiScope};
  access_token_fetcher_ =
      identity_manager_->CreateAccessTokenFetcherForPrimaryAccount(
          "ntp_snippets", scopes,
          base::BindOnce(&SubscriptionManagerImpl::AccessTokenFetchFinished,
                         base::Unretained(this), subscription_token),
          identity::PrimaryAccountAccessTokenFetcher::Mode::
              kWaitUntilAvailable);
}

void SubscriptionManagerImpl::AccessTokenFetchFinished(
    const std::string& subscription_token,
    const GoogleServiceAuthError& error,
    const std::string& access_token) {
  // Delete the fetcher only after we leave this method (which is called from
  // the fetcher itself).
  std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher>
      access_token_fetcher_deleter(std::move(access_token_fetcher_));

  if (error.state() != GoogleServiceAuthError::NONE) {
    // In case of error, we will retry on next Chrome restart.
    return;
  }
  DCHECK(!access_token.empty());
  SubscribeInternal(subscription_token, access_token);
}

void SubscriptionManagerImpl::DidSubscribe(
    const std::string& subscription_token,
    bool is_authenticated,
    const Status& status) {
  metrics::OnSubscriptionRequestCompleted(status);

  // Delete the request only after we leave this method (which is called from
  // the request itself).
  std::unique_ptr<internal::SubscriptionJsonRequest> request_deleter(
      std::move(request_));

  switch (status.code) {
    case StatusCode::SUCCESS:
      // In case of successful subscription, store the same data used for
      // subscription in order to be able to resubscribe in case of data
      // change.
      // TODO(mamir): Store region and language.
      pref_service_->SetString(prefs::kBreakingNewsSubscriptionDataToken,
                               subscription_token);
      pref_service_->SetBoolean(
          prefs::kBreakingNewsSubscriptionDataIsAuthenticated,
          is_authenticated);
      break;
    default:
      // TODO(mamir): Handle failure.
      break;
  }
}

void SubscriptionManagerImpl::Unsubscribe() {
  std::string token =
      pref_service_->GetString(prefs::kBreakingNewsSubscriptionDataToken);
  ResubscribeInternal(/*old_token=*/token, /*new_token=*/std::string());
}

void SubscriptionManagerImpl::ResubscribeInternal(
    const std::string& old_token,
    const std::string& new_token) {
  // If there is an request in flight, cancel it.
  if (request_) {
    request_ = nullptr;
  }

  SubscriptionJsonRequest::Builder builder;
  builder.SetToken(old_token).SetUrlRequestContextGetter(
      url_request_context_getter_);
  builder.SetUrl(
      net::AppendQueryParameter(unsubscribe_url_, kApiKeyParamName, api_key_));

  request_ = builder.Build();
  request_->Start(base::BindOnce(&SubscriptionManagerImpl::DidUnsubscribe,
                                 base::Unretained(this), new_token));
}

bool SubscriptionManagerImpl::IsSubscribed() {
  std::string subscription_token =
      pref_service_->GetString(prefs::kBreakingNewsSubscriptionDataToken);
  return !subscription_token.empty();
}

bool SubscriptionManagerImpl::NeedsToResubscribe() {
  // Check if authentication state changed after subscription.
  bool is_auth_subscribe = pref_service_->GetBoolean(
      prefs::kBreakingNewsSubscriptionDataIsAuthenticated);
  bool is_authenticated = identity_manager_->HasPrimaryAccount();
  return is_auth_subscribe != is_authenticated;
}

void SubscriptionManagerImpl::Resubscribe(const std::string& new_token) {
  std::string old_token =
      pref_service_->GetString(prefs::kBreakingNewsSubscriptionDataToken);
  if (old_token == new_token) {
    // If the token didn't change, subscribe directly. The server handles the
    // unsubscription if previous subscriptions exists.
    Subscribe(old_token);
  } else {
    ResubscribeInternal(old_token, new_token);
  }
}

void SubscriptionManagerImpl::DidUnsubscribe(const std::string& new_token,
                                             const Status& status) {
  metrics::OnUnsubscriptionRequestCompleted(status);

  // Delete the request only after we leave this method (which is called from
  // the request itself).
  std::unique_ptr<internal::SubscriptionJsonRequest> request_deleter(
      std::move(request_));

  switch (status.code) {
    case StatusCode::SUCCESS:
      // In case of successful unsubscription, clear the previously stored data.
      // TODO(mamir): Clear stored region and language.
      pref_service_->ClearPref(prefs::kBreakingNewsSubscriptionDataToken);
      pref_service_->ClearPref(
          prefs::kBreakingNewsSubscriptionDataIsAuthenticated);
      if (!new_token.empty()) {
        Subscribe(new_token);
      }
      break;
    default:
      // TODO(mamir): Handle failure.
      break;
  }
}

void SubscriptionManagerImpl::OnPrimaryAccountSet(
    const AccountInfo& account_info) {
  SigninStatusChanged();
}

void SubscriptionManagerImpl::OnPrimaryAccountCleared(
    const AccountInfo& account_info) {
  SigninStatusChanged();
}

void SubscriptionManagerImpl::SigninStatusChanged() {
  // If subscribed already, resubscribe.
  if (IsSubscribed()) {
    if (request_) {
      request_ = nullptr;
    }
    std::string token =
        pref_service_->GetString(prefs::kBreakingNewsSubscriptionDataToken);
    Subscribe(token);
  }
}

// static
void SubscriptionManagerImpl::RegisterProfilePrefs(
    PrefRegistrySimple* registry) {
  registry->RegisterStringPref(prefs::kBreakingNewsSubscriptionDataToken,
                               std::string());
  registry->RegisterBooleanPref(
      prefs::kBreakingNewsSubscriptionDataIsAuthenticated, false);
}

// TODO(vitaliii): Add a test to ensure that this clears everything.
// static
void SubscriptionManagerImpl::ClearProfilePrefs(PrefService* pref_service) {
  pref_service->ClearPref(prefs::kBreakingNewsSubscriptionDataToken);
  pref_service->ClearPref(prefs::kBreakingNewsSubscriptionDataIsAuthenticated);
}

}  // namespace ntp_snippets