1 // Copyright 2014 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. 4 5 #include "chrome/browser/search/suggestions/suggestions_store.h" 6 7 #include <string> 8 9 #include "base/base64.h" 10 #include "base/prefs/pref_service.h" 11 #include "chrome/common/pref_names.h" 12 #include "components/pref_registry/pref_registry_syncable.h" 13 14 namespace suggestions { 15 SuggestionsStore(PrefService * profile_prefs)16SuggestionsStore::SuggestionsStore(PrefService* profile_prefs) 17 : pref_service_(profile_prefs) { 18 DCHECK(profile_prefs); 19 } 20 ~SuggestionsStore()21SuggestionsStore::~SuggestionsStore() {} 22 LoadSuggestions(SuggestionsProfile * suggestions)23bool SuggestionsStore::LoadSuggestions(SuggestionsProfile* suggestions) { 24 DCHECK(suggestions); 25 26 const std::string base64_suggestions_data = 27 pref_service_->GetString(prefs::kSuggestionsData); 28 if (base64_suggestions_data.empty()) { 29 suggestions->Clear(); 30 return false; 31 } 32 33 // If the decode process fails, assume the pref value is corrupt and clear it. 34 std::string suggestions_data; 35 if (!base::Base64Decode(base64_suggestions_data, &suggestions_data) || 36 !suggestions->ParseFromString(suggestions_data)) { 37 VLOG(1) << "Suggestions data in profile pref is corrupt, clearing it."; 38 suggestions->Clear(); 39 ClearSuggestions(); 40 return false; 41 } 42 43 return true; 44 } 45 StoreSuggestions(const SuggestionsProfile & suggestions)46bool SuggestionsStore::StoreSuggestions(const SuggestionsProfile& suggestions) { 47 std::string suggestions_data; 48 if (!suggestions.SerializeToString(&suggestions_data)) return false; 49 50 std::string base64_suggestions_data; 51 base::Base64Encode(suggestions_data, &base64_suggestions_data); 52 53 pref_service_->SetString(prefs::kSuggestionsData, base64_suggestions_data); 54 return true; 55 } 56 ClearSuggestions()57void SuggestionsStore::ClearSuggestions() { 58 pref_service_->ClearPref(prefs::kSuggestionsData); 59 } 60 61 // static RegisterProfilePrefs(user_prefs::PrefRegistrySyncable * registry)62void SuggestionsStore::RegisterProfilePrefs( 63 user_prefs::PrefRegistrySyncable* registry) { 64 registry->RegisterStringPref( 65 prefs::kSuggestionsData, std::string(), 66 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 67 } 68 69 } // namespace suggestions 70