| OLD | NEW |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "components/ntp_snippets/remote/remote_suggestions_provider.h" | 5 #include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h" |
| 6 | 6 |
| 7 #include <algorithm> | 7 #include <algorithm> |
| 8 #include <iterator> | 8 #include <iterator> |
| 9 #include <utility> | 9 #include <utility> |
| 10 | 10 |
| 11 #include "base/command_line.h" | 11 #include "base/command_line.h" |
| 12 #include "base/feature_list.h" | 12 #include "base/feature_list.h" |
| 13 #include "base/location.h" | 13 #include "base/location.h" |
| 14 #include "base/memory/ptr_util.h" | 14 #include "base/memory/ptr_util.h" |
| 15 #include "base/metrics/histogram_macros.h" | 15 #include "base/metrics/histogram_macros.h" |
| 16 #include "base/metrics/sparse_histogram.h" | 16 #include "base/metrics/sparse_histogram.h" |
| 17 #include "base/path_service.h" | 17 #include "base/path_service.h" |
| 18 #include "base/stl_util.h" | 18 #include "base/stl_util.h" |
| 19 #include "base/strings/string_number_conversions.h" | 19 #include "base/strings/string_number_conversions.h" |
| 20 #include "base/strings/utf_string_conversions.h" | 20 #include "base/strings/utf_string_conversions.h" |
| 21 #include "base/time/default_clock.h" | 21 #include "base/time/default_clock.h" |
| 22 #include "base/time/time.h" | 22 #include "base/time/time.h" |
| 23 #include "base/values.h" | 23 #include "base/values.h" |
| 24 #include "components/data_use_measurement/core/data_use_user_data.h" | 24 #include "components/data_use_measurement/core/data_use_user_data.h" |
| 25 #include "components/history/core/browser/history_service.h" | 25 #include "components/history/core/browser/history_service.h" |
| 26 #include "components/image_fetcher/image_decoder.h" | 26 #include "components/image_fetcher/image_decoder.h" |
| 27 #include "components/image_fetcher/image_fetcher.h" | 27 #include "components/image_fetcher/image_fetcher.h" |
| 28 #include "components/ntp_snippets/category_rankers/category_ranker.h" | 28 #include "components/ntp_snippets/category_rankers/category_ranker.h" |
| 29 #include "components/ntp_snippets/features.h" | 29 #include "components/ntp_snippets/features.h" |
| 30 #include "components/ntp_snippets/pref_names.h" | 30 #include "components/ntp_snippets/pref_names.h" |
| 31 #include "components/ntp_snippets/remote/remote_suggestions_database.h" | 31 #include "components/ntp_snippets/remote/remote_suggestions_database.h" |
| 32 #include "components/ntp_snippets/switches.h" | 32 #include "components/ntp_snippets/switches.h" |
| 33 #include "components/ntp_snippets/user_classifier.h" | |
| 34 #include "components/prefs/pref_registry_simple.h" | 33 #include "components/prefs/pref_registry_simple.h" |
| 35 #include "components/prefs/pref_service.h" | 34 #include "components/prefs/pref_service.h" |
| 36 #include "components/variations/variations_associated_data.h" | 35 #include "components/variations/variations_associated_data.h" |
| 37 #include "grit/components_strings.h" | 36 #include "grit/components_strings.h" |
| 38 #include "ui/base/l10n/l10n_util.h" | 37 #include "ui/base/l10n/l10n_util.h" |
| 39 #include "ui/gfx/image/image.h" | 38 #include "ui/gfx/image/image.h" |
| 40 | 39 |
| 41 namespace ntp_snippets { | 40 namespace ntp_snippets { |
| 42 | 41 |
| 43 namespace { | 42 namespace { |
| 44 | 43 |
| 45 // Number of snippets requested to the server. Consider replacing sparse UMA | 44 // Number of snippets requested to the server. Consider replacing sparse UMA |
| 46 // histograms with COUNTS() if this number increases beyond 50. | 45 // histograms with COUNTS() if this number increases beyond 50. |
| 47 const int kMaxSnippetCount = 10; | 46 const int kMaxSnippetCount = 10; |
| 48 | 47 |
| 49 // Number of archived snippets we keep around in memory. | 48 // Number of archived snippets we keep around in memory. |
| 50 const int kMaxArchivedSnippetCount = 200; | 49 const int kMaxArchivedSnippetCount = 200; |
| 51 | 50 |
| 52 // Default values for fetching intervals, fallback and wifi. | |
| 53 const double kDefaultFetchingIntervalRareNtpUser[] = {48.0, 24.0}; | |
| 54 const double kDefaultFetchingIntervalActiveNtpUser[] = {24.0, 6.0}; | |
| 55 const double kDefaultFetchingIntervalActiveSuggestionsConsumer[] = {24.0, 6.0}; | |
| 56 | |
| 57 // Variation parameters than can override the default fetching intervals. | |
| 58 const char* kFetchingIntervalParamNameRareNtpUser[] = { | |
| 59 "fetching_interval_hours-fallback-rare_ntp_user", | |
| 60 "fetching_interval_hours-wifi-rare_ntp_user"}; | |
| 61 const char* kFetchingIntervalParamNameActiveNtpUser[] = { | |
| 62 "fetching_interval_hours-fallback-active_ntp_user", | |
| 63 "fetching_interval_hours-wifi-active_ntp_user"}; | |
| 64 const char* kFetchingIntervalParamNameActiveSuggestionsConsumer[] = { | |
| 65 "fetching_interval_hours-fallback-active_suggestions_consumer", | |
| 66 "fetching_interval_hours-wifi-active_suggestions_consumer"}; | |
| 67 | |
| 68 // Keys for storing CategoryContent info in prefs. | 51 // Keys for storing CategoryContent info in prefs. |
| 69 const char kCategoryContentId[] = "id"; | 52 const char kCategoryContentId[] = "id"; |
| 70 const char kCategoryContentTitle[] = "title"; | 53 const char kCategoryContentTitle[] = "title"; |
| 71 const char kCategoryContentProvidedByServer[] = "provided_by_server"; | 54 const char kCategoryContentProvidedByServer[] = "provided_by_server"; |
| 72 const char kCategoryContentAllowFetchingMore[] = "allow_fetching_more"; | 55 const char kCategoryContentAllowFetchingMore[] = "allow_fetching_more"; |
| 73 | 56 |
| 74 // TODO(treib): Remove after M57. | 57 // TODO(treib): Remove after M57. |
| 75 const char kDeprecatedSnippetHostsPref[] = "ntp_snippets.hosts"; | 58 const char kDeprecatedSnippetHostsPref[] = "ntp_snippets.hosts"; |
| 76 | 59 |
| 77 base::TimeDelta GetFetchingInterval(bool is_wifi, | |
| 78 UserClassifier::UserClass user_class) { | |
| 79 double value_hours = 0.0; | |
| 80 | |
| 81 const int index = is_wifi ? 1 : 0; | |
| 82 const char* param_name = ""; | |
| 83 switch (user_class) { | |
| 84 case UserClassifier::UserClass::RARE_NTP_USER: | |
| 85 value_hours = kDefaultFetchingIntervalRareNtpUser[index]; | |
| 86 param_name = kFetchingIntervalParamNameRareNtpUser[index]; | |
| 87 break; | |
| 88 case UserClassifier::UserClass::ACTIVE_NTP_USER: | |
| 89 value_hours = kDefaultFetchingIntervalActiveNtpUser[index]; | |
| 90 param_name = kFetchingIntervalParamNameActiveNtpUser[index]; | |
| 91 break; | |
| 92 case UserClassifier::UserClass::ACTIVE_SUGGESTIONS_CONSUMER: | |
| 93 value_hours = kDefaultFetchingIntervalActiveSuggestionsConsumer[index]; | |
| 94 param_name = kFetchingIntervalParamNameActiveSuggestionsConsumer[index]; | |
| 95 break; | |
| 96 } | |
| 97 | |
| 98 // The default value can be overridden by a variation parameter. | |
| 99 std::string param_value_str = variations::GetVariationParamValueByFeature( | |
| 100 ntp_snippets::kArticleSuggestionsFeature, param_name); | |
| 101 if (!param_value_str.empty()) { | |
| 102 double param_value_hours = 0.0; | |
| 103 if (base::StringToDouble(param_value_str, ¶m_value_hours)) { | |
| 104 value_hours = param_value_hours; | |
| 105 } else { | |
| 106 LOG(WARNING) << "Invalid value for variation parameter " << param_name; | |
| 107 } | |
| 108 } | |
| 109 | |
| 110 return base::TimeDelta::FromSecondsD(value_hours * 3600.0); | |
| 111 } | |
| 112 | |
| 113 std::unique_ptr<std::vector<std::string>> GetSnippetIDVector( | 60 std::unique_ptr<std::vector<std::string>> GetSnippetIDVector( |
| 114 const NTPSnippet::PtrVector& snippets) { | 61 const NTPSnippet::PtrVector& snippets) { |
| 115 auto result = base::MakeUnique<std::vector<std::string>>(); | 62 auto result = base::MakeUnique<std::vector<std::string>>(); |
| 116 for (const auto& snippet : snippets) { | 63 for (const auto& snippet : snippets) { |
| 117 result->push_back(snippet->id()); | 64 result->push_back(snippet->id()); |
| 118 } | 65 } |
| 119 return result; | 66 return result; |
| 120 } | 67 } |
| 121 | 68 |
| 122 bool HasIntersection(const std::vector<std::string>& a, | 69 bool HasIntersection(const std::vector<std::string>& a, |
| (...skipping 148 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 271 } | 218 } |
| 272 | 219 |
| 273 void CachedImageFetcher::OnSnippetImageFetchedFromDatabase( | 220 void CachedImageFetcher::OnSnippetImageFetchedFromDatabase( |
| 274 const ImageFetchedCallback& callback, | 221 const ImageFetchedCallback& callback, |
| 275 const ContentSuggestion::ID& suggestion_id, | 222 const ContentSuggestion::ID& suggestion_id, |
| 276 const GURL& url, | 223 const GURL& url, |
| 277 std::string data) { // SnippetImageCallback requires nonconst reference. | 224 std::string data) { // SnippetImageCallback requires nonconst reference. |
| 278 // |image_decoder_| is null in tests. | 225 // |image_decoder_| is null in tests. |
| 279 if (image_decoder_ && !data.empty()) { | 226 if (image_decoder_ && !data.empty()) { |
| 280 image_decoder_->DecodeImage( | 227 image_decoder_->DecodeImage( |
| 281 data, base::Bind( | 228 data, base::Bind(&CachedImageFetcher::OnSnippetImageDecodedFromDatabase, |
| 282 &CachedImageFetcher::OnSnippetImageDecodedFromDatabase, | 229 base::Unretained(this), callback, suggestion_id, url)); |
| 283 base::Unretained(this), callback, suggestion_id, url)); | |
| 284 return; | 230 return; |
| 285 } | 231 } |
| 286 // Fetching from the DB failed; start a network fetch. | 232 // Fetching from the DB failed; start a network fetch. |
| 287 FetchSnippetImageFromNetwork(suggestion_id, url, callback); | 233 FetchSnippetImageFromNetwork(suggestion_id, url, callback); |
| 288 } | 234 } |
| 289 | 235 |
| 290 void CachedImageFetcher::OnSnippetImageDecodedFromDatabase( | 236 void CachedImageFetcher::OnSnippetImageDecodedFromDatabase( |
| 291 const ImageFetchedCallback& callback, | 237 const ImageFetchedCallback& callback, |
| 292 const ContentSuggestion::ID& suggestion_id, | 238 const ContentSuggestion::ID& suggestion_id, |
| 293 const GURL& url, | 239 const GURL& url, |
| (...skipping 20 matching lines...) Expand all Loading... |
| 314 callback.Run(gfx::Image()); | 260 callback.Run(gfx::Image()); |
| 315 return; | 261 return; |
| 316 } | 262 } |
| 317 | 263 |
| 318 image_fetcher_->StartOrQueueNetworkRequest( | 264 image_fetcher_->StartOrQueueNetworkRequest( |
| 319 suggestion_id.id_within_category(), url, | 265 suggestion_id.id_within_category(), url, |
| 320 base::Bind(&CachedImageFetcher::OnImageDecodingDone, | 266 base::Bind(&CachedImageFetcher::OnImageDecodingDone, |
| 321 base::Unretained(this), callback)); | 267 base::Unretained(this), callback)); |
| 322 } | 268 } |
| 323 | 269 |
| 324 RemoteSuggestionsProvider::RemoteSuggestionsProvider( | 270 RemoteSuggestionsProviderImpl::RemoteSuggestionsProviderImpl( |
| 325 Observer* observer, | 271 Observer* observer, |
| 326 PrefService* pref_service, | 272 PrefService* pref_service, |
| 327 const std::string& application_language_code, | 273 const std::string& application_language_code, |
| 328 CategoryRanker* category_ranker, | 274 CategoryRanker* category_ranker, |
| 329 const UserClassifier* user_classifier, | |
| 330 NTPSnippetsScheduler* scheduler, | |
| 331 std::unique_ptr<NTPSnippetsFetcher> snippets_fetcher, | 275 std::unique_ptr<NTPSnippetsFetcher> snippets_fetcher, |
| 332 std::unique_ptr<image_fetcher::ImageFetcher> image_fetcher, | 276 std::unique_ptr<image_fetcher::ImageFetcher> image_fetcher, |
| 333 std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, | 277 std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, |
| 334 std::unique_ptr<RemoteSuggestionsDatabase> database, | 278 std::unique_ptr<RemoteSuggestionsDatabase> database, |
| 335 std::unique_ptr<RemoteSuggestionsStatusService> status_service) | 279 std::unique_ptr<RemoteSuggestionsStatusService> status_service) |
| 336 : ContentSuggestionsProvider(observer), | 280 : RemoteSuggestionsProvider(observer), |
| 337 state_(State::NOT_INITED), | 281 state_(State::NOT_INITED), |
| 338 pref_service_(pref_service), | 282 pref_service_(pref_service), |
| 339 articles_category_( | 283 articles_category_( |
| 340 Category::FromKnownCategory(KnownCategories::ARTICLES)), | 284 Category::FromKnownCategory(KnownCategories::ARTICLES)), |
| 341 application_language_code_(application_language_code), | 285 application_language_code_(application_language_code), |
| 342 category_ranker_(category_ranker), | 286 category_ranker_(category_ranker), |
| 343 user_classifier_(user_classifier), | |
| 344 scheduler_(scheduler), | |
| 345 snippets_fetcher_(std::move(snippets_fetcher)), | 287 snippets_fetcher_(std::move(snippets_fetcher)), |
| 346 database_(std::move(database)), | 288 database_(std::move(database)), |
| 347 image_fetcher_(std::move(image_fetcher), | 289 image_fetcher_(std::move(image_fetcher), |
| 348 std::move(image_decoder), | 290 std::move(image_decoder), |
| 349 pref_service, | 291 pref_service, |
| 350 database_.get()), | 292 database_.get()), |
| 351 status_service_(std::move(status_service)), | 293 status_service_(std::move(status_service)), |
| 352 fetch_when_ready_(false), | 294 fetch_when_ready_(false), |
| 295 fetch_when_ready_interactive_(false), |
| 353 nuke_when_initialized_(false), | 296 nuke_when_initialized_(false), |
| 354 clock_(base::MakeUnique<base::DefaultClock>()) { | 297 clock_(base::MakeUnique<base::DefaultClock>()) { |
| 355 pref_service_->ClearPref(kDeprecatedSnippetHostsPref); | 298 pref_service_->ClearPref(kDeprecatedSnippetHostsPref); |
| 356 | 299 |
| 357 RestoreCategoriesFromPrefs(); | 300 RestoreCategoriesFromPrefs(); |
| 358 // The articles category always exists. Add it if we didn't get it from prefs. | 301 // The articles category always exists. Add it if we didn't get it from prefs. |
| 359 // TODO(treib): Rethink this. | 302 // TODO(treib): Rethink this. |
| 360 category_contents_.insert( | 303 category_contents_.insert( |
| 361 std::make_pair(articles_category_, | 304 std::make_pair(articles_category_, |
| 362 CategoryContent(BuildArticleCategoryInfo(base::nullopt)))); | 305 CategoryContent(BuildArticleCategoryInfo(base::nullopt)))); |
| 363 // Tell the observer about all the categories. | 306 // Tell the observer about all the categories. |
| 364 for (const auto& entry : category_contents_) { | 307 for (const auto& entry : category_contents_) { |
| 365 observer->OnCategoryStatusChanged(this, entry.first, entry.second.status); | 308 observer->OnCategoryStatusChanged(this, entry.first, entry.second.status); |
| 366 } | 309 } |
| 367 | 310 |
| 368 if (database_->IsErrorState()) { | 311 if (database_->IsErrorState()) { |
| 369 EnterState(State::ERROR_OCCURRED); | 312 EnterState(State::ERROR_OCCURRED); |
| 370 UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); | 313 UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); |
| 371 return; | 314 return; |
| 372 } | 315 } |
| 373 | 316 |
| 374 database_->SetErrorCallback(base::Bind( | 317 database_->SetErrorCallback(base::Bind( |
| 375 &RemoteSuggestionsProvider::OnDatabaseError, base::Unretained(this))); | 318 &RemoteSuggestionsProviderImpl::OnDatabaseError, base::Unretained(this))); |
| 376 | 319 |
| 377 // We transition to other states while finalizing the initialization, when the | 320 // We transition to other states while finalizing the initialization, when the |
| 378 // database is done loading. | 321 // database is done loading. |
| 379 database_load_start_ = base::TimeTicks::Now(); | 322 database_load_start_ = base::TimeTicks::Now(); |
| 380 database_->LoadSnippets(base::Bind( | 323 database_->LoadSnippets( |
| 381 &RemoteSuggestionsProvider::OnDatabaseLoaded, base::Unretained(this))); | 324 base::Bind(&RemoteSuggestionsProviderImpl::OnDatabaseLoaded, |
| 325 base::Unretained(this))); |
| 382 } | 326 } |
| 383 | 327 |
| 384 RemoteSuggestionsProvider::~RemoteSuggestionsProvider() = default; | 328 RemoteSuggestionsProviderImpl::~RemoteSuggestionsProviderImpl() = default; |
| 385 | 329 |
| 386 // static | 330 // static |
| 387 void RemoteSuggestionsProvider::RegisterProfilePrefs( | 331 void RemoteSuggestionsProviderImpl::RegisterProfilePrefs( |
| 388 PrefRegistrySimple* registry) { | 332 PrefRegistrySimple* registry) { |
| 389 // TODO(treib): Remove after M57. | 333 // TODO(treib): Remove after M57. |
| 390 registry->RegisterListPref(kDeprecatedSnippetHostsPref); | 334 registry->RegisterListPref(kDeprecatedSnippetHostsPref); |
| 391 registry->RegisterListPref(prefs::kRemoteSuggestionCategories); | 335 registry->RegisterListPref(prefs::kRemoteSuggestionCategories); |
| 392 registry->RegisterInt64Pref(prefs::kSnippetBackgroundFetchingIntervalWifi, 0); | |
| 393 registry->RegisterInt64Pref(prefs::kSnippetBackgroundFetchingIntervalFallback, | |
| 394 0); | |
| 395 registry->RegisterInt64Pref(prefs::kLastSuccessfulBackgroundFetchTime, 0); | 336 registry->RegisterInt64Pref(prefs::kLastSuccessfulBackgroundFetchTime, 0); |
| 396 | 337 |
| 397 RemoteSuggestionsStatusService::RegisterProfilePrefs(registry); | 338 RemoteSuggestionsStatusService::RegisterProfilePrefs(registry); |
| 398 } | 339 } |
| 399 | 340 |
| 400 void RemoteSuggestionsProvider::FetchSnippetsInTheBackground() { | 341 void RemoteSuggestionsProviderImpl::SetProviderStatusCallback( |
| 401 FetchSnippets(/*interactive_request=*/false); | 342 const ProviderStatusCallback& callback) { |
| 343 provider_status_callback_ = callback; |
| 344 // Call the observer right away if we've reached any final state. |
| 402 } | 345 } |
| 403 | 346 |
| 404 void RemoteSuggestionsProvider::FetchSnippetsForAllCategories() { | 347 void RemoteSuggestionsProviderImpl::ReloadSuggestions() { |
| 405 // TODO(markusheintz): Investigate whether we can call the Fetch method | 348 FetchSnippets(/*interactive_request=*/true, FetchStatusCallback()); |
| 406 // instead of the FetchSnippets. | |
| 407 FetchSnippets(/*interactive_request=*/true); | |
| 408 } | 349 } |
| 409 | 350 |
| 410 void RemoteSuggestionsProvider::FetchSnippets( | 351 void RemoteSuggestionsProviderImpl::RefetchInTheBackground( |
| 411 bool interactive_request) { | 352 const FetchStatusCallback& callback) { |
| 353 FetchSnippets(/*interactive_request=*/false, callback); |
| 354 } |
| 355 |
| 356 const NTPSnippetsFetcher* |
| 357 RemoteSuggestionsProviderImpl::snippets_fetcher_for_testing_and_debugging() |
| 358 const { |
| 359 return snippets_fetcher_.get(); |
| 360 } |
| 361 |
| 362 void RemoteSuggestionsProviderImpl::FetchSnippets( |
| 363 bool interactive_request, |
| 364 const FetchStatusCallback& callback) { |
| 412 if (!ready()) { | 365 if (!ready()) { |
| 413 fetch_when_ready_ = true; | 366 fetch_when_ready_ = true; |
| 367 fetch_when_ready_interactive_ = interactive_request; |
| 368 fetch_when_ready_callback_ = callback; |
| 414 return; | 369 return; |
| 415 } | 370 } |
| 416 | 371 |
| 417 MarkEmptyCategoriesAsLoading(); | 372 MarkEmptyCategoriesAsLoading(); |
| 418 | 373 |
| 419 NTPSnippetsFetcher::Params params = BuildFetchParams(); | 374 NTPSnippetsFetcher::Params params = BuildFetchParams(); |
| 420 params.interactive_request = interactive_request; | 375 params.interactive_request = interactive_request; |
| 421 snippets_fetcher_->FetchSnippets( | 376 snippets_fetcher_->FetchSnippets( |
| 422 params, base::BindOnce(&RemoteSuggestionsProvider::OnFetchFinished, | 377 params, base::BindOnce(&RemoteSuggestionsProviderImpl::OnFetchFinished, |
| 423 base::Unretained(this), interactive_request)); | 378 base::Unretained(this), callback, |
| 379 interactive_request)); |
| 424 } | 380 } |
| 425 | 381 |
| 426 void RemoteSuggestionsProvider::Fetch( | 382 void RemoteSuggestionsProviderImpl::Fetch( |
| 427 const Category& category, | 383 const Category& category, |
| 428 const std::set<std::string>& known_suggestion_ids, | 384 const std::set<std::string>& known_suggestion_ids, |
| 429 const FetchDoneCallback& callback) { | 385 const FetchDoneCallback& callback) { |
| 430 if (!ready()) { | 386 if (!ready()) { |
| 431 CallWithEmptyResults(callback, | 387 CallWithEmptyResults(callback, |
| 432 Status(StatusCode::TEMPORARY_ERROR, | 388 Status(StatusCode::TEMPORARY_ERROR, |
| 433 "RemoteSuggestionsProvider is not ready!")); | 389 "RemoteSuggestionsProvider is not ready!")); |
| 434 return; | 390 return; |
| 435 } | 391 } |
| 436 NTPSnippetsFetcher::Params params = BuildFetchParams(); | 392 NTPSnippetsFetcher::Params params = BuildFetchParams(); |
| 437 params.excluded_ids.insert(known_suggestion_ids.begin(), | 393 params.excluded_ids.insert(known_suggestion_ids.begin(), |
| 438 known_suggestion_ids.end()); | 394 known_suggestion_ids.end()); |
| 439 params.interactive_request = true; | 395 params.interactive_request = true; |
| 440 params.exclusive_category = category; | 396 params.exclusive_category = category; |
| 441 | 397 |
| 442 snippets_fetcher_->FetchSnippets( | 398 snippets_fetcher_->FetchSnippets( |
| 443 params, base::BindOnce(&RemoteSuggestionsProvider::OnFetchMoreFinished, | 399 params, |
| 444 base::Unretained(this), callback)); | 400 base::BindOnce(&RemoteSuggestionsProviderImpl::OnFetchMoreFinished, |
| 401 base::Unretained(this), callback)); |
| 445 } | 402 } |
| 446 | 403 |
| 447 // Builds default fetcher params. | 404 // Builds default fetcher params. |
| 448 NTPSnippetsFetcher::Params RemoteSuggestionsProvider::BuildFetchParams() const { | 405 NTPSnippetsFetcher::Params RemoteSuggestionsProviderImpl::BuildFetchParams() |
| 406 const { |
| 449 NTPSnippetsFetcher::Params result; | 407 NTPSnippetsFetcher::Params result; |
| 450 result.language_code = application_language_code_; | 408 result.language_code = application_language_code_; |
| 451 result.count_to_fetch = kMaxSnippetCount; | 409 result.count_to_fetch = kMaxSnippetCount; |
| 452 for (const auto& map_entry : category_contents_) { | 410 for (const auto& map_entry : category_contents_) { |
| 453 const CategoryContent& content = map_entry.second; | 411 const CategoryContent& content = map_entry.second; |
| 454 for (const auto& dismissed_snippet : content.dismissed) { | 412 for (const auto& dismissed_snippet : content.dismissed) { |
| 455 result.excluded_ids.insert(dismissed_snippet->id()); | 413 result.excluded_ids.insert(dismissed_snippet->id()); |
| 456 } | 414 } |
| 457 } | 415 } |
| 458 return result; | 416 return result; |
| 459 } | 417 } |
| 460 | 418 |
| 461 void RemoteSuggestionsProvider::MarkEmptyCategoriesAsLoading() { | 419 void RemoteSuggestionsProviderImpl::MarkEmptyCategoriesAsLoading() { |
| 462 for (const auto& item : category_contents_) { | 420 for (const auto& item : category_contents_) { |
| 463 Category category = item.first; | 421 Category category = item.first; |
| 464 const CategoryContent& content = item.second; | 422 const CategoryContent& content = item.second; |
| 465 if (content.snippets.empty()) { | 423 if (content.snippets.empty()) { |
| 466 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE_LOADING); | 424 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE_LOADING); |
| 467 } | 425 } |
| 468 } | 426 } |
| 469 } | 427 } |
| 470 | 428 |
| 471 void RemoteSuggestionsProvider::RescheduleFetching(bool force) { | 429 CategoryStatus RemoteSuggestionsProviderImpl::GetCategoryStatus( |
| 472 // The scheduler only exists on Android so far, it's null on other platforms. | 430 Category category) { |
| 473 if (!scheduler_) { | |
| 474 return; | |
| 475 } | |
| 476 | |
| 477 if (ready()) { | |
| 478 base::TimeDelta old_interval_wifi = base::TimeDelta::FromInternalValue( | |
| 479 pref_service_->GetInt64(prefs::kSnippetBackgroundFetchingIntervalWifi)); | |
| 480 base::TimeDelta old_interval_fallback = | |
| 481 base::TimeDelta::FromInternalValue(pref_service_->GetInt64( | |
| 482 prefs::kSnippetBackgroundFetchingIntervalFallback)); | |
| 483 UserClassifier::UserClass user_class = user_classifier_->GetUserClass(); | |
| 484 base::TimeDelta interval_wifi = | |
| 485 GetFetchingInterval(/*is_wifi=*/true, user_class); | |
| 486 base::TimeDelta interval_fallback = | |
| 487 GetFetchingInterval(/*is_wifi=*/false, user_class); | |
| 488 if (force || interval_wifi != old_interval_wifi || | |
| 489 interval_fallback != old_interval_fallback) { | |
| 490 scheduler_->Schedule(interval_wifi, interval_fallback); | |
| 491 pref_service_->SetInt64(prefs::kSnippetBackgroundFetchingIntervalWifi, | |
| 492 interval_wifi.ToInternalValue()); | |
| 493 pref_service_->SetInt64(prefs::kSnippetBackgroundFetchingIntervalFallback, | |
| 494 interval_fallback.ToInternalValue()); | |
| 495 } | |
| 496 } else { | |
| 497 // If we're NOT_INITED, we don't know whether to schedule or unschedule. | |
| 498 // If |force| is false, all is well: We'll reschedule on the next state | |
| 499 // change anyway. If it's true, then unschedule here, to make sure that the | |
| 500 // next reschedule actually happens. | |
| 501 if (state_ != State::NOT_INITED || force) { | |
| 502 scheduler_->Unschedule(); | |
| 503 pref_service_->ClearPref(prefs::kSnippetBackgroundFetchingIntervalWifi); | |
| 504 pref_service_->ClearPref( | |
| 505 prefs::kSnippetBackgroundFetchingIntervalFallback); | |
| 506 } | |
| 507 } | |
| 508 } | |
| 509 | |
| 510 CategoryStatus RemoteSuggestionsProvider::GetCategoryStatus(Category category) { | |
| 511 auto content_it = category_contents_.find(category); | 431 auto content_it = category_contents_.find(category); |
| 512 DCHECK(content_it != category_contents_.end()); | 432 DCHECK(content_it != category_contents_.end()); |
| 513 return content_it->second.status; | 433 return content_it->second.status; |
| 514 } | 434 } |
| 515 | 435 |
| 516 CategoryInfo RemoteSuggestionsProvider::GetCategoryInfo(Category category) { | 436 CategoryInfo RemoteSuggestionsProviderImpl::GetCategoryInfo(Category category) { |
| 517 auto content_it = category_contents_.find(category); | 437 auto content_it = category_contents_.find(category); |
| 518 DCHECK(content_it != category_contents_.end()); | 438 DCHECK(content_it != category_contents_.end()); |
| 519 return content_it->second.info; | 439 return content_it->second.info; |
| 520 } | 440 } |
| 521 | 441 |
| 522 void RemoteSuggestionsProvider::DismissSuggestion( | 442 void RemoteSuggestionsProviderImpl::DismissSuggestion( |
| 523 const ContentSuggestion::ID& suggestion_id) { | 443 const ContentSuggestion::ID& suggestion_id) { |
| 524 if (!ready()) { | 444 if (!ready()) { |
| 525 return; | 445 return; |
| 526 } | 446 } |
| 527 | 447 |
| 528 auto content_it = category_contents_.find(suggestion_id.category()); | 448 auto content_it = category_contents_.find(suggestion_id.category()); |
| 529 DCHECK(content_it != category_contents_.end()); | 449 DCHECK(content_it != category_contents_.end()); |
| 530 CategoryContent* content = &content_it->second; | 450 CategoryContent* content = &content_it->second; |
| 531 DismissSuggestionFromCategoryContent(content, | 451 DismissSuggestionFromCategoryContent(content, |
| 532 suggestion_id.id_within_category()); | 452 suggestion_id.id_within_category()); |
| 533 } | 453 } |
| 534 | 454 |
| 535 void RemoteSuggestionsProvider::ClearHistory( | 455 void RemoteSuggestionsProviderImpl::ClearHistory( |
| 536 base::Time begin, | 456 base::Time begin, |
| 537 base::Time end, | 457 base::Time end, |
| 538 const base::Callback<bool(const GURL& url)>& filter) { | 458 const base::Callback<bool(const GURL& url)>& filter) { |
| 539 // Both time range and the filter are ignored and all suggestions are removed, | 459 // Both time range and the filter are ignored and all suggestions are removed, |
| 540 // because it is not known which history entries were used for the suggestions | 460 // because it is not known which history entries were used for the suggestions |
| 541 // personalization. | 461 // personalization. |
| 542 if (!ready()) { | 462 if (!ready()) { |
| 543 nuke_when_initialized_ = true; | 463 nuke_when_initialized_ = true; |
| 544 } else { | 464 } else { |
| 545 NukeAllSnippets(); | 465 NukeAllSnippets(); |
| 546 } | 466 } |
| 547 } | 467 } |
| 548 | 468 |
| 549 void RemoteSuggestionsProvider::ClearCachedSuggestions(Category category) { | 469 void RemoteSuggestionsProviderImpl::ClearCachedSuggestions(Category category) { |
| 550 if (!initialized()) { | 470 if (!initialized()) { |
| 551 return; | 471 return; |
| 552 } | 472 } |
| 553 | 473 |
| 554 auto content_it = category_contents_.find(category); | 474 auto content_it = category_contents_.find(category); |
| 555 if (content_it == category_contents_.end()) { | 475 if (content_it == category_contents_.end()) { |
| 556 return; | 476 return; |
| 557 } | 477 } |
| 558 CategoryContent* content = &content_it->second; | 478 CategoryContent* content = &content_it->second; |
| 559 if (content->snippets.empty()) { | 479 if (content->snippets.empty()) { |
| 560 return; | 480 return; |
| 561 } | 481 } |
| 562 | 482 |
| 563 database_->DeleteSnippets(GetSnippetIDVector(content->snippets)); | 483 database_->DeleteSnippets(GetSnippetIDVector(content->snippets)); |
| 564 database_->DeleteImages(GetSnippetIDVector(content->snippets)); | 484 database_->DeleteImages(GetSnippetIDVector(content->snippets)); |
| 565 content->snippets.clear(); | 485 content->snippets.clear(); |
| 566 | 486 |
| 567 if (IsCategoryStatusAvailable(content->status)) { | 487 if (IsCategoryStatusAvailable(content->status)) { |
| 568 NotifyNewSuggestions(category, *content); | 488 NotifyNewSuggestions(category, *content); |
| 569 } | 489 } |
| 570 } | 490 } |
| 571 | 491 |
| 572 void RemoteSuggestionsProvider::OnSignInStateChanged() { | 492 void RemoteSuggestionsProviderImpl::OnSignInStateChanged() { |
| 573 // Make sure the status service is registered and we already initialised its | 493 // Make sure the status service is registered and we already initialised its |
| 574 // start state. | 494 // start state. |
| 575 if (!initialized()) { | 495 if (!initialized()) { |
| 576 return; | 496 return; |
| 577 } | 497 } |
| 578 | 498 |
| 579 status_service_->OnSignInStateChanged(); | 499 status_service_->OnSignInStateChanged(); |
| 580 } | 500 } |
| 581 | 501 |
| 582 void RemoteSuggestionsProvider::GetDismissedSuggestionsForDebugging( | 502 void RemoteSuggestionsProviderImpl::GetDismissedSuggestionsForDebugging( |
| 583 Category category, | 503 Category category, |
| 584 const DismissedSuggestionsCallback& callback) { | 504 const DismissedSuggestionsCallback& callback) { |
| 585 auto content_it = category_contents_.find(category); | 505 auto content_it = category_contents_.find(category); |
| 586 DCHECK(content_it != category_contents_.end()); | 506 DCHECK(content_it != category_contents_.end()); |
| 587 callback.Run( | 507 callback.Run( |
| 588 ConvertToContentSuggestions(category, content_it->second.dismissed)); | 508 ConvertToContentSuggestions(category, content_it->second.dismissed)); |
| 589 } | 509 } |
| 590 | 510 |
| 591 void RemoteSuggestionsProvider::ClearDismissedSuggestionsForDebugging( | 511 void RemoteSuggestionsProviderImpl::ClearDismissedSuggestionsForDebugging( |
| 592 Category category) { | 512 Category category) { |
| 593 auto content_it = category_contents_.find(category); | 513 auto content_it = category_contents_.find(category); |
| 594 DCHECK(content_it != category_contents_.end()); | 514 DCHECK(content_it != category_contents_.end()); |
| 595 CategoryContent* content = &content_it->second; | 515 CategoryContent* content = &content_it->second; |
| 596 | 516 |
| 597 if (!initialized()) { | 517 if (!initialized()) { |
| 598 return; | 518 return; |
| 599 } | 519 } |
| 600 | 520 |
| 601 if (content->dismissed.empty()) { | 521 if (content->dismissed.empty()) { |
| 602 return; | 522 return; |
| 603 } | 523 } |
| 604 | 524 |
| 605 database_->DeleteSnippets(GetSnippetIDVector(content->dismissed)); | 525 database_->DeleteSnippets(GetSnippetIDVector(content->dismissed)); |
| 606 // The image got already deleted when the suggestion was dismissed. | 526 // The image got already deleted when the suggestion was dismissed. |
| 607 | 527 |
| 608 content->dismissed.clear(); | 528 content->dismissed.clear(); |
| 609 } | 529 } |
| 610 | 530 |
| 611 // static | 531 // static |
| 612 int RemoteSuggestionsProvider::GetMaxSnippetCountForTesting() { | 532 int RemoteSuggestionsProviderImpl::GetMaxSnippetCountForTesting() { |
| 613 return kMaxSnippetCount; | 533 return kMaxSnippetCount; |
| 614 } | 534 } |
| 615 | 535 |
| 616 //////////////////////////////////////////////////////////////////////////////// | 536 //////////////////////////////////////////////////////////////////////////////// |
| 617 // Private methods | 537 // Private methods |
| 618 | 538 |
| 619 GURL RemoteSuggestionsProvider::FindSnippetImageUrl( | 539 GURL RemoteSuggestionsProviderImpl::FindSnippetImageUrl( |
| 620 const ContentSuggestion::ID& suggestion_id) const { | 540 const ContentSuggestion::ID& suggestion_id) const { |
| 621 DCHECK(base::ContainsKey(category_contents_, suggestion_id.category())); | 541 DCHECK(base::ContainsKey(category_contents_, suggestion_id.category())); |
| 622 | 542 |
| 623 const CategoryContent& content = | 543 const CategoryContent& content = |
| 624 category_contents_.at(suggestion_id.category()); | 544 category_contents_.at(suggestion_id.category()); |
| 625 const NTPSnippet* snippet = | 545 const NTPSnippet* snippet = |
| 626 content.FindSnippet(suggestion_id.id_within_category()); | 546 content.FindSnippet(suggestion_id.id_within_category()); |
| 627 if (!snippet) { | 547 if (!snippet) { |
| 628 return GURL(); | 548 return GURL(); |
| 629 } | 549 } |
| 630 return snippet->salient_image_url(); | 550 return snippet->salient_image_url(); |
| 631 } | 551 } |
| 632 | 552 |
| 633 void RemoteSuggestionsProvider::OnDatabaseLoaded( | 553 void RemoteSuggestionsProviderImpl::OnDatabaseLoaded( |
| 634 NTPSnippet::PtrVector snippets) { | 554 NTPSnippet::PtrVector snippets) { |
| 635 if (state_ == State::ERROR_OCCURRED) { | 555 if (state_ == State::ERROR_OCCURRED) { |
| 636 return; | 556 return; |
| 637 } | 557 } |
| 638 DCHECK(state_ == State::NOT_INITED); | 558 DCHECK(state_ == State::NOT_INITED); |
| 639 DCHECK(base::ContainsKey(category_contents_, articles_category_)); | 559 DCHECK(base::ContainsKey(category_contents_, articles_category_)); |
| 640 | 560 |
| 641 base::TimeDelta database_load_time = | 561 base::TimeDelta database_load_time = |
| 642 base::TimeTicks::Now() - database_load_start_; | 562 base::TimeTicks::Now() - database_load_start_; |
| 643 UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.Snippets.DatabaseLoadTime", | 563 UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.Snippets.DatabaseLoadTime", |
| (...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 679 } | 599 } |
| 680 | 600 |
| 681 // TODO(tschumann): If I move ClearExpiredDismissedSnippets() to the beginning | 601 // TODO(tschumann): If I move ClearExpiredDismissedSnippets() to the beginning |
| 682 // of the function, it essentially does nothing but tests are still green. Fix | 602 // of the function, it essentially does nothing but tests are still green. Fix |
| 683 // this! | 603 // this! |
| 684 ClearExpiredDismissedSnippets(); | 604 ClearExpiredDismissedSnippets(); |
| 685 ClearOrphanedImages(); | 605 ClearOrphanedImages(); |
| 686 FinishInitialization(); | 606 FinishInitialization(); |
| 687 } | 607 } |
| 688 | 608 |
| 689 void RemoteSuggestionsProvider::OnDatabaseError() { | 609 void RemoteSuggestionsProviderImpl::OnDatabaseError() { |
| 690 EnterState(State::ERROR_OCCURRED); | 610 EnterState(State::ERROR_OCCURRED); |
| 691 UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); | 611 UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); |
| 692 } | 612 } |
| 693 | 613 |
| 694 void RemoteSuggestionsProvider::OnFetchMoreFinished( | 614 void RemoteSuggestionsProviderImpl::OnFetchMoreFinished( |
| 695 const FetchDoneCallback& fetching_callback, | 615 const FetchDoneCallback& fetching_callback, |
| 696 Status status, | 616 Status status, |
| 697 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { | 617 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { |
| 698 if (!fetched_categories) { | 618 if (!fetched_categories) { |
| 699 DCHECK(!status.IsSuccess()); | 619 DCHECK(!status.IsSuccess()); |
| 700 CallWithEmptyResults(fetching_callback, status); | 620 CallWithEmptyResults(fetching_callback, status); |
| 701 return; | 621 return; |
| 702 } | 622 } |
| 703 if (fetched_categories->size() != 1u) { | 623 if (fetched_categories->size() != 1u) { |
| 704 LOG(DFATAL) << "Requested one exclusive category but received " | 624 LOG(DFATAL) << "Requested one exclusive category but received " |
| (...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 744 // e.g. to make sure we don't serve results after the sign-out. Revisit this | 664 // e.g. to make sure we don't serve results after the sign-out. Revisit this |
| 745 // once the snippets fetcher supports concurrent requests. We can then see if | 665 // once the snippets fetcher supports concurrent requests. We can then see if |
| 746 // Nuke should also cancel outstanding requests or we want to check the | 666 // Nuke should also cancel outstanding requests or we want to check the |
| 747 // status. | 667 // status. |
| 748 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); | 668 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); |
| 749 // Notify callers and observers. | 669 // Notify callers and observers. |
| 750 fetching_callback.Run(Status::Success(), std::move(result)); | 670 fetching_callback.Run(Status::Success(), std::move(result)); |
| 751 NotifyNewSuggestions(category, *existing_content); | 671 NotifyNewSuggestions(category, *existing_content); |
| 752 } | 672 } |
| 753 | 673 |
| 754 void RemoteSuggestionsProvider::OnFetchFinished( | 674 void RemoteSuggestionsProviderImpl::OnFetchFinished( |
| 675 const FetchStatusCallback& callback, |
| 755 bool interactive_request, | 676 bool interactive_request, |
| 756 Status status, | 677 Status status, |
| 757 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { | 678 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { |
| 758 if (!ready()) { | 679 if (!ready()) { |
| 759 // TODO(tschumann): What happens if this was a user-triggered, interactive | 680 // TODO(tschumann): What happens if this was a user-triggered, interactive |
| 760 // request? Is the UI waiting indefinitely now? | 681 // request? Is the UI waiting indefinitely now? |
| 761 return; | 682 return; |
| 762 } | 683 } |
| 763 | 684 |
| 764 // Record the fetch time of a successfull background fetch. | 685 // Record the fetch time of a successfull background fetch. |
| (...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 820 auto content_it = category_contents_.find(articles_category_); | 741 auto content_it = category_contents_.find(articles_category_); |
| 821 DCHECK(content_it != category_contents_.end()); | 742 DCHECK(content_it != category_contents_.end()); |
| 822 const CategoryContent& content = content_it->second; | 743 const CategoryContent& content = content_it->second; |
| 823 UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumArticles", | 744 UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumArticles", |
| 824 content.snippets.size()); | 745 content.snippets.size()); |
| 825 if (content.snippets.empty() && !content.dismissed.empty()) { | 746 if (content.snippets.empty() && !content.dismissed.empty()) { |
| 826 UMA_HISTOGRAM_COUNTS("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded", | 747 UMA_HISTOGRAM_COUNTS("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded", |
| 827 content.dismissed.size()); | 748 content.dismissed.size()); |
| 828 } | 749 } |
| 829 | 750 |
| 830 // Reschedule after a successful fetch. This resets all currently scheduled | 751 callback.Run(status); |
| 831 // fetches, to make sure the fallback interval triggers only if no wifi fetch | |
| 832 // succeeded, and also that we don't do a background fetch immediately after | |
| 833 // a user-initiated one. | |
| 834 if (fetched_categories) { | |
| 835 RescheduleFetching(true); | |
| 836 } | |
| 837 } | 752 } |
| 838 | 753 |
| 839 void RemoteSuggestionsProvider::ArchiveSnippets( | 754 void RemoteSuggestionsProviderImpl::ArchiveSnippets( |
| 840 CategoryContent* content, | 755 CategoryContent* content, |
| 841 NTPSnippet::PtrVector* to_archive) { | 756 NTPSnippet::PtrVector* to_archive) { |
| 842 // Archive previous snippets - move them at the beginning of the list. | 757 // Archive previous snippets - move them at the beginning of the list. |
| 843 content->archived.insert(content->archived.begin(), | 758 content->archived.insert(content->archived.begin(), |
| 844 std::make_move_iterator(to_archive->begin()), | 759 std::make_move_iterator(to_archive->begin()), |
| 845 std::make_move_iterator(to_archive->end())); | 760 std::make_move_iterator(to_archive->end())); |
| 846 to_archive->clear(); | 761 to_archive->clear(); |
| 847 | 762 |
| 848 // If there are more archived snippets than we want to keep, delete the | 763 // If there are more archived snippets than we want to keep, delete the |
| 849 // oldest ones by their fetch time (which are always in the back). | 764 // oldest ones by their fetch time (which are always in the back). |
| 850 if (content->archived.size() > kMaxArchivedSnippetCount) { | 765 if (content->archived.size() > kMaxArchivedSnippetCount) { |
| 851 NTPSnippet::PtrVector to_delete( | 766 NTPSnippet::PtrVector to_delete( |
| 852 std::make_move_iterator(content->archived.begin() + | 767 std::make_move_iterator(content->archived.begin() + |
| 853 kMaxArchivedSnippetCount), | 768 kMaxArchivedSnippetCount), |
| 854 std::make_move_iterator(content->archived.end())); | 769 std::make_move_iterator(content->archived.end())); |
| 855 content->archived.resize(kMaxArchivedSnippetCount); | 770 content->archived.resize(kMaxArchivedSnippetCount); |
| 856 database_->DeleteImages(GetSnippetIDVector(to_delete)); | 771 database_->DeleteImages(GetSnippetIDVector(to_delete)); |
| 857 } | 772 } |
| 858 } | 773 } |
| 859 | 774 |
| 860 void RemoteSuggestionsProvider::SanitizeReceivedSnippets( | 775 void RemoteSuggestionsProviderImpl::SanitizeReceivedSnippets( |
| 861 const NTPSnippet::PtrVector& dismissed, | 776 const NTPSnippet::PtrVector& dismissed, |
| 862 NTPSnippet::PtrVector* snippets) { | 777 NTPSnippet::PtrVector* snippets) { |
| 863 DCHECK(ready()); | 778 DCHECK(ready()); |
| 864 EraseMatchingSnippets(snippets, dismissed); | 779 EraseMatchingSnippets(snippets, dismissed); |
| 865 RemoveIncompleteSnippets(snippets); | 780 RemoveIncompleteSnippets(snippets); |
| 866 } | 781 } |
| 867 | 782 |
| 868 void RemoteSuggestionsProvider::IntegrateSnippets( | 783 void RemoteSuggestionsProviderImpl::IntegrateSnippets( |
| 869 CategoryContent* content, | 784 CategoryContent* content, |
| 870 NTPSnippet::PtrVector new_snippets) { | 785 NTPSnippet::PtrVector new_snippets) { |
| 871 DCHECK(ready()); | 786 DCHECK(ready()); |
| 872 | 787 |
| 873 // Do not touch the current set of snippets if the newly fetched one is empty. | 788 // Do not touch the current set of snippets if the newly fetched one is empty. |
| 874 // TODO(tschumann): This should go. If we get empty results we should update | 789 // TODO(tschumann): This should go. If we get empty results we should update |
| 875 // accordingly and remove the old one (only of course if this was not received | 790 // accordingly and remove the old one (only of course if this was not received |
| 876 // through a fetch-more). | 791 // through a fetch-more). |
| 877 if (new_snippets.empty()) { | 792 if (new_snippets.empty()) { |
| 878 return; | 793 return; |
| 879 } | 794 } |
| 880 | 795 |
| 881 // It's entirely possible that the newly fetched snippets contain articles | 796 // It's entirely possible that the newly fetched snippets contain articles |
| 882 // that have been present before. | 797 // that have been present before. |
| 883 // We need to make sure to only delete and archive snippets that don't | 798 // We need to make sure to only delete and archive snippets that don't |
| 884 // appear with the same ID in the new suggestions (it's fine for additional | 799 // appear with the same ID in the new suggestions (it's fine for additional |
| 885 // IDs though). | 800 // IDs though). |
| 886 EraseByPrimaryID(&content->snippets, *GetSnippetIDVector(new_snippets)); | 801 EraseByPrimaryID(&content->snippets, *GetSnippetIDVector(new_snippets)); |
| 887 // Do not delete the thumbnail images as they are still handy on open NTPs. | 802 // Do not delete the thumbnail images as they are still handy on open NTPs. |
| 888 database_->DeleteSnippets(GetSnippetIDVector(content->snippets)); | 803 database_->DeleteSnippets(GetSnippetIDVector(content->snippets)); |
| 889 // Note, that ArchiveSnippets will clear |content->snippets|. | 804 // Note, that ArchiveSnippets will clear |content->snippets|. |
| 890 ArchiveSnippets(content, &content->snippets); | 805 ArchiveSnippets(content, &content->snippets); |
| 891 | 806 |
| 892 database_->SaveSnippets(new_snippets); | 807 database_->SaveSnippets(new_snippets); |
| 893 | 808 |
| 894 content->snippets = std::move(new_snippets); | 809 content->snippets = std::move(new_snippets); |
| 895 } | 810 } |
| 896 | 811 |
| 897 void RemoteSuggestionsProvider::DismissSuggestionFromCategoryContent( | 812 void RemoteSuggestionsProviderImpl::DismissSuggestionFromCategoryContent( |
| 898 CategoryContent* content, | 813 CategoryContent* content, |
| 899 const std::string& id_within_category) { | 814 const std::string& id_within_category) { |
| 900 auto it = std::find_if( | 815 auto it = std::find_if( |
| 901 content->snippets.begin(), content->snippets.end(), | 816 content->snippets.begin(), content->snippets.end(), |
| 902 [&id_within_category](const std::unique_ptr<NTPSnippet>& snippet) { | 817 [&id_within_category](const std::unique_ptr<NTPSnippet>& snippet) { |
| 903 return snippet->id() == id_within_category; | 818 return snippet->id() == id_within_category; |
| 904 }); | 819 }); |
| 905 if (it == content->snippets.end()) { | 820 if (it == content->snippets.end()) { |
| 906 return; | 821 return; |
| 907 } | 822 } |
| 908 | 823 |
| 909 (*it)->set_dismissed(true); | 824 (*it)->set_dismissed(true); |
| 910 | 825 |
| 911 database_->SaveSnippet(**it); | 826 database_->SaveSnippet(**it); |
| 912 | 827 |
| 913 content->dismissed.push_back(std::move(*it)); | 828 content->dismissed.push_back(std::move(*it)); |
| 914 content->snippets.erase(it); | 829 content->snippets.erase(it); |
| 915 } | 830 } |
| 916 | 831 |
| 917 void RemoteSuggestionsProvider::ClearExpiredDismissedSnippets() { | 832 void RemoteSuggestionsProviderImpl::ClearExpiredDismissedSnippets() { |
| 918 std::vector<Category> categories_to_erase; | 833 std::vector<Category> categories_to_erase; |
| 919 | 834 |
| 920 const base::Time now = base::Time::Now(); | 835 const base::Time now = base::Time::Now(); |
| 921 | 836 |
| 922 for (auto& item : category_contents_) { | 837 for (auto& item : category_contents_) { |
| 923 Category category = item.first; | 838 Category category = item.first; |
| 924 CategoryContent* content = &item.second; | 839 CategoryContent* content = &item.second; |
| 925 | 840 |
| 926 NTPSnippet::PtrVector to_delete; | 841 NTPSnippet::PtrVector to_delete; |
| 927 // Move expired dismissed snippets over into |to_delete|. | 842 // Move expired dismissed snippets over into |to_delete|. |
| (...skipping 17 matching lines...) Expand all Loading... |
| 945 } | 860 } |
| 946 | 861 |
| 947 for (Category category : categories_to_erase) { | 862 for (Category category : categories_to_erase) { |
| 948 UpdateCategoryStatus(category, CategoryStatus::NOT_PROVIDED); | 863 UpdateCategoryStatus(category, CategoryStatus::NOT_PROVIDED); |
| 949 category_contents_.erase(category); | 864 category_contents_.erase(category); |
| 950 } | 865 } |
| 951 | 866 |
| 952 StoreCategoriesToPrefs(); | 867 StoreCategoriesToPrefs(); |
| 953 } | 868 } |
| 954 | 869 |
| 955 void RemoteSuggestionsProvider::ClearOrphanedImages() { | 870 void RemoteSuggestionsProviderImpl::ClearOrphanedImages() { |
| 956 auto alive_snippets = base::MakeUnique<std::set<std::string>>(); | 871 auto alive_snippets = base::MakeUnique<std::set<std::string>>(); |
| 957 for (const auto& entry : category_contents_) { | 872 for (const auto& entry : category_contents_) { |
| 958 const CategoryContent& content = entry.second; | 873 const CategoryContent& content = entry.second; |
| 959 for (const auto& snippet_ptr : content.snippets) { | 874 for (const auto& snippet_ptr : content.snippets) { |
| 960 alive_snippets->insert(snippet_ptr->id()); | 875 alive_snippets->insert(snippet_ptr->id()); |
| 961 } | 876 } |
| 962 for (const auto& snippet_ptr : content.dismissed) { | 877 for (const auto& snippet_ptr : content.dismissed) { |
| 963 alive_snippets->insert(snippet_ptr->id()); | 878 alive_snippets->insert(snippet_ptr->id()); |
| 964 } | 879 } |
| 965 } | 880 } |
| 966 database_->GarbageCollectImages(std::move(alive_snippets)); | 881 database_->GarbageCollectImages(std::move(alive_snippets)); |
| 967 } | 882 } |
| 968 | 883 |
| 969 void RemoteSuggestionsProvider::NukeAllSnippets() { | 884 void RemoteSuggestionsProviderImpl::NukeAllSnippets() { |
| 970 std::vector<Category> categories_to_erase; | 885 std::vector<Category> categories_to_erase; |
| 971 | 886 |
| 972 // Empty the ARTICLES category and remove all others, since they may or may | 887 // Empty the ARTICLES category and remove all others, since they may or may |
| 973 // not be personalized. | 888 // not be personalized. |
| 974 for (const auto& item : category_contents_) { | 889 for (const auto& item : category_contents_) { |
| 975 Category category = item.first; | 890 Category category = item.first; |
| 976 | 891 |
| 977 ClearCachedSuggestions(category); | 892 ClearCachedSuggestions(category); |
| 978 ClearDismissedSuggestionsForDebugging(category); | 893 ClearDismissedSuggestionsForDebugging(category); |
| 979 | 894 |
| 980 UpdateCategoryStatus(category, CategoryStatus::NOT_PROVIDED); | 895 UpdateCategoryStatus(category, CategoryStatus::NOT_PROVIDED); |
| 981 | 896 |
| 982 // Remove the category entirely; it may or may not reappear. | 897 // Remove the category entirely; it may or may not reappear. |
| 983 if (category != articles_category_) { | 898 if (category != articles_category_) { |
| 984 categories_to_erase.push_back(category); | 899 categories_to_erase.push_back(category); |
| 985 } | 900 } |
| 986 } | 901 } |
| 987 | 902 |
| 988 for (Category category : categories_to_erase) { | 903 for (Category category : categories_to_erase) { |
| 989 category_contents_.erase(category); | 904 category_contents_.erase(category); |
| 990 } | 905 } |
| 991 | 906 |
| 992 StoreCategoriesToPrefs(); | 907 StoreCategoriesToPrefs(); |
| 993 } | 908 } |
| 994 | 909 |
| 995 void RemoteSuggestionsProvider::FetchSuggestionImage( | 910 void RemoteSuggestionsProviderImpl::FetchSuggestionImage( |
| 996 const ContentSuggestion::ID& suggestion_id, | 911 const ContentSuggestion::ID& suggestion_id, |
| 997 const ImageFetchedCallback& callback) { | 912 const ImageFetchedCallback& callback) { |
| 998 if (!base::ContainsKey(category_contents_, suggestion_id.category())) { | 913 if (!base::ContainsKey(category_contents_, suggestion_id.category())) { |
| 999 base::ThreadTaskRunnerHandle::Get()->PostTask( | 914 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 1000 FROM_HERE, base::Bind(callback, gfx::Image())); | 915 FROM_HERE, base::Bind(callback, gfx::Image())); |
| 1001 return; | 916 return; |
| 1002 } | 917 } |
| 1003 GURL image_url = FindSnippetImageUrl(suggestion_id); | 918 GURL image_url = FindSnippetImageUrl(suggestion_id); |
| 1004 if (image_url.is_empty()) { | 919 if (image_url.is_empty()) { |
| 1005 // As we don't know the corresponding snippet anymore, we don't expect to | 920 // As we don't know the corresponding snippet anymore, we don't expect to |
| 1006 // find it in the database (and also can't fetch it remotely). Cut the | 921 // find it in the database (and also can't fetch it remotely). Cut the |
| 1007 // lookup short and return directly. | 922 // lookup short and return directly. |
| 1008 base::ThreadTaskRunnerHandle::Get()->PostTask( | 923 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 1009 FROM_HERE, base::Bind(callback, gfx::Image())); | 924 FROM_HERE, base::Bind(callback, gfx::Image())); |
| 1010 return; | 925 return; |
| 1011 } | 926 } |
| 1012 image_fetcher_.FetchSuggestionImage(suggestion_id, image_url, callback); | 927 image_fetcher_.FetchSuggestionImage(suggestion_id, image_url, callback); |
| 1013 } | 928 } |
| 1014 | 929 |
| 1015 void RemoteSuggestionsProvider::EnterStateReady() { | 930 void RemoteSuggestionsProviderImpl::EnterStateReady() { |
| 1016 if (nuke_when_initialized_) { | 931 if (nuke_when_initialized_) { |
| 1017 NukeAllSnippets(); | 932 NukeAllSnippets(); |
| 1018 nuke_when_initialized_ = false; | 933 nuke_when_initialized_ = false; |
| 1019 } | 934 } |
| 1020 | 935 |
| 1021 auto article_category_it = category_contents_.find(articles_category_); | 936 auto article_category_it = category_contents_.find(articles_category_); |
| 1022 DCHECK(article_category_it != category_contents_.end()); | 937 DCHECK(article_category_it != category_contents_.end()); |
| 1023 if (article_category_it->second.snippets.empty() || fetch_when_ready_) { | 938 if (article_category_it->second.snippets.empty() || fetch_when_ready_) { |
| 1024 // TODO(jkrcal): Fetching snippets automatically upon creation of this | 939 // TODO(jkrcal): Fetching snippets automatically upon creation of this |
| 1025 // lazily created service can cause troubles, e.g. in unit tests where | 940 // lazily created service can cause troubles, e.g. in unit tests where |
| 1026 // network I/O is not allowed. | 941 // network I/O is not allowed. |
| 1027 // Either add a DCHECK here that we actually are allowed to do network I/O | 942 // Either add a DCHECK here that we actually are allowed to do network I/O |
| 1028 // or change the logic so that some explicit call is always needed for the | 943 // or change the logic so that some explicit call is always needed for the |
| 1029 // network request. | 944 // network request. |
| 1030 FetchSnippets(/*interactive_request=*/false); | 945 FetchSnippets(fetch_when_ready_interactive_, |
| 946 fetch_when_ready_callback_); |
| 1031 fetch_when_ready_ = false; | 947 fetch_when_ready_ = false; |
| 948 fetch_when_ready_callback_ = FetchStatusCallback(); |
| 1032 } | 949 } |
| 1033 | 950 |
| 1034 for (const auto& item : category_contents_) { | 951 for (const auto& item : category_contents_) { |
| 1035 Category category = item.first; | 952 Category category = item.first; |
| 1036 const CategoryContent& content = item.second; | 953 const CategoryContent& content = item.second; |
| 1037 // FetchSnippets has set the status to |AVAILABLE_LOADING| if relevant, | 954 // FetchSnippets has set the status to |AVAILABLE_LOADING| if relevant, |
| 1038 // otherwise we transition to |AVAILABLE| here. | 955 // otherwise we transition to |AVAILABLE| here. |
| 1039 if (content.status != CategoryStatus::AVAILABLE_LOADING) { | 956 if (content.status != CategoryStatus::AVAILABLE_LOADING) { |
| 1040 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); | 957 UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); |
| 1041 } | 958 } |
| 1042 } | 959 } |
| 1043 } | 960 } |
| 1044 | 961 |
| 1045 void RemoteSuggestionsProvider::EnterStateDisabled() { | 962 void RemoteSuggestionsProviderImpl::EnterStateDisabled() { |
| 1046 NukeAllSnippets(); | 963 NukeAllSnippets(); |
| 1047 } | 964 } |
| 1048 | 965 |
| 1049 void RemoteSuggestionsProvider::EnterStateError() { | 966 void RemoteSuggestionsProviderImpl::EnterStateError() { |
| 1050 status_service_.reset(); | 967 status_service_.reset(); |
| 1051 } | 968 } |
| 1052 | 969 |
| 1053 void RemoteSuggestionsProvider::FinishInitialization() { | 970 void RemoteSuggestionsProviderImpl::FinishInitialization() { |
| 1054 if (nuke_when_initialized_) { | 971 if (nuke_when_initialized_) { |
| 1055 // We nuke here in addition to EnterStateReady, so that it happens even if | 972 // We nuke here in addition to EnterStateReady, so that it happens even if |
| 1056 // we enter the DISABLED state below. | 973 // we enter the DISABLED state below. |
| 1057 NukeAllSnippets(); | 974 NukeAllSnippets(); |
| 1058 nuke_when_initialized_ = false; | 975 nuke_when_initialized_ = false; |
| 1059 } | 976 } |
| 1060 | 977 |
| 1061 // Note: Initializing the status service will run the callback right away with | 978 // Note: Initializing the status service will run the callback right away with |
| 1062 // the current state. | 979 // the current state. |
| 1063 status_service_->Init(base::Bind(&RemoteSuggestionsProvider::OnStatusChanged, | 980 status_service_->Init(base::Bind( |
| 1064 base::Unretained(this))); | 981 &RemoteSuggestionsProviderImpl::OnStatusChanged, base::Unretained(this))); |
| 1065 | 982 |
| 1066 // Always notify here even if we got nothing from the database, because we | 983 // Always notify here even if we got nothing from the database, because we |
| 1067 // don't know how long the fetch will take or if it will even complete. | 984 // don't know how long the fetch will take or if it will even complete. |
| 1068 for (const auto& item : category_contents_) { | 985 for (const auto& item : category_contents_) { |
| 1069 Category category = item.first; | 986 Category category = item.first; |
| 1070 const CategoryContent& content = item.second; | 987 const CategoryContent& content = item.second; |
| 1071 // Note: We might be in a non-available status here, e.g. DISABLED due to | 988 // Note: We might be in a non-available status here, e.g. DISABLED due to |
| 1072 // enterprise policy. | 989 // enterprise policy. |
| 1073 if (IsCategoryStatusAvailable(content.status)) { | 990 if (IsCategoryStatusAvailable(content.status)) { |
| 1074 NotifyNewSuggestions(category, content); | 991 NotifyNewSuggestions(category, content); |
| 1075 } | 992 } |
| 1076 } | 993 } |
| 1077 } | 994 } |
| 1078 | 995 |
| 1079 void RemoteSuggestionsProvider::OnStatusChanged( | 996 void RemoteSuggestionsProviderImpl::OnStatusChanged( |
| 1080 RemoteSuggestionsStatus old_status, | 997 RemoteSuggestionsStatus old_status, |
| 1081 RemoteSuggestionsStatus new_status) { | 998 RemoteSuggestionsStatus new_status) { |
| 1082 switch (new_status) { | 999 switch (new_status) { |
| 1083 case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN: | 1000 case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN: |
| 1084 if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT) { | 1001 if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT) { |
| 1085 DCHECK(state_ == State::READY); | 1002 DCHECK(state_ == State::READY); |
| 1086 // Clear nonpersonalized suggestions. | 1003 // Clear nonpersonalized suggestions. |
| 1087 NukeAllSnippets(); | 1004 NukeAllSnippets(); |
| 1088 // Fetch personalized ones. | 1005 // Fetch personalized ones. |
| 1089 FetchSnippets(/*interactive_request=*/true); | 1006 // TODO(jkrcal): Loop in SchedulingRemoteSuggestionsProvider somehow. |
| 1007 FetchSnippets(/*interactive_request=*/true, FetchStatusCallback()); |
| 1090 } else { | 1008 } else { |
| 1091 // Do not change the status. That will be done in EnterStateReady(). | 1009 // Do not change the status. That will be done in EnterStateReady(). |
| 1092 EnterState(State::READY); | 1010 EnterState(State::READY); |
| 1093 } | 1011 } |
| 1094 break; | 1012 break; |
| 1095 | 1013 |
| 1096 case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT: | 1014 case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT: |
| 1097 if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN) { | 1015 if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN) { |
| 1098 DCHECK(state_ == State::READY); | 1016 DCHECK(state_ == State::READY); |
| 1099 // Clear personalized suggestions. | 1017 // Clear personalized suggestions. |
| 1100 NukeAllSnippets(); | 1018 NukeAllSnippets(); |
| 1101 // Fetch nonpersonalized ones. | 1019 // Fetch nonpersonalized ones. |
| 1102 FetchSnippets(/*interactive_request=*/true); | 1020 // TODO(jkrcal): Loop in SchedulingRemoteSuggestionsProvider somehow. |
| 1021 FetchSnippets(/*interactive_request=*/true, FetchStatusCallback()); |
| 1103 } else { | 1022 } else { |
| 1104 // Do not change the status. That will be done in EnterStateReady(). | 1023 // Do not change the status. That will be done in EnterStateReady(). |
| 1105 EnterState(State::READY); | 1024 EnterState(State::READY); |
| 1106 } | 1025 } |
| 1107 break; | 1026 break; |
| 1108 | 1027 |
| 1109 case RemoteSuggestionsStatus::EXPLICITLY_DISABLED: | 1028 case RemoteSuggestionsStatus::EXPLICITLY_DISABLED: |
| 1110 EnterState(State::DISABLED); | 1029 EnterState(State::DISABLED); |
| 1111 UpdateAllCategoryStatus(CategoryStatus::CATEGORY_EXPLICITLY_DISABLED); | 1030 UpdateAllCategoryStatus(CategoryStatus::CATEGORY_EXPLICITLY_DISABLED); |
| 1112 break; | 1031 break; |
| 1113 | 1032 |
| 1114 case RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED: | 1033 case RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED: |
| 1115 EnterState(State::DISABLED); | 1034 EnterState(State::DISABLED); |
| 1116 UpdateAllCategoryStatus(CategoryStatus::SIGNED_OUT); | 1035 UpdateAllCategoryStatus(CategoryStatus::SIGNED_OUT); |
| 1117 break; | 1036 break; |
| 1118 } | 1037 } |
| 1119 } | 1038 } |
| 1120 | 1039 |
| 1121 void RemoteSuggestionsProvider::EnterState(State state) { | 1040 void RemoteSuggestionsProviderImpl::EnterState(State state) { |
| 1122 if (state == state_) { | 1041 if (state == state_) { |
| 1123 return; | 1042 return; |
| 1124 } | 1043 } |
| 1125 | 1044 |
| 1126 UMA_HISTOGRAM_ENUMERATION("NewTabPage.Snippets.EnteredState", | 1045 UMA_HISTOGRAM_ENUMERATION("NewTabPage.Snippets.EnteredState", |
| 1127 static_cast<int>(state), | 1046 static_cast<int>(state), |
| 1128 static_cast<int>(State::COUNT)); | 1047 static_cast<int>(State::COUNT)); |
| 1129 | 1048 |
| 1130 switch (state) { | 1049 switch (state) { |
| 1131 case State::NOT_INITED: | 1050 case State::NOT_INITED: |
| (...skipping 21 matching lines...) Expand all Loading... |
| 1153 DVLOG(1) << "Entering state: ERROR_OCCURRED"; | 1072 DVLOG(1) << "Entering state: ERROR_OCCURRED"; |
| 1154 state_ = State::ERROR_OCCURRED; | 1073 state_ = State::ERROR_OCCURRED; |
| 1155 EnterStateError(); | 1074 EnterStateError(); |
| 1156 break; | 1075 break; |
| 1157 | 1076 |
| 1158 case State::COUNT: | 1077 case State::COUNT: |
| 1159 NOTREACHED(); | 1078 NOTREACHED(); |
| 1160 break; | 1079 break; |
| 1161 } | 1080 } |
| 1162 | 1081 |
| 1163 // Schedule or un-schedule background fetching after each state change. | 1082 NotifyStateChanged(); |
| 1164 RescheduleFetching(false); | |
| 1165 } | 1083 } |
| 1166 | 1084 |
| 1167 void RemoteSuggestionsProvider::NotifyNewSuggestions( | 1085 void RemoteSuggestionsProviderImpl::NotifyStateChanged() { |
| 1086 switch (state_) { |
| 1087 case State::NOT_INITED: |
| 1088 // Initial state, not sure yet whether active or not. |
| 1089 break; |
| 1090 case State::READY: |
| 1091 provider_status_callback_.Run(ProviderStatus::ACTIVE); |
| 1092 break; |
| 1093 case State::DISABLED: |
| 1094 provider_status_callback_.Run(ProviderStatus::INACTIVE); |
| 1095 break; |
| 1096 case State::ERROR_OCCURRED: |
| 1097 provider_status_callback_.Run(ProviderStatus::INACTIVE); |
| 1098 break; |
| 1099 case State::COUNT: |
| 1100 NOTREACHED(); |
| 1101 break; |
| 1102 } |
| 1103 } |
| 1104 |
| 1105 void RemoteSuggestionsProviderImpl::NotifyNewSuggestions( |
| 1168 Category category, | 1106 Category category, |
| 1169 const CategoryContent& content) { | 1107 const CategoryContent& content) { |
| 1170 DCHECK(IsCategoryStatusAvailable(content.status)); | 1108 DCHECK(IsCategoryStatusAvailable(content.status)); |
| 1171 | 1109 |
| 1172 std::vector<ContentSuggestion> result = | 1110 std::vector<ContentSuggestion> result = |
| 1173 ConvertToContentSuggestions(category, content.snippets); | 1111 ConvertToContentSuggestions(category, content.snippets); |
| 1174 | 1112 |
| 1175 DVLOG(1) << "NotifyNewSuggestions(): " << result.size() | 1113 DVLOG(1) << "NotifyNewSuggestions(): " << result.size() |
| 1176 << " items in category " << category; | 1114 << " items in category " << category; |
| 1177 observer()->OnNewSuggestions(this, category, std::move(result)); | 1115 observer()->OnNewSuggestions(this, category, std::move(result)); |
| 1178 } | 1116 } |
| 1179 | 1117 |
| 1180 void RemoteSuggestionsProvider::UpdateCategoryStatus(Category category, | 1118 void RemoteSuggestionsProviderImpl::UpdateCategoryStatus( |
| 1181 CategoryStatus status) { | 1119 Category category, |
| 1120 CategoryStatus status) { |
| 1182 auto content_it = category_contents_.find(category); | 1121 auto content_it = category_contents_.find(category); |
| 1183 DCHECK(content_it != category_contents_.end()); | 1122 DCHECK(content_it != category_contents_.end()); |
| 1184 CategoryContent& content = content_it->second; | 1123 CategoryContent& content = content_it->second; |
| 1185 | 1124 |
| 1186 if (status == content.status) { | 1125 if (status == content.status) { |
| 1187 return; | 1126 return; |
| 1188 } | 1127 } |
| 1189 | 1128 |
| 1190 DVLOG(1) << "UpdateCategoryStatus(): " << category.id() << ": " | 1129 DVLOG(1) << "UpdateCategoryStatus(): " << category.id() << ": " |
| 1191 << static_cast<int>(content.status) << " -> " | 1130 << static_cast<int>(content.status) << " -> " |
| 1192 << static_cast<int>(status); | 1131 << static_cast<int>(status); |
| 1193 content.status = status; | 1132 content.status = status; |
| 1194 observer()->OnCategoryStatusChanged(this, category, content.status); | 1133 observer()->OnCategoryStatusChanged(this, category, content.status); |
| 1195 } | 1134 } |
| 1196 | 1135 |
| 1197 void RemoteSuggestionsProvider::UpdateAllCategoryStatus(CategoryStatus status) { | 1136 void RemoteSuggestionsProviderImpl::UpdateAllCategoryStatus( |
| 1137 CategoryStatus status) { |
| 1198 for (const auto& category : category_contents_) { | 1138 for (const auto& category : category_contents_) { |
| 1199 UpdateCategoryStatus(category.first, status); | 1139 UpdateCategoryStatus(category.first, status); |
| 1200 } | 1140 } |
| 1201 } | 1141 } |
| 1202 | 1142 |
| 1203 namespace { | 1143 namespace { |
| 1204 | 1144 |
| 1205 template <typename T> | 1145 template <typename T> |
| 1206 typename T::const_iterator FindSnippetInContainer( | 1146 typename T::const_iterator FindSnippetInContainer( |
| 1207 const T& container, | 1147 const T& container, |
| 1208 const std::string& id_within_category) { | 1148 const std::string& id_within_category) { |
| 1209 return std::find_if( | 1149 return std::find_if( |
| 1210 container.begin(), container.end(), | 1150 container.begin(), container.end(), |
| 1211 [&id_within_category](const std::unique_ptr<NTPSnippet>& snippet) { | 1151 [&id_within_category](const std::unique_ptr<NTPSnippet>& snippet) { |
| 1212 return snippet->id() == id_within_category; | 1152 return snippet->id() == id_within_category; |
| 1213 }); | 1153 }); |
| 1214 } | 1154 } |
| 1215 | 1155 |
| 1216 } // namespace | 1156 } // namespace |
| 1217 | 1157 |
| 1218 const NTPSnippet* RemoteSuggestionsProvider::CategoryContent::FindSnippet( | 1158 const NTPSnippet* RemoteSuggestionsProviderImpl::CategoryContent::FindSnippet( |
| 1219 const std::string& id_within_category) const { | 1159 const std::string& id_within_category) const { |
| 1220 // Search for the snippet in current and archived snippets. | 1160 // Search for the snippet in current and archived snippets. |
| 1221 auto it = FindSnippetInContainer(snippets, id_within_category); | 1161 auto it = FindSnippetInContainer(snippets, id_within_category); |
| 1222 if (it != snippets.end()) { | 1162 if (it != snippets.end()) { |
| 1223 return it->get(); | 1163 return it->get(); |
| 1224 } | 1164 } |
| 1225 auto archived_it = FindSnippetInContainer(archived, id_within_category); | 1165 auto archived_it = FindSnippetInContainer(archived, id_within_category); |
| 1226 if (archived_it != archived.end()) { | 1166 if (archived_it != archived.end()) { |
| 1227 return archived_it->get(); | 1167 return archived_it->get(); |
| 1228 } | 1168 } |
| 1229 auto dismissed_it = FindSnippetInContainer(dismissed, id_within_category); | 1169 auto dismissed_it = FindSnippetInContainer(dismissed, id_within_category); |
| 1230 if (dismissed_it != dismissed.end()) { | 1170 if (dismissed_it != dismissed.end()) { |
| 1231 return dismissed_it->get(); | 1171 return dismissed_it->get(); |
| 1232 } | 1172 } |
| 1233 return nullptr; | 1173 return nullptr; |
| 1234 } | 1174 } |
| 1235 | 1175 |
| 1236 RemoteSuggestionsProvider::CategoryContent* | 1176 RemoteSuggestionsProviderImpl::CategoryContent* |
| 1237 RemoteSuggestionsProvider::UpdateCategoryInfo(Category category, | 1177 RemoteSuggestionsProviderImpl::UpdateCategoryInfo(Category category, |
| 1238 const CategoryInfo& info) { | 1178 const CategoryInfo& info) { |
| 1239 auto content_it = category_contents_.find(category); | 1179 auto content_it = category_contents_.find(category); |
| 1240 if (content_it == category_contents_.end()) { | 1180 if (content_it == category_contents_.end()) { |
| 1241 content_it = category_contents_ | 1181 content_it = category_contents_ |
| 1242 .insert(std::make_pair(category, CategoryContent(info))) | 1182 .insert(std::make_pair(category, CategoryContent(info))) |
| 1243 .first; | 1183 .first; |
| 1244 } else { | 1184 } else { |
| 1245 content_it->second.info = info; | 1185 content_it->second.info = info; |
| 1246 } | 1186 } |
| 1247 return &content_it->second; | 1187 return &content_it->second; |
| 1248 } | 1188 } |
| 1249 | 1189 |
| 1250 void RemoteSuggestionsProvider::RestoreCategoriesFromPrefs() { | 1190 void RemoteSuggestionsProviderImpl::RestoreCategoriesFromPrefs() { |
| 1251 // This must only be called at startup, before there are any categories. | 1191 // This must only be called at startup, before there are any categories. |
| 1252 DCHECK(category_contents_.empty()); | 1192 DCHECK(category_contents_.empty()); |
| 1253 | 1193 |
| 1254 const base::ListValue* list = | 1194 const base::ListValue* list = |
| 1255 pref_service_->GetList(prefs::kRemoteSuggestionCategories); | 1195 pref_service_->GetList(prefs::kRemoteSuggestionCategories); |
| 1256 for (const std::unique_ptr<base::Value>& entry : *list) { | 1196 for (const std::unique_ptr<base::Value>& entry : *list) { |
| 1257 const base::DictionaryValue* dict = nullptr; | 1197 const base::DictionaryValue* dict = nullptr; |
| 1258 if (!entry->GetAsDictionary(&dict)) { | 1198 if (!entry->GetAsDictionary(&dict)) { |
| 1259 DLOG(WARNING) << "Invalid category pref value: " << *entry; | 1199 DLOG(WARNING) << "Invalid category pref value: " << *entry; |
| 1260 continue; | 1200 continue; |
| (...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1293 CategoryInfo info = | 1233 CategoryInfo info = |
| 1294 category == articles_category_ | 1234 category == articles_category_ |
| 1295 ? BuildArticleCategoryInfo(title) | 1235 ? BuildArticleCategoryInfo(title) |
| 1296 : BuildRemoteCategoryInfo(title, allow_fetching_more_results); | 1236 : BuildRemoteCategoryInfo(title, allow_fetching_more_results); |
| 1297 CategoryContent* content = UpdateCategoryInfo(category, info); | 1237 CategoryContent* content = UpdateCategoryInfo(category, info); |
| 1298 content->included_in_last_server_response = | 1238 content->included_in_last_server_response = |
| 1299 included_in_last_server_response; | 1239 included_in_last_server_response; |
| 1300 } | 1240 } |
| 1301 } | 1241 } |
| 1302 | 1242 |
| 1303 void RemoteSuggestionsProvider::StoreCategoriesToPrefs() { | 1243 void RemoteSuggestionsProviderImpl::StoreCategoriesToPrefs() { |
| 1304 // Collect all the CategoryContents. | 1244 // Collect all the CategoryContents. |
| 1305 std::vector<std::pair<Category, const CategoryContent*>> to_store; | 1245 std::vector<std::pair<Category, const CategoryContent*>> to_store; |
| 1306 for (const auto& entry : category_contents_) { | 1246 for (const auto& entry : category_contents_) { |
| 1307 to_store.emplace_back(entry.first, &entry.second); | 1247 to_store.emplace_back(entry.first, &entry.second); |
| 1308 } | 1248 } |
| 1309 // The ranker may not persist the order, thus, it is stored by the provider. | 1249 // The ranker may not persist the order, thus, it is stored by the provider. |
| 1310 std::sort(to_store.begin(), to_store.end(), | 1250 std::sort(to_store.begin(), to_store.end(), |
| 1311 [this](const std::pair<Category, const CategoryContent*>& left, | 1251 [this](const std::pair<Category, const CategoryContent*>& left, |
| 1312 const std::pair<Category, const CategoryContent*>& right) { | 1252 const std::pair<Category, const CategoryContent*>& right) { |
| 1313 return category_ranker_->Compare(left.first, right.first); | 1253 return category_ranker_->Compare(left.first, right.first); |
| (...skipping 10 matching lines...) Expand all Loading... |
| 1324 dict->SetBoolean(kCategoryContentProvidedByServer, | 1264 dict->SetBoolean(kCategoryContentProvidedByServer, |
| 1325 content.included_in_last_server_response); | 1265 content.included_in_last_server_response); |
| 1326 dict->SetBoolean(kCategoryContentAllowFetchingMore, | 1266 dict->SetBoolean(kCategoryContentAllowFetchingMore, |
| 1327 content.info.has_more_action()); | 1267 content.info.has_more_action()); |
| 1328 list.Append(std::move(dict)); | 1268 list.Append(std::move(dict)); |
| 1329 } | 1269 } |
| 1330 // Finally, store the result in the pref service. | 1270 // Finally, store the result in the pref service. |
| 1331 pref_service_->Set(prefs::kRemoteSuggestionCategories, list); | 1271 pref_service_->Set(prefs::kRemoteSuggestionCategories, list); |
| 1332 } | 1272 } |
| 1333 | 1273 |
| 1334 RemoteSuggestionsProvider::CategoryContent::CategoryContent( | 1274 RemoteSuggestionsProviderImpl::CategoryContent::CategoryContent( |
| 1335 const CategoryInfo& info) | 1275 const CategoryInfo& info) |
| 1336 : info(info) {} | 1276 : info(info) {} |
| 1337 | 1277 |
| 1338 RemoteSuggestionsProvider::CategoryContent::CategoryContent(CategoryContent&&) = | 1278 RemoteSuggestionsProviderImpl::CategoryContent::CategoryContent( |
| 1339 default; | 1279 CategoryContent&&) = default; |
| 1340 | 1280 |
| 1341 RemoteSuggestionsProvider::CategoryContent::~CategoryContent() = default; | 1281 RemoteSuggestionsProviderImpl::CategoryContent::~CategoryContent() = default; |
| 1342 | 1282 |
| 1343 RemoteSuggestionsProvider::CategoryContent& | 1283 RemoteSuggestionsProviderImpl::CategoryContent& |
| 1344 RemoteSuggestionsProvider::CategoryContent::operator=(CategoryContent&&) = | 1284 RemoteSuggestionsProviderImpl::CategoryContent::operator=(CategoryContent&&) = |
| 1345 default; | 1285 default; |
| 1346 | 1286 |
| 1347 } // namespace ntp_snippets | 1287 } // namespace ntp_snippets |
| OLD | NEW |