Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(138)

Side by Side Diff: chrome/browser/ui/webui/history_ui.cc

Issue 1462813003: Split BrowsingHistoryHandler out of history_ui.cc (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Review comments Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « chrome/browser/ui/webui/history_ui.h ('k') | chrome/browser/ui/webui/history_ui_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/ui/webui/history_ui.h" 5 #include "chrome/browser/ui/webui/history_ui.h"
6 6
7 #include <set>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h" 7 #include "base/command_line.h"
12 #include "base/i18n/rtl.h" 8 #include "base/memory/ref_counted_memory.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" 9 #include "base/prefs/pref_service.h"
18 #include "base/strings/string16.h" 10 #include "base/strings/string16.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h" 11 #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/engagement/site_engagement_service.h"
27 #include "chrome/browser/history/history_service_factory.h"
28 #include "chrome/browser/history/history_utils.h"
29 #include "chrome/browser/history/web_history_service_factory.h" 12 #include "chrome/browser/history/web_history_service_factory.h"
30 #include "chrome/browser/prefs/incognito_mode_prefs.h" 13 #include "chrome/browser/prefs/incognito_mode_prefs.h"
31 #include "chrome/browser/profiles/profile.h" 14 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/signin/signin_manager_factory.h" 15 #include "chrome/browser/signin/signin_manager_factory.h"
33 #include "chrome/browser/sync/profile_sync_service_factory.h" 16 #include "chrome/browser/ui/webui/browsing_history_handler.h"
34 #include "chrome/browser/ui/browser_finder.h"
35 #include "chrome/browser/ui/chrome_pages.h"
36 #include "chrome/browser/ui/webui/favicon_source.h"
37 #include "chrome/browser/ui/webui/metrics_handler.h" 17 #include "chrome/browser/ui/webui/metrics_handler.h"
38 #include "chrome/common/chrome_switches.h" 18 #include "chrome/common/chrome_switches.h"
39 #include "chrome/common/pref_names.h" 19 #include "chrome/common/pref_names.h"
40 #include "chrome/common/url_constants.h" 20 #include "chrome/common/url_constants.h"
41 #include "chrome/grit/generated_resources.h" 21 #include "chrome/grit/generated_resources.h"
42 #include "components/bookmarks/browser/bookmark_model.h"
43 #include "components/bookmarks/browser/bookmark_utils.h"
44 #include "components/browser_sync/browser/profile_sync_service.h"
45 #include "components/history/core/browser/history_service.h"
46 #include "components/history/core/browser/history_types.h"
47 #include "components/history/core/browser/web_history_service.h"
48 #include "components/search/search.h" 22 #include "components/search/search.h"
49 #include "components/signin/core/browser/signin_manager.h" 23 #include "components/signin/core/browser/signin_manager.h"
50 #include "components/sync_driver/device_info.h"
51 #include "components/url_formatter/url_formatter.h"
52 #include "content/public/browser/url_data_source.h"
53 #include "content/public/browser/web_ui.h" 24 #include "content/public/browser/web_ui.h"
54 #include "content/public/browser/web_ui_data_source.h" 25 #include "content/public/browser/web_ui_data_source.h"
55 #include "grit/browser_resources.h" 26 #include "grit/browser_resources.h"
56 #include "grit/theme_resources.h" 27 #include "grit/theme_resources.h"
57 #include "net/base/escape.h"
58 #include "sync/protocol/history_delete_directive_specifics.pb.h"
59 #include "ui/base/l10n/l10n_util.h" 28 #include "ui/base/l10n/l10n_util.h"
60 #include "ui/base/l10n/time_format.h"
61 #include "ui/base/resource/resource_bundle.h" 29 #include "ui/base/resource/resource_bundle.h"
62 #include "ui/base/webui/web_ui_util.h"
63
64 #if defined(ENABLE_EXTENSIONS)
65 #include "chrome/browser/extensions/activity_log/activity_log.h"
66 #endif
67
68 #if defined(ENABLE_SUPERVISED_USERS)
69 #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h"
70 #include "chrome/browser/supervised_user/supervised_user_service.h"
71 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
72 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
73 #endif
74
75 #if defined(OS_ANDROID)
76 #include "chrome/browser/android/chrome_application.h"
77 #endif
78 30
79 #if !defined(OS_ANDROID) && !defined(OS_IOS) 31 #if !defined(OS_ANDROID) && !defined(OS_IOS)
80 #include "chrome/browser/ui/webui/foreign_session_handler.h" 32 #include "chrome/browser/ui/webui/foreign_session_handler.h"
81 #include "chrome/browser/ui/webui/history_login_handler.h" 33 #include "chrome/browser/ui/webui/history_login_handler.h"
82 #endif 34 #endif
83 35
84 using bookmarks::BookmarkModel;
85
86 static const char kStringsJsFile[] = "strings.js"; 36 static const char kStringsJsFile[] = "strings.js";
87 static const char kHistoryJsFile[] = "history.js"; 37 static const char kHistoryJsFile[] = "history.js";
88 static const char kOtherDevicesJsFile[] = "other_devices.js"; 38 static const char kOtherDevicesJsFile[] = "other_devices.js";
89 39
90 // The amount of time to wait for a response from the WebHistoryService.
91 static const int kWebHistoryTimeoutSeconds = 3;
92
93 namespace { 40 namespace {
94 41
95 // Buckets for UMA histograms.
96 enum WebHistoryQueryBuckets {
97 WEB_HISTORY_QUERY_FAILED = 0,
98 WEB_HISTORY_QUERY_SUCCEEDED,
99 WEB_HISTORY_QUERY_TIMED_OUT,
100 NUM_WEB_HISTORY_QUERY_BUCKETS
101 };
102
103 #if defined(OS_MACOSX) 42 #if defined(OS_MACOSX)
104 const char kIncognitoModeShortcut[] = "(" 43 const char kIncognitoModeShortcut[] = "("
105 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW'). 44 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
106 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN'). 45 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
107 "N)"; 46 "N)";
108 #elif defined(OS_WIN) 47 #elif defined(OS_WIN)
109 const char kIncognitoModeShortcut[] = "(Ctrl+Shift+N)"; 48 const char kIncognitoModeShortcut[] = "(Ctrl+Shift+N)";
110 #else 49 #else
111 const char kIncognitoModeShortcut[] = "(Shift+Ctrl+N)"; 50 const char kIncognitoModeShortcut[] = "(Shift+Ctrl+N)";
112 #endif 51 #endif
113 52
114 // Identifiers for the type of device from which a history entry originated.
115 static const char kDeviceTypeLaptop[] = "laptop";
116 static const char kDeviceTypePhone[] = "phone";
117 static const char kDeviceTypeTablet[] = "tablet";
118
119 content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) { 53 content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) {
120 PrefService* prefs = profile->GetPrefs(); 54 PrefService* prefs = profile->GetPrefs();
121 55
122 // Check if the profile is authenticated. Guest profiles or incognito 56 // Check if the profile is authenticated. Guest profiles or incognito
123 // windows may not have a sign in manager, and are considered not 57 // windows may not have a sign in manager, and are considered not
124 // authenticated. 58 // authenticated.
125 SigninManagerBase* signin_manager = 59 SigninManagerBase* signin_manager =
126 SigninManagerFactory::GetForProfile(profile); 60 SigninManagerFactory::GetForProfile(profile);
127 bool is_authenticated = signin_manager != nullptr && 61 bool is_authenticated = signin_manager != nullptr &&
128 signin_manager->IsAuthenticated(); 62 signin_manager->IsAuthenticated();
(...skipping 87 matching lines...) Expand 10 before | Expand all | Expand 10 after
216 150
217 source->SetJsonPath(kStringsJsFile); 151 source->SetJsonPath(kStringsJsFile);
218 source->AddResourcePath(kHistoryJsFile, IDR_HISTORY_JS); 152 source->AddResourcePath(kHistoryJsFile, IDR_HISTORY_JS);
219 source->AddResourcePath(kOtherDevicesJsFile, IDR_OTHER_DEVICES_JS); 153 source->AddResourcePath(kOtherDevicesJsFile, IDR_OTHER_DEVICES_JS);
220 source->SetDefaultResource(IDR_HISTORY_HTML); 154 source->SetDefaultResource(IDR_HISTORY_HTML);
221 source->DisableDenyXFrameOptions(); 155 source->DisableDenyXFrameOptions();
222 156
223 return source; 157 return source;
224 } 158 }
225 159
226 // Returns a localized version of |visit_time| including a relative
227 // indicator (e.g. today, yesterday).
228 base::string16 getRelativeDateLocalized(const base::Time& visit_time) {
229 base::Time midnight = base::Time::Now().LocalMidnight();
230 base::string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight);
231 if (date_str.empty()) {
232 date_str = base::TimeFormatFriendlyDate(visit_time);
233 } else {
234 date_str = l10n_util::GetStringFUTF16(
235 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
236 date_str,
237 base::TimeFormatFriendlyDate(visit_time));
238 }
239 return date_str;
240 }
241
242
243 // Sets the correct year when substracting months from a date.
244 void normalizeMonths(base::Time::Exploded* exploded) {
245 // Decrease a year at a time until we have a proper date.
246 while (exploded->month < 1) {
247 exploded->month += 12;
248 exploded->year--;
249 }
250 }
251
252 // Returns true if |entry| represents a local visit that had no corresponding
253 // visit on the server.
254 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry& entry) {
255 return entry.entry_type == BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY;
256 }
257
258 // Gets the name and type of a device for the given sync client ID.
259 // |name| and |type| are out parameters.
260 void GetDeviceNameAndType(const ProfileSyncService* sync_service,
261 const std::string& client_id,
262 std::string* name,
263 std::string* type) {
264 // DeviceInfoTracker must be syncing in order for remote history entries to
265 // be available.
266 DCHECK(sync_service);
267 DCHECK(sync_service->GetDeviceInfoTracker());
268 DCHECK(sync_service->GetDeviceInfoTracker()->IsSyncing());
269
270 scoped_ptr<sync_driver::DeviceInfo> device_info =
271 sync_service->GetDeviceInfoTracker()->GetDeviceInfo(client_id);
272 if (device_info.get()) {
273 *name = device_info->client_name();
274 switch (device_info->device_type()) {
275 case sync_pb::SyncEnums::TYPE_PHONE:
276 *type = kDeviceTypePhone;
277 break;
278 case sync_pb::SyncEnums::TYPE_TABLET:
279 *type = kDeviceTypeTablet;
280 break;
281 default:
282 *type = kDeviceTypeLaptop;
283 }
284 return;
285 }
286
287 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE);
288 *type = kDeviceTypeLaptop;
289 }
290
291 } // namespace 160 } // namespace
292 161
293 ////////////////////////////////////////////////////////////////////////////////
294 //
295 // BrowsingHistoryHandler
296 //
297 ////////////////////////////////////////////////////////////////////////////////
298
299 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
300 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type,
301 const GURL& url, const base::string16& title, base::Time time,
302 const std::string& client_id, bool is_search_result,
303 const base::string16& snippet, bool blocked_visit,
304 const std::string& accept_languages) {
305 this->entry_type = entry_type;
306 this->url = url;
307 this->title = title;
308 this->time = time;
309 this->client_id = client_id;
310 all_timestamps.insert(time.ToInternalValue());
311 this->is_search_result = is_search_result;
312 this->snippet = snippet;
313 this->blocked_visit = blocked_visit;
314 this->accept_languages = accept_languages;
315 }
316
317 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
318 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) {
319 }
320
321 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
322 }
323
324 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
325 base::DictionaryValue* result) const {
326 result->SetString("url", url.spec());
327
328 bool using_url_as_the_title = false;
329 base::string16 title_to_set(title);
330 if (title.empty()) {
331 using_url_as_the_title = true;
332 title_to_set = base::UTF8ToUTF16(url.spec());
333 }
334
335 // Since the title can contain BiDi text, we need to mark the text as either
336 // RTL or LTR, depending on the characters in the string. If we use the URL
337 // as the title, we mark the title as LTR since URLs are always treated as
338 // left to right strings.
339 if (base::i18n::IsRTL()) {
340 if (using_url_as_the_title)
341 base::i18n::WrapStringWithLTRFormatting(&title_to_set);
342 else
343 base::i18n::AdjustStringForLocaleDirection(&title_to_set);
344 }
345 result->SetString("title", title_to_set);
346 }
347
348 scoped_ptr<base::DictionaryValue> BrowsingHistoryHandler::HistoryEntry::ToValue(
349 BookmarkModel* bookmark_model,
350 SupervisedUserService* supervised_user_service,
351 const ProfileSyncService* sync_service) const {
352 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
353 SetUrlAndTitle(result.get());
354
355 base::string16 domain =
356 url_formatter::IDNToUnicode(url.host(), accept_languages);
357 // When the domain is empty, use the scheme instead. This allows for a
358 // sensible treatment of e.g. file: URLs when group by domain is on.
359 if (domain.empty())
360 domain = base::UTF8ToUTF16(url.scheme() + ":");
361
362 // The items which are to be written into result are also described in
363 // chrome/browser/resources/history/history.js in @typedef for
364 // HistoryEntry. Please update it whenever you add or remove
365 // any keys in result.
366 result->SetString("domain", domain);
367 result->SetDouble("time", time.ToJsTime());
368
369 // Pass the timestamps in a list.
370 scoped_ptr<base::ListValue> timestamps(new base::ListValue);
371 for (std::set<int64>::const_iterator it = all_timestamps.begin();
372 it != all_timestamps.end(); ++it) {
373 timestamps->AppendDouble(base::Time::FromInternalValue(*it).ToJsTime());
374 }
375 result->Set("allTimestamps", timestamps.release());
376
377 // Always pass the short date since it is needed both in the search and in
378 // the monthly view.
379 result->SetString("dateShort", base::TimeFormatShortDate(time));
380
381 // Only pass in the strings we need (search results need a shortdate
382 // and snippet, browse results need day and time information).
383 if (is_search_result) {
384 result->SetString("snippet", snippet);
385 } else {
386 base::Time midnight = base::Time::Now().LocalMidnight();
387 base::string16 date_str = ui::TimeFormat::RelativeDate(time, &midnight);
388 if (date_str.empty()) {
389 date_str = base::TimeFormatFriendlyDate(time);
390 } else {
391 date_str = l10n_util::GetStringFUTF16(
392 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
393 date_str,
394 base::TimeFormatFriendlyDate(time));
395 }
396 result->SetString("dateRelativeDay", date_str);
397 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time));
398 }
399 result->SetBoolean("starred", bookmark_model->IsBookmarked(url));
400
401 std::string device_name;
402 std::string device_type;
403 if (!client_id.empty())
404 GetDeviceNameAndType(sync_service, client_id, &device_name, &device_type);
405 result->SetString("deviceName", device_name);
406 result->SetString("deviceType", device_type);
407
408 #if defined(ENABLE_SUPERVISED_USERS)
409 if (supervised_user_service) {
410 const SupervisedUserURLFilter* url_filter =
411 supervised_user_service->GetURLFilterForUIThread();
412 int filtering_behavior =
413 url_filter->GetFilteringBehaviorForURL(url.GetWithEmptyPath());
414 result->SetInteger("hostFilteringBehavior", filtering_behavior);
415
416 result->SetBoolean("blockedVisit", blocked_visit);
417 }
418 #endif
419
420 return result.Pass();
421 }
422
423 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
424 const BrowsingHistoryHandler::HistoryEntry& entry1,
425 const BrowsingHistoryHandler::HistoryEntry& entry2) {
426 return entry1.time > entry2.time;
427 }
428
429 BrowsingHistoryHandler::BrowsingHistoryHandler()
430 : has_pending_delete_request_(false),
431 history_service_observer_(this),
432 weak_factory_(this) {
433 }
434
435 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
436 query_task_tracker_.TryCancelAll();
437 web_history_request_.reset();
438 }
439
440 void BrowsingHistoryHandler::RegisterMessages() {
441 // Create our favicon data source.
442 Profile* profile = Profile::FromWebUI(web_ui());
443 content::URLDataSource::Add(
444 profile, new FaviconSource(profile, FaviconSource::ANY));
445
446 // Get notifications when history is cleared.
447 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
448 profile, ServiceAccessType::EXPLICIT_ACCESS);
449 if (hs)
450 history_service_observer_.Add(hs);
451
452 web_ui()->RegisterMessageCallback("queryHistory",
453 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory,
454 base::Unretained(this)));
455 web_ui()->RegisterMessageCallback("removeVisits",
456 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits,
457 base::Unretained(this)));
458 web_ui()->RegisterMessageCallback("clearBrowsingData",
459 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData,
460 base::Unretained(this)));
461 web_ui()->RegisterMessageCallback("removeBookmark",
462 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark,
463 base::Unretained(this)));
464 }
465
466 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
467 const base::ListValue* value,
468 int index,
469 int* out_int) {
470 double double_value;
471 if (value->GetDouble(index, &double_value)) {
472 *out_int = static_cast<int>(double_value);
473 return true;
474 }
475 NOTREACHED();
476 return false;
477 }
478
479 void BrowsingHistoryHandler::WebHistoryTimeout() {
480 // TODO(dubroy): Communicate the failure to the front end.
481 if (!query_task_tracker_.HasTrackedTasks())
482 ReturnResultsToFrontEnd();
483
484 UMA_HISTOGRAM_ENUMERATION(
485 "WebHistory.QueryCompletion",
486 WEB_HISTORY_QUERY_TIMED_OUT, NUM_WEB_HISTORY_QUERY_BUCKETS);
487 }
488
489 void BrowsingHistoryHandler::QueryHistory(
490 const base::string16& search_text,
491 const history::QueryOptions& options) {
492 Profile* profile = Profile::FromWebUI(web_ui());
493
494 // Anything in-flight is invalid.
495 query_task_tracker_.TryCancelAll();
496 web_history_request_.reset();
497
498 query_results_.clear();
499 results_info_value_.Clear();
500
501 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
502 profile, ServiceAccessType::EXPLICIT_ACCESS);
503 hs->QueryHistory(search_text,
504 options,
505 base::Bind(&BrowsingHistoryHandler::QueryComplete,
506 base::Unretained(this),
507 search_text,
508 options),
509 &query_task_tracker_);
510
511 history::WebHistoryService* web_history =
512 WebHistoryServiceFactory::GetForProfile(profile);
513 if (web_history) {
514 web_history_query_results_.clear();
515 web_history_request_ = web_history->QueryHistory(
516 search_text,
517 options,
518 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete,
519 base::Unretained(this),
520 search_text, options,
521 base::TimeTicks::Now()));
522 // Start a timer so we know when to give up.
523 web_history_timer_.Start(
524 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds),
525 this, &BrowsingHistoryHandler::WebHistoryTimeout);
526
527 // Set this to false until the results actually arrive.
528 results_info_value_.SetBoolean("hasSyncedResults", false);
529 }
530 }
531
532 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) {
533 history::QueryOptions options;
534
535 // Parse the arguments from JavaScript. There are five required arguments:
536 // - the text to search for (may be empty)
537 // - the offset from which the search should start (in multiples of week or
538 // month, set by the next argument).
539 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
540 // of the query.
541 // - the end time for the query. Only results older than this time will be
542 // returned.
543 // - the maximum number of results to return (may be 0, meaning that there
544 // is no maximum).
545 base::string16 search_text = ExtractStringValue(args);
546 int offset;
547 if (!args->GetInteger(1, &offset)) {
548 NOTREACHED() << "Failed to convert argument 1. ";
549 return;
550 }
551 int range;
552 if (!args->GetInteger(2, &range)) {
553 NOTREACHED() << "Failed to convert argument 2. ";
554 return;
555 }
556
557 if (range == BrowsingHistoryHandler::MONTH)
558 SetQueryTimeInMonths(offset, &options);
559 else if (range == BrowsingHistoryHandler::WEEK)
560 SetQueryTimeInWeeks(offset, &options);
561
562 double end_time;
563 if (!args->GetDouble(3, &end_time)) {
564 NOTREACHED() << "Failed to convert argument 3. ";
565 return;
566 }
567 if (end_time)
568 options.end_time = base::Time::FromJsTime(end_time);
569
570 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) {
571 NOTREACHED() << "Failed to convert argument 4.";
572 return;
573 }
574
575 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY;
576 QueryHistory(search_text, options);
577 }
578
579 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
580 Profile* profile = Profile::FromWebUI(web_ui());
581 // TODO(davidben): history.js is not aware of this failure and will still
582 // override |deleteCompleteCallback_|.
583 if (delete_task_tracker_.HasTrackedTasks() ||
584 has_pending_delete_request_ ||
585 !profile->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
586 web_ui()->CallJavascriptFunction("deleteFailed");
587 return;
588 }
589
590 history::HistoryService* history_service =
591 HistoryServiceFactory::GetForProfile(profile,
592 ServiceAccessType::EXPLICIT_ACCESS);
593 history::WebHistoryService* web_history =
594 WebHistoryServiceFactory::GetForProfile(profile);
595
596 base::Time now = base::Time::Now();
597 std::vector<history::ExpireHistoryArgs> expire_list;
598 expire_list.reserve(args->GetSize());
599
600 DCHECK(urls_to_be_deleted_.empty());
601 for (base::ListValue::const_iterator it = args->begin();
602 it != args->end(); ++it) {
603 base::DictionaryValue* deletion = NULL;
604 base::string16 url;
605 base::ListValue* timestamps = NULL;
606
607 // Each argument is a dictionary with properties "url" and "timestamps".
608 if (!((*it)->GetAsDictionary(&deletion) &&
609 deletion->GetString("url", &url) &&
610 deletion->GetList("timestamps", &timestamps))) {
611 NOTREACHED() << "Unable to extract arguments";
612 return;
613 }
614 DCHECK(timestamps->GetSize() > 0);
615
616 // In order to ensure that visits will be deleted from the server and other
617 // clients (even if they are offline), create a sync delete directive for
618 // each visit to be deleted.
619 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive;
620 sync_pb::GlobalIdDirective* global_id_directive =
621 delete_directive.mutable_global_id_directive();
622
623 double timestamp;
624 history::ExpireHistoryArgs* expire_args = NULL;
625 for (base::ListValue::const_iterator ts_iterator = timestamps->begin();
626 ts_iterator != timestamps->end(); ++ts_iterator) {
627 if (!(*ts_iterator)->GetAsDouble(&timestamp)) {
628 NOTREACHED() << "Unable to extract visit timestamp.";
629 continue;
630 }
631 base::Time visit_time = base::Time::FromJsTime(timestamp);
632 if (!expire_args) {
633 GURL gurl(url);
634 expire_list.resize(expire_list.size() + 1);
635 expire_args = &expire_list.back();
636 expire_args->SetTimeRangeForOneDay(visit_time);
637 expire_args->urls.insert(gurl);
638 urls_to_be_deleted_.insert(gurl);
639 }
640 // The local visit time is treated as a global ID for the visit.
641 global_id_directive->add_global_id(visit_time.ToInternalValue());
642 }
643
644 // Set the start and end time in microseconds since the Unix epoch.
645 global_id_directive->set_start_time_usec(
646 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds());
647
648 // Delete directives shouldn't have an end time in the future.
649 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
650 base::Time end_time = std::min(expire_args->end_time, now);
651
652 // -1 because end time in delete directives is inclusive.
653 global_id_directive->set_end_time_usec(
654 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1);
655
656 // TODO(dubroy): Figure out the proper way to handle an error here.
657 if (web_history)
658 history_service->ProcessLocalDeleteDirective(delete_directive);
659 }
660
661 history_service->ExpireHistory(
662 expire_list,
663 base::Bind(&BrowsingHistoryHandler::RemoveComplete,
664 base::Unretained(this)),
665 &delete_task_tracker_);
666
667 if (web_history) {
668 has_pending_delete_request_ = true;
669 web_history->ExpireHistory(
670 expire_list,
671 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete,
672 weak_factory_.GetWeakPtr()));
673 }
674
675 #if defined(ENABLE_EXTENSIONS)
676 // If the profile has activity logging enabled also clean up any URLs from
677 // the extension activity log. The extension activity log contains URLS
678 // which websites an extension has activity on so it will indirectly
679 // contain websites that a user has visited.
680 extensions::ActivityLog* activity_log =
681 extensions::ActivityLog::GetInstance(profile);
682 for (std::vector<history::ExpireHistoryArgs>::const_iterator it =
683 expire_list.begin(); it != expire_list.end(); ++it) {
684 activity_log->RemoveURLs(it->urls);
685 }
686 #endif
687
688 for (const history::ExpireHistoryArgs& expire_entry : expire_list)
689 AppBannerSettingsHelper::ClearHistoryForURLs(profile, expire_entry.urls);
690 }
691
692 void BrowsingHistoryHandler::HandleClearBrowsingData(
693 const base::ListValue* args) {
694 #if defined(OS_ANDROID)
695 chrome::android::ChromeApplication::OpenClearBrowsingData(
696 web_ui()->GetWebContents());
697 #else
698 // TODO(beng): This is an improper direct dependency on Browser. Route this
699 // through some sort of delegate.
700 Browser* browser = chrome::FindBrowserWithWebContents(
701 web_ui()->GetWebContents());
702 chrome::ShowClearBrowsingDataDialog(browser);
703 #endif
704 }
705
706 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue* args) {
707 base::string16 url = ExtractStringValue(args);
708 Profile* profile = Profile::FromWebUI(web_ui());
709 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
710 bookmarks::RemoveAllBookmarks(model, GURL(url));
711 }
712
713 // static
714 void BrowsingHistoryHandler::MergeDuplicateResults(
715 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) {
716 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results;
717 // Pre-reserve the size of the new vector. Since we're working with pointers
718 // later on not doing this could lead to the vector being resized and to
719 // pointers to invalid locations.
720 new_results.reserve(results->size());
721 // Maps a URL to the most recent entry on a particular day.
722 std::map<GURL, BrowsingHistoryHandler::HistoryEntry*> current_day_entries;
723
724 // Keeps track of the day that |current_day_urls| is holding the URLs for,
725 // in order to handle removing per-day duplicates.
726 base::Time current_day_midnight;
727
728 std::sort(
729 results->begin(), results->end(), HistoryEntry::SortByTimeDescending);
730
731 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::const_iterator it =
732 results->begin(); it != results->end(); ++it) {
733 // Reset the list of found URLs when a visit from a new day is encountered.
734 if (current_day_midnight != it->time.LocalMidnight()) {
735 current_day_entries.clear();
736 current_day_midnight = it->time.LocalMidnight();
737 }
738
739 // Keep this visit if it's the first visit to this URL on the current day.
740 if (current_day_entries.count(it->url) == 0) {
741 new_results.push_back(*it);
742 current_day_entries[it->url] = &new_results.back();
743 } else {
744 // Keep track of the timestamps of all visits to the URL on the same day.
745 BrowsingHistoryHandler::HistoryEntry* entry =
746 current_day_entries[it->url];
747 entry->all_timestamps.insert(
748 it->all_timestamps.begin(), it->all_timestamps.end());
749
750 if (entry->entry_type != it->entry_type) {
751 entry->entry_type =
752 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY;
753 }
754 }
755 }
756 results->swap(new_results);
757 }
758
759 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
760 Profile* profile = Profile::FromWebUI(web_ui());
761 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile);
762 SupervisedUserService* supervised_user_service = NULL;
763 #if defined(ENABLE_SUPERVISED_USERS)
764 if (profile->IsSupervised())
765 supervised_user_service =
766 SupervisedUserServiceFactory::GetForProfile(profile);
767 #endif
768 ProfileSyncService* sync_service =
769 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
770
771 // Combine the local and remote results into |query_results_|, and remove
772 // any duplicates.
773 if (!web_history_query_results_.empty()) {
774 int local_result_count = query_results_.size();
775 query_results_.insert(query_results_.end(),
776 web_history_query_results_.begin(),
777 web_history_query_results_.end());
778 MergeDuplicateResults(&query_results_);
779
780 if (local_result_count) {
781 // In the best case, we expect that all local results are duplicated on
782 // the server. Keep track of how many are missing.
783 int missing_count = std::count_if(
784 query_results_.begin(), query_results_.end(), IsLocalOnlyResult);
785 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
786 missing_count * 100.0 / local_result_count);
787 }
788 }
789
790 // Convert the result vector into a ListValue.
791 base::ListValue results_value;
792 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::iterator it =
793 query_results_.begin(); it != query_results_.end(); ++it) {
794 scoped_ptr<base::Value> value(
795 it->ToValue(bookmark_model, supervised_user_service, sync_service));
796 results_value.Append(value.release());
797 }
798
799 web_ui()->CallJavascriptFunction(
800 "historyResult", results_info_value_, results_value);
801 results_info_value_.Clear();
802 query_results_.clear();
803 web_history_query_results_.clear();
804 }
805
806 void BrowsingHistoryHandler::QueryComplete(
807 const base::string16& search_text,
808 const history::QueryOptions& options,
809 history::QueryResults* results) {
810 DCHECK_EQ(0U, query_results_.size());
811 query_results_.reserve(results->size());
812 const std::string accept_languages = GetAcceptLanguages();
813
814 for (size_t i = 0; i < results->size(); ++i) {
815 history::URLResult const &page = (*results)[i];
816 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
817 query_results_.push_back(
818 HistoryEntry(
819 HistoryEntry::LOCAL_ENTRY,
820 page.url(),
821 page.title(),
822 page.visit_time(),
823 std::string(),
824 !search_text.empty(),
825 page.snippet().text(),
826 page.blocked_visit(),
827 accept_languages));
828 }
829
830 // The items which are to be written into results_info_value_ are also
831 // described in chrome/browser/resources/history/history.js in @typedef for
832 // HistoryQuery. Please update it whenever you add or remove any keys in
833 // results_info_value_.
834 results_info_value_.SetString("term", search_text);
835 results_info_value_.SetBoolean("finished", results->reached_beginning());
836
837 // Add the specific dates that were searched to display them.
838 // TODO(sergiu): Put today if the start is in the future.
839 results_info_value_.SetString("queryStartTime",
840 getRelativeDateLocalized(options.begin_time));
841 if (!options.end_time.is_null()) {
842 results_info_value_.SetString("queryEndTime",
843 getRelativeDateLocalized(options.end_time -
844 base::TimeDelta::FromDays(1)));
845 } else {
846 results_info_value_.SetString("queryEndTime",
847 getRelativeDateLocalized(base::Time::Now()));
848 }
849 if (!web_history_timer_.IsRunning())
850 ReturnResultsToFrontEnd();
851 }
852
853 void BrowsingHistoryHandler::WebHistoryQueryComplete(
854 const base::string16& search_text,
855 const history::QueryOptions& options,
856 base::TimeTicks start_time,
857 history::WebHistoryService::Request* request,
858 const base::DictionaryValue* results_value) {
859 base::TimeDelta delta = base::TimeTicks::Now() - start_time;
860 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta);
861 const std::string accept_languages = GetAcceptLanguages();
862
863 // If the response came in too late, do nothing.
864 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
865 if (!web_history_timer_.IsRunning())
866 return;
867 web_history_timer_.Stop();
868
869 UMA_HISTOGRAM_ENUMERATION(
870 "WebHistory.QueryCompletion",
871 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED,
872 NUM_WEB_HISTORY_QUERY_BUCKETS);
873
874 DCHECK_EQ(0U, web_history_query_results_.size());
875 const base::ListValue* events = NULL;
876 if (results_value && results_value->GetList("event", &events)) {
877 web_history_query_results_.reserve(events->GetSize());
878 for (unsigned int i = 0; i < events->GetSize(); ++i) {
879 const base::DictionaryValue* event = NULL;
880 const base::DictionaryValue* result = NULL;
881 const base::ListValue* results = NULL;
882 const base::ListValue* ids = NULL;
883 base::string16 url;
884 base::string16 title;
885 base::Time visit_time;
886
887 if (!(events->GetDictionary(i, &event) &&
888 event->GetList("result", &results) &&
889 results->GetDictionary(0, &result) &&
890 result->GetString("url", &url) &&
891 result->GetList("id", &ids) &&
892 ids->GetSize() > 0)) {
893 LOG(WARNING) << "Improperly formed JSON response from history server.";
894 continue;
895 }
896
897 // Ignore any URLs that should not be shown in the history page.
898 GURL gurl(url);
899 if (!CanAddURLToHistory(gurl))
900 continue;
901
902 // Title is optional, so the return value is ignored here.
903 result->GetString("title", &title);
904
905 // Extract the timestamps of all the visits to this URL.
906 // They are referred to as "IDs" by the server.
907 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) {
908 const base::DictionaryValue* id = NULL;
909 std::string timestamp_string;
910 int64 timestamp_usec = 0;
911
912 if (!ids->GetDictionary(j, &id) ||
913 !id->GetString("timestamp_usec", &timestamp_string) ||
914 !base::StringToInt64(timestamp_string, &timestamp_usec)) {
915 NOTREACHED() << "Unable to extract timestamp.";
916 continue;
917 }
918 // The timestamp on the server is a Unix time.
919 base::Time time = base::Time::UnixEpoch() +
920 base::TimeDelta::FromMicroseconds(timestamp_usec);
921
922 // Get the ID of the client that this visit came from.
923 std::string client_id;
924 id->GetString("client_id", &client_id);
925
926 web_history_query_results_.push_back(
927 HistoryEntry(
928 HistoryEntry::REMOTE_ENTRY,
929 gurl,
930 title,
931 time,
932 client_id,
933 !search_text.empty(),
934 base::string16(),
935 /* blocked_visit */ false,
936 accept_languages));
937 }
938 }
939 }
940 results_info_value_.SetBoolean("hasSyncedResults", results_value != NULL);
941 if (!query_task_tracker_.HasTrackedTasks())
942 ReturnResultsToFrontEnd();
943 }
944
945 void BrowsingHistoryHandler::RemoveComplete() {
946 urls_to_be_deleted_.clear();
947
948 // Notify the page that the deletion request is complete, but only if a web
949 // history delete request is not still pending.
950 if (!has_pending_delete_request_)
951 web_ui()->CallJavascriptFunction("deleteComplete");
952 }
953
954 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success) {
955 has_pending_delete_request_ = false;
956 // TODO(dubroy): Should we handle failure somehow? Delete directives will
957 // ensure that the visits are eventually deleted, so maybe it's not necessary.
958 if (!delete_task_tracker_.HasTrackedTasks())
959 RemoveComplete();
960 }
961
962 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
963 int offset, history::QueryOptions* options) {
964 // LocalMidnight returns the beginning of the current day so get the
965 // beginning of the next one.
966 base::Time midnight = base::Time::Now().LocalMidnight() +
967 base::TimeDelta::FromDays(1);
968 options->end_time = midnight -
969 base::TimeDelta::FromDays(7 * offset);
970 options->begin_time = midnight -
971 base::TimeDelta::FromDays(7 * (offset + 1));
972 }
973
974 void BrowsingHistoryHandler::SetQueryTimeInMonths(
975 int offset, history::QueryOptions* options) {
976 // Configure the begin point of the search to the start of the
977 // current month.
978 base::Time::Exploded exploded;
979 base::Time::Now().LocalMidnight().LocalExplode(&exploded);
980 exploded.day_of_month = 1;
981
982 if (offset == 0) {
983 options->begin_time = base::Time::FromLocalExploded(exploded);
984
985 // Set the end time of this first search to null (which will
986 // show results from the future, should the user's clock have
987 // been set incorrectly).
988 options->end_time = base::Time();
989 } else {
990 // Go back |offset| months in the past. The end time is not inclusive, so
991 // use the first day of the |offset| - 1 and |offset| months (e.g. for
992 // the last month, |offset| = 1, use the first days of the last month and
993 // the current month.
994 exploded.month -= offset - 1;
995 // Set the correct year.
996 normalizeMonths(&exploded);
997 options->end_time = base::Time::FromLocalExploded(exploded);
998
999 exploded.month -= 1;
1000 // Set the correct year
1001 normalizeMonths(&exploded);
1002 options->begin_time = base::Time::FromLocalExploded(exploded);
1003 }
1004 }
1005
1006 // Helper function for Observe that determines if there are any differences
1007 // between the URLs noticed for deletion and the ones we are expecting.
1008 static bool DeletionsDiffer(const history::URLRows& deleted_rows,
1009 const std::set<GURL>& urls_to_be_deleted) {
1010 if (deleted_rows.size() != urls_to_be_deleted.size())
1011 return true;
1012 for (const auto& i : deleted_rows) {
1013 if (urls_to_be_deleted.find(i.url()) == urls_to_be_deleted.end())
1014 return true;
1015 }
1016 return false;
1017 }
1018
1019 std::string BrowsingHistoryHandler::GetAcceptLanguages() const {
1020 Profile* profile = Profile::FromWebUI(web_ui());
1021 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1022 }
1023
1024 void BrowsingHistoryHandler::OnURLsDeleted(
1025 history::HistoryService* history_service,
1026 bool all_history,
1027 bool expired,
1028 const history::URLRows& deleted_rows,
1029 const std::set<GURL>& favicon_urls) {
1030 if (all_history || DeletionsDiffer(deleted_rows, urls_to_be_deleted_))
1031 web_ui()->CallJavascriptFunction("historyDeleted");
1032 }
1033
1034 ////////////////////////////////////////////////////////////////////////////////
1035 //
1036 // HistoryUI
1037 //
1038 ////////////////////////////////////////////////////////////////////////////////
1039
1040 HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) { 162 HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
1041 web_ui->AddMessageHandler(new BrowsingHistoryHandler()); 163 web_ui->AddMessageHandler(new BrowsingHistoryHandler());
1042 web_ui->AddMessageHandler(new MetricsHandler()); 164 web_ui->AddMessageHandler(new MetricsHandler());
1043 165
1044 // On mobile we deal with foreign sessions differently. 166 // On mobile we deal with foreign sessions differently.
1045 #if !defined(OS_ANDROID) && !defined(OS_IOS) 167 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1046 if (search::IsInstantExtendedAPIEnabled()) { 168 if (search::IsInstantExtendedAPIEnabled()) {
1047 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler()); 169 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler());
1048 web_ui->AddMessageHandler(new HistoryLoginHandler()); 170 web_ui->AddMessageHandler(new HistoryLoginHandler());
1049 } 171 }
1050 #endif 172 #endif
1051 173
1052 // Set up the chrome://history-frame/ source. 174 // Set up the chrome://history-frame/ source.
1053 Profile* profile = Profile::FromWebUI(web_ui); 175 Profile* profile = Profile::FromWebUI(web_ui);
1054 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile)); 176 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile));
1055 } 177 }
1056 178
1057 HistoryUI::~HistoryUI() {} 179 HistoryUI::~HistoryUI() {}
1058 180
1059 // static 181 // static
1060 base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes( 182 base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes(
1061 ui::ScaleFactor scale_factor) { 183 ui::ScaleFactor scale_factor) {
1062 return ResourceBundle::GetSharedInstance(). 184 return ResourceBundle::GetSharedInstance().
1063 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor); 185 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor);
1064 } 186 }
OLDNEW
« no previous file with comments | « chrome/browser/ui/webui/history_ui.h ('k') | chrome/browser/ui/webui/history_ui_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698