| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 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 "ios/chrome/browser/ui/webui/history/browsing_history_handler.h" | |
| 6 | |
| 7 #include <stddef.h> | |
| 8 | |
| 9 #include <set> | |
| 10 | |
| 11 #include "base/bind.h" | |
| 12 #include "base/bind_helpers.h" | |
| 13 #include "base/i18n/rtl.h" | |
| 14 #include "base/i18n/time_formatting.h" | |
| 15 #include "base/metrics/histogram.h" | |
| 16 #include "base/strings/string16.h" | |
| 17 #include "base/strings/string_number_conversions.h" | |
| 18 #include "base/strings/utf_string_conversions.h" | |
| 19 #include "base/time/time.h" | |
| 20 #include "base/values.h" | |
| 21 #include "components/bookmarks/browser/bookmark_model.h" | |
| 22 #include "components/bookmarks/browser/bookmark_utils.h" | |
| 23 #include "components/browser_sync/profile_sync_service.h" | |
| 24 #include "components/browsing_data/core/history_notice_utils.h" | |
| 25 #include "components/history/core/browser/history_service.h" | |
| 26 #include "components/history/core/browser/history_types.h" | |
| 27 #include "components/history/core/browser/top_sites.h" | |
| 28 #include "components/history/core/browser/web_history_service.h" | |
| 29 #include "components/keyed_service/core/service_access_type.h" | |
| 30 #include "components/strings/grit/components_strings.h" | |
| 31 #include "components/sync/device_info/device_info.h" | |
| 32 #include "components/sync/device_info/device_info_tracker.h" | |
| 33 #include "components/sync/protocol/history_delete_directive_specifics.pb.h" | |
| 34 #include "components/sync/protocol/sync_enums.pb.h" | |
| 35 #include "components/url_formatter/url_formatter.h" | |
| 36 #include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" | |
| 37 #include "ios/chrome/browser/browser_state/chrome_browser_state.h" | |
| 38 #include "ios/chrome/browser/chrome_url_constants.h" | |
| 39 #include "ios/chrome/browser/favicon/favicon_service_factory.h" | |
| 40 #include "ios/chrome/browser/history/history_service_factory.h" | |
| 41 #include "ios/chrome/browser/history/history_utils.h" | |
| 42 #include "ios/chrome/browser/history/top_sites_factory.h" | |
| 43 #include "ios/chrome/browser/history/web_history_service_factory.h" | |
| 44 #include "ios/chrome/browser/sync/ios_chrome_profile_sync_service_factory.h" | |
| 45 #include "ios/chrome/browser/ui/show_privacy_settings_util.h" | |
| 46 #include "ios/chrome/browser/ui/webui/history/favicon_source.h" | |
| 47 #include "ios/web/public/url_data_source_ios.h" | |
| 48 #include "ios/web/public/webui/web_ui_ios.h" | |
| 49 #include "ui/base/l10n/l10n_util.h" | |
| 50 #include "ui/base/l10n/time_format.h" | |
| 51 | |
| 52 // The amount of time to wait for a response from the WebHistoryService. | |
| 53 static const int kWebHistoryTimeoutSeconds = 3; | |
| 54 | |
| 55 using bookmarks::BookmarkModel; | |
| 56 | |
| 57 namespace { | |
| 58 | |
| 59 // Buckets for UMA histograms. | |
| 60 enum WebHistoryQueryBuckets { | |
| 61 WEB_HISTORY_QUERY_FAILED = 0, | |
| 62 WEB_HISTORY_QUERY_SUCCEEDED, | |
| 63 WEB_HISTORY_QUERY_TIMED_OUT, | |
| 64 NUM_WEB_HISTORY_QUERY_BUCKETS | |
| 65 }; | |
| 66 | |
| 67 // Identifiers for the type of device from which a history entry originated. | |
| 68 static const char kDeviceTypeLaptop[] = "laptop"; | |
| 69 static const char kDeviceTypePhone[] = "phone"; | |
| 70 static const char kDeviceTypeTablet[] = "tablet"; | |
| 71 | |
| 72 // Returns a localized version of |visit_time| including a relative | |
| 73 // indicator (e.g. today, yesterday). | |
| 74 base::string16 GetRelativeDateLocalized(const base::Time& visit_time) { | |
| 75 base::Time midnight = base::Time::Now().LocalMidnight(); | |
| 76 base::string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight); | |
| 77 if (date_str.empty()) { | |
| 78 date_str = base::TimeFormatFriendlyDate(visit_time); | |
| 79 } else { | |
| 80 date_str = l10n_util::GetStringFUTF16( | |
| 81 IDS_HISTORY_DATE_WITH_RELATIVE_TIME, date_str, | |
| 82 base::TimeFormatFriendlyDate(visit_time)); | |
| 83 } | |
| 84 return date_str; | |
| 85 } | |
| 86 | |
| 87 // Sets the correct year when substracting months from a date. | |
| 88 void NormalizeMonths(base::Time::Exploded* exploded) { | |
| 89 // Decrease a year at a time until we have a proper date. | |
| 90 while (exploded->month < 1) { | |
| 91 exploded->month += 12; | |
| 92 exploded->year--; | |
| 93 } | |
| 94 } | |
| 95 | |
| 96 // Returns true if |entry| represents a local visit that had no corresponding | |
| 97 // visit on the server. | |
| 98 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry& entry) { | |
| 99 return entry.entry_type == BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY; | |
| 100 } | |
| 101 | |
| 102 // Gets the name and type of a device for the given sync client ID. | |
| 103 // |name| and |type| are out parameters. | |
| 104 void GetDeviceNameAndType(const browser_sync::ProfileSyncService* sync_service, | |
| 105 const std::string& client_id, | |
| 106 std::string* name, | |
| 107 std::string* type) { | |
| 108 // DeviceInfoTracker must be syncing in order for remote history entries to | |
| 109 // be available. | |
| 110 DCHECK(sync_service); | |
| 111 DCHECK(sync_service->GetDeviceInfoTracker()); | |
| 112 DCHECK(sync_service->GetDeviceInfoTracker()->IsSyncing()); | |
| 113 | |
| 114 std::unique_ptr<syncer::DeviceInfo> device_info = | |
| 115 sync_service->GetDeviceInfoTracker()->GetDeviceInfo(client_id); | |
| 116 if (device_info.get()) { | |
| 117 *name = device_info->client_name(); | |
| 118 switch (device_info->device_type()) { | |
| 119 case sync_pb::SyncEnums::TYPE_PHONE: | |
| 120 *type = kDeviceTypePhone; | |
| 121 break; | |
| 122 case sync_pb::SyncEnums::TYPE_TABLET: | |
| 123 *type = kDeviceTypeTablet; | |
| 124 break; | |
| 125 default: | |
| 126 *type = kDeviceTypeLaptop; | |
| 127 } | |
| 128 return; | |
| 129 } | |
| 130 | |
| 131 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE); | |
| 132 *type = kDeviceTypeLaptop; | |
| 133 } | |
| 134 | |
| 135 void RecordMetricsForNoticeAboutOtherFormsOfBrowsingHistory(bool shown) { | |
| 136 UMA_HISTOGRAM_BOOLEAN("History.ShownHeaderAboutOtherFormsOfBrowsingHistory", | |
| 137 shown); | |
| 138 } | |
| 139 | |
| 140 } // namespace | |
| 141 | |
| 142 BrowsingHistoryHandler::HistoryEntry::HistoryEntry( | |
| 143 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type, | |
| 144 const GURL& url, | |
| 145 const base::string16& title, | |
| 146 base::Time time, | |
| 147 const std::string& client_id, | |
| 148 bool is_search_result, | |
| 149 const base::string16& snippet, | |
| 150 bool blocked_visit) { | |
| 151 this->entry_type = entry_type; | |
| 152 this->url = url; | |
| 153 this->title = title; | |
| 154 this->time = time; | |
| 155 this->client_id = client_id; | |
| 156 all_timestamps.insert(time.ToInternalValue()); | |
| 157 this->is_search_result = is_search_result; | |
| 158 this->snippet = snippet; | |
| 159 this->blocked_visit = blocked_visit; | |
| 160 } | |
| 161 | |
| 162 BrowsingHistoryHandler::HistoryEntry::HistoryEntry() | |
| 163 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) {} | |
| 164 | |
| 165 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(const HistoryEntry& other) = | |
| 166 default; | |
| 167 | |
| 168 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {} | |
| 169 | |
| 170 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle( | |
| 171 base::DictionaryValue* result) const { | |
| 172 result->SetString("url", url.spec()); | |
| 173 | |
| 174 bool using_url_as_the_title = false; | |
| 175 base::string16 title_to_set(title); | |
| 176 if (title.empty()) { | |
| 177 using_url_as_the_title = true; | |
| 178 title_to_set = base::UTF8ToUTF16(url.spec()); | |
| 179 } | |
| 180 | |
| 181 // Since the title can contain BiDi text, we need to mark the text as either | |
| 182 // RTL or LTR, depending on the characters in the string. If we use the URL | |
| 183 // as the title, we mark the title as LTR since URLs are always treated as | |
| 184 // left to right strings. | |
| 185 if (base::i18n::IsRTL()) { | |
| 186 if (using_url_as_the_title) | |
| 187 base::i18n::WrapStringWithLTRFormatting(&title_to_set); | |
| 188 else | |
| 189 base::i18n::AdjustStringForLocaleDirection(&title_to_set); | |
| 190 } | |
| 191 result->SetString("title", title_to_set); | |
| 192 } | |
| 193 | |
| 194 std::unique_ptr<base::DictionaryValue> | |
| 195 BrowsingHistoryHandler::HistoryEntry::ToValue( | |
| 196 BookmarkModel* bookmark_model, | |
| 197 SupervisedUserService* supervised_user_service, | |
| 198 const browser_sync::ProfileSyncService* sync_service) const { | |
| 199 std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); | |
| 200 SetUrlAndTitle(result.get()); | |
| 201 | |
| 202 base::string16 domain = url_formatter::IDNToUnicode(url.host()); | |
| 203 // When the domain is empty, use the scheme instead. This allows for a | |
| 204 // sensible treatment of e.g. file: URLs when group by domain is on. | |
| 205 if (domain.empty()) | |
| 206 domain = base::UTF8ToUTF16(url.scheme() + ":"); | |
| 207 | |
| 208 // The items which are to be written into result are also described in | |
| 209 // chrome/browser/resources/history/history.js in @typedef for | |
| 210 // HistoryEntry. Please update it whenever you add or remove | |
| 211 // any keys in result. | |
| 212 result->SetString("domain", domain); | |
| 213 result->SetDouble("time", time.ToJsTime()); | |
| 214 | |
| 215 // Pass the timestamps in a list. | |
| 216 std::unique_ptr<base::ListValue> timestamps(new base::ListValue); | |
| 217 for (int64_t timestamp : all_timestamps) { | |
| 218 timestamps->AppendDouble( | |
| 219 base::Time::FromInternalValue(timestamp).ToJsTime()); | |
| 220 } | |
| 221 result->Set("allTimestamps", timestamps.release()); | |
| 222 | |
| 223 // Always pass the short date since it is needed both in the search and in | |
| 224 // the monthly view. | |
| 225 result->SetString("dateShort", base::TimeFormatShortDate(time)); | |
| 226 | |
| 227 // Only pass in the strings we need (search results need a shortdate | |
| 228 // and snippet, browse results need day and time information). | |
| 229 if (is_search_result) { | |
| 230 result->SetString("snippet", snippet); | |
| 231 } else { | |
| 232 base::Time midnight = base::Time::Now().LocalMidnight(); | |
| 233 base::string16 date_str = ui::TimeFormat::RelativeDate(time, &midnight); | |
| 234 if (date_str.empty()) { | |
| 235 date_str = base::TimeFormatFriendlyDate(time); | |
| 236 } else { | |
| 237 date_str = l10n_util::GetStringFUTF16(IDS_HISTORY_DATE_WITH_RELATIVE_TIME, | |
| 238 date_str, | |
| 239 base::TimeFormatFriendlyDate(time)); | |
| 240 } | |
| 241 result->SetString("dateRelativeDay", date_str); | |
| 242 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time)); | |
| 243 } | |
| 244 result->SetBoolean("starred", bookmark_model->IsBookmarked(url)); | |
| 245 | |
| 246 std::string device_name; | |
| 247 std::string device_type; | |
| 248 if (!client_id.empty()) | |
| 249 GetDeviceNameAndType(sync_service, client_id, &device_name, &device_type); | |
| 250 result->SetString("deviceName", device_name); | |
| 251 result->SetString("deviceType", device_type); | |
| 252 | |
| 253 return result; | |
| 254 } | |
| 255 | |
| 256 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending( | |
| 257 const BrowsingHistoryHandler::HistoryEntry& entry1, | |
| 258 const BrowsingHistoryHandler::HistoryEntry& entry2) { | |
| 259 return entry1.time > entry2.time; | |
| 260 } | |
| 261 | |
| 262 BrowsingHistoryHandler::BrowsingHistoryHandler() | |
| 263 : has_pending_delete_request_(false), | |
| 264 history_service_observer_(this), | |
| 265 has_synced_results_(false), | |
| 266 has_other_forms_of_browsing_history_(false), | |
| 267 weak_factory_(this) {} | |
| 268 | |
| 269 BrowsingHistoryHandler::~BrowsingHistoryHandler() { | |
| 270 query_task_tracker_.TryCancelAll(); | |
| 271 web_history_request_.reset(); | |
| 272 } | |
| 273 | |
| 274 void BrowsingHistoryHandler::RegisterMessages() { | |
| 275 // Create our favicon data source. | |
| 276 ios::ChromeBrowserState* browser_state = | |
| 277 ios::ChromeBrowserState::FromWebUIIOS(web_ui()); | |
| 278 ios::ChromeBrowserState* original_browser_state = | |
| 279 browser_state->GetOriginalChromeBrowserState(); | |
| 280 favicon::FaviconService* favicon_service = | |
| 281 ios::FaviconServiceFactory::GetForBrowserState( | |
| 282 original_browser_state, ServiceAccessType::EXPLICIT_ACCESS); | |
| 283 scoped_refptr<history::TopSites> top_sites = | |
| 284 ios::TopSitesFactory::GetForBrowserState(original_browser_state); | |
| 285 syncer::SyncService* sync_service = | |
| 286 IOSChromeProfileSyncServiceFactory::GetForBrowserState( | |
| 287 original_browser_state); | |
| 288 web::URLDataSourceIOS::Add( | |
| 289 browser_state, | |
| 290 new FaviconSource(favicon_service, top_sites, sync_service)); | |
| 291 | |
| 292 // Get notifications when history is cleared. | |
| 293 history::HistoryService* hs = ios::HistoryServiceFactory::GetForBrowserState( | |
| 294 browser_state, ServiceAccessType::EXPLICIT_ACCESS); | |
| 295 if (hs) | |
| 296 history_service_observer_.Add(hs); | |
| 297 | |
| 298 web_ui()->RegisterMessageCallback( | |
| 299 "queryHistory", base::Bind(&BrowsingHistoryHandler::HandleQueryHistory, | |
| 300 base::Unretained(this))); | |
| 301 web_ui()->RegisterMessageCallback( | |
| 302 "removeVisits", base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits, | |
| 303 base::Unretained(this))); | |
| 304 web_ui()->RegisterMessageCallback( | |
| 305 "clearBrowsingData", | |
| 306 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData, | |
| 307 base::Unretained(this))); | |
| 308 web_ui()->RegisterMessageCallback( | |
| 309 "removeBookmark", | |
| 310 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark, | |
| 311 base::Unretained(this))); | |
| 312 } | |
| 313 | |
| 314 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex( | |
| 315 const base::ListValue* value, | |
| 316 int index, | |
| 317 int* out_int) { | |
| 318 double double_value; | |
| 319 if (value->GetDouble(index, &double_value)) { | |
| 320 *out_int = static_cast<int>(double_value); | |
| 321 return true; | |
| 322 } | |
| 323 NOTREACHED(); | |
| 324 return false; | |
| 325 } | |
| 326 | |
| 327 void BrowsingHistoryHandler::WebHistoryTimeout() { | |
| 328 // TODO(dubroy): Communicate the failure to the front end. | |
| 329 if (!query_task_tracker_.HasTrackedTasks()) | |
| 330 ReturnResultsToFrontEnd(); | |
| 331 | |
| 332 UMA_HISTOGRAM_ENUMERATION("WebHistory.QueryCompletion", | |
| 333 WEB_HISTORY_QUERY_TIMED_OUT, | |
| 334 NUM_WEB_HISTORY_QUERY_BUCKETS); | |
| 335 } | |
| 336 | |
| 337 void BrowsingHistoryHandler::QueryHistory( | |
| 338 const base::string16& search_text, | |
| 339 const history::QueryOptions& options) { | |
| 340 ios::ChromeBrowserState* browser_state = | |
| 341 ios::ChromeBrowserState::FromWebUIIOS(web_ui()); | |
| 342 | |
| 343 // Anything in-flight is invalid. | |
| 344 query_task_tracker_.TryCancelAll(); | |
| 345 web_history_request_.reset(); | |
| 346 | |
| 347 query_results_.clear(); | |
| 348 results_info_value_.Clear(); | |
| 349 has_synced_results_ = false; | |
| 350 has_other_forms_of_browsing_history_ = false; | |
| 351 | |
| 352 history::HistoryService* hs = ios::HistoryServiceFactory::GetForBrowserState( | |
| 353 browser_state, ServiceAccessType::EXPLICIT_ACCESS); | |
| 354 hs->QueryHistory(search_text, options, | |
| 355 base::Bind(&BrowsingHistoryHandler::QueryComplete, | |
| 356 base::Unretained(this), search_text, options), | |
| 357 &query_task_tracker_); | |
| 358 | |
| 359 history::WebHistoryService* web_history = | |
| 360 ios::WebHistoryServiceFactory::GetForBrowserState(browser_state); | |
| 361 if (web_history) { | |
| 362 web_history_query_results_.clear(); | |
| 363 web_history_request_ = web_history->QueryHistory( | |
| 364 search_text, options, | |
| 365 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete, | |
| 366 base::Unretained(this), search_text, options, | |
| 367 base::TimeTicks::Now())); | |
| 368 // Start a timer so we know when to give up. | |
| 369 web_history_timer_.Start( | |
| 370 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds), | |
| 371 this, &BrowsingHistoryHandler::WebHistoryTimeout); | |
| 372 | |
| 373 browser_sync::ProfileSyncService* sync_service = | |
| 374 IOSChromeProfileSyncServiceFactory::GetInstance()->GetForBrowserState( | |
| 375 browser_state); | |
| 376 // Test the existence of other forms of browsing history. | |
| 377 browsing_data::ShouldShowNoticeAboutOtherFormsOfBrowsingHistory( | |
| 378 sync_service, web_history, | |
| 379 base::Bind( | |
| 380 &BrowsingHistoryHandler::OtherFormsOfBrowsingHistoryQueryComplete, | |
| 381 weak_factory_.GetWeakPtr())); | |
| 382 | |
| 383 // Set this to false until the results actually arrive. | |
| 384 results_info_value_.SetBoolean("hasSyncedResults", false); | |
| 385 } else { | |
| 386 // The notice could not have been shown, because there is no web history. | |
| 387 RecordMetricsForNoticeAboutOtherFormsOfBrowsingHistory(false); | |
| 388 } | |
| 389 } | |
| 390 | |
| 391 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) { | |
| 392 history::QueryOptions options; | |
| 393 | |
| 394 // Parse the arguments from JavaScript. There are five required arguments: | |
| 395 // - the text to search for (may be empty) | |
| 396 // - the offset from which the search should start (in multiples of week or | |
| 397 // month, set by the next argument). | |
| 398 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range | |
| 399 // of the query. | |
| 400 // - the end time for the query. Only results older than this time will be | |
| 401 // returned. | |
| 402 // - the maximum number of results to return (may be 0, meaning that there | |
| 403 // is no maximum). | |
| 404 base::string16 search_text = ExtractStringValue(args); | |
| 405 int offset; | |
| 406 if (!args->GetInteger(1, &offset)) { | |
| 407 NOTREACHED() << "Failed to convert argument 1. "; | |
| 408 return; | |
| 409 } | |
| 410 int range; | |
| 411 if (!args->GetInteger(2, &range)) { | |
| 412 NOTREACHED() << "Failed to convert argument 2. "; | |
| 413 return; | |
| 414 } | |
| 415 | |
| 416 if (range == BrowsingHistoryHandler::MONTH) | |
| 417 SetQueryTimeInMonths(offset, &options); | |
| 418 else if (range == BrowsingHistoryHandler::WEEK) | |
| 419 SetQueryTimeInWeeks(offset, &options); | |
| 420 | |
| 421 double end_time; | |
| 422 if (!args->GetDouble(3, &end_time)) { | |
| 423 NOTREACHED() << "Failed to convert argument 3. "; | |
| 424 return; | |
| 425 } | |
| 426 if (end_time) | |
| 427 options.end_time = base::Time::FromJsTime(end_time); | |
| 428 | |
| 429 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) { | |
| 430 NOTREACHED() << "Failed to convert argument 4."; | |
| 431 return; | |
| 432 } | |
| 433 | |
| 434 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY; | |
| 435 QueryHistory(search_text, options); | |
| 436 } | |
| 437 | |
| 438 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) { | |
| 439 ios::ChromeBrowserState* browser_state = | |
| 440 ios::ChromeBrowserState::FromWebUIIOS(web_ui()); | |
| 441 // TODO(davidben): history.js is not aware of this failure and will still | |
| 442 // override |deleteCompleteCallback_|. | |
| 443 if (delete_task_tracker_.HasTrackedTasks() || has_pending_delete_request_) { | |
| 444 web_ui()->CallJavascriptFunction("deleteFailed"); | |
| 445 return; | |
| 446 } | |
| 447 | |
| 448 history::HistoryService* history_service = | |
| 449 ios::HistoryServiceFactory::GetForBrowserState( | |
| 450 browser_state, ServiceAccessType::EXPLICIT_ACCESS); | |
| 451 history::WebHistoryService* web_history = | |
| 452 ios::WebHistoryServiceFactory::GetForBrowserState(browser_state); | |
| 453 | |
| 454 base::Time now = base::Time::Now(); | |
| 455 std::vector<history::ExpireHistoryArgs> expire_list; | |
| 456 expire_list.reserve(args->GetSize()); | |
| 457 | |
| 458 DCHECK(urls_to_be_deleted_.empty()); | |
| 459 for (const auto& arg : *args) { | |
| 460 base::DictionaryValue* deletion = NULL; | |
| 461 base::string16 url; | |
| 462 base::ListValue* timestamps = NULL; | |
| 463 | |
| 464 // Each argument is a dictionary with properties "url" and "timestamps". | |
| 465 if (!(arg->GetAsDictionary(&deletion) && deletion->GetString("url", &url) && | |
| 466 deletion->GetList("timestamps", ×tamps))) { | |
| 467 NOTREACHED() << "Unable to extract arguments"; | |
| 468 return; | |
| 469 } | |
| 470 DCHECK(timestamps->GetSize() > 0); | |
| 471 | |
| 472 // In order to ensure that visits will be deleted from the server and other | |
| 473 // clients (even if they are offline), create a sync delete directive for | |
| 474 // each visit to be deleted. | |
| 475 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive; | |
| 476 sync_pb::GlobalIdDirective* global_id_directive = | |
| 477 delete_directive.mutable_global_id_directive(); | |
| 478 | |
| 479 double timestamp; | |
| 480 history::ExpireHistoryArgs* expire_args = NULL; | |
| 481 for (const auto& timestamp_value : *timestamps) { | |
| 482 if (!timestamp_value->GetAsDouble(×tamp)) { | |
| 483 NOTREACHED() << "Unable to extract visit timestamp."; | |
| 484 continue; | |
| 485 } | |
| 486 base::Time visit_time = base::Time::FromJsTime(timestamp); | |
| 487 if (!expire_args) { | |
| 488 GURL gurl(url); | |
| 489 expire_list.resize(expire_list.size() + 1); | |
| 490 expire_args = &expire_list.back(); | |
| 491 expire_args->SetTimeRangeForOneDay(visit_time); | |
| 492 expire_args->urls.insert(gurl); | |
| 493 urls_to_be_deleted_.insert(gurl); | |
| 494 } | |
| 495 // The local visit time is treated as a global ID for the visit. | |
| 496 global_id_directive->add_global_id(visit_time.ToInternalValue()); | |
| 497 } | |
| 498 | |
| 499 // Set the start and end time in microseconds since the Unix epoch. | |
| 500 global_id_directive->set_start_time_usec( | |
| 501 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds()); | |
| 502 | |
| 503 // Delete directives shouldn't have an end time in the future. | |
| 504 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready. | |
| 505 base::Time end_time = std::min(expire_args->end_time, now); | |
| 506 | |
| 507 // -1 because end time in delete directives is inclusive. | |
| 508 global_id_directive->set_end_time_usec( | |
| 509 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1); | |
| 510 | |
| 511 // TODO(dubroy): Figure out the proper way to handle an error here. | |
| 512 if (web_history) | |
| 513 history_service->ProcessLocalDeleteDirective(delete_directive); | |
| 514 } | |
| 515 | |
| 516 history_service->ExpireHistory( | |
| 517 expire_list, base::Bind(&BrowsingHistoryHandler::RemoveComplete, | |
| 518 base::Unretained(this)), | |
| 519 &delete_task_tracker_); | |
| 520 | |
| 521 if (web_history) { | |
| 522 has_pending_delete_request_ = true; | |
| 523 web_history->ExpireHistory( | |
| 524 expire_list, | |
| 525 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete, | |
| 526 weak_factory_.GetWeakPtr())); | |
| 527 } | |
| 528 } | |
| 529 | |
| 530 void BrowsingHistoryHandler::HandleClearBrowsingData( | |
| 531 const base::ListValue* args) { | |
| 532 ShowClearBrowsingData(); | |
| 533 } | |
| 534 | |
| 535 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue* args) { | |
| 536 base::string16 url = ExtractStringValue(args); | |
| 537 ios::ChromeBrowserState* browser_state = | |
| 538 ios::ChromeBrowserState::FromWebUIIOS(web_ui()); | |
| 539 BookmarkModel* model = | |
| 540 ios::BookmarkModelFactory::GetForBrowserState(browser_state); | |
| 541 bookmarks::RemoveAllBookmarks(model, GURL(url)); | |
| 542 } | |
| 543 | |
| 544 // static | |
| 545 void BrowsingHistoryHandler::MergeDuplicateResults( | |
| 546 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) { | |
| 547 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results; | |
| 548 // Pre-reserve the size of the new vector. Since we're working with pointers | |
| 549 // later on not doing this could lead to the vector being resized and to | |
| 550 // pointers to invalid locations. | |
| 551 new_results.reserve(results->size()); | |
| 552 // Maps a URL to the most recent entry on a particular day. | |
| 553 std::map<GURL, BrowsingHistoryHandler::HistoryEntry*> current_day_entries; | |
| 554 | |
| 555 // Keeps track of the day that |current_day_urls| is holding the URLs for, | |
| 556 // in order to handle removing per-day duplicates. | |
| 557 base::Time current_day_midnight; | |
| 558 | |
| 559 std::sort(results->begin(), results->end(), | |
| 560 HistoryEntry::SortByTimeDescending); | |
| 561 | |
| 562 for (const BrowsingHistoryHandler::HistoryEntry& entry : *results) { | |
| 563 // Reset the list of found URLs when a visit from a new day is encountered. | |
| 564 if (current_day_midnight != entry.time.LocalMidnight()) { | |
| 565 current_day_entries.clear(); | |
| 566 current_day_midnight = entry.time.LocalMidnight(); | |
| 567 } | |
| 568 | |
| 569 // Keep this visit if it's the first visit to this URL on the current day. | |
| 570 if (current_day_entries.count(entry.url) == 0) { | |
| 571 new_results.push_back(entry); | |
| 572 current_day_entries[entry.url] = &new_results.back(); | |
| 573 } else { | |
| 574 // Keep track of the timestamps of all visits to the URL on the same day. | |
| 575 BrowsingHistoryHandler::HistoryEntry* combined_entry = | |
| 576 current_day_entries[entry.url]; | |
| 577 combined_entry->all_timestamps.insert(entry.all_timestamps.begin(), | |
| 578 entry.all_timestamps.end()); | |
| 579 | |
| 580 if (combined_entry->entry_type != entry.entry_type) { | |
| 581 combined_entry->entry_type = | |
| 582 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY; | |
| 583 } | |
| 584 } | |
| 585 } | |
| 586 results->swap(new_results); | |
| 587 } | |
| 588 | |
| 589 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() { | |
| 590 ios::ChromeBrowserState* browser_state = | |
| 591 ios::ChromeBrowserState::FromWebUIIOS(web_ui()); | |
| 592 BookmarkModel* bookmark_model = | |
| 593 ios::BookmarkModelFactory::GetForBrowserState(browser_state); | |
| 594 browser_sync::ProfileSyncService* sync_service = | |
| 595 IOSChromeProfileSyncServiceFactory::GetForBrowserState(browser_state); | |
| 596 | |
| 597 // Combine the local and remote results into |query_results_|, and remove | |
| 598 // any duplicates. | |
| 599 if (!web_history_query_results_.empty()) { | |
| 600 int local_result_count = query_results_.size(); | |
| 601 query_results_.insert(query_results_.end(), | |
| 602 web_history_query_results_.begin(), | |
| 603 web_history_query_results_.end()); | |
| 604 MergeDuplicateResults(&query_results_); | |
| 605 | |
| 606 if (local_result_count) { | |
| 607 // In the best case, we expect that all local results are duplicated on | |
| 608 // the server. Keep track of how many are missing. | |
| 609 int missing_count = std::count_if( | |
| 610 query_results_.begin(), query_results_.end(), IsLocalOnlyResult); | |
| 611 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer", | |
| 612 missing_count * 100.0 / local_result_count); | |
| 613 } | |
| 614 } | |
| 615 | |
| 616 // Convert the result vector into a ListValue. | |
| 617 base::ListValue results_value; | |
| 618 for (const BrowsingHistoryHandler::HistoryEntry& entry : query_results_) { | |
| 619 std::unique_ptr<base::Value> value( | |
| 620 entry.ToValue(bookmark_model, nullptr, sync_service)); | |
| 621 results_value.Append(value.release()); | |
| 622 } | |
| 623 | |
| 624 web_ui()->CallJavascriptFunction("historyResult", results_info_value_, | |
| 625 results_value); | |
| 626 web_ui()->CallJavascriptFunction( | |
| 627 "showNotification", base::FundamentalValue(has_synced_results_), | |
| 628 base::FundamentalValue(has_other_forms_of_browsing_history_)); | |
| 629 results_info_value_.Clear(); | |
| 630 query_results_.clear(); | |
| 631 web_history_query_results_.clear(); | |
| 632 } | |
| 633 | |
| 634 void BrowsingHistoryHandler::QueryComplete(const base::string16& search_text, | |
| 635 const history::QueryOptions& options, | |
| 636 history::QueryResults* results) { | |
| 637 DCHECK_EQ(0U, query_results_.size()); | |
| 638 query_results_.reserve(results->size()); | |
| 639 | |
| 640 for (size_t i = 0; i < results->size(); ++i) { | |
| 641 history::URLResult const& page = (*results)[i]; | |
| 642 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready. | |
| 643 query_results_.push_back( | |
| 644 HistoryEntry(HistoryEntry::LOCAL_ENTRY, page.url(), page.title(), | |
| 645 page.visit_time(), std::string(), !search_text.empty(), | |
| 646 page.snippet().text(), page.blocked_visit())); | |
| 647 } | |
| 648 | |
| 649 // The items which are to be written into results_info_value_ are also | |
| 650 // described in chrome/browser/resources/history/history.js in @typedef for | |
| 651 // HistoryQuery. Please update it whenever you add or remove any keys in | |
| 652 // results_info_value_. | |
| 653 results_info_value_.SetString("term", search_text); | |
| 654 results_info_value_.SetBoolean("finished", results->reached_beginning()); | |
| 655 | |
| 656 // Add the specific dates that were searched to display them. | |
| 657 // TODO(sergiu): Put today if the start is in the future. | |
| 658 results_info_value_.SetString("queryStartTime", | |
| 659 GetRelativeDateLocalized(options.begin_time)); | |
| 660 if (!options.end_time.is_null()) { | |
| 661 results_info_value_.SetString( | |
| 662 "queryEndTime", GetRelativeDateLocalized(options.end_time - | |
| 663 base::TimeDelta::FromDays(1))); | |
| 664 } else { | |
| 665 results_info_value_.SetString("queryEndTime", | |
| 666 GetRelativeDateLocalized(base::Time::Now())); | |
| 667 } | |
| 668 if (!web_history_timer_.IsRunning()) | |
| 669 ReturnResultsToFrontEnd(); | |
| 670 } | |
| 671 | |
| 672 void BrowsingHistoryHandler::WebHistoryQueryComplete( | |
| 673 const base::string16& search_text, | |
| 674 const history::QueryOptions& options, | |
| 675 base::TimeTicks start_time, | |
| 676 history::WebHistoryService::Request* request, | |
| 677 const base::DictionaryValue* results_value) { | |
| 678 base::TimeDelta delta = base::TimeTicks::Now() - start_time; | |
| 679 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta); | |
| 680 | |
| 681 // If the response came in too late, do nothing. | |
| 682 // TODO(dubroy): Maybe show a banner, and prompt the user to reload? | |
| 683 if (!web_history_timer_.IsRunning()) | |
| 684 return; | |
| 685 web_history_timer_.Stop(); | |
| 686 | |
| 687 UMA_HISTOGRAM_ENUMERATION( | |
| 688 "WebHistory.QueryCompletion", | |
| 689 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED, | |
| 690 NUM_WEB_HISTORY_QUERY_BUCKETS); | |
| 691 | |
| 692 DCHECK_EQ(0U, web_history_query_results_.size()); | |
| 693 const base::ListValue* events = NULL; | |
| 694 if (results_value && results_value->GetList("event", &events)) { | |
| 695 web_history_query_results_.reserve(events->GetSize()); | |
| 696 for (unsigned int i = 0; i < events->GetSize(); ++i) { | |
| 697 const base::DictionaryValue* event = NULL; | |
| 698 const base::DictionaryValue* result = NULL; | |
| 699 const base::ListValue* results = NULL; | |
| 700 const base::ListValue* ids = NULL; | |
| 701 base::string16 url; | |
| 702 base::string16 title; | |
| 703 base::Time visit_time; | |
| 704 | |
| 705 if (!(events->GetDictionary(i, &event) && | |
| 706 event->GetList("result", &results) && | |
| 707 results->GetDictionary(0, &result) && | |
| 708 result->GetString("url", &url) && result->GetList("id", &ids) && | |
| 709 ids->GetSize() > 0)) { | |
| 710 LOG(WARNING) << "Improperly formed JSON response from history server."; | |
| 711 continue; | |
| 712 } | |
| 713 | |
| 714 // Ignore any URLs that should not be shown in the history page. | |
| 715 GURL gurl(url); | |
| 716 if (!ios::CanAddURLToHistory(gurl)) | |
| 717 continue; | |
| 718 | |
| 719 // Title is optional, so the return value is ignored here. | |
| 720 result->GetString("title", &title); | |
| 721 | |
| 722 // Extract the timestamps of all the visits to this URL. | |
| 723 // They are referred to as "IDs" by the server. | |
| 724 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) { | |
| 725 const base::DictionaryValue* id = NULL; | |
| 726 std::string timestamp_string; | |
| 727 int64_t timestamp_usec = 0; | |
| 728 | |
| 729 if (!ids->GetDictionary(j, &id) || | |
| 730 !id->GetString("timestamp_usec", ×tamp_string) || | |
| 731 !base::StringToInt64(timestamp_string, ×tamp_usec)) { | |
| 732 NOTREACHED() << "Unable to extract timestamp."; | |
| 733 continue; | |
| 734 } | |
| 735 // The timestamp on the server is a Unix time. | |
| 736 base::Time time = base::Time::UnixEpoch() + | |
| 737 base::TimeDelta::FromMicroseconds(timestamp_usec); | |
| 738 | |
| 739 // Get the ID of the client that this visit came from. | |
| 740 std::string client_id; | |
| 741 id->GetString("client_id", &client_id); | |
| 742 | |
| 743 web_history_query_results_.push_back( | |
| 744 HistoryEntry(HistoryEntry::REMOTE_ENTRY, gurl, title, time, | |
| 745 client_id, !search_text.empty(), base::string16(), | |
| 746 /* blocked_visit */ false)); | |
| 747 } | |
| 748 } | |
| 749 } | |
| 750 has_synced_results_ = results_value != nullptr; | |
| 751 results_info_value_.SetBoolean("hasSyncedResults", has_synced_results_); | |
| 752 if (!query_task_tracker_.HasTrackedTasks()) | |
| 753 ReturnResultsToFrontEnd(); | |
| 754 } | |
| 755 | |
| 756 void BrowsingHistoryHandler::OtherFormsOfBrowsingHistoryQueryComplete( | |
| 757 bool found_other_forms_of_browsing_history) { | |
| 758 has_other_forms_of_browsing_history_ = found_other_forms_of_browsing_history; | |
| 759 RecordMetricsForNoticeAboutOtherFormsOfBrowsingHistory( | |
| 760 has_other_forms_of_browsing_history_); | |
| 761 web_ui()->CallJavascriptFunction( | |
| 762 "showNotification", base::FundamentalValue(has_synced_results_), | |
| 763 base::FundamentalValue(has_other_forms_of_browsing_history_)); | |
| 764 } | |
| 765 | |
| 766 void BrowsingHistoryHandler::RemoveComplete() { | |
| 767 urls_to_be_deleted_.clear(); | |
| 768 | |
| 769 // Notify the page that the deletion request is complete, but only if a web | |
| 770 // history delete request is not still pending. | |
| 771 if (!has_pending_delete_request_) | |
| 772 web_ui()->CallJavascriptFunction("deleteComplete"); | |
| 773 } | |
| 774 | |
| 775 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success) { | |
| 776 has_pending_delete_request_ = false; | |
| 777 // TODO(dubroy): Should we handle failure somehow? Delete directives will | |
| 778 // ensure that the visits are eventually deleted, so maybe it's not necessary. | |
| 779 if (!delete_task_tracker_.HasTrackedTasks()) | |
| 780 RemoveComplete(); | |
| 781 } | |
| 782 | |
| 783 void BrowsingHistoryHandler::SetQueryTimeInWeeks( | |
| 784 int offset, | |
| 785 history::QueryOptions* options) { | |
| 786 // LocalMidnight returns the beginning of the current day so get the | |
| 787 // beginning of the next one. | |
| 788 base::Time midnight = | |
| 789 base::Time::Now().LocalMidnight() + base::TimeDelta::FromDays(1); | |
| 790 options->end_time = midnight - base::TimeDelta::FromDays(7 * offset); | |
| 791 options->begin_time = midnight - base::TimeDelta::FromDays(7 * (offset + 1)); | |
| 792 } | |
| 793 | |
| 794 void BrowsingHistoryHandler::SetQueryTimeInMonths( | |
| 795 int offset, | |
| 796 history::QueryOptions* options) { | |
| 797 // Configure the begin point of the search to the start of the | |
| 798 // current month. | |
| 799 base::Time::Exploded exploded; | |
| 800 base::Time::Now().LocalMidnight().LocalExplode(&exploded); | |
| 801 exploded.day_of_month = 1; | |
| 802 | |
| 803 if (offset == 0) { | |
| 804 if (!base::Time::FromLocalExploded(exploded, &options->begin_time)) { | |
| 805 // This file will be deprecated soon. No need to implement failure | |
| 806 // handling here. | |
| 807 NOTIMPLEMENTED(); | |
| 808 } | |
| 809 | |
| 810 // Set the end time of this first search to null (which will | |
| 811 // show results from the future, should the user's clock have | |
| 812 // been set incorrectly). | |
| 813 options->end_time = base::Time(); | |
| 814 } else { | |
| 815 // Go back |offset| months in the past. The end time is not inclusive, so | |
| 816 // use the first day of the |offset| - 1 and |offset| months (e.g. for | |
| 817 // the last month, |offset| = 1, use the first days of the last month and | |
| 818 // the current month. | |
| 819 exploded.month -= offset - 1; | |
| 820 // Set the correct year. | |
| 821 NormalizeMonths(&exploded); | |
| 822 if (!base::Time::FromLocalExploded(exploded, &options->end_time)) { | |
| 823 // This file will be deprecated soon. No need to implement failure | |
| 824 // handling here. | |
| 825 NOTIMPLEMENTED(); | |
| 826 } | |
| 827 | |
| 828 exploded.month -= 1; | |
| 829 // Set the correct year | |
| 830 NormalizeMonths(&exploded); | |
| 831 if (!base::Time::FromLocalExploded(exploded, &options->begin_time)) { | |
| 832 // This file will be deprecated soon. No need to implement failure | |
| 833 // handling here. | |
| 834 NOTIMPLEMENTED(); | |
| 835 } | |
| 836 } | |
| 837 } | |
| 838 | |
| 839 // Helper function for Observe that determines if there are any differences | |
| 840 // between the URLs noticed for deletion and the ones we are expecting. | |
| 841 static bool DeletionsDiffer(const history::URLRows& deleted_rows, | |
| 842 const std::set<GURL>& urls_to_be_deleted) { | |
| 843 if (deleted_rows.size() != urls_to_be_deleted.size()) | |
| 844 return true; | |
| 845 for (const auto& i : deleted_rows) { | |
| 846 if (urls_to_be_deleted.find(i.url()) == urls_to_be_deleted.end()) | |
| 847 return true; | |
| 848 } | |
| 849 return false; | |
| 850 } | |
| 851 | |
| 852 void BrowsingHistoryHandler::OnURLsDeleted( | |
| 853 history::HistoryService* history_service, | |
| 854 bool all_history, | |
| 855 bool expired, | |
| 856 const history::URLRows& deleted_rows, | |
| 857 const std::set<GURL>& favicon_urls) { | |
| 858 if (all_history || DeletionsDiffer(deleted_rows, urls_to_be_deleted_)) | |
| 859 web_ui()->CallJavascriptFunction("historyDeleted"); | |
| 860 } | |
| OLD | NEW |