personal_data_manager.h revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright 2013 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#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_ 6#define COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_ 7 8#include <set> 9#include <vector> 10 11#include "base/basictypes.h" 12#include "base/memory/scoped_ptr.h" 13#include "base/memory/scoped_vector.h" 14#include "base/observer_list.h" 15#include "base/strings/string16.h" 16#include "components/autofill/core/browser/autofill_metrics.h" 17#include "components/autofill/core/browser/autofill_profile.h" 18#include "components/autofill/core/browser/credit_card.h" 19#include "components/autofill/core/browser/field_types.h" 20#include "components/autofill/core/browser/webdata/autofill_webdata_service.h" 21#include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h" 22#include "components/webdata/common/web_data_service_consumer.h" 23 24class PrefService; 25class RemoveAutofillTester; 26 27namespace autofill { 28class AutofillInteractiveTest; 29class AutofillTest; 30class FormStructure; 31class PersonalDataManagerObserver; 32class PersonalDataManagerFactory; 33} // namespace autofill 34 35namespace autofill_helper { 36void SetProfiles(int, std::vector<autofill::AutofillProfile>*); 37void SetCreditCards(int, std::vector<autofill::CreditCard>*); 38} // namespace autofill_helper 39 40namespace autofill { 41 42// Handles loading and saving Autofill profile information to the web database. 43// This class also stores the profiles loaded from the database for use during 44// Autofill. 45class PersonalDataManager : public WebDataServiceConsumer, 46 public AutofillWebDataServiceObserverOnUIThread { 47 public: 48 // A pair of GUID and variant index. Represents a single FormGroup and a 49 // specific data variant. 50 typedef std::pair<std::string, size_t> GUIDPair; 51 52 explicit PersonalDataManager(const std::string& app_locale); 53 virtual ~PersonalDataManager(); 54 55 // Kicks off asynchronous loading of profiles and credit cards. 56 // |pref_service| must outlive this instance. |is_off_the_record| informs 57 // this instance whether the user is currently operating in an off-the-record 58 // context. 59 void Init(scoped_refptr<AutofillWebDataService> database, 60 PrefService* pref_service, 61 bool is_off_the_record); 62 63 // WebDataServiceConsumer: 64 virtual void OnWebDataServiceRequestDone( 65 WebDataServiceBase::Handle h, 66 const WDTypedResult* result) OVERRIDE; 67 68 // AutofillWebDataServiceObserverOnUIThread: 69 virtual void AutofillMultipleChanged() OVERRIDE; 70 71 // Adds a listener to be notified of PersonalDataManager events. 72 virtual void AddObserver(PersonalDataManagerObserver* observer); 73 74 // Removes |observer| as an observer of this PersonalDataManager. 75 virtual void RemoveObserver(PersonalDataManagerObserver* observer); 76 77 // Scans the given |form| for importable Autofill data. If the form includes 78 // sufficient address data, it is immediately imported. If the form includes 79 // sufficient credit card data, it is stored into |credit_card|, so that we 80 // can prompt the user whether to save this data. 81 // Returns |true| if sufficient address or credit card data was found. 82 bool ImportFormData(const FormStructure& form, 83 scoped_ptr<CreditCard>* credit_card); 84 85 // Saves |imported_profile| to the WebDB if it exists. Returns the guid of 86 // the new or updated profile, or the empty string if no profile was saved. 87 virtual std::string SaveImportedProfile( 88 const AutofillProfile& imported_profile); 89 90 // Saves a credit card value detected in |ImportedFormData|. Returns the guid 91 // of the new or updated card, or the empty string if no card was saved. 92 virtual std::string SaveImportedCreditCard( 93 const CreditCard& imported_credit_card); 94 95 // Adds |profile| to the web database. 96 void AddProfile(const AutofillProfile& profile); 97 98 // Updates |profile| which already exists in the web database. 99 void UpdateProfile(const AutofillProfile& profile); 100 101 // Removes the profile or credit card represented by |guid|. 102 virtual void RemoveByGUID(const std::string& guid); 103 104 // Returns the profile with the specified |guid|, or NULL if there is no 105 // profile with the specified |guid|. Both web and auxiliary profiles may 106 // be returned. 107 AutofillProfile* GetProfileByGUID(const std::string& guid); 108 109 // Adds |credit_card| to the web database. 110 void AddCreditCard(const CreditCard& credit_card); 111 112 // Updates |credit_card| which already exists in the web database. 113 void UpdateCreditCard(const CreditCard& credit_card); 114 115 // Returns the credit card with the specified |guid|, or NULL if there is 116 // no credit card with the specified |guid|. 117 CreditCard* GetCreditCardByGUID(const std::string& guid); 118 119 // Gets the field types availabe in the stored address and credit card data. 120 void GetNonEmptyTypes(ServerFieldTypeSet* non_empty_types); 121 122 // Returns true if the credit card information is stored with a password. 123 bool HasPassword(); 124 125 // Returns whether the personal data has been loaded from the web database. 126 virtual bool IsDataLoaded() const; 127 128 // This PersonalDataManager owns these profiles and credit cards. Their 129 // lifetime is until the web database is updated with new profile and credit 130 // card information, respectively. |GetProfiles()| returns both web and 131 // auxiliary profiles. |web_profiles()| returns only web profiles. 132 virtual const std::vector<AutofillProfile*>& GetProfiles() const; 133 virtual const std::vector<AutofillProfile*>& web_profiles() const; 134 virtual const std::vector<CreditCard*>& GetCreditCards() const; 135 136 // Loads profiles that can suggest data for |type|. |field_contents| is the 137 // part the user has already typed. |field_is_autofilled| is true if the field 138 // has already been autofilled. |other_field_types| represents the rest of 139 // form. Identifying info is loaded into the last four outparams. 140 void GetProfileSuggestions( 141 const AutofillType& type, 142 const base::string16& field_contents, 143 bool field_is_autofilled, 144 const std::vector<ServerFieldType>& other_field_types, 145 std::vector<base::string16>* values, 146 std::vector<base::string16>* labels, 147 std::vector<base::string16>* icons, 148 std::vector<GUIDPair>* guid_pairs); 149 150 // Gets credit cards that can suggest data for |type|. See 151 // GetProfileSuggestions for argument descriptions. The variant in each 152 // GUID pair should be ignored. 153 void GetCreditCardSuggestions( 154 const AutofillType& type, 155 const base::string16& field_contents, 156 std::vector<base::string16>* values, 157 std::vector<base::string16>* labels, 158 std::vector<base::string16>* icons, 159 std::vector<GUIDPair>* guid_pairs); 160 161 // Re-loads profiles and credit cards from the WebDatabase asynchronously. 162 // In the general case, this is a no-op and will re-create the same 163 // in-memory model as existed prior to the call. If any change occurred to 164 // profiles in the WebDatabase directly, as is the case if the browser sync 165 // engine processed a change from the cloud, we will learn of these as a 166 // result of this call. 167 // 168 // Also see SetProfile for more details. 169 virtual void Refresh(); 170 171 const std::string& app_locale() const { return app_locale_; } 172 173 // Checks suitability of |profile| for adding to the user's set of profiles. 174 static bool IsValidLearnableProfile(const AutofillProfile& profile, 175 const std::string& app_locale); 176 177 // Merges |new_profile| into one of the |existing_profiles| if possible; 178 // otherwise appends |new_profile| to the end of that list. Fills 179 // |merged_profiles| with the result. Returns the |guid| of the new or updated 180 // profile. 181 static std::string MergeProfile( 182 const AutofillProfile& new_profile, 183 const std::vector<AutofillProfile*>& existing_profiles, 184 const std::string& app_locale, 185 std::vector<AutofillProfile>* merged_profiles); 186 187 // Returns true if |country_code| is a country that the user is likely to 188 // be associated with the user. More concretely, it checks if there are any 189 // addresses with this country or if the user's system timezone is in the 190 // given country. 191 virtual bool IsCountryOfInterest(const std::string& country_code) const; 192 193 // Returns our best guess for the country a user is likely to use when 194 // inputting a new address. The value is calculated once and cached, so it 195 // will only update when Chrome is restarted. 196 virtual const std::string& GetDefaultCountryCodeForNewAddress() const; 197 198 protected: 199 // Only PersonalDataManagerFactory and certain tests can create instances of 200 // PersonalDataManager. 201 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast); 202 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup); 203 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest, 204 AggregateExistingAuxiliaryProfile); 205 friend class autofill::AutofillInteractiveTest; 206 friend class autofill::AutofillTest; 207 friend class autofill::PersonalDataManagerFactory; 208 friend class PersonalDataManagerTest; 209 friend class ProfileSyncServiceAutofillTest; 210 friend class ::RemoveAutofillTester; 211 friend class TestingAutomationProvider; 212 friend struct base::DefaultDeleter<PersonalDataManager>; 213 friend void autofill_helper::SetProfiles( 214 int, std::vector<autofill::AutofillProfile>*); 215 friend void autofill_helper::SetCreditCards( 216 int, std::vector<autofill::CreditCard>*); 217 218 // Sets |web_profiles_| to the contents of |profiles| and updates the web 219 // database by adding, updating and removing profiles. 220 // The relationship between this and Refresh is subtle. 221 // A call to |SetProfiles| could include out-of-date data that may conflict 222 // if we didn't refresh-to-latest before an Autofill window was opened for 223 // editing. |SetProfiles| is implemented to make a "best effort" to apply the 224 // changes, but in extremely rare edge cases it is possible not all of the 225 // updates in |profiles| make it to the DB. This is why SetProfiles will 226 // invoke Refresh after finishing, to ensure we get into a 227 // consistent state. See Refresh for details. 228 void SetProfiles(std::vector<AutofillProfile>* profiles); 229 230 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web 231 // database by adding, updating and removing credit cards. 232 void SetCreditCards(std::vector<CreditCard>* credit_cards); 233 234 // Loads the saved profiles from the web database. 235 virtual void LoadProfiles(); 236 237 // Loads the auxiliary profiles. Currently Mac and Android only. 238 virtual void LoadAuxiliaryProfiles() const; 239 240 // Loads the saved credit cards from the web database. 241 virtual void LoadCreditCards(); 242 243 // Receives the loaded profiles from the web data service and stores them in 244 // |credit_cards_|. 245 void ReceiveLoadedProfiles(WebDataServiceBase::Handle h, 246 const WDTypedResult* result); 247 248 // Receives the loaded credit cards from the web data service and stores them 249 // in |credit_cards_|. 250 void ReceiveLoadedCreditCards(WebDataServiceBase::Handle h, 251 const WDTypedResult* result); 252 253 // Cancels a pending query to the web database. |handle| is a pointer to the 254 // query handle. 255 void CancelPendingQuery(WebDataServiceBase::Handle* handle); 256 257 // The first time this is called, logs an UMA metrics for the number of 258 // profiles the user has. On subsequent calls, does nothing. 259 void LogProfileCount() const; 260 261 // Returns the value of the AutofillEnabled pref. 262 virtual bool IsAutofillEnabled() const; 263 264 // Overrideable for testing. 265 virtual std::string CountryCodeForCurrentTimezone() const; 266 267 // For tests. 268 const AutofillMetrics* metric_logger() const { return metric_logger_.get(); } 269 270 void set_database(scoped_refptr<AutofillWebDataService> database) { 271 database_ = database; 272 } 273 274 void set_metric_logger(const AutofillMetrics* metric_logger) { 275 metric_logger_.reset(metric_logger); 276 } 277 278 void set_pref_service(PrefService* pref_service) { 279 pref_service_ = pref_service; 280 } 281 282 // The backing database that this PersonalDataManager uses. 283 scoped_refptr<AutofillWebDataService> database_; 284 285 // True if personal data has been loaded from the web database. 286 bool is_data_loaded_; 287 288 // The loaded web profiles. 289 ScopedVector<AutofillProfile> web_profiles_; 290 291 // Auxiliary profiles. 292 mutable ScopedVector<AutofillProfile> auxiliary_profiles_; 293 294 // Storage for combined web and auxiliary profiles. Contents are weak 295 // references. Lifetime managed by |web_profiles_| and |auxiliary_profiles_|. 296 mutable std::vector<AutofillProfile*> profiles_; 297 298 // The loaded credit cards. 299 ScopedVector<CreditCard> credit_cards_; 300 301 // When the manager makes a request from WebDataServiceBase, the database 302 // is queried on another thread, we record the query handle until we 303 // get called back. We store handles for both profile and credit card queries 304 // so they can be loaded at the same time. 305 WebDataServiceBase::Handle pending_profiles_query_; 306 WebDataServiceBase::Handle pending_creditcards_query_; 307 308 // The observers. 309 ObserverList<PersonalDataManagerObserver> observers_; 310 311 private: 312 // Finds the country code that occurs most frequently among all profiles. 313 // Prefers verified profiles over unverified ones. 314 std::string MostCommonCountryCodeFromProfiles() const; 315 316 const std::string app_locale_; 317 318 // The default country code for new addresses. 319 mutable std::string default_country_code_; 320 321 // For logging UMA metrics. Overridden by metrics tests. 322 scoped_ptr<const AutofillMetrics> metric_logger_; 323 324 // The PrefService that this instance uses. Must outlive this instance. 325 PrefService* pref_service_; 326 327 // Whether the user is currently operating in an off-the-record context. 328 // Default value is false. 329 bool is_off_the_record_; 330 331 // Whether we have already logged the number of profiles this session. 332 mutable bool has_logged_profile_count_; 333 334 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager); 335}; 336 337} // namespace autofill 338 339#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_ 340