blob: 7a3f5700c59e7f1226ef9dccda80157765690288 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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.
4
5#include "chrome/browser/ui/webui/history_ui.h"
6
7#include <set>
8
9#include "base/bind.h"
10#include "base/bind_helpers.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000011#include "base/command_line.h"
12#include "base/i18n/rtl.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000013#include "base/i18n/time_formatting.h"
14#include "base/memory/singleton.h"
Ben Murdoch9ab55632013-07-18 11:57:30 +010015#include "base/message_loop/message_loop.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000016#include "base/metrics/histogram.h"
17#include "base/prefs/pref_service.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010018#include "base/strings/string16.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000019#include "base/strings/string_number_conversions.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010020#include "base/strings/utf_string_conversions.h"
Ben Murdocheb525c52013-07-10 11:40:50 +010021#include "base/time/time.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000022#include "base/values.h"
23#include "chrome/browser/bookmarks/bookmark_model.h"
24#include "chrome/browser/bookmarks/bookmark_model_factory.h"
25#include "chrome/browser/bookmarks/bookmark_utils.h"
Ben Murdoch7dbb3d52013-07-17 14:55:54 +010026#include "chrome/browser/chrome_notification_types.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000027#include "chrome/browser/history/history_notifications.h"
28#include "chrome/browser/history/history_service_factory.h"
29#include "chrome/browser/history/history_types.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000030#include "chrome/browser/history/web_history_service.h"
31#include "chrome/browser/history/web_history_service_factory.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000032#include "chrome/browser/profiles/profile.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000033#include "chrome/browser/search/search.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010034#include "chrome/browser/sync/glue/device_info.h"
35#include "chrome/browser/sync/profile_sync_service.h"
36#include "chrome/browser/sync/profile_sync_service_factory.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000037#include "chrome/browser/ui/browser_finder.h"
38#include "chrome/browser/ui/chrome_pages.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000039#include "chrome/browser/ui/webui/favicon_source.h"
Ben Murdocheb525c52013-07-10 11:40:50 +010040#include "chrome/browser/ui/webui/metrics_handler.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000041#include "chrome/common/chrome_switches.h"
42#include "chrome/common/pref_names.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000043#include "chrome/common/url_constants.h"
44#include "content/public/browser/notification_details.h"
45#include "content/public/browser/notification_source.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000046#include "content/public/browser/url_data_source.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000047#include "content/public/browser/web_ui.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000048#include "content/public/browser/web_ui_data_source.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000049#include "grit/browser_resources.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000050#include "grit/generated_resources.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000051#include "grit/theme_resources.h"
52#include "net/base/escape.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000053#include "sync/protocol/history_delete_directive_specifics.pb.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000054#include "ui/base/l10n/l10n_util.h"
Ben Murdochbb1529c2013-08-08 10:24:53 +010055#include "ui/base/l10n/time_format.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000056#include "ui/base/resource/resource_bundle.h"
57
Ben Murdoch2385ea32013-08-06 11:01:04 +010058#if defined(ENABLE_MANAGED_USERS)
59#include "chrome/browser/managed_mode/managed_mode_navigation_observer.h"
60#include "chrome/browser/managed_mode/managed_mode_url_filter.h"
61#include "chrome/browser/managed_mode/managed_user_service.h"
62#include "chrome/browser/managed_mode/managed_user_service_factory.h"
63#endif
64
Torne (Richard Coles)58218062012-11-14 11:43:16 +000065#if defined(OS_ANDROID)
66#include "chrome/browser/ui/android/tab_model/tab_model.h"
67#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
68#endif
69
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000070#if !defined(OS_ANDROID) && !defined(OS_IOS)
71#include "chrome/browser/ui/webui/ntp/foreign_session_handler.h"
72#include "chrome/browser/ui/webui/ntp/ntp_login_handler.h"
73#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +000074
75static const char kStringsJsFile[] = "strings.js";
76static const char kHistoryJsFile[] = "history.js";
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000077static const char kOtherDevicesJsFile[] = "other_devices.js";
78
79// The amount of time to wait for a response from the WebHistoryService.
80static const int kWebHistoryTimeoutSeconds = 3;
Torne (Richard Coles)58218062012-11-14 11:43:16 +000081
82namespace {
83
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000084// Buckets for UMA histograms.
85enum WebHistoryQueryBuckets {
86 WEB_HISTORY_QUERY_FAILED = 0,
87 WEB_HISTORY_QUERY_SUCCEEDED,
88 WEB_HISTORY_QUERY_TIMED_OUT,
89 NUM_WEB_HISTORY_QUERY_BUCKETS
90};
91
Torne (Richard Coles)58218062012-11-14 11:43:16 +000092#if defined(OS_MACOSX)
93const char kIncognitoModeShortcut[] = "("
94 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
95 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
96 "N)";
97#elif defined(OS_WIN)
98const char kIncognitoModeShortcut[] = "(Ctrl+Shift+N)";
99#else
100const char kIncognitoModeShortcut[] = "(Shift+Ctrl+N)";
101#endif
102
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100103// Identifiers for the type of device from which a history entry originated.
104static const char kDeviceTypeLaptop[] = "laptop";
105static const char kDeviceTypePhone[] = "phone";
106static const char kDeviceTypeTablet[] = "tablet";
107
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000108content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100109 PrefService* prefs = profile->GetPrefs();
110
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000111 content::WebUIDataSource* source =
112 content::WebUIDataSource::Create(chrome::kChromeUIHistoryFrameHost);
113 source->AddBoolean("isUserSignedIn",
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100114 !prefs->GetString(prefs::kGoogleServicesUsername).empty());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000115 source->AddLocalizedString("collapseSessionMenuItemText",
116 IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION);
117 source->AddLocalizedString("expandSessionMenuItemText",
118 IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION);
119 source->AddLocalizedString("restoreSessionMenuItemText",
120 IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL);
121 source->AddLocalizedString("xMore", IDS_OTHER_DEVICES_X_MORE);
122 source->AddLocalizedString("loading", IDS_HISTORY_LOADING);
123 source->AddLocalizedString("title", IDS_HISTORY_TITLE);
124 source->AddLocalizedString("newest", IDS_HISTORY_NEWEST);
125 source->AddLocalizedString("newer", IDS_HISTORY_NEWER);
126 source->AddLocalizedString("older", IDS_HISTORY_OLDER);
127 source->AddLocalizedString("searchResultsFor", IDS_HISTORY_SEARCHRESULTSFOR);
128 source->AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS);
129 source->AddLocalizedString("cont", IDS_HISTORY_CONTINUED);
130 source->AddLocalizedString("searchButton", IDS_HISTORY_SEARCH_BUTTON);
131 source->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS);
132 source->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS);
133 source->AddLocalizedString("historyInterval", IDS_HISTORY_INTERVAL);
134 source->AddLocalizedString("removeSelected",
135 IDS_HISTORY_REMOVE_SELECTED_ITEMS);
136 source->AddLocalizedString("clearAllHistory",
137 IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG);
138 source->AddString(
139 "deleteWarning",
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000140 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING,
141 UTF8ToUTF16(kIncognitoModeShortcut)));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000142 source->AddLocalizedString("actionMenuDescription",
143 IDS_HISTORY_ACTION_MENU_DESCRIPTION);
144 source->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE);
145 source->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE);
146 source->AddLocalizedString("groupByDomainLabel", IDS_GROUP_BY_DOMAIN_LABEL);
147 source->AddLocalizedString("rangeLabel", IDS_HISTORY_RANGE_LABEL);
148 source->AddLocalizedString("rangeAllTime", IDS_HISTORY_RANGE_ALL_TIME);
149 source->AddLocalizedString("rangeWeek", IDS_HISTORY_RANGE_WEEK);
150 source->AddLocalizedString("rangeMonth", IDS_HISTORY_RANGE_MONTH);
151 source->AddLocalizedString("rangeToday", IDS_HISTORY_RANGE_TODAY);
152 source->AddLocalizedString("rangeNext", IDS_HISTORY_RANGE_NEXT);
153 source->AddLocalizedString("rangePrevious", IDS_HISTORY_RANGE_PREVIOUS);
154 source->AddLocalizedString("numberVisits", IDS_HISTORY_NUMBER_VISITS);
155 source->AddLocalizedString("filterAllowed", IDS_HISTORY_FILTER_ALLOWED);
156 source->AddLocalizedString("filterBlocked", IDS_HISTORY_FILTER_BLOCKED);
157 source->AddLocalizedString("inContentPack", IDS_HISTORY_IN_CONTENT_PACK);
158 source->AddLocalizedString("allowItems", IDS_HISTORY_FILTER_ALLOW_ITEMS);
159 source->AddLocalizedString("blockItems", IDS_HISTORY_FILTER_BLOCK_ITEMS);
160 source->AddLocalizedString("lockButton", IDS_HISTORY_LOCK_BUTTON);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100161 source->AddLocalizedString("blockedVisitText",
162 IDS_HISTORY_BLOCKED_VISIT_TEXT);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000163 source->AddLocalizedString("unlockButton", IDS_HISTORY_UNLOCK_BUTTON);
164 source->AddLocalizedString("hasSyncedResults",
165 IDS_HISTORY_HAS_SYNCED_RESULTS);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100166 source->AddLocalizedString("noSyncedResults", IDS_HISTORY_NO_SYNCED_RESULTS);
167 source->AddLocalizedString("cancel", IDS_CANCEL);
168 source->AddLocalizedString("deleteConfirm",
169 IDS_HISTORY_DELETE_PRIOR_VISITS_CONFIRM_BUTTON);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000170 source->AddBoolean("isFullHistorySyncEnabled",
171 WebHistoryServiceFactory::GetForProfile(profile) != NULL);
172 source->AddBoolean("groupByDomain",
173 CommandLine::ForCurrentProcess()->HasSwitch(
174 switches::kHistoryEnableGroupByDomain));
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100175 source->AddBoolean("allowDeletingHistory",
Ben Murdoch558790d2013-07-30 15:19:42 +0100176 prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
177 source->AddBoolean("isInstantExtendedApiEnabled",
178 chrome::IsInstantExtendedAPIEnabled());
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100179
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000180 source->SetJsonPath(kStringsJsFile);
181 source->AddResourcePath(kHistoryJsFile, IDR_HISTORY_JS);
182 source->AddResourcePath(kOtherDevicesJsFile, IDR_OTHER_DEVICES_JS);
183 source->SetDefaultResource(IDR_HISTORY_HTML);
184 source->SetUseJsonJSFormatV2();
185 source->DisableDenyXFrameOptions();
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100186 source->AddBoolean("isManagedProfile", profile->IsManaged());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000187
188 return source;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000189}
190
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000191// Returns a localized version of |visit_time| including a relative
192// indicator (e.g. today, yesterday).
193string16 getRelativeDateLocalized(const base::Time& visit_time) {
194 base::Time midnight = base::Time::Now().LocalMidnight();
Ben Murdochbb1529c2013-08-08 10:24:53 +0100195 string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000196 if (date_str.empty()) {
197 date_str = base::TimeFormatFriendlyDate(visit_time);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000198 } else {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000199 date_str = l10n_util::GetStringFUTF16(
200 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
201 date_str,
202 base::TimeFormatFriendlyDate(visit_time));
203 }
204 return date_str;
205}
206
207
208// Sets the correct year when substracting months from a date.
209void normalizeMonths(base::Time::Exploded* exploded) {
210 // Decrease a year at a time until we have a proper date.
211 while (exploded->month < 1) {
212 exploded->month += 12;
213 exploded->year--;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000214 }
215}
216
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000217// Returns the URL of a query result value.
218bool GetResultTimeAndUrl(Value* result, base::Time* time, string16* url) {
219 DictionaryValue* result_dict;
220 double timestamp;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000221
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000222 if (result->GetAsDictionary(&result_dict) &&
223 result_dict->GetDouble("time", &timestamp) &&
224 result_dict->GetString("url", url)) {
225 *time = base::Time::FromJsTime(timestamp);
226 return true;
227 }
228 return false;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000229}
230
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000231// Returns true if |entry| represents a local visit that had no corresponding
232// visit on the server.
233bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry& entry) {
234 return entry.entry_type == BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY;
235}
236
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100237// Gets the name and type of a device for the given sync client ID.
238// |name| and |type| are out parameters.
239void GetDeviceNameAndType(const ProfileSyncService* sync_service,
240 const std::string& client_id,
241 std::string* name,
242 std::string* type) {
243 if (sync_service && sync_service->sync_initialized()) {
244 scoped_ptr<browser_sync::DeviceInfo> device_info =
245 sync_service->GetDeviceInfo(client_id);
246 if (device_info.get()) {
247 *name = device_info->client_name();
248 switch (device_info->device_type()) {
249 case sync_pb::SyncEnums::TYPE_PHONE:
250 *type = kDeviceTypePhone;
251 break;
252 case sync_pb::SyncEnums::TYPE_TABLET:
253 *type = kDeviceTypeTablet;
254 break;
255 default:
256 *type = kDeviceTypeLaptop;
257 }
258 return;
259 }
260 } else {
261 NOTREACHED() << "Got a remote history entry but no ProfileSyncService.";
262 }
263 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE);
264 *type = kDeviceTypeLaptop;
265}
266
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000267} // namespace
268
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000269////////////////////////////////////////////////////////////////////////////////
270//
271// BrowsingHistoryHandler
272//
273////////////////////////////////////////////////////////////////////////////////
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000274
275BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
276 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type,
277 const GURL& url, const string16& title, base::Time time,
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100278 const std::string& client_id, bool is_search_result,
279 const string16& snippet, bool blocked_visit) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000280 this->entry_type = entry_type;
281 this->url = url;
282 this->title = title;
283 this->time = time;
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100284 this->client_id = client_id;
285 all_timestamps.insert(time.ToInternalValue());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000286 this->is_search_result = is_search_result;
287 this->snippet = snippet;
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100288 this->blocked_visit = blocked_visit;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000289}
290
291BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100292 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000293}
294
295BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
296}
297
298void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
299 DictionaryValue* result) const {
300 result->SetString("url", url.spec());
301
302 bool using_url_as_the_title = false;
303 string16 title_to_set(title);
304 if (title.empty()) {
305 using_url_as_the_title = true;
306 title_to_set = UTF8ToUTF16(url.spec());
307 }
308
309 // Since the title can contain BiDi text, we need to mark the text as either
310 // RTL or LTR, depending on the characters in the string. If we use the URL
311 // as the title, we mark the title as LTR since URLs are always treated as
312 // left to right strings.
313 if (base::i18n::IsRTL()) {
314 if (using_url_as_the_title)
315 base::i18n::WrapStringWithLTRFormatting(&title_to_set);
316 else
317 base::i18n::AdjustStringForLocaleDirection(&title_to_set);
318 }
319 result->SetString("title", title_to_set);
320}
321
322scoped_ptr<DictionaryValue> BrowsingHistoryHandler::HistoryEntry::ToValue(
323 BookmarkModel* bookmark_model,
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100324 ManagedUserService* managed_user_service,
325 const ProfileSyncService* sync_service) const {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000326 scoped_ptr<DictionaryValue> result(new DictionaryValue());
327 SetUrlAndTitle(result.get());
328 result->SetDouble("time", time.ToJsTime());
329
330 // Pass the timestamps in a list.
331 scoped_ptr<ListValue> timestamps(new ListValue);
332 for (std::set<int64>::const_iterator it = all_timestamps.begin();
333 it != all_timestamps.end(); ++it) {
334 timestamps->AppendDouble(base::Time::FromInternalValue(*it).ToJsTime());
335 }
336 result->Set("allTimestamps", timestamps.release());
337
338 // Always pass the short date since it is needed both in the search and in
339 // the monthly view.
340 result->SetString("dateShort", base::TimeFormatShortDate(time));
341
342 // Only pass in the strings we need (search results need a shortdate
343 // and snippet, browse results need day and time information).
344 if (is_search_result) {
345 result->SetString("snippet", snippet);
346 } else {
347 base::Time midnight = base::Time::Now().LocalMidnight();
Ben Murdochbb1529c2013-08-08 10:24:53 +0100348 string16 date_str = ui::TimeFormat::RelativeDate(time, &midnight);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000349 if (date_str.empty()) {
350 date_str = base::TimeFormatFriendlyDate(time);
351 } else {
352 date_str = l10n_util::GetStringFUTF16(
353 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
354 date_str,
355 base::TimeFormatFriendlyDate(time));
356 }
357 result->SetString("dateRelativeDay", date_str);
358 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time));
359 }
360 result->SetBoolean("starred", bookmark_model->IsBookmarked(url));
361
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100362 std::string device_name;
363 std::string device_type;
364 if (!client_id.empty())
365 GetDeviceNameAndType(sync_service, client_id, &device_name, &device_type);
366 result->SetString("deviceName", device_name);
367 result->SetString("deviceType", device_type);
368
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000369#if defined(ENABLE_MANAGED_USERS)
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100370 if (managed_user_service) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100371 const ManagedModeURLFilter* url_filter =
372 managed_user_service->GetURLFilterForUIThread();
373 int filtering_behavior =
374 url_filter->GetFilteringBehaviorForURL(url.GetWithEmptyPath());
375 result->SetInteger("hostFilteringBehavior", filtering_behavior);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100376
377 result->SetBoolean("blockedVisit", blocked_visit);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000378 }
379#endif
380
381 return result.Pass();
382}
383
384bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
385 const BrowsingHistoryHandler::HistoryEntry& entry1,
386 const BrowsingHistoryHandler::HistoryEntry& entry2) {
387 return entry1.time > entry2.time;
388}
389
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000390BrowsingHistoryHandler::BrowsingHistoryHandler() {}
391
392BrowsingHistoryHandler::~BrowsingHistoryHandler() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000393 history_request_consumer_.CancelAllRequests();
394 web_history_request_.reset();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000395}
396
397void BrowsingHistoryHandler::RegisterMessages() {
398 // Create our favicon data source.
399 Profile* profile = Profile::FromWebUI(web_ui());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000400 content::URLDataSource::Add(
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100401 profile, new FaviconSource(profile, FaviconSource::ANY));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000402
403 // Get notifications when history is cleared.
404 registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED,
405 content::Source<Profile>(profile->GetOriginalProfile()));
406
407 web_ui()->RegisterMessageCallback("queryHistory",
408 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory,
409 base::Unretained(this)));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000410 web_ui()->RegisterMessageCallback("removeVisits",
411 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000412 base::Unretained(this)));
413 web_ui()->RegisterMessageCallback("clearBrowsingData",
414 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData,
415 base::Unretained(this)));
416 web_ui()->RegisterMessageCallback("removeBookmark",
417 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark,
418 base::Unretained(this)));
419}
420
421bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(const ListValue* value,
422 int index,
423 int* out_int) {
424 double double_value;
425 if (value->GetDouble(index, &double_value)) {
426 *out_int = static_cast<int>(double_value);
427 return true;
428 }
429 NOTREACHED();
430 return false;
431}
432
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000433void BrowsingHistoryHandler::WebHistoryTimeout() {
434 // TODO(dubroy): Communicate the failure to the front end.
435 if (!history_request_consumer_.HasPendingRequests())
436 ReturnResultsToFrontEnd();
437
438 UMA_HISTOGRAM_ENUMERATION(
439 "WebHistory.QueryCompletion",
440 WEB_HISTORY_QUERY_TIMED_OUT, NUM_WEB_HISTORY_QUERY_BUCKETS);
441}
442
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000443void BrowsingHistoryHandler::QueryHistory(
444 string16 search_text, const history::QueryOptions& options) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000445 Profile* profile = Profile::FromWebUI(web_ui());
446
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000447 // Anything in-flight is invalid.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000448 history_request_consumer_.CancelAllRequests();
449 web_history_request_.reset();
450
451 query_results_.clear();
452 results_info_value_.Clear();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000453
454 HistoryService* hs = HistoryServiceFactory::GetForProfile(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000455 profile, Profile::EXPLICIT_ACCESS);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000456 hs->QueryHistory(search_text,
457 options,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000458 &history_request_consumer_,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000459 base::Bind(&BrowsingHistoryHandler::QueryComplete,
460 base::Unretained(this), search_text, options));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000461
462 history::WebHistoryService* web_history =
463 WebHistoryServiceFactory::GetForProfile(profile);
464 if (web_history) {
465 web_history_query_results_.clear();
466 web_history_request_ = web_history->QueryHistory(
467 search_text,
468 options,
469 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete,
470 base::Unretained(this),
471 search_text, options,
472 base::TimeTicks::Now()));
473 // Start a timer so we know when to give up.
474 web_history_timer_.Start(
475 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds),
476 this, &BrowsingHistoryHandler::WebHistoryTimeout);
477
478 // Set this to false until the results actually arrive.
479 results_info_value_.SetBoolean("hasSyncedResults", false);
480 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000481}
482
483void BrowsingHistoryHandler::HandleQueryHistory(const ListValue* args) {
484 history::QueryOptions options;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000485
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000486 // Parse the arguments from JavaScript. There are five required arguments:
487 // - the text to search for (may be empty)
488 // - the offset from which the search should start (in multiples of week or
489 // month, set by the next argument).
490 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
491 // of the query.
492 // - the end time for the query. Only results older than this time will be
493 // returned.
494 // - the maximum number of results to return (may be 0, meaning that there
495 // is no maximum).
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000496 string16 search_text = ExtractStringValue(args);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000497 int offset;
498 if (!args->GetInteger(1, &offset)) {
499 NOTREACHED() << "Failed to convert argument 1. ";
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000500 return;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000501 }
502 int range;
503 if (!args->GetInteger(2, &range)) {
504 NOTREACHED() << "Failed to convert argument 2. ";
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000505 return;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000506 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000507
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000508 if (range == BrowsingHistoryHandler::MONTH)
509 SetQueryTimeInMonths(offset, &options);
510 else if (range == BrowsingHistoryHandler::WEEK)
511 SetQueryTimeInWeeks(offset, &options);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000512
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000513 double end_time;
514 if (!args->GetDouble(3, &end_time)) {
515 NOTREACHED() << "Failed to convert argument 3. ";
516 return;
517 }
518 if (end_time)
519 options.end_time = base::Time::FromJsTime(end_time);
520
521 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) {
522 NOTREACHED() << "Failed to convert argument 4.";
523 return;
524 }
525
526 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000527 QueryHistory(search_text, options);
528}
529
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000530void BrowsingHistoryHandler::HandleRemoveVisits(const ListValue* args) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100531 Profile* profile = Profile::FromWebUI(web_ui());
532 if (delete_task_tracker_.HasTrackedTasks() ||
533 !profile->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000534 web_ui()->CallJavascriptFunction("deleteFailed");
535 return;
536 }
537
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000538 HistoryService* history_service =
539 HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS);
540 history::WebHistoryService* web_history =
541 WebHistoryServiceFactory::GetForProfile(profile);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000542
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000543 base::Time now = base::Time::Now();
544 std::vector<history::ExpireHistoryArgs> expire_list;
545 expire_list.reserve(args->GetSize());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000546
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100547 DCHECK(urls_to_be_deleted_.empty());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000548 for (ListValue::const_iterator it = args->begin(); it != args->end(); ++it) {
549 DictionaryValue* deletion = NULL;
550 string16 url;
551 ListValue* timestamps = NULL;
552
553 // Each argument is a dictionary with properties "url" and "timestamps".
554 if (!((*it)->GetAsDictionary(&deletion) &&
555 deletion->GetString("url", &url) &&
556 deletion->GetList("timestamps", &timestamps))) {
557 NOTREACHED() << "Unable to extract arguments";
558 return;
559 }
560 DCHECK(timestamps->GetSize() > 0);
561
562 // In order to ensure that visits will be deleted from the server and other
563 // clients (even if they are offline), create a sync delete directive for
564 // each visit to be deleted.
565 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive;
566 sync_pb::GlobalIdDirective* global_id_directive =
567 delete_directive.mutable_global_id_directive();
568
569 double timestamp;
570 history::ExpireHistoryArgs* expire_args = NULL;
571 for (ListValue::const_iterator ts_iterator = timestamps->begin();
572 ts_iterator != timestamps->end(); ++ts_iterator) {
573 if (!(*ts_iterator)->GetAsDouble(&timestamp)) {
574 NOTREACHED() << "Unable to extract visit timestamp.";
575 continue;
576 }
577 base::Time visit_time = base::Time::FromJsTime(timestamp);
578 if (!expire_args) {
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100579 GURL gurl(url);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000580 expire_list.resize(expire_list.size() + 1);
581 expire_args = &expire_list.back();
582 expire_args->SetTimeRangeForOneDay(visit_time);
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100583 expire_args->urls.insert(gurl);
584 urls_to_be_deleted_.insert(gurl);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000585 }
586 // The local visit time is treated as a global ID for the visit.
587 global_id_directive->add_global_id(visit_time.ToInternalValue());
588 }
589
590 // Set the start and end time in microseconds since the Unix epoch.
591 global_id_directive->set_start_time_usec(
592 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds());
593
594 // Delete directives shouldn't have an end time in the future.
595 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
596 base::Time end_time = std::min(expire_args->end_time, now);
597
598 // -1 because end time in delete directives is inclusive.
599 global_id_directive->set_end_time_usec(
600 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1);
601
602 // TODO(dubroy): Figure out the proper way to handle an error here.
603 if (web_history)
604 history_service->ProcessLocalDeleteDirective(delete_directive);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000605 }
606
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000607 history_service->ExpireHistory(
608 expire_list,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000609 base::Bind(&BrowsingHistoryHandler::RemoveComplete,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000610 base::Unretained(this)),
611 &delete_task_tracker_);
612
613 if (web_history) {
614 web_history_delete_request_ = web_history->ExpireHistory(
615 expire_list,
616 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete,
617 base::Unretained(this)));
618 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000619}
620
621void BrowsingHistoryHandler::HandleClearBrowsingData(const ListValue* args) {
622#if defined(OS_ANDROID)
623 Profile* profile = Profile::FromWebUI(web_ui());
624 const TabModel* tab_model =
625 TabModelList::GetTabModelWithProfile(profile);
626 if (tab_model)
627 tab_model->OpenClearBrowsingData();
628#else
629 // TODO(beng): This is an improper direct dependency on Browser. Route this
630 // through some sort of delegate.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000631 Browser* browser = chrome::FindBrowserWithWebContents(
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000632 web_ui()->GetWebContents());
633 chrome::ShowClearBrowsingDataDialog(browser);
634#endif
635}
636
637void BrowsingHistoryHandler::HandleRemoveBookmark(const ListValue* args) {
638 string16 url = ExtractStringValue(args);
639 Profile* profile = Profile::FromWebUI(web_ui());
640 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
641 bookmark_utils::RemoveAllBookmarks(model, GURL(url));
642}
643
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000644// static
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100645void BrowsingHistoryHandler::MergeDuplicateResults(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000646 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) {
647 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results;
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100648 // Pre-reserve the size of the new vector. Since we're working with pointers
649 // later on not doing this could lead to the vector being resized and to
650 // pointers to invalid locations.
651 new_results.reserve(results->size());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000652 // Maps a URL to the most recent entry on a particular day.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100653 std::map<GURL,BrowsingHistoryHandler::HistoryEntry*>
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000654 current_day_entries;
655
656 // Keeps track of the day that |current_day_urls| is holding the URLs for,
657 // in order to handle removing per-day duplicates.
658 base::Time current_day_midnight;
659
660 std::sort(
661 results->begin(), results->end(), HistoryEntry::SortByTimeDescending);
662
663 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::const_iterator it =
664 results->begin(); it != results->end(); ++it) {
665 // Reset the list of found URLs when a visit from a new day is encountered.
666 if (current_day_midnight != it->time.LocalMidnight()) {
667 current_day_entries.clear();
668 current_day_midnight = it->time.LocalMidnight();
669 }
670
671 // Keep this visit if it's the first visit to this URL on the current day.
672 if (current_day_entries.count(it->url) == 0) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000673 new_results.push_back(*it);
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100674 current_day_entries[it->url] = &new_results.back();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000675 } else {
676 // Keep track of the timestamps of all visits to the URL on the same day.
677 BrowsingHistoryHandler::HistoryEntry* entry =
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100678 current_day_entries[it->url];
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000679 entry->all_timestamps.insert(
680 it->all_timestamps.begin(), it->all_timestamps.end());
681
682 if (entry->entry_type != it->entry_type) {
683 entry->entry_type =
684 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY;
685 }
686 }
687 }
688 results->swap(new_results);
689}
690
691void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
692 Profile* profile = Profile::FromWebUI(web_ui());
693 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile);
694 ManagedUserService* managed_user_service = NULL;
695#if defined(ENABLE_MANAGED_USERS)
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100696 if (profile->IsManaged())
697 managed_user_service = ManagedUserServiceFactory::GetForProfile(profile);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000698#endif
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100699 ProfileSyncService* sync_service =
700 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000701
702 // Combine the local and remote results into |query_results_|, and remove
703 // any duplicates.
704 if (!web_history_query_results_.empty()) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000705 int local_result_count = query_results_.size();
706 query_results_.insert(query_results_.end(),
707 web_history_query_results_.begin(),
708 web_history_query_results_.end());
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100709 MergeDuplicateResults(&query_results_);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000710
711 if (local_result_count) {
712 // In the best case, we expect that all local results are duplicated on
713 // the server. Keep track of how many are missing.
714 int missing_count = std::count_if(
715 query_results_.begin(), query_results_.end(), IsLocalOnlyResult);
716 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
717 missing_count * 100.0 / local_result_count);
718 }
719 }
720
721 // Convert the result vector into a ListValue.
722 ListValue results_value;
723 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::iterator it =
724 query_results_.begin(); it != query_results_.end(); ++it) {
725 scoped_ptr<base::Value> value(
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100726 it->ToValue(bookmark_model, managed_user_service, sync_service));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000727 results_value.Append(value.release());
728 }
729
730 web_ui()->CallJavascriptFunction(
731 "historyResult", results_info_value_, results_value);
732 results_info_value_.Clear();
733 query_results_.clear();
734 web_history_query_results_.clear();
735}
736
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000737void BrowsingHistoryHandler::QueryComplete(
738 const string16& search_text,
739 const history::QueryOptions& options,
740 HistoryService::Handle request_handle,
741 history::QueryResults* results) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000742 DCHECK_EQ(0U, query_results_.size());
743 query_results_.reserve(results->size());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000744
745 for (size_t i = 0; i < results->size(); ++i) {
746 history::URLResult const &page = (*results)[i];
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100747 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000748 query_results_.push_back(
749 HistoryEntry(
750 HistoryEntry::LOCAL_ENTRY,
751 page.url(),
752 page.title(),
753 page.visit_time(),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100754 std::string(),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000755 !search_text.empty(),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100756 page.snippet().text(),
757 page.blocked_visit()));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000758 }
759
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000760 results_info_value_.SetString("term", search_text);
761 results_info_value_.SetBoolean("finished", results->reached_beginning());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000762
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000763 // Add the specific dates that were searched to display them.
764 // TODO(sergiu): Put today if the start is in the future.
765 results_info_value_.SetString("queryStartTime",
766 getRelativeDateLocalized(options.begin_time));
767 if (!options.end_time.is_null()) {
768 results_info_value_.SetString("queryEndTime",
769 getRelativeDateLocalized(options.end_time -
770 base::TimeDelta::FromDays(1)));
771 } else {
772 results_info_value_.SetString("queryEndTime",
773 getRelativeDateLocalized(base::Time::Now()));
774 }
775 if (!web_history_timer_.IsRunning())
776 ReturnResultsToFrontEnd();
777}
778
779void BrowsingHistoryHandler::WebHistoryQueryComplete(
780 const string16& search_text,
781 const history::QueryOptions& options,
782 base::TimeTicks start_time,
783 history::WebHistoryService::Request* request,
784 const DictionaryValue* results_value) {
785 base::TimeDelta delta = base::TimeTicks::Now() - start_time;
786 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta);
787
788 // If the response came in too late, do nothing.
789 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
790 if (!web_history_timer_.IsRunning())
791 return;
792 web_history_timer_.Stop();
793
794 UMA_HISTOGRAM_ENUMERATION(
795 "WebHistory.QueryCompletion",
796 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED,
797 NUM_WEB_HISTORY_QUERY_BUCKETS);
798
799 DCHECK_EQ(0U, web_history_query_results_.size());
800 const ListValue* events = NULL;
801 if (results_value && results_value->GetList("event", &events)) {
802 web_history_query_results_.reserve(events->GetSize());
803 for (unsigned int i = 0; i < events->GetSize(); ++i) {
804 const DictionaryValue* event = NULL;
805 const DictionaryValue* result = NULL;
806 const ListValue* results = NULL;
807 const ListValue* ids = NULL;
808 string16 url;
809 string16 title;
810 base::Time visit_time;
811
812 if (!(events->GetDictionary(i, &event) &&
813 event->GetList("result", &results) &&
814 results->GetDictionary(0, &result) &&
815 result->GetString("url", &url) &&
816 result->GetList("id", &ids) &&
817 ids->GetSize() > 0)) {
818 LOG(WARNING) << "Improperly formed JSON response from history server.";
819 continue;
820 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000821 // Title is optional, so the return value is ignored here.
822 result->GetString("title", &title);
823
824 // Extract the timestamps of all the visits to this URL.
825 // They are referred to as "IDs" by the server.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000826 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) {
827 const DictionaryValue* id = NULL;
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100828 std::string timestamp_string;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000829 int64 timestamp_usec;
830
831 if (!(ids->GetDictionary(j, &id) &&
832 id->GetString("timestamp_usec", &timestamp_string) &&
833 base::StringToInt64(timestamp_string, &timestamp_usec))) {
834 NOTREACHED() << "Unable to extract timestamp.";
835 continue;
836 }
837 // The timestamp on the server is a Unix time.
838 base::Time time = base::Time::UnixEpoch() +
839 base::TimeDelta::FromMicroseconds(timestamp_usec);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000840
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100841 // Get the ID of the client that this visit came from.
842 std::string client_id;
843 id->GetString("client_id", &client_id);
844
845 web_history_query_results_.push_back(
846 HistoryEntry(
847 HistoryEntry::REMOTE_ENTRY,
848 GURL(url),
849 title,
850 time,
851 client_id,
852 !search_text.empty(),
853 string16(),
854 /* blocked_visit */ false));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000855 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000856 }
857 } else if (results_value) {
858 NOTREACHED() << "Failed to parse JSON response.";
859 }
860 results_info_value_.SetBoolean("hasSyncedResults", results_value != NULL);
861 if (!history_request_consumer_.HasPendingRequests())
862 ReturnResultsToFrontEnd();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000863}
864
865void BrowsingHistoryHandler::RemoveComplete() {
866 urls_to_be_deleted_.clear();
867
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100868 // Notify the page that the deletion request is complete, but only if a web
869 // history delete request is not still pending.
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100870 if (!(web_history_delete_request_.get() &&
871 web_history_delete_request_->is_pending())) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100872 web_ui()->CallJavascriptFunction("deleteComplete");
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100873 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000874}
875
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000876void BrowsingHistoryHandler::RemoveWebHistoryComplete(
877 history::WebHistoryService::Request* request, bool success) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100878 // TODO(dubroy): Should we handle failure somehow? Delete directives will
879 // ensure that the visits are eventually deleted, so maybe it's not necessary.
880 if (!delete_task_tracker_.HasTrackedTasks())
881 RemoveComplete();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000882}
883
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000884void BrowsingHistoryHandler::SetQueryTimeInWeeks(
885 int offset, history::QueryOptions* options) {
886 // LocalMidnight returns the beginning of the current day so get the
887 // beginning of the next one.
888 base::Time midnight = base::Time::Now().LocalMidnight() +
889 base::TimeDelta::FromDays(1);
890 options->end_time = midnight -
891 base::TimeDelta::FromDays(7 * offset);
892 options->begin_time = midnight -
893 base::TimeDelta::FromDays(7 * (offset + 1));
894}
895
896void BrowsingHistoryHandler::SetQueryTimeInMonths(
897 int offset, history::QueryOptions* options) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000898 // Configure the begin point of the search to the start of the
899 // current month.
900 base::Time::Exploded exploded;
901 base::Time::Now().LocalMidnight().LocalExplode(&exploded);
902 exploded.day_of_month = 1;
903
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000904 if (offset == 0) {
905 options->begin_time = base::Time::FromLocalExploded(exploded);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000906
907 // Set the end time of this first search to null (which will
908 // show results from the future, should the user's clock have
909 // been set incorrectly).
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000910 options->end_time = base::Time();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000911 } else {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000912 // Go back |offset| months in the past. The end time is not inclusive, so
913 // use the first day of the |offset| - 1 and |offset| months (e.g. for
914 // the last month, |offset| = 1, use the first days of the last month and
915 // the current month.
916 exploded.month -= offset - 1;
917 // Set the correct year.
918 normalizeMonths(&exploded);
919 options->end_time = base::Time::FromLocalExploded(exploded);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000920
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000921 exploded.month -= 1;
922 // Set the correct year
923 normalizeMonths(&exploded);
924 options->begin_time = base::Time::FromLocalExploded(exploded);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000925 }
926}
927
928// Helper function for Observe that determines if there are any differences
929// between the URLs noticed for deletion and the ones we are expecting.
930static bool DeletionsDiffer(const history::URLRows& deleted_rows,
931 const std::set<GURL>& urls_to_be_deleted) {
932 if (deleted_rows.size() != urls_to_be_deleted.size())
933 return true;
934 for (history::URLRows::const_iterator i = deleted_rows.begin();
935 i != deleted_rows.end(); ++i) {
936 if (urls_to_be_deleted.find(i->url()) == urls_to_be_deleted.end())
937 return true;
938 }
939 return false;
940}
941
942void BrowsingHistoryHandler::Observe(
943 int type,
944 const content::NotificationSource& source,
945 const content::NotificationDetails& details) {
946 if (type != chrome::NOTIFICATION_HISTORY_URLS_DELETED) {
947 NOTREACHED();
948 return;
949 }
950 history::URLsDeletedDetails* deletedDetails =
951 content::Details<history::URLsDeletedDetails>(details).ptr();
952 if (deletedDetails->all_history ||
953 DeletionsDiffer(deletedDetails->rows, urls_to_be_deleted_))
954 web_ui()->CallJavascriptFunction("historyDeleted");
955}
956
957////////////////////////////////////////////////////////////////////////////////
958//
959// HistoryUI
960//
961////////////////////////////////////////////////////////////////////////////////
962
963HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
964 web_ui->AddMessageHandler(new BrowsingHistoryHandler());
Ben Murdocheb525c52013-07-10 11:40:50 +0100965 web_ui->AddMessageHandler(new MetricsHandler());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000966
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000967// On mobile we deal with foreign sessions differently.
968#if !defined(OS_ANDROID) && !defined(OS_IOS)
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100969 if (chrome::IsInstantExtendedAPIEnabled()) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000970 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler());
971 web_ui->AddMessageHandler(new NTPLoginHandler());
972 }
973#endif
974
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000975 // Set up the chrome://history-frame/ source.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000976 Profile* profile = Profile::FromWebUI(web_ui);
977 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000978}
979
980// static
981const GURL HistoryUI::GetHistoryURLWithSearchText(const string16& text) {
982 return GURL(std::string(chrome::kChromeUIHistoryURL) + "#q=" +
983 net::EscapeQueryParamValue(UTF16ToUTF8(text), true));
984}
985
986// static
987base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes(
988 ui::ScaleFactor scale_factor) {
989 return ResourceBundle::GetSharedInstance().
990 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor);
991}