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