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