Add ability to gather metrics to BubbleManager.
[chromium-blink-merge.git] / chrome / browser / ui / webui / history_ui.cc
blob8140e2e7f22a146b82853addccb07bb9b7c51b0f
1 // Copyright (c) 2012 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.
5 #include "chrome/browser/ui/webui/history_ui.h"
7 #include <set>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h"
12 #include "base/i18n/rtl.h"
13 #include "base/i18n/time_formatting.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "base/values.h"
23 #include "chrome/browser/banners/app_banner_settings_helper.h"
24 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/history/history_service_factory.h"
27 #include "chrome/browser/history/web_history_service_factory.h"
28 #include "chrome/browser/prefs/incognito_mode_prefs.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/signin/signin_manager_factory.h"
31 #include "chrome/browser/sync/profile_sync_service.h"
32 #include "chrome/browser/sync/profile_sync_service_factory.h"
33 #include "chrome/browser/ui/browser_finder.h"
34 #include "chrome/browser/ui/chrome_pages.h"
35 #include "chrome/browser/ui/webui/favicon_source.h"
36 #include "chrome/browser/ui/webui/metrics_handler.h"
37 #include "chrome/common/chrome_switches.h"
38 #include "chrome/common/pref_names.h"
39 #include "chrome/common/url_constants.h"
40 #include "chrome/grit/generated_resources.h"
41 #include "components/bookmarks/browser/bookmark_model.h"
42 #include "components/bookmarks/browser/bookmark_utils.h"
43 #include "components/history/core/browser/history_service.h"
44 #include "components/history/core/browser/history_types.h"
45 #include "components/history/core/browser/web_history_service.h"
46 #include "components/search/search.h"
47 #include "components/signin/core/browser/signin_manager.h"
48 #include "components/sync_driver/device_info.h"
49 #include "components/url_formatter/url_formatter.h"
50 #include "content/public/browser/url_data_source.h"
51 #include "content/public/browser/web_ui.h"
52 #include "content/public/browser/web_ui_data_source.h"
53 #include "grit/browser_resources.h"
54 #include "grit/theme_resources.h"
55 #include "net/base/escape.h"
56 #include "sync/protocol/history_delete_directive_specifics.pb.h"
57 #include "ui/base/l10n/l10n_util.h"
58 #include "ui/base/l10n/time_format.h"
59 #include "ui/base/resource/resource_bundle.h"
60 #include "ui/base/webui/web_ui_util.h"
62 #if defined(ENABLE_EXTENSIONS)
63 #include "chrome/browser/extensions/activity_log/activity_log.h"
64 #endif
66 #if defined(ENABLE_SUPERVISED_USERS)
67 #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h"
68 #include "chrome/browser/supervised_user/supervised_user_service.h"
69 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
70 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
71 #endif
73 #if defined(OS_ANDROID)
74 #include "chrome/browser/android/chrome_application.h"
75 #endif
77 #if !defined(OS_ANDROID) && !defined(OS_IOS)
78 #include "chrome/browser/ui/webui/foreign_session_handler.h"
79 #include "chrome/browser/ui/webui/history_login_handler.h"
80 #endif
82 using bookmarks::BookmarkModel;
84 static const char kStringsJsFile[] = "strings.js";
85 static const char kHistoryJsFile[] = "history.js";
86 static const char kOtherDevicesJsFile[] = "other_devices.js";
88 // The amount of time to wait for a response from the WebHistoryService.
89 static const int kWebHistoryTimeoutSeconds = 3;
91 namespace {
93 // Buckets for UMA histograms.
94 enum WebHistoryQueryBuckets {
95 WEB_HISTORY_QUERY_FAILED = 0,
96 WEB_HISTORY_QUERY_SUCCEEDED,
97 WEB_HISTORY_QUERY_TIMED_OUT,
98 NUM_WEB_HISTORY_QUERY_BUCKETS
101 #if defined(OS_MACOSX)
102 const char kIncognitoModeShortcut[] = "("
103 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
104 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
105 "N)";
106 #elif defined(OS_WIN)
107 const char kIncognitoModeShortcut[] = "(Ctrl+Shift+N)";
108 #else
109 const char kIncognitoModeShortcut[] = "(Shift+Ctrl+N)";
110 #endif
112 // Identifiers for the type of device from which a history entry originated.
113 static const char kDeviceTypeLaptop[] = "laptop";
114 static const char kDeviceTypePhone[] = "phone";
115 static const char kDeviceTypeTablet[] = "tablet";
117 content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) {
118 PrefService* prefs = profile->GetPrefs();
120 // Check if the profile is authenticated. Guest profiles or incognito
121 // windows may not have a sign in manager, and are considered not
122 // authenticated.
123 SigninManagerBase* signin_manager =
124 SigninManagerFactory::GetForProfile(profile);
125 bool is_authenticated = signin_manager != nullptr &&
126 signin_manager->IsAuthenticated();
128 content::WebUIDataSource* source =
129 content::WebUIDataSource::Create(chrome::kChromeUIHistoryFrameHost);
130 source->AddBoolean("isUserSignedIn", is_authenticated);
131 source->AddLocalizedString("collapseSessionMenuItemText",
132 IDS_HISTORY_OTHER_SESSIONS_COLLAPSE_SESSION);
133 source->AddLocalizedString("expandSessionMenuItemText",
134 IDS_HISTORY_OTHER_SESSIONS_EXPAND_SESSION);
135 source->AddLocalizedString("restoreSessionMenuItemText",
136 IDS_HISTORY_OTHER_SESSIONS_OPEN_ALL);
137 source->AddLocalizedString("xMore", IDS_HISTORY_OTHER_DEVICES_X_MORE);
138 source->AddLocalizedString("loading", IDS_HISTORY_LOADING);
139 source->AddLocalizedString("title", IDS_HISTORY_TITLE);
140 source->AddLocalizedString("newest", IDS_HISTORY_NEWEST);
141 source->AddLocalizedString("newer", IDS_HISTORY_NEWER);
142 source->AddLocalizedString("older", IDS_HISTORY_OLDER);
143 source->AddLocalizedString("searchResultsFor", IDS_HISTORY_SEARCHRESULTSFOR);
144 source->AddLocalizedString("searchResult", IDS_HISTORY_SEARCH_RESULT);
145 source->AddLocalizedString("searchResults", IDS_HISTORY_SEARCH_RESULTS);
146 source->AddLocalizedString("foundSearchResults",
147 IDS_HISTORY_FOUND_SEARCH_RESULTS);
148 source->AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS);
149 source->AddLocalizedString("cont", IDS_HISTORY_CONTINUED);
150 source->AddLocalizedString("searchButton", IDS_HISTORY_SEARCH_BUTTON);
151 source->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS);
152 source->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS);
153 source->AddLocalizedString("historyInterval", IDS_HISTORY_INTERVAL);
154 source->AddLocalizedString("removeSelected",
155 IDS_HISTORY_REMOVE_SELECTED_ITEMS);
156 source->AddLocalizedString("clearAllHistory",
157 IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG);
159 auto availability = IncognitoModePrefs::GetAvailability(profile->GetPrefs());
160 base::string16 delete_warning = availability == IncognitoModePrefs::ENABLED ?
161 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING,
162 base::UTF8ToUTF16(kIncognitoModeShortcut)) :
163 l10n_util::GetStringUTF16(
164 IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING_NO_INCOGNITO);
165 source->AddString("deleteWarning", delete_warning);
167 source->AddLocalizedString("removeBookmark", IDS_HISTORY_REMOVE_BOOKMARK);
168 source->AddLocalizedString("actionMenuDescription",
169 IDS_HISTORY_ACTION_MENU_DESCRIPTION);
170 source->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE);
171 source->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE);
172 source->AddLocalizedString("groupByDomainLabel", IDS_GROUP_BY_DOMAIN_LABEL);
173 source->AddLocalizedString("rangeLabel", IDS_HISTORY_RANGE_LABEL);
174 source->AddLocalizedString("rangeAllTime", IDS_HISTORY_RANGE_ALL_TIME);
175 source->AddLocalizedString("rangeWeek", IDS_HISTORY_RANGE_WEEK);
176 source->AddLocalizedString("rangeMonth", IDS_HISTORY_RANGE_MONTH);
177 source->AddLocalizedString("rangeToday", IDS_HISTORY_RANGE_TODAY);
178 source->AddLocalizedString("rangeNext", IDS_HISTORY_RANGE_NEXT);
179 source->AddLocalizedString("rangePrevious", IDS_HISTORY_RANGE_PREVIOUS);
180 source->AddLocalizedString("numberVisits", IDS_HISTORY_NUMBER_VISITS);
181 source->AddLocalizedString("filterAllowed", IDS_HISTORY_FILTER_ALLOWED);
182 source->AddLocalizedString("filterBlocked", IDS_HISTORY_FILTER_BLOCKED);
183 source->AddLocalizedString("inContentPack", IDS_HISTORY_IN_CONTENT_PACK);
184 source->AddLocalizedString("allowItems", IDS_HISTORY_FILTER_ALLOW_ITEMS);
185 source->AddLocalizedString("blockItems", IDS_HISTORY_FILTER_BLOCK_ITEMS);
186 source->AddLocalizedString("blockedVisitText",
187 IDS_HISTORY_BLOCKED_VISIT_TEXT);
188 source->AddLocalizedString("hasSyncedResults",
189 IDS_HISTORY_HAS_SYNCED_RESULTS);
190 source->AddLocalizedString("noSyncedResults", IDS_HISTORY_NO_SYNCED_RESULTS);
191 source->AddLocalizedString("cancel", IDS_CANCEL);
192 source->AddLocalizedString("deleteConfirm",
193 IDS_HISTORY_DELETE_PRIOR_VISITS_CONFIRM_BUTTON);
194 source->AddLocalizedString("bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED);
195 source->AddLocalizedString("entrySummary", IDS_HISTORY_ENTRY_SUMMARY);
196 source->AddBoolean("isFullHistorySyncEnabled",
197 WebHistoryServiceFactory::GetForProfile(profile) != NULL);
198 bool group_by_domain = base::CommandLine::ForCurrentProcess()->HasSwitch(
199 switches::kHistoryEnableGroupByDomain);
200 // Supervised users get the "group by domain" version, but not on mobile,
201 // because that version isn't adjusted for small screens yet. crbug.com/452859
202 #if !defined(OS_ANDROID) && !defined(OS_IOS)
203 group_by_domain = group_by_domain || profile->IsSupervised();
204 #endif
205 source->AddBoolean("groupByDomain", group_by_domain);
206 bool allow_deleting_history =
207 prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory);
208 source->AddBoolean("allowDeletingHistory", allow_deleting_history);
209 source->AddBoolean("isInstantExtendedApiEnabled",
210 search::IsInstantExtendedAPIEnabled());
211 source->AddBoolean("isSupervisedProfile", profile->IsSupervised());
212 source->AddBoolean("hideDeleteVisitUI",
213 profile->IsSupervised() && !allow_deleting_history);
215 source->SetJsonPath(kStringsJsFile);
216 source->AddResourcePath(kHistoryJsFile, IDR_HISTORY_JS);
217 source->AddResourcePath(kOtherDevicesJsFile, IDR_OTHER_DEVICES_JS);
218 source->SetDefaultResource(IDR_HISTORY_HTML);
219 source->DisableDenyXFrameOptions();
221 return source;
224 // Returns a localized version of |visit_time| including a relative
225 // indicator (e.g. today, yesterday).
226 base::string16 getRelativeDateLocalized(const base::Time& visit_time) {
227 base::Time midnight = base::Time::Now().LocalMidnight();
228 base::string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight);
229 if (date_str.empty()) {
230 date_str = base::TimeFormatFriendlyDate(visit_time);
231 } else {
232 date_str = l10n_util::GetStringFUTF16(
233 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
234 date_str,
235 base::TimeFormatFriendlyDate(visit_time));
237 return date_str;
241 // Sets the correct year when substracting months from a date.
242 void normalizeMonths(base::Time::Exploded* exploded) {
243 // Decrease a year at a time until we have a proper date.
244 while (exploded->month < 1) {
245 exploded->month += 12;
246 exploded->year--;
250 // Returns true if |entry| represents a local visit that had no corresponding
251 // visit on the server.
252 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry& entry) {
253 return entry.entry_type == BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY;
256 // Gets the name and type of a device for the given sync client ID.
257 // |name| and |type| are out parameters.
258 void GetDeviceNameAndType(const ProfileSyncService* sync_service,
259 const std::string& client_id,
260 std::string* name,
261 std::string* type) {
262 // DeviceInfoTracker must be syncing in order for remote history entries to
263 // be available.
264 DCHECK(sync_service);
265 DCHECK(sync_service->GetDeviceInfoTracker());
266 DCHECK(sync_service->GetDeviceInfoTracker()->IsSyncing());
268 scoped_ptr<sync_driver::DeviceInfo> device_info =
269 sync_service->GetDeviceInfoTracker()->GetDeviceInfo(client_id);
270 if (device_info.get()) {
271 *name = device_info->client_name();
272 switch (device_info->device_type()) {
273 case sync_pb::SyncEnums::TYPE_PHONE:
274 *type = kDeviceTypePhone;
275 break;
276 case sync_pb::SyncEnums::TYPE_TABLET:
277 *type = kDeviceTypeTablet;
278 break;
279 default:
280 *type = kDeviceTypeLaptop;
282 return;
285 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE);
286 *type = kDeviceTypeLaptop;
289 } // namespace
291 ////////////////////////////////////////////////////////////////////////////////
293 // BrowsingHistoryHandler
295 ////////////////////////////////////////////////////////////////////////////////
297 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
298 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type,
299 const GURL& url, const base::string16& title, base::Time time,
300 const std::string& client_id, bool is_search_result,
301 const base::string16& snippet, bool blocked_visit,
302 const std::string& accept_languages) {
303 this->entry_type = entry_type;
304 this->url = url;
305 this->title = title;
306 this->time = time;
307 this->client_id = client_id;
308 all_timestamps.insert(time.ToInternalValue());
309 this->is_search_result = is_search_result;
310 this->snippet = snippet;
311 this->blocked_visit = blocked_visit;
312 this->accept_languages = accept_languages;
315 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
316 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) {
319 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
322 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
323 base::DictionaryValue* result) const {
324 result->SetString("url", url.spec());
326 bool using_url_as_the_title = false;
327 base::string16 title_to_set(title);
328 if (title.empty()) {
329 using_url_as_the_title = true;
330 title_to_set = base::UTF8ToUTF16(url.spec());
333 // Since the title can contain BiDi text, we need to mark the text as either
334 // RTL or LTR, depending on the characters in the string. If we use the URL
335 // as the title, we mark the title as LTR since URLs are always treated as
336 // left to right strings.
337 if (base::i18n::IsRTL()) {
338 if (using_url_as_the_title)
339 base::i18n::WrapStringWithLTRFormatting(&title_to_set);
340 else
341 base::i18n::AdjustStringForLocaleDirection(&title_to_set);
343 result->SetString("title", title_to_set);
346 scoped_ptr<base::DictionaryValue> BrowsingHistoryHandler::HistoryEntry::ToValue(
347 BookmarkModel* bookmark_model,
348 SupervisedUserService* supervised_user_service,
349 const ProfileSyncService* sync_service) const {
350 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
351 SetUrlAndTitle(result.get());
353 base::string16 domain =
354 url_formatter::IDNToUnicode(url.host(), accept_languages);
355 // When the domain is empty, use the scheme instead. This allows for a
356 // sensible treatment of e.g. file: URLs when group by domain is on.
357 if (domain.empty())
358 domain = base::UTF8ToUTF16(url.scheme() + ":");
360 // The items which are to be written into result are also described in
361 // chrome/browser/resources/history/history.js in @typedef for
362 // HistoryEntry. Please update it whenever you add or remove
363 // any keys in result.
364 result->SetString("domain", domain);
365 result->SetDouble("time", time.ToJsTime());
367 // Pass the timestamps in a list.
368 scoped_ptr<base::ListValue> timestamps(new base::ListValue);
369 for (std::set<int64>::const_iterator it = all_timestamps.begin();
370 it != all_timestamps.end(); ++it) {
371 timestamps->AppendDouble(base::Time::FromInternalValue(*it).ToJsTime());
373 result->Set("allTimestamps", timestamps.release());
375 // Always pass the short date since it is needed both in the search and in
376 // the monthly view.
377 result->SetString("dateShort", base::TimeFormatShortDate(time));
379 // Only pass in the strings we need (search results need a shortdate
380 // and snippet, browse results need day and time information).
381 if (is_search_result) {
382 result->SetString("snippet", snippet);
383 } else {
384 base::Time midnight = base::Time::Now().LocalMidnight();
385 base::string16 date_str = ui::TimeFormat::RelativeDate(time, &midnight);
386 if (date_str.empty()) {
387 date_str = base::TimeFormatFriendlyDate(time);
388 } else {
389 date_str = l10n_util::GetStringFUTF16(
390 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
391 date_str,
392 base::TimeFormatFriendlyDate(time));
394 result->SetString("dateRelativeDay", date_str);
395 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time));
397 result->SetBoolean("starred", bookmark_model->IsBookmarked(url));
399 std::string device_name;
400 std::string device_type;
401 if (!client_id.empty())
402 GetDeviceNameAndType(sync_service, client_id, &device_name, &device_type);
403 result->SetString("deviceName", device_name);
404 result->SetString("deviceType", device_type);
406 #if defined(ENABLE_SUPERVISED_USERS)
407 if (supervised_user_service) {
408 const SupervisedUserURLFilter* url_filter =
409 supervised_user_service->GetURLFilterForUIThread();
410 int filtering_behavior =
411 url_filter->GetFilteringBehaviorForURL(url.GetWithEmptyPath());
412 result->SetInteger("hostFilteringBehavior", filtering_behavior);
414 result->SetBoolean("blockedVisit", blocked_visit);
416 #endif
418 return result.Pass();
421 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
422 const BrowsingHistoryHandler::HistoryEntry& entry1,
423 const BrowsingHistoryHandler::HistoryEntry& entry2) {
424 return entry1.time > entry2.time;
427 BrowsingHistoryHandler::BrowsingHistoryHandler()
428 : has_pending_delete_request_(false),
429 history_service_observer_(this),
430 weak_factory_(this) {
433 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
434 query_task_tracker_.TryCancelAll();
435 web_history_request_.reset();
438 void BrowsingHistoryHandler::RegisterMessages() {
439 // Create our favicon data source.
440 Profile* profile = Profile::FromWebUI(web_ui());
441 content::URLDataSource::Add(
442 profile, new FaviconSource(profile, FaviconSource::ANY));
444 // Get notifications when history is cleared.
445 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
446 profile, ServiceAccessType::EXPLICIT_ACCESS);
447 if (hs)
448 history_service_observer_.Add(hs);
450 web_ui()->RegisterMessageCallback("queryHistory",
451 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory,
452 base::Unretained(this)));
453 web_ui()->RegisterMessageCallback("removeVisits",
454 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits,
455 base::Unretained(this)));
456 web_ui()->RegisterMessageCallback("clearBrowsingData",
457 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData,
458 base::Unretained(this)));
459 web_ui()->RegisterMessageCallback("removeBookmark",
460 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark,
461 base::Unretained(this)));
464 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
465 const base::ListValue* value,
466 int index,
467 int* out_int) {
468 double double_value;
469 if (value->GetDouble(index, &double_value)) {
470 *out_int = static_cast<int>(double_value);
471 return true;
473 NOTREACHED();
474 return false;
477 void BrowsingHistoryHandler::WebHistoryTimeout() {
478 // TODO(dubroy): Communicate the failure to the front end.
479 if (!query_task_tracker_.HasTrackedTasks())
480 ReturnResultsToFrontEnd();
482 UMA_HISTOGRAM_ENUMERATION(
483 "WebHistory.QueryCompletion",
484 WEB_HISTORY_QUERY_TIMED_OUT, NUM_WEB_HISTORY_QUERY_BUCKETS);
487 void BrowsingHistoryHandler::QueryHistory(
488 const base::string16& search_text,
489 const history::QueryOptions& options) {
490 Profile* profile = Profile::FromWebUI(web_ui());
492 // Anything in-flight is invalid.
493 query_task_tracker_.TryCancelAll();
494 web_history_request_.reset();
496 query_results_.clear();
497 results_info_value_.Clear();
499 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
500 profile, ServiceAccessType::EXPLICIT_ACCESS);
501 hs->QueryHistory(search_text,
502 options,
503 base::Bind(&BrowsingHistoryHandler::QueryComplete,
504 base::Unretained(this),
505 search_text,
506 options),
507 &query_task_tracker_);
509 history::WebHistoryService* web_history =
510 WebHistoryServiceFactory::GetForProfile(profile);
511 if (web_history) {
512 web_history_query_results_.clear();
513 web_history_request_ = web_history->QueryHistory(
514 search_text,
515 options,
516 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete,
517 base::Unretained(this),
518 search_text, options,
519 base::TimeTicks::Now()));
520 // Start a timer so we know when to give up.
521 web_history_timer_.Start(
522 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds),
523 this, &BrowsingHistoryHandler::WebHistoryTimeout);
525 // Set this to false until the results actually arrive.
526 results_info_value_.SetBoolean("hasSyncedResults", false);
530 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) {
531 history::QueryOptions options;
533 // Parse the arguments from JavaScript. There are five required arguments:
534 // - the text to search for (may be empty)
535 // - the offset from which the search should start (in multiples of week or
536 // month, set by the next argument).
537 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
538 // of the query.
539 // - the end time for the query. Only results older than this time will be
540 // returned.
541 // - the maximum number of results to return (may be 0, meaning that there
542 // is no maximum).
543 base::string16 search_text = ExtractStringValue(args);
544 int offset;
545 if (!args->GetInteger(1, &offset)) {
546 NOTREACHED() << "Failed to convert argument 1. ";
547 return;
549 int range;
550 if (!args->GetInteger(2, &range)) {
551 NOTREACHED() << "Failed to convert argument 2. ";
552 return;
555 if (range == BrowsingHistoryHandler::MONTH)
556 SetQueryTimeInMonths(offset, &options);
557 else if (range == BrowsingHistoryHandler::WEEK)
558 SetQueryTimeInWeeks(offset, &options);
560 double end_time;
561 if (!args->GetDouble(3, &end_time)) {
562 NOTREACHED() << "Failed to convert argument 3. ";
563 return;
565 if (end_time)
566 options.end_time = base::Time::FromJsTime(end_time);
568 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) {
569 NOTREACHED() << "Failed to convert argument 4.";
570 return;
573 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY;
574 QueryHistory(search_text, options);
577 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
578 Profile* profile = Profile::FromWebUI(web_ui());
579 // TODO(davidben): history.js is not aware of this failure and will still
580 // override |deleteCompleteCallback_|.
581 if (delete_task_tracker_.HasTrackedTasks() ||
582 has_pending_delete_request_ ||
583 !profile->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
584 web_ui()->CallJavascriptFunction("deleteFailed");
585 return;
588 history::HistoryService* history_service =
589 HistoryServiceFactory::GetForProfile(profile,
590 ServiceAccessType::EXPLICIT_ACCESS);
591 history::WebHistoryService* web_history =
592 WebHistoryServiceFactory::GetForProfile(profile);
594 base::Time now = base::Time::Now();
595 std::vector<history::ExpireHistoryArgs> expire_list;
596 expire_list.reserve(args->GetSize());
598 DCHECK(urls_to_be_deleted_.empty());
599 for (base::ListValue::const_iterator it = args->begin();
600 it != args->end(); ++it) {
601 base::DictionaryValue* deletion = NULL;
602 base::string16 url;
603 base::ListValue* timestamps = NULL;
605 // Each argument is a dictionary with properties "url" and "timestamps".
606 if (!((*it)->GetAsDictionary(&deletion) &&
607 deletion->GetString("url", &url) &&
608 deletion->GetList("timestamps", &timestamps))) {
609 NOTREACHED() << "Unable to extract arguments";
610 return;
612 DCHECK(timestamps->GetSize() > 0);
614 // In order to ensure that visits will be deleted from the server and other
615 // clients (even if they are offline), create a sync delete directive for
616 // each visit to be deleted.
617 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive;
618 sync_pb::GlobalIdDirective* global_id_directive =
619 delete_directive.mutable_global_id_directive();
621 double timestamp;
622 history::ExpireHistoryArgs* expire_args = NULL;
623 for (base::ListValue::const_iterator ts_iterator = timestamps->begin();
624 ts_iterator != timestamps->end(); ++ts_iterator) {
625 if (!(*ts_iterator)->GetAsDouble(&timestamp)) {
626 NOTREACHED() << "Unable to extract visit timestamp.";
627 continue;
629 base::Time visit_time = base::Time::FromJsTime(timestamp);
630 if (!expire_args) {
631 GURL gurl(url);
632 expire_list.resize(expire_list.size() + 1);
633 expire_args = &expire_list.back();
634 expire_args->SetTimeRangeForOneDay(visit_time);
635 expire_args->urls.insert(gurl);
636 urls_to_be_deleted_.insert(gurl);
638 // The local visit time is treated as a global ID for the visit.
639 global_id_directive->add_global_id(visit_time.ToInternalValue());
642 // Set the start and end time in microseconds since the Unix epoch.
643 global_id_directive->set_start_time_usec(
644 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds());
646 // Delete directives shouldn't have an end time in the future.
647 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
648 base::Time end_time = std::min(expire_args->end_time, now);
650 // -1 because end time in delete directives is inclusive.
651 global_id_directive->set_end_time_usec(
652 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1);
654 // TODO(dubroy): Figure out the proper way to handle an error here.
655 if (web_history)
656 history_service->ProcessLocalDeleteDirective(delete_directive);
659 history_service->ExpireHistory(
660 expire_list,
661 base::Bind(&BrowsingHistoryHandler::RemoveComplete,
662 base::Unretained(this)),
663 &delete_task_tracker_);
665 if (web_history) {
666 has_pending_delete_request_ = true;
667 web_history->ExpireHistory(
668 expire_list,
669 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete,
670 weak_factory_.GetWeakPtr()));
673 #if defined(ENABLE_EXTENSIONS)
674 // If the profile has activity logging enabled also clean up any URLs from
675 // the extension activity log. The extension activity log contains URLS
676 // which websites an extension has activity on so it will indirectly
677 // contain websites that a user has visited.
678 extensions::ActivityLog* activity_log =
679 extensions::ActivityLog::GetInstance(profile);
680 for (std::vector<history::ExpireHistoryArgs>::const_iterator it =
681 expire_list.begin(); it != expire_list.end(); ++it) {
682 activity_log->RemoveURLs(it->urls);
684 #endif
686 for (const history::ExpireHistoryArgs& expire_entry : expire_list)
687 AppBannerSettingsHelper::ClearHistoryForURLs(profile, expire_entry.urls);
690 void BrowsingHistoryHandler::HandleClearBrowsingData(
691 const base::ListValue* args) {
692 #if defined(OS_ANDROID)
693 chrome::android::ChromeApplication::OpenClearBrowsingData(
694 web_ui()->GetWebContents());
695 #else
696 // TODO(beng): This is an improper direct dependency on Browser. Route this
697 // through some sort of delegate.
698 Browser* browser = chrome::FindBrowserWithWebContents(
699 web_ui()->GetWebContents());
700 chrome::ShowClearBrowsingDataDialog(browser);
701 #endif
704 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue* args) {
705 base::string16 url = ExtractStringValue(args);
706 Profile* profile = Profile::FromWebUI(web_ui());
707 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
708 bookmarks::RemoveAllBookmarks(model, GURL(url));
711 // static
712 void BrowsingHistoryHandler::MergeDuplicateResults(
713 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) {
714 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results;
715 // Pre-reserve the size of the new vector. Since we're working with pointers
716 // later on not doing this could lead to the vector being resized and to
717 // pointers to invalid locations.
718 new_results.reserve(results->size());
719 // Maps a URL to the most recent entry on a particular day.
720 std::map<GURL, BrowsingHistoryHandler::HistoryEntry*> current_day_entries;
722 // Keeps track of the day that |current_day_urls| is holding the URLs for,
723 // in order to handle removing per-day duplicates.
724 base::Time current_day_midnight;
726 std::sort(
727 results->begin(), results->end(), HistoryEntry::SortByTimeDescending);
729 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::const_iterator it =
730 results->begin(); it != results->end(); ++it) {
731 // Reset the list of found URLs when a visit from a new day is encountered.
732 if (current_day_midnight != it->time.LocalMidnight()) {
733 current_day_entries.clear();
734 current_day_midnight = it->time.LocalMidnight();
737 // Keep this visit if it's the first visit to this URL on the current day.
738 if (current_day_entries.count(it->url) == 0) {
739 new_results.push_back(*it);
740 current_day_entries[it->url] = &new_results.back();
741 } else {
742 // Keep track of the timestamps of all visits to the URL on the same day.
743 BrowsingHistoryHandler::HistoryEntry* entry =
744 current_day_entries[it->url];
745 entry->all_timestamps.insert(
746 it->all_timestamps.begin(), it->all_timestamps.end());
748 if (entry->entry_type != it->entry_type) {
749 entry->entry_type =
750 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY;
754 results->swap(new_results);
757 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
758 Profile* profile = Profile::FromWebUI(web_ui());
759 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile);
760 SupervisedUserService* supervised_user_service = NULL;
761 #if defined(ENABLE_SUPERVISED_USERS)
762 if (profile->IsSupervised())
763 supervised_user_service =
764 SupervisedUserServiceFactory::GetForProfile(profile);
765 #endif
766 ProfileSyncService* sync_service =
767 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
769 // Combine the local and remote results into |query_results_|, and remove
770 // any duplicates.
771 if (!web_history_query_results_.empty()) {
772 int local_result_count = query_results_.size();
773 query_results_.insert(query_results_.end(),
774 web_history_query_results_.begin(),
775 web_history_query_results_.end());
776 MergeDuplicateResults(&query_results_);
778 if (local_result_count) {
779 // In the best case, we expect that all local results are duplicated on
780 // the server. Keep track of how many are missing.
781 int missing_count = std::count_if(
782 query_results_.begin(), query_results_.end(), IsLocalOnlyResult);
783 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
784 missing_count * 100.0 / local_result_count);
788 // Convert the result vector into a ListValue.
789 base::ListValue results_value;
790 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::iterator it =
791 query_results_.begin(); it != query_results_.end(); ++it) {
792 scoped_ptr<base::Value> value(
793 it->ToValue(bookmark_model, supervised_user_service, sync_service));
794 results_value.Append(value.release());
797 web_ui()->CallJavascriptFunction(
798 "historyResult", results_info_value_, results_value);
799 results_info_value_.Clear();
800 query_results_.clear();
801 web_history_query_results_.clear();
804 void BrowsingHistoryHandler::QueryComplete(
805 const base::string16& search_text,
806 const history::QueryOptions& options,
807 history::QueryResults* results) {
808 DCHECK_EQ(0U, query_results_.size());
809 query_results_.reserve(results->size());
810 const std::string accept_languages = GetAcceptLanguages();
812 for (size_t i = 0; i < results->size(); ++i) {
813 history::URLResult const &page = (*results)[i];
814 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
815 query_results_.push_back(
816 HistoryEntry(
817 HistoryEntry::LOCAL_ENTRY,
818 page.url(),
819 page.title(),
820 page.visit_time(),
821 std::string(),
822 !search_text.empty(),
823 page.snippet().text(),
824 page.blocked_visit(),
825 accept_languages));
828 // The items which are to be written into results_info_value_ are also
829 // described in chrome/browser/resources/history/history.js in @typedef for
830 // HistoryQuery. Please update it whenever you add or remove any keys in
831 // results_info_value_.
832 results_info_value_.SetString("term", search_text);
833 results_info_value_.SetBoolean("finished", results->reached_beginning());
835 // Add the specific dates that were searched to display them.
836 // TODO(sergiu): Put today if the start is in the future.
837 results_info_value_.SetString("queryStartTime",
838 getRelativeDateLocalized(options.begin_time));
839 if (!options.end_time.is_null()) {
840 results_info_value_.SetString("queryEndTime",
841 getRelativeDateLocalized(options.end_time -
842 base::TimeDelta::FromDays(1)));
843 } else {
844 results_info_value_.SetString("queryEndTime",
845 getRelativeDateLocalized(base::Time::Now()));
847 if (!web_history_timer_.IsRunning())
848 ReturnResultsToFrontEnd();
851 void BrowsingHistoryHandler::WebHistoryQueryComplete(
852 const base::string16& search_text,
853 const history::QueryOptions& options,
854 base::TimeTicks start_time,
855 history::WebHistoryService::Request* request,
856 const base::DictionaryValue* results_value) {
857 base::TimeDelta delta = base::TimeTicks::Now() - start_time;
858 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta);
859 const std::string accept_languages = GetAcceptLanguages();
861 // If the response came in too late, do nothing.
862 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
863 if (!web_history_timer_.IsRunning())
864 return;
865 web_history_timer_.Stop();
867 UMA_HISTOGRAM_ENUMERATION(
868 "WebHistory.QueryCompletion",
869 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED,
870 NUM_WEB_HISTORY_QUERY_BUCKETS);
872 DCHECK_EQ(0U, web_history_query_results_.size());
873 const base::ListValue* events = NULL;
874 if (results_value && results_value->GetList("event", &events)) {
875 web_history_query_results_.reserve(events->GetSize());
876 for (unsigned int i = 0; i < events->GetSize(); ++i) {
877 const base::DictionaryValue* event = NULL;
878 const base::DictionaryValue* result = NULL;
879 const base::ListValue* results = NULL;
880 const base::ListValue* ids = NULL;
881 base::string16 url;
882 base::string16 title;
883 base::Time visit_time;
885 if (!(events->GetDictionary(i, &event) &&
886 event->GetList("result", &results) &&
887 results->GetDictionary(0, &result) &&
888 result->GetString("url", &url) &&
889 result->GetList("id", &ids) &&
890 ids->GetSize() > 0)) {
891 LOG(WARNING) << "Improperly formed JSON response from history server.";
892 continue;
894 // Title is optional, so the return value is ignored here.
895 result->GetString("title", &title);
897 // Extract the timestamps of all the visits to this URL.
898 // They are referred to as "IDs" by the server.
899 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) {
900 const base::DictionaryValue* id = NULL;
901 std::string timestamp_string;
902 int64 timestamp_usec = 0;
904 if (!ids->GetDictionary(j, &id) ||
905 !id->GetString("timestamp_usec", &timestamp_string) ||
906 !base::StringToInt64(timestamp_string, &timestamp_usec)) {
907 NOTREACHED() << "Unable to extract timestamp.";
908 continue;
910 // The timestamp on the server is a Unix time.
911 base::Time time = base::Time::UnixEpoch() +
912 base::TimeDelta::FromMicroseconds(timestamp_usec);
914 // Get the ID of the client that this visit came from.
915 std::string client_id;
916 id->GetString("client_id", &client_id);
918 web_history_query_results_.push_back(
919 HistoryEntry(
920 HistoryEntry::REMOTE_ENTRY,
921 GURL(url),
922 title,
923 time,
924 client_id,
925 !search_text.empty(),
926 base::string16(),
927 /* blocked_visit */ false,
928 accept_languages));
931 } else if (results_value) {
932 NOTREACHED() << "Failed to parse JSON response.";
934 results_info_value_.SetBoolean("hasSyncedResults", results_value != NULL);
935 if (!query_task_tracker_.HasTrackedTasks())
936 ReturnResultsToFrontEnd();
939 void BrowsingHistoryHandler::RemoveComplete() {
940 urls_to_be_deleted_.clear();
942 // Notify the page that the deletion request is complete, but only if a web
943 // history delete request is not still pending.
944 if (!has_pending_delete_request_)
945 web_ui()->CallJavascriptFunction("deleteComplete");
948 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success) {
949 has_pending_delete_request_ = false;
950 // TODO(dubroy): Should we handle failure somehow? Delete directives will
951 // ensure that the visits are eventually deleted, so maybe it's not necessary.
952 if (!delete_task_tracker_.HasTrackedTasks())
953 RemoveComplete();
956 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
957 int offset, history::QueryOptions* options) {
958 // LocalMidnight returns the beginning of the current day so get the
959 // beginning of the next one.
960 base::Time midnight = base::Time::Now().LocalMidnight() +
961 base::TimeDelta::FromDays(1);
962 options->end_time = midnight -
963 base::TimeDelta::FromDays(7 * offset);
964 options->begin_time = midnight -
965 base::TimeDelta::FromDays(7 * (offset + 1));
968 void BrowsingHistoryHandler::SetQueryTimeInMonths(
969 int offset, history::QueryOptions* options) {
970 // Configure the begin point of the search to the start of the
971 // current month.
972 base::Time::Exploded exploded;
973 base::Time::Now().LocalMidnight().LocalExplode(&exploded);
974 exploded.day_of_month = 1;
976 if (offset == 0) {
977 options->begin_time = base::Time::FromLocalExploded(exploded);
979 // Set the end time of this first search to null (which will
980 // show results from the future, should the user's clock have
981 // been set incorrectly).
982 options->end_time = base::Time();
983 } else {
984 // Go back |offset| months in the past. The end time is not inclusive, so
985 // use the first day of the |offset| - 1 and |offset| months (e.g. for
986 // the last month, |offset| = 1, use the first days of the last month and
987 // the current month.
988 exploded.month -= offset - 1;
989 // Set the correct year.
990 normalizeMonths(&exploded);
991 options->end_time = base::Time::FromLocalExploded(exploded);
993 exploded.month -= 1;
994 // Set the correct year
995 normalizeMonths(&exploded);
996 options->begin_time = base::Time::FromLocalExploded(exploded);
1000 // Helper function for Observe that determines if there are any differences
1001 // between the URLs noticed for deletion and the ones we are expecting.
1002 static bool DeletionsDiffer(const history::URLRows& deleted_rows,
1003 const std::set<GURL>& urls_to_be_deleted) {
1004 if (deleted_rows.size() != urls_to_be_deleted.size())
1005 return true;
1006 for (const auto& i : deleted_rows) {
1007 if (urls_to_be_deleted.find(i.url()) == urls_to_be_deleted.end())
1008 return true;
1010 return false;
1013 std::string BrowsingHistoryHandler::GetAcceptLanguages() const {
1014 Profile* profile = Profile::FromWebUI(web_ui());
1015 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1018 void BrowsingHistoryHandler::OnURLsDeleted(
1019 history::HistoryService* history_service,
1020 bool all_history,
1021 bool expired,
1022 const history::URLRows& deleted_rows,
1023 const std::set<GURL>& favicon_urls) {
1024 if (all_history || DeletionsDiffer(deleted_rows, urls_to_be_deleted_))
1025 web_ui()->CallJavascriptFunction("historyDeleted");
1028 ////////////////////////////////////////////////////////////////////////////////
1030 // HistoryUI
1032 ////////////////////////////////////////////////////////////////////////////////
1034 HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
1035 web_ui->AddMessageHandler(new BrowsingHistoryHandler());
1036 web_ui->AddMessageHandler(new MetricsHandler());
1038 // On mobile we deal with foreign sessions differently.
1039 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1040 if (search::IsInstantExtendedAPIEnabled()) {
1041 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler());
1042 web_ui->AddMessageHandler(new HistoryLoginHandler());
1044 #endif
1046 // Set up the chrome://history-frame/ source.
1047 Profile* profile = Profile::FromWebUI(web_ui);
1048 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile));
1051 HistoryUI::~HistoryUI() {}
1053 // static
1054 base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes(
1055 ui::ScaleFactor scale_factor) {
1056 return ResourceBundle::GetSharedInstance().
1057 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor);