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