history_backend.cc revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "chrome/browser/history/history_backend.h" 6 7#include <algorithm> 8#include <functional> 9#include <list> 10#include <map> 11#include <set> 12#include <vector> 13 14#include "base/basictypes.h" 15#include "base/bind.h" 16#include "base/compiler_specific.h" 17#include "base/file_util.h" 18#include "base/memory/scoped_ptr.h" 19#include "base/memory/scoped_vector.h" 20#include "base/message_loop.h" 21#include "base/metrics/histogram.h" 22#include "base/rand_util.h" 23#include "base/string_util.h" 24#include "base/time.h" 25#include "base/utf_string_conversions.h" 26#include "chrome/browser/autocomplete/history_url_provider.h" 27#include "chrome/browser/bookmarks/bookmark_service.h" 28#include "chrome/browser/history/download_row.h" 29#include "chrome/browser/history/history_db_task.h" 30#include "chrome/browser/history/history_notifications.h" 31#include "chrome/browser/history/history_publisher.h" 32#include "chrome/browser/history/in_memory_history_backend.h" 33#include "chrome/browser/history/page_usage_data.h" 34#include "chrome/browser/history/select_favicon_frames.h" 35#include "chrome/browser/history/top_sites.h" 36#include "chrome/browser/history/typed_url_syncable_service.h" 37#include "chrome/browser/history/visit_filter.h" 38#include "chrome/common/chrome_constants.h" 39#include "chrome/common/chrome_notification_types.h" 40#include "chrome/common/url_constants.h" 41#include "googleurl/src/gurl.h" 42#include "grit/chromium_strings.h" 43#include "grit/generated_resources.h" 44#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 45#include "sql/error_delegate_util.h" 46 47#if defined(OS_ANDROID) 48#include "chrome/browser/history/android/android_provider_backend.h" 49#endif 50 51using base::Time; 52using base::TimeDelta; 53using base::TimeTicks; 54 55/* The HistoryBackend consists of a number of components: 56 57 HistoryDatabase (stores past 3 months of history) 58 URLDatabase (stores a list of URLs) 59 DownloadDatabase (stores a list of downloads) 60 VisitDatabase (stores a list of visits for the URLs) 61 VisitSegmentDatabase (stores groups of URLs for the most visited view). 62 63 ArchivedDatabase (stores history older than 3 months) 64 URLDatabase (stores a list of URLs) 65 DownloadDatabase (stores a list of downloads) 66 VisitDatabase (stores a list of visits for the URLs) 67 68 (this does not store visit segments as they expire after 3 mos.) 69 70 TextDatabaseManager (manages multiple text database for different times) 71 TextDatabase (represents a single month of full-text index). 72 ...more TextDatabase objects... 73 74 ExpireHistoryBackend (manages moving things from HistoryDatabase to 75 the ArchivedDatabase and deleting) 76*/ 77 78namespace history { 79 80// How long we keep segment data for in days. Currently 3 months. 81// This value needs to be greater or equal to 82// MostVisitedModel::kMostVisitedScope but we don't want to introduce a direct 83// dependency between MostVisitedModel and the history backend. 84static const int kSegmentDataRetention = 90; 85 86// How long we'll wait to do a commit, so that things are batched together. 87static const int kCommitIntervalSeconds = 10; 88 89// The amount of time before we re-fetch the favicon. 90static const int kFaviconRefetchDays = 7; 91 92// GetSessionTabs returns all open tabs, or tabs closed kSessionCloseTimeWindow 93// seconds ago. 94static const int kSessionCloseTimeWindowSecs = 10; 95 96// The maximum number of items we'll allow in the redirect list before 97// deleting some. 98static const int kMaxRedirectCount = 32; 99 100// The number of days old a history entry can be before it is considered "old" 101// and is archived. 102static const int kArchiveDaysThreshold = 90; 103 104// Converts from PageUsageData to MostVisitedURL. |redirects| is a 105// list of redirects for this URL. Empty list means no redirects. 106MostVisitedURL MakeMostVisitedURL(const PageUsageData& page_data, 107 const RedirectList& redirects) { 108 MostVisitedURL mv; 109 mv.url = page_data.GetURL(); 110 mv.title = page_data.GetTitle(); 111 if (redirects.empty()) { 112 // Redirects must contain at least the target url. 113 mv.redirects.push_back(mv.url); 114 } else { 115 mv.redirects = redirects; 116 if (mv.redirects[mv.redirects.size() - 1] != mv.url) { 117 // The last url must be the target url. 118 mv.redirects.push_back(mv.url); 119 } 120 } 121 return mv; 122} 123 124// This task is run on a timer so that commits happen at regular intervals 125// so they are batched together. The important thing about this class is that 126// it supports canceling of the task so the reference to the backend will be 127// freed. The problem is that when history is shutting down, there is likely 128// to be one of these commits still pending and holding a reference. 129// 130// The backend can call Cancel to have this task release the reference. The 131// task will still run (if we ever get to processing the event before 132// shutdown), but it will not do anything. 133// 134// Note that this is a refcounted object and is not a task in itself. It should 135// be assigned to a RunnableMethod. 136// 137// TODO(brettw): bug 1165182: This should be replaced with a 138// base::WeakPtrFactory which will handle everything automatically (like we do 139// in ExpireHistoryBackend). 140class CommitLaterTask : public base::RefCounted<CommitLaterTask> { 141 public: 142 explicit CommitLaterTask(HistoryBackend* history_backend) 143 : history_backend_(history_backend) { 144 } 145 146 // The backend will call this function if it is being destroyed so that we 147 // release our reference. 148 void Cancel() { 149 history_backend_ = NULL; 150 } 151 152 void RunCommit() { 153 if (history_backend_) 154 history_backend_->Commit(); 155 } 156 157 private: 158 friend class base::RefCounted<CommitLaterTask>; 159 160 ~CommitLaterTask() {} 161 162 scoped_refptr<HistoryBackend> history_backend_; 163}; 164 165// Handles querying first the main database, then the full text database if that 166// fails. It will optionally keep track of all URLs seen so duplicates can be 167// eliminated. This is used by the querying sub-functions. 168// 169// TODO(brettw): This class may be able to be simplified or eliminated. After 170// this was written, QueryResults can efficiently look up by URL, so the need 171// for this extra set of previously queried URLs is less important. 172class HistoryBackend::URLQuerier { 173 public: 174 URLQuerier(URLDatabase* main_db, URLDatabase* archived_db, bool track_unique) 175 : main_db_(main_db), 176 archived_db_(archived_db), 177 track_unique_(track_unique) { 178 } 179 180 // When we're tracking unique URLs, returns true if this URL has been 181 // previously queried. Only call when tracking unique URLs. 182 bool HasURL(const GURL& url) { 183 DCHECK(track_unique_); 184 return unique_urls_.find(url) != unique_urls_.end(); 185 } 186 187 bool GetRowForURL(const GURL& url, URLRow* row) { 188 if (!main_db_->GetRowForURL(url, row)) { 189 if (!archived_db_ || !archived_db_->GetRowForURL(url, row)) { 190 // This row is neither in the main nor the archived DB. 191 return false; 192 } 193 } 194 195 if (track_unique_) 196 unique_urls_.insert(url); 197 return true; 198 } 199 200 private: 201 URLDatabase* main_db_; // Guaranteed non-NULL. 202 URLDatabase* archived_db_; // Possibly NULL. 203 204 bool track_unique_; 205 206 // When track_unique_ is set, this is updated with every URL seen so far. 207 std::set<GURL> unique_urls_; 208 209 DISALLOW_COPY_AND_ASSIGN(URLQuerier); 210}; 211 212// KillHistoryDatabaseErrorDelegate ------------------------------------------- 213 214class KillHistoryDatabaseErrorDelegate : public sql::ErrorDelegate { 215 public: 216 explicit KillHistoryDatabaseErrorDelegate(HistoryBackend* backend) 217 : backend_(backend), 218 scheduled_killing_database_(false) { 219 } 220 221 // sql::ErrorDelegate implementation. 222 virtual int OnError(int error, 223 sql::Connection* connection, 224 sql::Statement* stmt) OVERRIDE { 225 // Do not schedule killing database more than once. If the first time 226 // failed, it is unlikely that a second time will be successful. 227 if (!scheduled_killing_database_ && sql::IsErrorCatastrophic(error)) { 228 scheduled_killing_database_ = true; 229 230 // Don't just do the close/delete here, as we are being called by |db| and 231 // that seems dangerous. 232 MessageLoop::current()->PostTask( 233 FROM_HERE, 234 base::Bind(&HistoryBackend::KillHistoryDatabase, backend_)); 235 } 236 237 return error; 238 } 239 240 // Returns true if the delegate has previously scheduled killing the database. 241 bool scheduled_killing_database() const { 242 return scheduled_killing_database_; 243 } 244 245 private: 246 // Do not increment the count on |HistoryBackend| as that would create a 247 // circular reference (HistoryBackend -> HistoryDatabase -> Connection -> 248 // ErrorDelegate -> HistoryBackend). 249 HistoryBackend* backend_; 250 251 // True if the backend has previously scheduled killing the history database. 252 bool scheduled_killing_database_; 253 254 DISALLOW_COPY_AND_ASSIGN(KillHistoryDatabaseErrorDelegate); 255}; 256 257// HistoryBackend -------------------------------------------------------------- 258 259HistoryBackend::HistoryBackend(const base::FilePath& history_dir, 260 int id, 261 Delegate* delegate, 262 BookmarkService* bookmark_service) 263 : delegate_(delegate), 264 id_(id), 265 history_dir_(history_dir), 266 expirer_(this, bookmark_service), 267 recent_redirects_(kMaxRedirectCount), 268 backend_destroy_message_loop_(NULL), 269 segment_queried_(false), 270 bookmark_service_(bookmark_service) { 271} 272 273HistoryBackend::~HistoryBackend() { 274 DCHECK(!scheduled_commit_) << "Deleting without cleanup"; 275 ReleaseDBTasks(); 276 277#if defined(OS_ANDROID) 278 // Release AndroidProviderBackend before other objects. 279 android_provider_backend_.reset(); 280#endif 281 282 // First close the databases before optionally running the "destroy" task. 283 CloseAllDatabases(); 284 285 if (!backend_destroy_task_.is_null()) { 286 // Notify an interested party (typically a unit test) that we're done. 287 DCHECK(backend_destroy_message_loop_); 288 backend_destroy_message_loop_->PostTask(FROM_HERE, backend_destroy_task_); 289 } 290 291#if defined(OS_ANDROID) 292 file_util::Delete(GetAndroidCacheFileName(), false); 293#endif 294} 295 296void HistoryBackend::Init(const std::string& languages, bool force_fail) { 297 if (!force_fail) 298 InitImpl(languages); 299 delegate_->DBLoaded(id_); 300 typed_url_syncable_service_.reset(new TypedUrlSyncableService(this)); 301} 302 303void HistoryBackend::SetOnBackendDestroyTask(MessageLoop* message_loop, 304 const base::Closure& task) { 305 if (!backend_destroy_task_.is_null()) 306 DLOG(WARNING) << "Setting more than one destroy task, overriding"; 307 backend_destroy_message_loop_ = message_loop; 308 backend_destroy_task_ = task; 309} 310 311void HistoryBackend::Closing() { 312 // Any scheduled commit will have a reference to us, we must make it 313 // release that reference before we can be destroyed. 314 CancelScheduledCommit(); 315 316 // Release our reference to the delegate, this reference will be keeping the 317 // history service alive. 318 delegate_.reset(); 319} 320 321void HistoryBackend::NotifyRenderProcessHostDestruction(const void* host) { 322 tracker_.NotifyRenderProcessHostDestruction(host); 323} 324 325base::FilePath HistoryBackend::GetThumbnailFileName() const { 326 return history_dir_.Append(chrome::kThumbnailsFilename); 327} 328 329base::FilePath HistoryBackend::GetFaviconsFileName() const { 330 return history_dir_.Append(chrome::kFaviconsFilename); 331} 332 333base::FilePath HistoryBackend::GetArchivedFileName() const { 334 return history_dir_.Append(chrome::kArchivedHistoryFilename); 335} 336 337#if defined(OS_ANDROID) 338base::FilePath HistoryBackend::GetAndroidCacheFileName() const { 339 return history_dir_.Append(chrome::kAndroidCacheFilename); 340} 341#endif 342 343SegmentID HistoryBackend::GetLastSegmentID(VisitID from_visit) { 344 // Set is used to detect referrer loops. Should not happen, but can 345 // if the database is corrupt. 346 std::set<VisitID> visit_set; 347 VisitID visit_id = from_visit; 348 while (visit_id) { 349 VisitRow row; 350 if (!db_->GetRowForVisit(visit_id, &row)) 351 return 0; 352 if (row.segment_id) 353 return row.segment_id; // Found a visit in this change with a segment. 354 355 // Check the referrer of this visit, if any. 356 visit_id = row.referring_visit; 357 358 if (visit_set.find(visit_id) != visit_set.end()) { 359 NOTREACHED() << "Loop in referer chain, giving up"; 360 break; 361 } 362 visit_set.insert(visit_id); 363 } 364 return 0; 365} 366 367SegmentID HistoryBackend::UpdateSegments( 368 const GURL& url, 369 VisitID from_visit, 370 VisitID visit_id, 371 content::PageTransition transition_type, 372 const Time ts) { 373 if (!db_) 374 return 0; 375 376 // We only consider main frames. 377 if (!content::PageTransitionIsMainFrame(transition_type)) 378 return 0; 379 380 SegmentID segment_id = 0; 381 content::PageTransition t = 382 content::PageTransitionStripQualifier(transition_type); 383 384 // Are we at the beginning of a new segment? 385 // Note that navigating to an existing entry (with back/forward) reuses the 386 // same transition type. We are not adding it as a new segment in that case 387 // because if this was the target of a redirect, we might end up with 388 // 2 entries for the same final URL. Ex: User types google.net, gets 389 // redirected to google.com. A segment is created for google.net. On 390 // google.com users navigates through a link, then press back. That last 391 // navigation is for the entry google.com transition typed. We end up adding 392 // a segment for that one as well. So we end up with google.net and google.com 393 // in the segement table, showing as 2 entries in the NTP. 394 // Note also that we should still be updating the visit count for that segment 395 // which we are not doing now. It should be addressed when 396 // http://crbug.com/96860 is fixed. 397 if ((t == content::PAGE_TRANSITION_TYPED || 398 t == content::PAGE_TRANSITION_AUTO_BOOKMARK) && 399 (transition_type & content::PAGE_TRANSITION_FORWARD_BACK) == 0) { 400 // If so, create or get the segment. 401 std::string segment_name = db_->ComputeSegmentName(url); 402 URLID url_id = db_->GetRowForURL(url, NULL); 403 if (!url_id) 404 return 0; 405 406 if (!(segment_id = db_->GetSegmentNamed(segment_name))) { 407 if (!(segment_id = db_->CreateSegment(url_id, segment_name))) { 408 NOTREACHED(); 409 return 0; 410 } 411 } else { 412 // Note: if we update an existing segment, we update the url used to 413 // represent that segment in order to minimize stale most visited 414 // images. 415 db_->UpdateSegmentRepresentationURL(segment_id, url_id); 416 } 417 } else { 418 // Note: it is possible there is no segment ID set for this visit chain. 419 // This can happen if the initial navigation wasn't AUTO_BOOKMARK or 420 // TYPED. (For example GENERATED). In this case this visit doesn't count 421 // toward any segment. 422 if (!(segment_id = GetLastSegmentID(from_visit))) 423 return 0; 424 } 425 426 // Set the segment in the visit. 427 if (!db_->SetSegmentID(visit_id, segment_id)) { 428 NOTREACHED(); 429 return 0; 430 } 431 432 // Finally, increase the counter for that segment / day. 433 if (!db_->IncreaseSegmentVisitCount(segment_id, ts, 1)) { 434 NOTREACHED(); 435 return 0; 436 } 437 return segment_id; 438} 439 440void HistoryBackend::UpdateWithPageEndTime(const void* host, 441 int32 page_id, 442 const GURL& url, 443 Time end_ts) { 444 // Will be filled with the URL ID and the visit ID of the last addition. 445 VisitID visit_id = tracker_.GetLastVisit(host, page_id, url); 446 UpdateVisitDuration(visit_id, end_ts); 447} 448 449void HistoryBackend::UpdateVisitDuration(VisitID visit_id, const Time end_ts) { 450 if (!db_) 451 return; 452 453 // Get the starting visit_time for visit_id. 454 VisitRow visit_row; 455 if (db_->GetRowForVisit(visit_id, &visit_row)) { 456 // We should never have a negative duration time even when time is skewed. 457 visit_row.visit_duration = end_ts > visit_row.visit_time ? 458 end_ts - visit_row.visit_time : TimeDelta::FromMicroseconds(0); 459 db_->UpdateVisitRow(visit_row); 460 } 461} 462 463void HistoryBackend::AddPage(const HistoryAddPageArgs& request) { 464 if (!db_) 465 return; 466 467 // Will be filled with the URL ID and the visit ID of the last addition. 468 std::pair<URLID, VisitID> last_ids(0, tracker_.GetLastVisit( 469 request.id_scope, request.page_id, request.referrer)); 470 471 VisitID from_visit_id = last_ids.second; 472 473 // If a redirect chain is given, we expect the last item in that chain to be 474 // the final URL. 475 DCHECK(request.redirects.empty() || 476 request.redirects.back() == request.url); 477 478 // If the user is adding older history, we need to make sure our times 479 // are correct. 480 if (request.time < first_recorded_time_) 481 first_recorded_time_ = request.time; 482 483 content::PageTransition request_transition = request.transition; 484 content::PageTransition stripped_transition = 485 content::PageTransitionStripQualifier(request_transition); 486 bool is_keyword_generated = 487 (stripped_transition == content::PAGE_TRANSITION_KEYWORD_GENERATED); 488 489 // If the user is navigating to a not-previously-typed intranet hostname, 490 // change the transition to TYPED so that the omnibox will learn that this is 491 // a known host. 492 bool has_redirects = request.redirects.size() > 1; 493 if (content::PageTransitionIsMainFrame(request_transition) && 494 (stripped_transition != content::PAGE_TRANSITION_TYPED) && 495 !is_keyword_generated) { 496 const GURL& origin_url(has_redirects ? 497 request.redirects[0] : request.url); 498 if (origin_url.SchemeIs(chrome::kHttpScheme) || 499 origin_url.SchemeIs(chrome::kHttpsScheme) || 500 origin_url.SchemeIs(chrome::kFtpScheme)) { 501 std::string host(origin_url.host()); 502 if ((net::RegistryControlledDomainService::GetRegistryLength( 503 host, false) == 0) && !db_->IsTypedHost(host)) { 504 stripped_transition = content::PAGE_TRANSITION_TYPED; 505 request_transition = 506 content::PageTransitionFromInt( 507 stripped_transition | 508 content::PageTransitionGetQualifier(request_transition)); 509 } 510 } 511 } 512 513 if (!has_redirects) { 514 // The single entry is both a chain start and end. 515 content::PageTransition t = content::PageTransitionFromInt( 516 request_transition | 517 content::PAGE_TRANSITION_CHAIN_START | 518 content::PAGE_TRANSITION_CHAIN_END); 519 520 // No redirect case (one element means just the page itself). 521 last_ids = AddPageVisit(request.url, request.time, 522 last_ids.second, t, request.visit_source); 523 524 // Update the segment for this visit. KEYWORD_GENERATED visits should not 525 // result in changing most visited, so we don't update segments (most 526 // visited db). 527 if (!is_keyword_generated) { 528 UpdateSegments(request.url, from_visit_id, last_ids.second, t, 529 request.time); 530 531 // Update the referrer's duration. 532 UpdateVisitDuration(from_visit_id, request.time); 533 } 534 } else { 535 // Redirect case. Add the redirect chain. 536 537 content::PageTransition redirect_info = 538 content::PAGE_TRANSITION_CHAIN_START; 539 540 RedirectList redirects = request.redirects; 541 if (redirects[0].SchemeIs(chrome::kAboutScheme)) { 542 // When the redirect source + referrer is "about" we skip it. This 543 // happens when a page opens a new frame/window to about:blank and then 544 // script sets the URL to somewhere else (used to hide the referrer). It 545 // would be nice to keep all these redirects properly but we don't ever 546 // see the initial about:blank load, so we don't know where the 547 // subsequent client redirect came from. 548 // 549 // In this case, we just don't bother hooking up the source of the 550 // redirects, so we remove it. 551 redirects.erase(redirects.begin()); 552 } else if (request_transition & content::PAGE_TRANSITION_CLIENT_REDIRECT) { 553 redirect_info = content::PAGE_TRANSITION_CLIENT_REDIRECT; 554 // The first entry in the redirect chain initiated a client redirect. 555 // We don't add this to the database since the referrer is already 556 // there, so we skip over it but change the transition type of the first 557 // transition to client redirect. 558 // 559 // The referrer is invalid when restoring a session that features an 560 // https tab that redirects to a different host or to http. In this 561 // case we don't need to reconnect the new redirect with the existing 562 // chain. 563 if (request.referrer.is_valid()) { 564 DCHECK(request.referrer == redirects[0]); 565 redirects.erase(redirects.begin()); 566 567 // If the navigation entry for this visit has replaced that for the 568 // first visit, remove the CHAIN_END marker from the first visit. This 569 // can be called a lot, for example, the page cycler, and most of the 570 // time we won't have changed anything. 571 VisitRow visit_row; 572 if (request.did_replace_entry && 573 db_->GetRowForVisit(last_ids.second, &visit_row) && 574 visit_row.transition & content::PAGE_TRANSITION_CHAIN_END) { 575 visit_row.transition = content::PageTransitionFromInt( 576 visit_row.transition & ~content::PAGE_TRANSITION_CHAIN_END); 577 db_->UpdateVisitRow(visit_row); 578 } 579 } 580 } 581 582 for (size_t redirect_index = 0; redirect_index < redirects.size(); 583 redirect_index++) { 584 content::PageTransition t = 585 content::PageTransitionFromInt(stripped_transition | redirect_info); 586 587 // If this is the last transition, add a CHAIN_END marker 588 if (redirect_index == (redirects.size() - 1)) { 589 t = content::PageTransitionFromInt( 590 t | content::PAGE_TRANSITION_CHAIN_END); 591 } 592 593 // Record all redirect visits with the same timestamp. We don't display 594 // them anyway, and if we ever decide to, we can reconstruct their order 595 // from the redirect chain. 596 last_ids = AddPageVisit(redirects[redirect_index], 597 request.time, last_ids.second, 598 t, request.visit_source); 599 if (t & content::PAGE_TRANSITION_CHAIN_START) { 600 // Update the segment for this visit. 601 UpdateSegments(redirects[redirect_index], 602 from_visit_id, last_ids.second, t, request.time); 603 604 // Update the visit_details for this visit. 605 UpdateVisitDuration(from_visit_id, request.time); 606 } 607 608 // Subsequent transitions in the redirect list must all be server 609 // redirects. 610 redirect_info = content::PAGE_TRANSITION_SERVER_REDIRECT; 611 } 612 613 // Last, save this redirect chain for later so we can set titles & favicons 614 // on the redirected pages properly. It is indexed by the destination page. 615 recent_redirects_.Put(request.url, redirects); 616 } 617 618 // TODO(brettw) bug 1140015: Add an "add page" notification so the history 619 // views can keep in sync. 620 621 // Add the last visit to the tracker so we can get outgoing transitions. 622 // TODO(evanm): Due to http://b/1194536 we lose the referrers of a subframe 623 // navigation anyway, so last_visit_id is always zero for them. But adding 624 // them here confuses main frame history, so we skip them for now. 625 if (stripped_transition != content::PAGE_TRANSITION_AUTO_SUBFRAME && 626 stripped_transition != content::PAGE_TRANSITION_MANUAL_SUBFRAME && 627 !is_keyword_generated) { 628 tracker_.AddVisit(request.id_scope, request.page_id, request.url, 629 last_ids.second); 630 } 631 632 if (text_database_) { 633 text_database_->AddPageURL(request.url, last_ids.first, last_ids.second, 634 request.time); 635 } 636 637 ScheduleCommit(); 638} 639 640void HistoryBackend::InitImpl(const std::string& languages) { 641 DCHECK(!db_) << "Initializing HistoryBackend twice"; 642 // In the rare case where the db fails to initialize a dialog may get shown 643 // the blocks the caller, yet allows other messages through. For this reason 644 // we only set db_ to the created database if creation is successful. That 645 // way other methods won't do anything as db_ is still NULL. 646 647 TimeTicks beginning_time = TimeTicks::Now(); 648 649 // Compute the file names. Note that the index file can be removed when the 650 // text db manager is finished being hooked up. 651 base::FilePath history_name = history_dir_.Append(chrome::kHistoryFilename); 652 base::FilePath thumbnail_name = GetThumbnailFileName(); 653 base::FilePath archived_name = GetArchivedFileName(); 654 655 // History database. 656 db_.reset(new HistoryDatabase()); 657 658 // |HistoryDatabase::Init| takes ownership of |error_delegate|. 659 KillHistoryDatabaseErrorDelegate* error_delegate = 660 new KillHistoryDatabaseErrorDelegate(this); 661 662 sql::InitStatus status = db_->Init(history_name, error_delegate); 663 switch (status) { 664 case sql::INIT_OK: 665 break; 666 case sql::INIT_FAILURE: { 667 // A NULL db_ will cause all calls on this object to notice this error 668 // and to not continue. If the error delegate scheduled killing the 669 // database, the task it posted has not executed yet. Try killing the 670 // database now before we close it. 671 bool kill_database = error_delegate->scheduled_killing_database(); 672 if (kill_database) 673 KillHistoryDatabase(); 674 UMA_HISTOGRAM_BOOLEAN("History.AttemptedToFixProfileError", 675 kill_database); 676 delegate_->NotifyProfileError(id_, status); 677 db_.reset(); 678 return; 679 } 680 default: 681 NOTREACHED(); 682 } 683 684 // Fill the in-memory database and send it back to the history service on the 685 // main thread. 686 InMemoryHistoryBackend* mem_backend = new InMemoryHistoryBackend; 687 if (mem_backend->Init(history_name, db_.get())) 688 delegate_->SetInMemoryBackend(id_, mem_backend); // Takes ownership of 689 // pointer. 690 else 691 delete mem_backend; // Error case, run without the in-memory DB. 692 db_->BeginExclusiveMode(); // Must be after the mem backend read the data. 693 694 // Create the history publisher which needs to be passed on to the text and 695 // thumbnail databases for publishing history. 696 history_publisher_.reset(new HistoryPublisher()); 697 if (!history_publisher_->Init()) { 698 // The init may fail when there are no indexers wanting our history. 699 // Hence no need to log the failure. 700 history_publisher_.reset(); 701 } 702 703 // Full-text database. This has to be first so we can pass it to the 704 // HistoryDatabase for migration. 705 text_database_.reset(new TextDatabaseManager(history_dir_, 706 db_.get(), db_.get())); 707 if (!text_database_->Init(history_publisher_.get())) { 708 LOG(WARNING) << "Text database initialization failed, running without it."; 709 text_database_.reset(); 710 } 711 if (db_->needs_version_17_migration()) { 712 // See needs_version_17_migration() decl for more. In this case, we want 713 // to erase all the text database files. This must be done after the text 714 // database manager has been initialized, since it knows about all the 715 // files it manages. 716 text_database_->DeleteAll(); 717 } 718 719 // Thumbnail database. 720 thumbnail_db_.reset(new ThumbnailDatabase()); 721 if (!db_->GetNeedsThumbnailMigration()) { 722 // No convertion needed - use new filename right away. 723 thumbnail_name = GetFaviconsFileName(); 724 } 725 if (thumbnail_db_->Init(thumbnail_name, 726 history_publisher_.get(), 727 db_.get()) != sql::INIT_OK) { 728 // Unlike the main database, we don't error out when the database is too 729 // new because this error is much less severe. Generally, this shouldn't 730 // happen since the thumbnail and main datbase versions should be in sync. 731 // We'll just continue without thumbnails & favicons in this case or any 732 // other error. 733 LOG(WARNING) << "Could not initialize the thumbnail database."; 734 thumbnail_db_.reset(); 735 } 736 737 if (db_->GetNeedsThumbnailMigration()) { 738 VLOG(1) << "Starting TopSites migration"; 739 delegate_->StartTopSitesMigration(id_); 740 } 741 742 // Archived database. 743 if (db_->needs_version_17_migration()) { 744 // See needs_version_17_migration() decl for more. In this case, we want 745 // to delete the archived database and need to do so before we try to 746 // open the file. We can ignore any error (maybe the file doesn't exist). 747 file_util::Delete(archived_name, false); 748 } 749 archived_db_.reset(new ArchivedDatabase()); 750 if (!archived_db_->Init(archived_name)) { 751 LOG(WARNING) << "Could not initialize the archived database."; 752 archived_db_.reset(); 753 } 754 755 // Generate the history and thumbnail database metrics only after performing 756 // any migration work. 757 if (base::RandInt(1, 100) == 50) { 758 // Only do this computation sometimes since it can be expensive. 759 db_->ComputeDatabaseMetrics(history_name); 760 thumbnail_db_->ComputeDatabaseMetrics(); 761 } 762 763 // Tell the expiration module about all the nice databases we made. This must 764 // happen before db_->Init() is called since the callback ForceArchiveHistory 765 // may need to expire stuff. 766 // 767 // *sigh*, this can all be cleaned up when that migration code is removed. 768 // The main DB initialization should intuitively be first (not that it 769 // actually matters) and the expirer should be set last. 770 expirer_.SetDatabases(db_.get(), archived_db_.get(), 771 thumbnail_db_.get(), text_database_.get()); 772 773 // Open the long-running transaction. 774 db_->BeginTransaction(); 775 if (thumbnail_db_) 776 thumbnail_db_->BeginTransaction(); 777 if (archived_db_) 778 archived_db_->BeginTransaction(); 779 if (text_database_) 780 text_database_->BeginTransaction(); 781 782 // Get the first item in our database. 783 db_->GetStartDate(&first_recorded_time_); 784 785 // Start expiring old stuff. 786 expirer_.StartArchivingOldStuff(TimeDelta::FromDays(kArchiveDaysThreshold)); 787 788#if defined(OS_ANDROID) 789 if (thumbnail_db_) { 790 android_provider_backend_.reset(new AndroidProviderBackend( 791 GetAndroidCacheFileName(), db_.get(), thumbnail_db_.get(), 792 bookmark_service_, delegate_.get())); 793 } 794#endif 795 796 HISTOGRAM_TIMES("History.InitTime", 797 TimeTicks::Now() - beginning_time); 798} 799 800void HistoryBackend::CloseAllDatabases() { 801 if (db_) { 802 // Commit the long-running transaction. 803 db_->CommitTransaction(); 804 db_.reset(); 805 } 806 if (thumbnail_db_) { 807 thumbnail_db_->CommitTransaction(); 808 thumbnail_db_.reset(); 809 } 810 if (archived_db_) { 811 archived_db_->CommitTransaction(); 812 archived_db_.reset(); 813 } 814 if (text_database_) { 815 text_database_->CommitTransaction(); 816 text_database_.reset(); 817 } 818} 819 820std::pair<URLID, VisitID> HistoryBackend::AddPageVisit( 821 const GURL& url, 822 Time time, 823 VisitID referring_visit, 824 content::PageTransition transition, 825 VisitSource visit_source) { 826 // Top-level frame navigations are visible, everything else is hidden 827 bool new_hidden = !content::PageTransitionIsMainFrame(transition); 828 829 // NOTE: This code must stay in sync with 830 // ExpireHistoryBackend::ExpireURLsForVisits(). 831 // TODO(pkasting): http://b/1148304 We shouldn't be marking so many URLs as 832 // typed, which would eliminate the need for this code. 833 int typed_increment = 0; 834 content::PageTransition transition_type = 835 content::PageTransitionStripQualifier(transition); 836 if ((transition_type == content::PAGE_TRANSITION_TYPED && 837 !content::PageTransitionIsRedirect(transition)) || 838 transition_type == content::PAGE_TRANSITION_KEYWORD_GENERATED) 839 typed_increment = 1; 840 841 // See if this URL is already in the DB. 842 URLRow url_info(url); 843 URLID url_id = db_->GetRowForURL(url, &url_info); 844 if (url_id) { 845 // Update of an existing row. 846 if (content::PageTransitionStripQualifier(transition) != 847 content::PAGE_TRANSITION_RELOAD) 848 url_info.set_visit_count(url_info.visit_count() + 1); 849 if (typed_increment) 850 url_info.set_typed_count(url_info.typed_count() + typed_increment); 851 if (url_info.last_visit() < time) 852 url_info.set_last_visit(time); 853 854 // Only allow un-hiding of pages, never hiding. 855 if (!new_hidden) 856 url_info.set_hidden(false); 857 858 db_->UpdateURLRow(url_id, url_info); 859 } else { 860 // Addition of a new row. 861 url_info.set_visit_count(1); 862 url_info.set_typed_count(typed_increment); 863 url_info.set_last_visit(time); 864 url_info.set_hidden(new_hidden); 865 866 url_id = db_->AddURL(url_info); 867 if (!url_id) { 868 NOTREACHED() << "Adding URL failed."; 869 return std::make_pair(0, 0); 870 } 871 url_info.id_ = url_id; 872 873 // We don't actually add the URL to the full text index at this point. It 874 // might be nice to do this so that even if we get no title or body, the 875 // user can search for URL components and get the page. 876 // 877 // However, in most cases, we'll get at least a title and usually contents, 878 // and this add will be redundant, slowing everything down. As a result, 879 // we ignore this edge case. 880 } 881 882 // Add the visit with the time to the database. 883 VisitRow visit_info(url_id, time, referring_visit, transition, 0); 884 VisitID visit_id = db_->AddVisit(&visit_info, visit_source); 885 NotifyVisitObservers(visit_info); 886 887 if (visit_info.visit_time < first_recorded_time_) 888 first_recorded_time_ = visit_info.visit_time; 889 890 // Broadcast a notification of the visit. 891 if (visit_id) { 892 if (typed_url_syncable_service_.get()) 893 typed_url_syncable_service_->OnUrlVisited(transition, &url_info); 894 895 URLVisitedDetails* details = new URLVisitedDetails; 896 details->transition = transition; 897 details->row = url_info; 898 // TODO(meelapshah) Disabled due to potential PageCycler regression. 899 // Re-enable this. 900 // GetMostRecentRedirectsTo(url, &details->redirects); 901 BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URL_VISITED, details); 902 } else { 903 VLOG(0) << "Failed to build visit insert statement: " 904 << "url_id = " << url_id; 905 } 906 907 return std::make_pair(url_id, visit_id); 908} 909 910void HistoryBackend::AddPagesWithDetails(const URLRows& urls, 911 VisitSource visit_source) { 912 if (!db_) 913 return; 914 915 scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails); 916 for (URLRows::const_iterator i = urls.begin(); i != urls.end(); ++i) { 917 DCHECK(!i->last_visit().is_null()); 918 919 // We will add to either the archived database or the main one depending on 920 // the date of the added visit. 921 URLDatabase* url_database; 922 VisitDatabase* visit_database; 923 if (IsExpiredVisitTime(i->last_visit())) { 924 if (!archived_db_) 925 return; // No archived database to save it to, just forget this. 926 url_database = archived_db_.get(); 927 visit_database = archived_db_.get(); 928 } else { 929 url_database = db_.get(); 930 visit_database = db_.get(); 931 } 932 933 URLRow existing_url; 934 URLID url_id = url_database->GetRowForURL(i->url(), &existing_url); 935 if (!url_id) { 936 // Add the page if it doesn't exist. 937 url_id = url_database->AddURL(*i); 938 if (!url_id) { 939 NOTREACHED() << "Could not add row to DB"; 940 return; 941 } 942 943 if (i->typed_count() > 0) { 944 modified->changed_urls.push_back(*i); 945 modified->changed_urls.back().set_id(url_id); // *i likely has |id_| 0. 946 } 947 } 948 949 // Add the page to the full text index. This function is also used for 950 // importing. Even though we don't have page contents, we can at least 951 // add the title and URL to the index so they can be searched. We don't 952 // bother to delete any already-existing FTS entries for the URL, since 953 // this is normally called on import. 954 // 955 // If you ever import *after* first run (selecting import from the menu), 956 // then these additional entries will "shadow" the originals when querying 957 // for the most recent match only, and the user won't get snippets. This is 958 // a very minor issue, and fixing it will make import slower, so we don't 959 // bother. 960 bool has_indexed = false; 961 if (text_database_) { 962 // We do not have to make it update the visit database, below, we will 963 // create the visit entry with the indexed flag set. 964 has_indexed = text_database_->AddPageData(i->url(), url_id, 0, 965 i->last_visit(), 966 i->title(), string16()); 967 } 968 969 // Sync code manages the visits itself. 970 if (visit_source != SOURCE_SYNCED) { 971 // Make up a visit to correspond to the last visit to the page. 972 VisitRow visit_info(url_id, i->last_visit(), 0, 973 content::PageTransitionFromInt( 974 content::PAGE_TRANSITION_LINK | 975 content::PAGE_TRANSITION_CHAIN_START | 976 content::PAGE_TRANSITION_CHAIN_END), 0); 977 visit_info.is_indexed = has_indexed; 978 if (!visit_database->AddVisit(&visit_info, visit_source)) { 979 NOTREACHED() << "Adding visit failed."; 980 return; 981 } 982 NotifyVisitObservers(visit_info); 983 984 if (visit_info.visit_time < first_recorded_time_) 985 first_recorded_time_ = visit_info.visit_time; 986 } 987 } 988 989 if (typed_url_syncable_service_.get()) 990 typed_url_syncable_service_->OnUrlsModified(&modified->changed_urls); 991 992 // Broadcast a notification for typed URLs that have been modified. This 993 // will be picked up by the in-memory URL database on the main thread. 994 // 995 // TODO(brettw) bug 1140015: Add an "add page" notification so the history 996 // views can keep in sync. 997 BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_MODIFIED, 998 modified.release()); 999 1000 ScheduleCommit(); 1001} 1002 1003bool HistoryBackend::IsExpiredVisitTime(const base::Time& time) { 1004 return time < expirer_.GetCurrentArchiveTime(); 1005} 1006 1007void HistoryBackend::SetPageTitle(const GURL& url, 1008 const string16& title) { 1009 if (!db_) 1010 return; 1011 1012 // Update the full text index. 1013 if (text_database_) 1014 text_database_->AddPageTitle(url, title); 1015 1016 // Search for recent redirects which should get the same title. We make a 1017 // dummy list containing the exact URL visited if there are no redirects so 1018 // the processing below can be the same. 1019 history::RedirectList dummy_list; 1020 history::RedirectList* redirects; 1021 RedirectCache::iterator iter = recent_redirects_.Get(url); 1022 if (iter != recent_redirects_.end()) { 1023 redirects = &iter->second; 1024 1025 // This redirect chain should have the destination URL as the last item. 1026 DCHECK(!redirects->empty()); 1027 DCHECK(redirects->back() == url); 1028 } else { 1029 // No redirect chain stored, make up one containing the URL we want so we 1030 // can use the same logic below. 1031 dummy_list.push_back(url); 1032 redirects = &dummy_list; 1033 } 1034 1035 scoped_ptr<URLsModifiedDetails> details(new URLsModifiedDetails); 1036 for (size_t i = 0; i < redirects->size(); i++) { 1037 URLRow row; 1038 URLID row_id = db_->GetRowForURL(redirects->at(i), &row); 1039 if (row_id && row.title() != title) { 1040 row.set_title(title); 1041 db_->UpdateURLRow(row_id, row); 1042 details->changed_urls.push_back(row); 1043 } 1044 } 1045 1046 // Broadcast notifications for any URLs that have changed. This will 1047 // update the in-memory database and the InMemoryURLIndex. 1048 if (!details->changed_urls.empty()) { 1049 if (typed_url_syncable_service_.get()) 1050 typed_url_syncable_service_->OnUrlsModified(&details->changed_urls); 1051 BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_MODIFIED, 1052 details.release()); 1053 ScheduleCommit(); 1054 } 1055} 1056 1057void HistoryBackend::AddPageNoVisitForBookmark(const GURL& url, 1058 const string16& title) { 1059 if (!db_) 1060 return; 1061 1062 URLRow url_info(url); 1063 URLID url_id = db_->GetRowForURL(url, &url_info); 1064 if (url_id) { 1065 // URL is already known, nothing to do. 1066 return; 1067 } 1068 1069 if (!title.empty()) { 1070 url_info.set_title(title); 1071 } else { 1072 url_info.set_title(UTF8ToUTF16(url.spec())); 1073 } 1074 1075 url_info.set_last_visit(Time::Now()); 1076 // Mark the page hidden. If the user types it in, it'll unhide. 1077 url_info.set_hidden(true); 1078 1079 db_->AddURL(url_info); 1080} 1081 1082void HistoryBackend::IterateURLs( 1083 const scoped_refptr<components::VisitedLinkDelegate::URLEnumerator>& 1084 iterator) { 1085 if (db_) { 1086 HistoryDatabase::URLEnumerator e; 1087 if (db_->InitURLEnumeratorForEverything(&e)) { 1088 URLRow info; 1089 while (e.GetNextURL(&info)) { 1090 iterator->OnURL(info.url()); 1091 } 1092 iterator->OnComplete(true); // Success. 1093 return; 1094 } 1095 } 1096 iterator->OnComplete(false); // Failure. 1097} 1098 1099bool HistoryBackend::GetAllTypedURLs(URLRows* urls) { 1100 if (db_) 1101 return db_->GetAllTypedUrls(urls); 1102 return false; 1103} 1104 1105bool HistoryBackend::GetVisitsForURL(URLID id, VisitVector* visits) { 1106 if (db_) 1107 return db_->GetVisitsForURL(id, visits); 1108 return false; 1109} 1110 1111bool HistoryBackend::GetMostRecentVisitsForURL(URLID id, 1112 int max_visits, 1113 VisitVector* visits) { 1114 if (db_) 1115 return db_->GetMostRecentVisitsForURL(id, max_visits, visits); 1116 return false; 1117} 1118 1119bool HistoryBackend::UpdateURL(URLID id, const history::URLRow& url) { 1120 if (db_) 1121 return db_->UpdateURLRow(id, url); 1122 return false; 1123} 1124 1125bool HistoryBackend::AddVisits(const GURL& url, 1126 const std::vector<VisitInfo>& visits, 1127 VisitSource visit_source) { 1128 if (db_) { 1129 for (std::vector<VisitInfo>::const_iterator visit = visits.begin(); 1130 visit != visits.end(); ++visit) { 1131 if (!AddPageVisit( 1132 url, visit->first, 0, visit->second, visit_source).first) { 1133 return false; 1134 } 1135 } 1136 ScheduleCommit(); 1137 return true; 1138 } 1139 return false; 1140} 1141 1142bool HistoryBackend::RemoveVisits(const VisitVector& visits) { 1143 if (!db_) 1144 return false; 1145 1146 expirer_.ExpireVisits(visits); 1147 ScheduleCommit(); 1148 return true; 1149} 1150 1151bool HistoryBackend::GetVisitsSource(const VisitVector& visits, 1152 VisitSourceMap* sources) { 1153 if (!db_) 1154 return false; 1155 1156 db_->GetVisitsSource(visits, sources); 1157 return true; 1158} 1159 1160bool HistoryBackend::GetURL(const GURL& url, history::URLRow* url_row) { 1161 if (db_) 1162 return db_->GetRowForURL(url, url_row) != 0; 1163 return false; 1164} 1165 1166void HistoryBackend::QueryURL(scoped_refptr<QueryURLRequest> request, 1167 const GURL& url, 1168 bool want_visits) { 1169 if (request->canceled()) 1170 return; 1171 1172 bool success = false; 1173 URLRow* row = &request->value.a; 1174 VisitVector* visits = &request->value.b; 1175 if (db_) { 1176 if (db_->GetRowForURL(url, row)) { 1177 // Have a row. 1178 success = true; 1179 1180 // Optionally query the visits. 1181 if (want_visits) 1182 db_->GetVisitsForURL(row->id(), visits); 1183 } 1184 } 1185 request->ForwardResult(request->handle(), success, row, visits); 1186} 1187 1188TypedUrlSyncableService* HistoryBackend::GetTypedUrlSyncableService() const { 1189 return typed_url_syncable_service_.get(); 1190} 1191 1192// Segment usage --------------------------------------------------------------- 1193 1194void HistoryBackend::DeleteOldSegmentData() { 1195 if (db_) 1196 db_->DeleteSegmentData(Time::Now() - 1197 TimeDelta::FromDays(kSegmentDataRetention)); 1198} 1199 1200void HistoryBackend::QuerySegmentUsage( 1201 scoped_refptr<QuerySegmentUsageRequest> request, 1202 const Time from_time, 1203 int max_result_count) { 1204 if (request->canceled()) 1205 return; 1206 1207 if (db_) { 1208 db_->QuerySegmentUsage(from_time, max_result_count, &request->value.get()); 1209 1210 // If this is the first time we query segments, invoke 1211 // DeleteOldSegmentData asynchronously. We do this to cleanup old 1212 // entries. 1213 if (!segment_queried_) { 1214 segment_queried_ = true; 1215 MessageLoop::current()->PostTask( 1216 FROM_HERE, 1217 base::Bind(&HistoryBackend::DeleteOldSegmentData, this)); 1218 } 1219 } 1220 request->ForwardResult(request->handle(), &request->value.get()); 1221} 1222 1223void HistoryBackend::IncreaseSegmentDuration(const GURL& url, 1224 base::Time time, 1225 base::TimeDelta delta) { 1226 if (!db_) 1227 return; 1228 1229 const std::string segment_name(VisitSegmentDatabase::ComputeSegmentName(url)); 1230 SegmentID segment_id = db_->GetSegmentNamed(segment_name); 1231 if (!segment_id) { 1232 URLID url_id = db_->GetRowForURL(url, NULL); 1233 if (!url_id) 1234 return; 1235 segment_id = db_->CreateSegment(url_id, segment_name); 1236 if (!segment_id) 1237 return; 1238 } 1239 SegmentDurationID duration_id; 1240 base::TimeDelta total_delta; 1241 if (!db_->GetSegmentDuration(segment_id, time, &duration_id, 1242 &total_delta)) { 1243 db_->CreateSegmentDuration(segment_id, time, delta); 1244 return; 1245 } 1246 total_delta += delta; 1247 db_->SetSegmentDuration(duration_id, total_delta); 1248} 1249 1250void HistoryBackend::QuerySegmentDuration( 1251 scoped_refptr<QuerySegmentUsageRequest> request, 1252 const base::Time from_time, 1253 int max_result_count) { 1254 if (request->canceled()) 1255 return; 1256 1257 if (db_) { 1258 db_->QuerySegmentDuration(from_time, max_result_count, 1259 &request->value.get()); 1260 } 1261 request->ForwardResult(request->handle(), &request->value.get()); 1262} 1263 1264// Keyword visits -------------------------------------------------------------- 1265 1266void HistoryBackend::SetKeywordSearchTermsForURL(const GURL& url, 1267 TemplateURLID keyword_id, 1268 const string16& term) { 1269 if (!db_) 1270 return; 1271 1272 // Get the ID for this URL. 1273 URLRow url_row; 1274 if (!db_->GetRowForURL(url, &url_row)) { 1275 // There is a small possibility the url was deleted before the keyword 1276 // was added. Ignore the request. 1277 return; 1278 } 1279 1280 db_->SetKeywordSearchTermsForURL(url_row.id(), keyword_id, term); 1281 1282 // details is deleted by BroadcastNotifications. 1283 KeywordSearchTermDetails* details = new KeywordSearchTermDetails; 1284 details->url = url; 1285 details->keyword_id = keyword_id; 1286 details->term = term; 1287 BroadcastNotifications( 1288 chrome::NOTIFICATION_HISTORY_KEYWORD_SEARCH_TERM_UPDATED, details); 1289 ScheduleCommit(); 1290} 1291 1292void HistoryBackend::DeleteAllSearchTermsForKeyword( 1293 TemplateURLID keyword_id) { 1294 if (!db_) 1295 return; 1296 1297 db_->DeleteAllSearchTermsForKeyword(keyword_id); 1298 // TODO(sky): bug 1168470. Need to move from archive dbs too. 1299 ScheduleCommit(); 1300} 1301 1302void HistoryBackend::GetMostRecentKeywordSearchTerms( 1303 scoped_refptr<GetMostRecentKeywordSearchTermsRequest> request, 1304 TemplateURLID keyword_id, 1305 const string16& prefix, 1306 int max_count) { 1307 if (request->canceled()) 1308 return; 1309 1310 if (db_) { 1311 db_->GetMostRecentKeywordSearchTerms(keyword_id, prefix, max_count, 1312 &(request->value)); 1313 } 1314 request->ForwardResult(request->handle(), &request->value); 1315} 1316 1317// Downloads ------------------------------------------------------------------- 1318 1319void HistoryBackend::GetNextDownloadId(int* id) { 1320 if (db_) 1321 *id = db_->next_download_id(); 1322} 1323 1324// Get all the download entries from the database. 1325void HistoryBackend::QueryDownloads(std::vector<DownloadRow>* rows) { 1326 if (db_) 1327 db_->QueryDownloads(rows); 1328} 1329 1330// Update a particular download entry. 1331void HistoryBackend::UpdateDownload(const history::DownloadRow& data) { 1332 if (!db_) 1333 return; 1334 db_->UpdateDownload(data); 1335 ScheduleCommit(); 1336} 1337 1338void HistoryBackend::CreateDownload(const history::DownloadRow& history_info, 1339 int64* db_handle) { 1340 if (!db_) 1341 return; 1342 *db_handle = db_->CreateDownload(history_info); 1343 ScheduleCommit(); 1344} 1345 1346void HistoryBackend::RemoveDownloads(const std::set<int64>& handles) { 1347 if (!db_) 1348 return; 1349 int downloads_count_before = db_->CountDownloads(); 1350 base::TimeTicks started_removing = base::TimeTicks::Now(); 1351 // HistoryBackend uses a long-running Transaction that is committed 1352 // periodically, so this loop doesn't actually hit the disk too hard. 1353 for (std::set<int64>::const_iterator it = handles.begin(); 1354 it != handles.end(); ++it) { 1355 db_->RemoveDownload(*it); 1356 } 1357 base::TimeTicks finished_removing = base::TimeTicks::Now(); 1358 int downloads_count_after = db_->CountDownloads(); 1359 int num_downloads_deleted = downloads_count_before - downloads_count_after; 1360 if (num_downloads_deleted >= 0) { 1361 UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCount", 1362 num_downloads_deleted); 1363 base::TimeDelta micros = (1000 * (finished_removing - started_removing)); 1364 UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTime", micros); 1365 if (num_downloads_deleted > 0) { 1366 UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTimePerRecord", 1367 (1000 * micros) / num_downloads_deleted); 1368 } 1369 } 1370 int num_downloads_not_deleted = handles.size() - num_downloads_deleted; 1371 if (num_downloads_not_deleted >= 0) { 1372 UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCountNotRemoved", 1373 num_downloads_not_deleted); 1374 } 1375 ScheduleCommit(); 1376} 1377 1378void HistoryBackend::QueryHistory(scoped_refptr<QueryHistoryRequest> request, 1379 const string16& text_query, 1380 const QueryOptions& options) { 1381 if (request->canceled()) 1382 return; 1383 1384 TimeTicks beginning_time = TimeTicks::Now(); 1385 1386 if (db_) { 1387 if (text_query.empty()) { 1388 // Basic history query for the main database. 1389 QueryHistoryBasic(db_.get(), db_.get(), options, &request->value); 1390 1391 // Now query the archived database. This is a bit tricky because we don't 1392 // want to query it if the queried time range isn't going to find anything 1393 // in it. 1394 // TODO(brettw) bug 1171036: do blimpie querying for the archived database 1395 // as well. 1396 // if (archived_db_.get() && 1397 // expirer_.GetCurrentArchiveTime() - TimeDelta::FromDays(7)) { 1398 } else { 1399 // Full text history query. 1400 QueryHistoryFTS(text_query, options, &request->value); 1401 } 1402 } 1403 1404 request->ForwardResult(request->handle(), &request->value); 1405 1406 UMA_HISTOGRAM_TIMES("History.QueryHistory", 1407 TimeTicks::Now() - beginning_time); 1408} 1409 1410// Basic time-based querying of history. 1411void HistoryBackend::QueryHistoryBasic(URLDatabase* url_db, 1412 VisitDatabase* visit_db, 1413 const QueryOptions& options, 1414 QueryResults* result) { 1415 // First get all visits. 1416 VisitVector visits; 1417 bool has_more_results = visit_db->GetVisibleVisitsInRange(options, &visits); 1418 DCHECK(static_cast<int>(visits.size()) <= options.EffectiveMaxCount()); 1419 1420 // Now add them and the URL rows to the results. 1421 URLResult url_result; 1422 for (size_t i = 0; i < visits.size(); i++) { 1423 const VisitRow visit = visits[i]; 1424 1425 // Add a result row for this visit, get the URL info from the DB. 1426 if (!url_db->GetURLRow(visit.url_id, &url_result)) { 1427 VLOG(0) << "Failed to get id " << visit.url_id 1428 << " from history.urls."; 1429 continue; // DB out of sync and URL doesn't exist, try to recover. 1430 } 1431 1432 if (!url_result.url().is_valid()) { 1433 VLOG(0) << "Got invalid URL from history.urls with id " 1434 << visit.url_id << ": " 1435 << url_result.url().possibly_invalid_spec(); 1436 continue; // Don't report invalid URLs in case of corruption. 1437 } 1438 1439 // The archived database may be out of sync with respect to starring, 1440 // titles, last visit date, etc. Therefore, we query the main DB if the 1441 // current URL database is not the main one. 1442 if (url_db == db_.get()) { 1443 // Currently querying the archived DB, update with the main database to 1444 // catch any interesting stuff. This will update it if it exists in the 1445 // main DB, and do nothing otherwise. 1446 db_->GetRowForURL(url_result.url(), &url_result); 1447 } 1448 1449 url_result.set_visit_time(visit.visit_time); 1450 1451 // Set whether the visit was blocked for a managed user by looking at the 1452 // transition type. 1453 url_result.set_blocked_visit( 1454 (visit.transition & content::PAGE_TRANSITION_BLOCKED) != 0); 1455 1456 // We don't set any of the query-specific parts of the URLResult, since 1457 // snippets and stuff don't apply to basic querying. 1458 result->AppendURLBySwapping(&url_result); 1459 } 1460 1461 if (!has_more_results && options.begin_time <= first_recorded_time_) 1462 result->set_reached_beginning(true); 1463} 1464 1465void HistoryBackend::QueryHistoryFTS(const string16& text_query, 1466 const QueryOptions& options, 1467 QueryResults* result) { 1468 if (!text_database_) 1469 return; 1470 1471 // Full text query, first get all the FTS results in the time range. 1472 std::vector<TextDatabase::Match> fts_matches; 1473 Time first_time_searched; 1474 text_database_->GetTextMatches(text_query, options, 1475 &fts_matches, &first_time_searched); 1476 1477 URLQuerier querier(db_.get(), archived_db_.get(), true); 1478 1479 // Now get the row and visit information for each one. 1480 URLResult url_result; // Declare outside loop to prevent re-construction. 1481 for (size_t i = 0; i < fts_matches.size(); i++) { 1482 if (options.max_count != 0 && 1483 static_cast<int>(result->size()) >= options.max_count) 1484 break; // Got too many items. 1485 1486 // Get the URL, querying the main and archived databases as necessary. If 1487 // this is not found, the history and full text search databases are out 1488 // of sync and we give up with this result. 1489 if (!querier.GetRowForURL(fts_matches[i].url, &url_result)) 1490 continue; 1491 1492 if (!url_result.url().is_valid()) 1493 continue; // Don't report invalid URLs in case of corruption. 1494 1495 // Copy over the FTS stuff that the URLDatabase doesn't know about. 1496 // We do this with swap() to avoid copying, since we know we don't 1497 // need the original any more. Note that we override the title with the 1498 // one from FTS, since that will match the title_match_positions (the 1499 // FTS title and the history DB title may differ). 1500 url_result.set_title(fts_matches[i].title); 1501 url_result.title_match_positions_.swap( 1502 fts_matches[i].title_match_positions); 1503 url_result.snippet_.Swap(&fts_matches[i].snippet); 1504 1505 // The visit time also comes from the full text search database. Since it 1506 // has the time, we can avoid an extra query of the visits table. 1507 url_result.set_visit_time(fts_matches[i].time); 1508 1509 // Add it to the vector, this will clear our |url_row| object as a 1510 // result of the swap. 1511 result->AppendURLBySwapping(&url_result); 1512 } 1513 1514 if (first_time_searched <= first_recorded_time_) 1515 result->set_reached_beginning(true); 1516} 1517 1518// Frontend to GetMostRecentRedirectsFrom from the history thread. 1519void HistoryBackend::QueryRedirectsFrom( 1520 scoped_refptr<QueryRedirectsRequest> request, 1521 const GURL& url) { 1522 if (request->canceled()) 1523 return; 1524 bool success = GetMostRecentRedirectsFrom(url, &request->value); 1525 request->ForwardResult(request->handle(), url, success, &request->value); 1526} 1527 1528void HistoryBackend::QueryRedirectsTo( 1529 scoped_refptr<QueryRedirectsRequest> request, 1530 const GURL& url) { 1531 if (request->canceled()) 1532 return; 1533 bool success = GetMostRecentRedirectsTo(url, &request->value); 1534 request->ForwardResult(request->handle(), url, success, &request->value); 1535} 1536 1537void HistoryBackend::GetVisibleVisitCountToHost( 1538 scoped_refptr<GetVisibleVisitCountToHostRequest> request, 1539 const GURL& url) { 1540 if (request->canceled()) 1541 return; 1542 int count = 0; 1543 Time first_visit; 1544 const bool success = db_.get() && 1545 db_->GetVisibleVisitCountToHost(url, &count, &first_visit); 1546 request->ForwardResult(request->handle(), success, count, first_visit); 1547} 1548 1549void HistoryBackend::QueryTopURLsAndRedirects( 1550 scoped_refptr<QueryTopURLsAndRedirectsRequest> request, 1551 int result_count) { 1552 if (request->canceled()) 1553 return; 1554 1555 if (!db_) { 1556 request->ForwardResult(request->handle(), false, NULL, NULL); 1557 return; 1558 } 1559 1560 std::vector<GURL>* top_urls = &request->value.a; 1561 history::RedirectMap* redirects = &request->value.b; 1562 1563 ScopedVector<PageUsageData> data; 1564 db_->QuerySegmentUsage(base::Time::Now() - base::TimeDelta::FromDays(90), 1565 result_count, &data.get()); 1566 1567 for (size_t i = 0; i < data.size(); ++i) { 1568 top_urls->push_back(data[i]->GetURL()); 1569 RefCountedVector<GURL>* list = new RefCountedVector<GURL>; 1570 GetMostRecentRedirectsFrom(top_urls->back(), &list->data); 1571 (*redirects)[top_urls->back()] = list; 1572 } 1573 1574 request->ForwardResult(request->handle(), true, top_urls, redirects); 1575} 1576 1577// Will replace QueryTopURLsAndRedirectsRequest. 1578void HistoryBackend::QueryMostVisitedURLs( 1579 scoped_refptr<QueryMostVisitedURLsRequest> request, 1580 int result_count, 1581 int days_back) { 1582 if (request->canceled()) 1583 return; 1584 1585 if (!db_) { 1586 // No History Database - return an empty list. 1587 request->ForwardResult(request->handle(), MostVisitedURLList()); 1588 return; 1589 } 1590 1591 MostVisitedURLList* result = &request->value; 1592 QueryMostVisitedURLsImpl(result_count, days_back, result); 1593 request->ForwardResult(request->handle(), *result); 1594} 1595 1596void HistoryBackend::QueryFilteredURLs( 1597 scoped_refptr<QueryFilteredURLsRequest> request, 1598 int result_count, 1599 const history::VisitFilter& filter, 1600 bool extended_info) { 1601 if (request->canceled()) 1602 return; 1603 1604 base::Time request_start = base::Time::Now(); 1605 1606 if (!db_) { 1607 // No History Database - return an empty list. 1608 request->ForwardResult(request->handle(), FilteredURLList()); 1609 return; 1610 } 1611 1612 VisitVector visits; 1613 db_->GetDirectVisitsDuringTimes(filter, 0, &visits); 1614 1615 std::map<URLID, double> score_map; 1616 for (size_t i = 0; i < visits.size(); ++i) { 1617 score_map[visits[i].url_id] += filter.GetVisitScore(visits[i]); 1618 } 1619 1620 // TODO(georgey): experiment with visit_segment database granularity (it is 1621 // currently 24 hours) to use it directly instead of using visits database, 1622 // which is considerably slower. 1623 ScopedVector<PageUsageData> data; 1624 data.reserve(score_map.size()); 1625 for (std::map<URLID, double>::iterator it = score_map.begin(); 1626 it != score_map.end(); ++it) { 1627 PageUsageData* pud = new PageUsageData(it->first); 1628 pud->SetScore(it->second); 1629 data.push_back(pud); 1630 } 1631 1632 // Limit to the top |result_count| results. 1633 std::sort(data.begin(), data.end(), PageUsageData::Predicate); 1634 if (result_count && implicit_cast<int>(data.size()) > result_count) 1635 data.resize(result_count); 1636 1637 for (size_t i = 0; i < data.size(); ++i) { 1638 URLRow info; 1639 if (db_->GetURLRow(data[i]->GetID(), &info)) { 1640 data[i]->SetURL(info.url()); 1641 data[i]->SetTitle(info.title()); 1642 } 1643 } 1644 1645 FilteredURLList& result = request->value; 1646 for (size_t i = 0; i < data.size(); ++i) { 1647 PageUsageData* current_data = data[i]; 1648 FilteredURL url(*current_data); 1649 1650 if (extended_info) { 1651 VisitVector visits; 1652 db_->GetVisitsForURL(current_data->GetID(), &visits); 1653 if (visits.size() > 0) { 1654 url.extended_info.total_visits = visits.size(); 1655 for (size_t i = 0; i < visits.size(); ++i) { 1656 url.extended_info.duration_opened += 1657 visits[i].visit_duration.InSeconds(); 1658 if (visits[i].visit_time > url.extended_info.last_visit_time) { 1659 url.extended_info.last_visit_time = visits[i].visit_time; 1660 } 1661 } 1662 // TODO(macourteau): implement the url.extended_info.visits stat. 1663 } 1664 } 1665 result.push_back(url); 1666 } 1667 1668 int delta_time = std::max(1, std::min(999, 1669 static_cast<int>((base::Time::Now() - request_start).InMilliseconds()))); 1670 STATIC_HISTOGRAM_POINTER_BLOCK( 1671 "NewTabPage.SuggestedSitesLoadTime", 1672 Add(delta_time), 1673 base::LinearHistogram::FactoryGet("NewTabPage.SuggestedSitesLoadTime", 1674 1, 1000, 100, base::Histogram::kUmaTargetedHistogramFlag)); 1675 1676 request->ForwardResult(request->handle(), result); 1677} 1678 1679void HistoryBackend::QueryMostVisitedURLsImpl(int result_count, 1680 int days_back, 1681 MostVisitedURLList* result) { 1682 if (!db_) 1683 return; 1684 1685 ScopedVector<PageUsageData> data; 1686 db_->QuerySegmentUsage(base::Time::Now() - 1687 base::TimeDelta::FromDays(days_back), 1688 result_count, &data.get()); 1689 1690 for (size_t i = 0; i < data.size(); ++i) { 1691 PageUsageData* current_data = data[i]; 1692 RedirectList redirects; 1693 GetMostRecentRedirectsFrom(current_data->GetURL(), &redirects); 1694 MostVisitedURL url = MakeMostVisitedURL(*current_data, redirects); 1695 result->push_back(url); 1696 } 1697} 1698 1699void HistoryBackend::GetRedirectsFromSpecificVisit( 1700 VisitID cur_visit, history::RedirectList* redirects) { 1701 // Follow any redirects from the given visit and add them to the list. 1702 // It *should* be impossible to get a circular chain here, but we check 1703 // just in case to avoid infinite loops. 1704 GURL cur_url; 1705 std::set<VisitID> visit_set; 1706 visit_set.insert(cur_visit); 1707 while (db_->GetRedirectFromVisit(cur_visit, &cur_visit, &cur_url)) { 1708 if (visit_set.find(cur_visit) != visit_set.end()) { 1709 NOTREACHED() << "Loop in visit chain, giving up"; 1710 return; 1711 } 1712 visit_set.insert(cur_visit); 1713 redirects->push_back(cur_url); 1714 } 1715} 1716 1717void HistoryBackend::GetRedirectsToSpecificVisit( 1718 VisitID cur_visit, 1719 history::RedirectList* redirects) { 1720 // Follow redirects going to cur_visit. These are added to |redirects| in 1721 // the order they are found. If a redirect chain looks like A -> B -> C and 1722 // |cur_visit| = C, redirects will be {B, A} in that order. 1723 if (!db_) 1724 return; 1725 1726 GURL cur_url; 1727 std::set<VisitID> visit_set; 1728 visit_set.insert(cur_visit); 1729 while (db_->GetRedirectToVisit(cur_visit, &cur_visit, &cur_url)) { 1730 if (visit_set.find(cur_visit) != visit_set.end()) { 1731 NOTREACHED() << "Loop in visit chain, giving up"; 1732 return; 1733 } 1734 visit_set.insert(cur_visit); 1735 redirects->push_back(cur_url); 1736 } 1737} 1738 1739bool HistoryBackend::GetMostRecentRedirectsFrom( 1740 const GURL& from_url, 1741 history::RedirectList* redirects) { 1742 redirects->clear(); 1743 if (!db_) 1744 return false; 1745 1746 URLID from_url_id = db_->GetRowForURL(from_url, NULL); 1747 VisitID cur_visit = db_->GetMostRecentVisitForURL(from_url_id, NULL); 1748 if (!cur_visit) 1749 return false; // No visits for URL. 1750 1751 GetRedirectsFromSpecificVisit(cur_visit, redirects); 1752 return true; 1753} 1754 1755bool HistoryBackend::GetMostRecentRedirectsTo( 1756 const GURL& to_url, 1757 history::RedirectList* redirects) { 1758 redirects->clear(); 1759 if (!db_) 1760 return false; 1761 1762 URLID to_url_id = db_->GetRowForURL(to_url, NULL); 1763 VisitID cur_visit = db_->GetMostRecentVisitForURL(to_url_id, NULL); 1764 if (!cur_visit) 1765 return false; // No visits for URL. 1766 1767 GetRedirectsToSpecificVisit(cur_visit, redirects); 1768 return true; 1769} 1770 1771void HistoryBackend::ScheduleAutocomplete(HistoryURLProvider* provider, 1772 HistoryURLProviderParams* params) { 1773 // ExecuteWithDB should handle the NULL database case. 1774 provider->ExecuteWithDB(this, db_.get(), params); 1775} 1776 1777void HistoryBackend::SetPageContents(const GURL& url, 1778 const string16& contents) { 1779 // This is histogrammed in the text database manager. 1780 if (!text_database_) 1781 return; 1782 text_database_->AddPageContents(url, contents); 1783} 1784 1785void HistoryBackend::SetPageThumbnail( 1786 const GURL& url, 1787 const gfx::Image* thumbnail, 1788 const ThumbnailScore& score) { 1789 if (!db_ || !thumbnail_db_) 1790 return; 1791 1792 URLRow url_row; 1793 URLID url_id = db_->GetRowForURL(url, &url_row); 1794 if (url_id) { 1795 thumbnail_db_->SetPageThumbnail(url, url_id, thumbnail, score, 1796 url_row.last_visit()); 1797 } 1798 1799 ScheduleCommit(); 1800} 1801 1802void HistoryBackend::GetPageThumbnail( 1803 scoped_refptr<GetPageThumbnailRequest> request, 1804 const GURL& page_url) { 1805 if (request->canceled()) 1806 return; 1807 1808 scoped_refptr<base::RefCountedBytes> data; 1809 GetPageThumbnailDirectly(page_url, &data); 1810 1811 request->ForwardResult(request->handle(), data); 1812} 1813 1814void HistoryBackend::GetPageThumbnailDirectly( 1815 const GURL& page_url, 1816 scoped_refptr<base::RefCountedBytes>* data) { 1817 if (thumbnail_db_) { 1818 *data = new base::RefCountedBytes; 1819 1820 // Time the result. 1821 TimeTicks beginning_time = TimeTicks::Now(); 1822 1823 history::RedirectList redirects; 1824 URLID url_id; 1825 bool success = false; 1826 1827 // If there are some redirects, try to get a thumbnail from the last 1828 // redirect destination. 1829 if (GetMostRecentRedirectsFrom(page_url, &redirects) && 1830 !redirects.empty()) { 1831 if ((url_id = db_->GetRowForURL(redirects.back(), NULL))) 1832 success = thumbnail_db_->GetPageThumbnail(url_id, &(*data)->data()); 1833 } 1834 1835 // If we don't have a thumbnail from redirects, try the URL directly. 1836 if (!success) { 1837 if ((url_id = db_->GetRowForURL(page_url, NULL))) 1838 success = thumbnail_db_->GetPageThumbnail(url_id, &(*data)->data()); 1839 } 1840 1841 // In this rare case, we start to mine the older redirect sessions 1842 // from the visit table to try to find a thumbnail. 1843 if (!success) { 1844 success = GetThumbnailFromOlderRedirect(page_url, &(*data)->data()); 1845 } 1846 1847 if (!success) 1848 *data = NULL; // This will tell the callback there was an error. 1849 1850 UMA_HISTOGRAM_TIMES("History.GetPageThumbnail", 1851 TimeTicks::Now() - beginning_time); 1852 } 1853} 1854 1855void HistoryBackend::MigrateThumbnailsDatabase() { 1856 // If there is no History DB, we can't record that the migration was done. 1857 // It will be recorded on the next run. 1858 if (db_) { 1859 // If there is no thumbnail DB, we can still record a successful migration. 1860 if (thumbnail_db_) { 1861 thumbnail_db_->RenameAndDropThumbnails(GetThumbnailFileName(), 1862 GetFaviconsFileName()); 1863 } 1864 db_->ThumbnailMigrationDone(); 1865 } 1866} 1867 1868bool HistoryBackend::GetThumbnailFromOlderRedirect( 1869 const GURL& page_url, 1870 std::vector<unsigned char>* data) { 1871 // Look at a few previous visit sessions. 1872 VisitVector older_sessions; 1873 URLID page_url_id = db_->GetRowForURL(page_url, NULL); 1874 static const int kVisitsToSearchForThumbnail = 4; 1875 db_->GetMostRecentVisitsForURL( 1876 page_url_id, kVisitsToSearchForThumbnail, &older_sessions); 1877 1878 // Iterate across all those previous visits, and see if any of the 1879 // final destinations of those redirect chains have a good thumbnail 1880 // for us. 1881 bool success = false; 1882 for (VisitVector::const_iterator it = older_sessions.begin(); 1883 !success && it != older_sessions.end(); ++it) { 1884 history::RedirectList redirects; 1885 if (it->visit_id) { 1886 GetRedirectsFromSpecificVisit(it->visit_id, &redirects); 1887 1888 if (!redirects.empty()) { 1889 URLID url_id; 1890 if ((url_id = db_->GetRowForURL(redirects.back(), NULL))) 1891 success = thumbnail_db_->GetPageThumbnail(url_id, data); 1892 } 1893 } 1894 } 1895 1896 return success; 1897} 1898 1899void HistoryBackend::GetFavicons( 1900 const std::vector<GURL>& icon_urls, 1901 int icon_types, 1902 int desired_size_in_dip, 1903 const std::vector<ui::ScaleFactor>& desired_scale_factors, 1904 std::vector<FaviconBitmapResult>* bitmap_results) { 1905 UpdateFaviconMappingsAndFetchImpl(NULL, icon_urls, icon_types, 1906 desired_size_in_dip, desired_scale_factors, 1907 bitmap_results); 1908} 1909 1910void HistoryBackend::GetFaviconsForURL( 1911 const GURL& page_url, 1912 int icon_types, 1913 int desired_size_in_dip, 1914 const std::vector<ui::ScaleFactor>& desired_scale_factors, 1915 std::vector<FaviconBitmapResult>* bitmap_results) { 1916 DCHECK(bitmap_results); 1917 GetFaviconsFromDB(page_url, icon_types, desired_size_in_dip, 1918 desired_scale_factors, bitmap_results); 1919} 1920 1921void HistoryBackend::GetFaviconForID( 1922 FaviconID favicon_id, 1923 int desired_size_in_dip, 1924 ui::ScaleFactor desired_scale_factor, 1925 std::vector<FaviconBitmapResult>* bitmap_results) { 1926 std::vector<FaviconID> favicon_ids; 1927 favicon_ids.push_back(favicon_id); 1928 std::vector<ui::ScaleFactor> desired_scale_factors; 1929 desired_scale_factors.push_back(desired_scale_factor); 1930 1931 // Get results from DB. 1932 GetFaviconBitmapResultsForBestMatch(favicon_ids, 1933 desired_size_in_dip, 1934 desired_scale_factors, 1935 bitmap_results); 1936} 1937 1938void HistoryBackend::UpdateFaviconMappingsAndFetch( 1939 const GURL& page_url, 1940 const std::vector<GURL>& icon_urls, 1941 int icon_types, 1942 int desired_size_in_dip, 1943 const std::vector<ui::ScaleFactor>& desired_scale_factors, 1944 std::vector<FaviconBitmapResult>* bitmap_results) { 1945 UpdateFaviconMappingsAndFetchImpl(&page_url, icon_urls, icon_types, 1946 desired_size_in_dip, desired_scale_factors, 1947 bitmap_results); 1948} 1949 1950void HistoryBackend::MergeFavicon( 1951 const GURL& page_url, 1952 const GURL& icon_url, 1953 history::IconType icon_type, 1954 scoped_refptr<base::RefCountedMemory> bitmap_data, 1955 const gfx::Size& pixel_size) { 1956 if (!thumbnail_db_ || !db_) 1957 return; 1958 1959 FaviconID favicon_id = thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, 1960 icon_type, NULL); 1961 1962 if (!favicon_id) { 1963 // There is no favicon at |icon_url|, create it. 1964 favicon_id = thumbnail_db_->AddFavicon(icon_url, icon_type, 1965 GetDefaultFaviconSizes()); 1966 } 1967 1968 std::vector<FaviconBitmapIDSize> bitmap_id_sizes; 1969 thumbnail_db_->GetFaviconBitmapIDSizes(favicon_id, &bitmap_id_sizes); 1970 1971 // If there is already a favicon bitmap of |pixel_size| at |icon_url|, 1972 // replace it. 1973 bool bitmap_identical = false; 1974 bool replaced_bitmap = false; 1975 for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) { 1976 if (bitmap_id_sizes[i].pixel_size == pixel_size) { 1977 if (IsFaviconBitmapDataEqual(bitmap_id_sizes[i].bitmap_id, bitmap_data)) { 1978 thumbnail_db_->SetFaviconBitmapLastUpdateTime( 1979 bitmap_id_sizes[i].bitmap_id, base::Time::Now()); 1980 bitmap_identical = true; 1981 } else { 1982 thumbnail_db_->SetFaviconBitmap(bitmap_id_sizes[i].bitmap_id, 1983 bitmap_data, base::Time::Now()); 1984 replaced_bitmap = true; 1985 } 1986 break; 1987 } 1988 } 1989 1990 // Create a vector of the pixel sizes of the favicon bitmaps currently at 1991 // |icon_url|. 1992 std::vector<gfx::Size> favicon_sizes; 1993 for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) 1994 favicon_sizes.push_back(bitmap_id_sizes[i].pixel_size); 1995 1996 if (!replaced_bitmap && !bitmap_identical) { 1997 // Set the preexisting favicon bitmaps as expired as the preexisting favicon 1998 // bitmaps are not consistent with the merged in data. 1999 thumbnail_db_->SetFaviconOutOfDate(favicon_id); 2000 2001 // Delete an arbitrary favicon bitmap to avoid going over the limit of 2002 // |kMaxFaviconBitmapsPerIconURL|. 2003 if (bitmap_id_sizes.size() >= kMaxFaviconBitmapsPerIconURL) { 2004 thumbnail_db_->DeleteFaviconBitmap(bitmap_id_sizes[0].bitmap_id); 2005 favicon_sizes.erase(favicon_sizes.begin()); 2006 } 2007 thumbnail_db_->AddFaviconBitmap(favicon_id, bitmap_data, base::Time::Now(), 2008 pixel_size); 2009 favicon_sizes.push_back(pixel_size); 2010 } 2011 2012 // A site may have changed the favicons that it uses for |page_url|. 2013 // Example Scenario: 2014 // page_url = news.google.com 2015 // Intial State: www.google.com/favicon.ico 16x16, 32x32 2016 // MergeFavicon(news.google.com, news.google.com/news_specific.ico, ..., 2017 // ..., 16x16) 2018 // 2019 // Difficulties: 2020 // 1. Sync requires that a call to GetFaviconsForURL() returns the 2021 // |bitmap_data| passed into MergeFavicon(). 2022 // - It is invalid for the 16x16 bitmap for www.google.com/favicon.ico to 2023 // stay mapped to news.google.com because it would be unclear which 16x16 2024 // bitmap should be returned via GetFaviconsForURL(). 2025 // 2026 // 2. www.google.com/favicon.ico may be mapped to more than just 2027 // news.google.com (eg www.google.com). 2028 // - The 16x16 bitmap cannot be deleted from www.google.com/favicon.ico 2029 // 2030 // To resolve these problems, we copy all of the favicon bitmaps previously 2031 // mapped to news.google.com (|page_url|) and add them to the favicon at 2032 // news.google.com/news_specific.ico (|icon_url|). The favicon sizes for 2033 // |icon_url| are set to default to indicate that |icon_url| has incomplete 2034 // / incorrect data. 2035 // Difficlty 1: All but news.google.com/news_specific.ico are unmapped from 2036 // news.google.com 2037 // Difficulty 2: The favicon bitmaps for www.google.com/favicon.ico are not 2038 // modified. 2039 2040 std::vector<IconMapping> icon_mappings; 2041 thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_type, &icon_mappings); 2042 2043 // Copy the favicon bitmaps mapped to |page_url| to the favicon at |icon_url| 2044 // till the limit of |kMaxFaviconBitmapsPerIconURL| is reached. 2045 for (size_t i = 0; i < icon_mappings.size(); ++i) { 2046 if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL) 2047 break; 2048 2049 if (icon_mappings[i].icon_url == icon_url) 2050 continue; 2051 2052 std::vector<FaviconBitmap> bitmaps_to_copy; 2053 thumbnail_db_->GetFaviconBitmaps(icon_mappings[i].icon_id, 2054 &bitmaps_to_copy); 2055 for (size_t j = 0; j < bitmaps_to_copy.size(); ++j) { 2056 // Do not add a favicon bitmap at a pixel size for which there is already 2057 // a favicon bitmap mapped to |icon_url|. The one there is more correct 2058 // and having multiple equally sized favicon bitmaps for |page_url| is 2059 // ambiguous in terms of GetFaviconsForURL(). 2060 std::vector<gfx::Size>::iterator it = std::find(favicon_sizes.begin(), 2061 favicon_sizes.end(), bitmaps_to_copy[j].pixel_size); 2062 if (it != favicon_sizes.end()) 2063 continue; 2064 2065 // Add the favicon bitmap as expired as it is not consistent with the 2066 // merged in data. 2067 thumbnail_db_->AddFaviconBitmap(favicon_id, 2068 bitmaps_to_copy[j].bitmap_data, base::Time(), 2069 bitmaps_to_copy[j].pixel_size); 2070 favicon_sizes.push_back(bitmaps_to_copy[j].pixel_size); 2071 2072 if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL) 2073 break; 2074 } 2075 } 2076 2077 // Update the favicon mappings such that only |icon_url| is mapped to 2078 // |page_url|. 2079 bool mapping_changed = false; 2080 if (icon_mappings.size() != 1 || icon_mappings[0].icon_url != icon_url) { 2081 std::vector<FaviconID> favicon_ids; 2082 favicon_ids.push_back(favicon_id); 2083 SetFaviconMappingsForPageAndRedirects(page_url, icon_type, favicon_ids); 2084 mapping_changed = true; 2085 } 2086 2087 if (mapping_changed || !bitmap_identical) 2088 SendFaviconChangedNotificationForPageAndRedirects(page_url); 2089 ScheduleCommit(); 2090} 2091 2092void HistoryBackend::SetFavicons( 2093 const GURL& page_url, 2094 IconType icon_type, 2095 const std::vector<FaviconBitmapData>& favicon_bitmap_data) { 2096 if (!thumbnail_db_ || !db_) 2097 return; 2098 2099 DCHECK(ValidateSetFaviconsParams(favicon_bitmap_data)); 2100 2101 // Build map of FaviconBitmapData for each icon url. 2102 typedef std::map<GURL, std::vector<FaviconBitmapData> > 2103 BitmapDataByIconURL; 2104 BitmapDataByIconURL grouped_by_icon_url; 2105 for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) { 2106 const GURL& icon_url = favicon_bitmap_data[i].icon_url; 2107 grouped_by_icon_url[icon_url].push_back(favicon_bitmap_data[i]); 2108 } 2109 2110 // Track whether the method modifies or creates any favicon bitmaps, favicons 2111 // or icon mappings. 2112 bool data_modified = false; 2113 2114 std::vector<FaviconID> icon_ids; 2115 for (BitmapDataByIconURL::const_iterator it = grouped_by_icon_url.begin(); 2116 it != grouped_by_icon_url.end(); ++it) { 2117 const GURL& icon_url = it->first; 2118 FaviconID icon_id = 2119 thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, icon_type, NULL); 2120 2121 if (!icon_id) { 2122 // TODO(pkotwicz): Remove the favicon sizes attribute from 2123 // ThumbnailDatabase::AddFavicon(). 2124 icon_id = thumbnail_db_->AddFavicon(icon_url, icon_type, 2125 GetDefaultFaviconSizes()); 2126 data_modified = true; 2127 } 2128 icon_ids.push_back(icon_id); 2129 2130 if (!data_modified) 2131 SetFaviconBitmaps(icon_id, it->second, &data_modified); 2132 else 2133 SetFaviconBitmaps(icon_id, it->second, NULL); 2134 } 2135 2136 data_modified |= 2137 SetFaviconMappingsForPageAndRedirects(page_url, icon_type, icon_ids); 2138 2139 if (data_modified) { 2140 // Send notification to the UI as an icon mapping, favicon, or favicon 2141 // bitmap was changed by this function. 2142 SendFaviconChangedNotificationForPageAndRedirects(page_url); 2143 } 2144 ScheduleCommit(); 2145} 2146 2147void HistoryBackend::SetFaviconsOutOfDateForPage(const GURL& page_url) { 2148 std::vector<IconMapping> icon_mappings; 2149 2150 if (!thumbnail_db_ || 2151 !thumbnail_db_->GetIconMappingsForPageURL(page_url, 2152 &icon_mappings)) 2153 return; 2154 2155 for (std::vector<IconMapping>::iterator m = icon_mappings.begin(); 2156 m != icon_mappings.end(); ++m) { 2157 thumbnail_db_->SetFaviconOutOfDate(m->icon_id); 2158 } 2159 ScheduleCommit(); 2160} 2161 2162void HistoryBackend::CloneFavicons(const GURL& old_page_url, 2163 const GURL& new_page_url) { 2164 if (!thumbnail_db_) 2165 return; 2166 2167 // Prevent cross-domain cloning. 2168 if (old_page_url.GetOrigin() != new_page_url.GetOrigin()) 2169 return; 2170 2171 thumbnail_db_->CloneIconMappings(old_page_url, new_page_url); 2172 ScheduleCommit(); 2173} 2174 2175void HistoryBackend::SetImportedFavicons( 2176 const std::vector<ImportedFaviconUsage>& favicon_usage) { 2177 if (!db_ || !thumbnail_db_) 2178 return; 2179 2180 Time now = Time::Now(); 2181 2182 // Track all URLs that had their favicons set or updated. 2183 std::set<GURL> favicons_changed; 2184 2185 for (size_t i = 0; i < favicon_usage.size(); i++) { 2186 FaviconID favicon_id = thumbnail_db_->GetFaviconIDForFaviconURL( 2187 favicon_usage[i].favicon_url, history::FAVICON, NULL); 2188 if (!favicon_id) { 2189 // This favicon doesn't exist yet, so we create it using the given data. 2190 // TODO(pkotwicz): Pass in real pixel size. 2191 favicon_id = thumbnail_db_->AddFavicon( 2192 favicon_usage[i].favicon_url, 2193 history::FAVICON, 2194 GetDefaultFaviconSizes(), 2195 new base::RefCountedBytes(favicon_usage[i].png_data), 2196 now, 2197 gfx::Size()); 2198 } 2199 2200 // Save the mapping from all the URLs to the favicon. 2201 BookmarkService* bookmark_service = GetBookmarkService(); 2202 for (std::set<GURL>::const_iterator url = favicon_usage[i].urls.begin(); 2203 url != favicon_usage[i].urls.end(); ++url) { 2204 URLRow url_row; 2205 if (!db_->GetRowForURL(*url, &url_row)) { 2206 // If the URL is present as a bookmark, add the url in history to 2207 // save the favicon mapping. This will match with what history db does 2208 // for regular bookmarked URLs with favicons - when history db is 2209 // cleaned, we keep an entry in the db with 0 visits as long as that 2210 // url is bookmarked. 2211 if (bookmark_service && bookmark_service_->IsBookmarked(*url)) { 2212 URLRow url_info(*url); 2213 url_info.set_visit_count(0); 2214 url_info.set_typed_count(0); 2215 url_info.set_last_visit(base::Time()); 2216 url_info.set_hidden(false); 2217 db_->AddURL(url_info); 2218 thumbnail_db_->AddIconMapping(*url, favicon_id); 2219 favicons_changed.insert(*url); 2220 } 2221 } else { 2222 if (!thumbnail_db_->GetIconMappingsForPageURL(*url, FAVICON, NULL)) { 2223 // URL is present in history, update the favicon *only* if it is not 2224 // set already. 2225 thumbnail_db_->AddIconMapping(*url, favicon_id); 2226 favicons_changed.insert(*url); 2227 } 2228 } 2229 } 2230 } 2231 2232 if (!favicons_changed.empty()) { 2233 // Send the notification about the changed favicon URLs. 2234 FaviconChangeDetails* changed_details = new FaviconChangeDetails; 2235 changed_details->urls.swap(favicons_changed); 2236 BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED, 2237 changed_details); 2238 } 2239} 2240 2241void HistoryBackend::UpdateFaviconMappingsAndFetchImpl( 2242 const GURL* page_url, 2243 const std::vector<GURL>& icon_urls, 2244 int icon_types, 2245 int desired_size_in_dip, 2246 const std::vector<ui::ScaleFactor>& desired_scale_factors, 2247 std::vector<FaviconBitmapResult>* bitmap_results) { 2248 // If |page_url| is specified, |icon_types| must be either a single icon 2249 // type or icon types which are equivalent. 2250 DCHECK(!page_url || 2251 icon_types == FAVICON || 2252 icon_types == TOUCH_ICON || 2253 icon_types == TOUCH_PRECOMPOSED_ICON || 2254 icon_types == (TOUCH_ICON | TOUCH_PRECOMPOSED_ICON)); 2255 bitmap_results->clear(); 2256 2257 if (!thumbnail_db_) { 2258 return; 2259 } 2260 2261 std::vector<FaviconID> favicon_ids; 2262 2263 // The icon type for which the mappings will the updated and data will be 2264 // returned. 2265 IconType selected_icon_type = INVALID_ICON; 2266 2267 for (size_t i = 0; i < icon_urls.size(); ++i) { 2268 const GURL& icon_url = icon_urls[i]; 2269 IconType icon_type_out; 2270 const FaviconID favicon_id = thumbnail_db_->GetFaviconIDForFaviconURL( 2271 icon_url, icon_types, &icon_type_out); 2272 2273 if (favicon_id) { 2274 // Return and update icon mappings only for the largest icon type. As 2275 // |icon_urls| is not sorted in terms of icon type, clear |favicon_ids| 2276 // if an |icon_url| with a larger icon type is found. 2277 if (icon_type_out > selected_icon_type) { 2278 selected_icon_type = icon_type_out; 2279 favicon_ids.clear(); 2280 } 2281 if (icon_type_out == selected_icon_type) 2282 favicon_ids.push_back(favicon_id); 2283 } 2284 } 2285 2286 if (page_url && !favicon_ids.empty()) { 2287 bool mappings_updated = 2288 SetFaviconMappingsForPageAndRedirects(*page_url, selected_icon_type, 2289 favicon_ids); 2290 if (mappings_updated) { 2291 SendFaviconChangedNotificationForPageAndRedirects(*page_url); 2292 ScheduleCommit(); 2293 } 2294 } 2295 2296 GetFaviconBitmapResultsForBestMatch(favicon_ids, desired_size_in_dip, 2297 desired_scale_factors, bitmap_results); 2298} 2299 2300void HistoryBackend::SetFaviconBitmaps( 2301 FaviconID icon_id, 2302 const std::vector<FaviconBitmapData>& favicon_bitmap_data, 2303 bool* favicon_bitmaps_changed) { 2304 if (favicon_bitmaps_changed) 2305 *favicon_bitmaps_changed = false; 2306 2307 std::vector<FaviconBitmapIDSize> bitmap_id_sizes; 2308 thumbnail_db_->GetFaviconBitmapIDSizes(icon_id, &bitmap_id_sizes); 2309 2310 std::vector<FaviconBitmapData> to_add = favicon_bitmap_data; 2311 2312 for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) { 2313 const gfx::Size& pixel_size = bitmap_id_sizes[i].pixel_size; 2314 std::vector<FaviconBitmapData>::iterator match_it = to_add.end(); 2315 for (std::vector<FaviconBitmapData>::iterator it = to_add.begin(); 2316 it != to_add.end(); ++it) { 2317 if (it->pixel_size == pixel_size) { 2318 match_it = it; 2319 break; 2320 } 2321 } 2322 2323 FaviconBitmapID bitmap_id = bitmap_id_sizes[i].bitmap_id; 2324 if (match_it == to_add.end()) { 2325 thumbnail_db_->DeleteFaviconBitmap(bitmap_id); 2326 2327 if (favicon_bitmaps_changed) 2328 *favicon_bitmaps_changed = true; 2329 } else { 2330 if (favicon_bitmaps_changed && 2331 !*favicon_bitmaps_changed && 2332 IsFaviconBitmapDataEqual(bitmap_id, match_it->bitmap_data)) { 2333 thumbnail_db_->SetFaviconBitmapLastUpdateTime( 2334 bitmap_id, base::Time::Now()); 2335 } else { 2336 thumbnail_db_->SetFaviconBitmap(bitmap_id, match_it->bitmap_data, 2337 base::Time::Now()); 2338 2339 if (favicon_bitmaps_changed) 2340 *favicon_bitmaps_changed = true; 2341 } 2342 to_add.erase(match_it); 2343 } 2344 } 2345 2346 for (size_t i = 0; i < to_add.size(); ++i) { 2347 thumbnail_db_->AddFaviconBitmap(icon_id, to_add[i].bitmap_data, 2348 base::Time::Now(), to_add[i].pixel_size); 2349 2350 if (favicon_bitmaps_changed) 2351 *favicon_bitmaps_changed = true; 2352 } 2353} 2354 2355bool HistoryBackend::ValidateSetFaviconsParams( 2356 const std::vector<FaviconBitmapData>& favicon_bitmap_data) const { 2357 typedef std::map<GURL, size_t> BitmapsPerIconURL; 2358 BitmapsPerIconURL num_bitmaps_per_icon_url; 2359 for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) { 2360 if (!favicon_bitmap_data[i].bitmap_data) 2361 return false; 2362 2363 const GURL& icon_url = favicon_bitmap_data[i].icon_url; 2364 if (!num_bitmaps_per_icon_url.count(icon_url)) 2365 num_bitmaps_per_icon_url[icon_url] = 1u; 2366 else 2367 ++num_bitmaps_per_icon_url[icon_url]; 2368 } 2369 2370 if (num_bitmaps_per_icon_url.size() > kMaxFaviconsPerPage) 2371 return false; 2372 2373 for (BitmapsPerIconURL::const_iterator it = num_bitmaps_per_icon_url.begin(); 2374 it != num_bitmaps_per_icon_url.end(); ++it) { 2375 if (it->second > kMaxFaviconBitmapsPerIconURL) 2376 return false; 2377 } 2378 return true; 2379} 2380 2381bool HistoryBackend::IsFaviconBitmapDataEqual( 2382 FaviconBitmapID bitmap_id, 2383 const scoped_refptr<base::RefCountedMemory>& new_bitmap_data) { 2384 if (!new_bitmap_data) 2385 return false; 2386 2387 scoped_refptr<base::RefCountedMemory> original_bitmap_data; 2388 thumbnail_db_->GetFaviconBitmap(bitmap_id, 2389 NULL, 2390 &original_bitmap_data, 2391 NULL); 2392 return new_bitmap_data->Equals(original_bitmap_data); 2393} 2394 2395bool HistoryBackend::GetFaviconsFromDB( 2396 const GURL& page_url, 2397 int icon_types, 2398 int desired_size_in_dip, 2399 const std::vector<ui::ScaleFactor>& desired_scale_factors, 2400 std::vector<FaviconBitmapResult>* favicon_bitmap_results) { 2401 DCHECK(favicon_bitmap_results); 2402 favicon_bitmap_results->clear(); 2403 2404 if (!db_ || !thumbnail_db_) 2405 return false; 2406 2407 // Time the query. 2408 TimeTicks beginning_time = TimeTicks::Now(); 2409 2410 // Get FaviconIDs for |page_url| and one of |icon_types|. 2411 std::vector<IconMapping> icon_mappings; 2412 thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_types, 2413 &icon_mappings); 2414 std::vector<FaviconID> favicon_ids; 2415 for (size_t i = 0; i < icon_mappings.size(); ++i) 2416 favicon_ids.push_back(icon_mappings[i].icon_id); 2417 2418 // Populate |favicon_bitmap_results| and |icon_url_sizes|. 2419 bool success = GetFaviconBitmapResultsForBestMatch(favicon_ids, 2420 desired_size_in_dip, desired_scale_factors, favicon_bitmap_results); 2421 UMA_HISTOGRAM_TIMES("History.GetFavIconFromDB", // historical name 2422 TimeTicks::Now() - beginning_time); 2423 return success && !favicon_bitmap_results->empty(); 2424} 2425 2426bool HistoryBackend::GetFaviconBitmapResultsForBestMatch( 2427 const std::vector<FaviconID>& candidate_favicon_ids, 2428 int desired_size_in_dip, 2429 const std::vector<ui::ScaleFactor>& desired_scale_factors, 2430 std::vector<FaviconBitmapResult>* favicon_bitmap_results) { 2431 favicon_bitmap_results->clear(); 2432 2433 if (candidate_favicon_ids.empty()) 2434 return true; 2435 2436 // Find the FaviconID and the FaviconBitmapIDs which best match 2437 // |desired_size_in_dip| and |desired_scale_factors|. 2438 // TODO(pkotwicz): Select bitmap results from multiple favicons once 2439 // content::FaviconStatus supports multiple icon URLs. 2440 FaviconID best_favicon_id = 0; 2441 std::vector<FaviconBitmapID> best_bitmap_ids; 2442 float highest_score = kSelectFaviconFramesInvalidScore; 2443 for (size_t i = 0; i < candidate_favicon_ids.size(); ++i) { 2444 std::vector<FaviconBitmapIDSize> bitmap_id_sizes; 2445 thumbnail_db_->GetFaviconBitmapIDSizes(candidate_favicon_ids[i], 2446 &bitmap_id_sizes); 2447 2448 // Build vector of gfx::Size from |bitmap_id_sizes|. 2449 std::vector<gfx::Size> sizes; 2450 for (size_t j = 0; j < bitmap_id_sizes.size(); ++j) 2451 sizes.push_back(bitmap_id_sizes[j].pixel_size); 2452 2453 std::vector<size_t> candidate_bitmap_indices; 2454 float score = 0; 2455 SelectFaviconFrameIndices(sizes, 2456 desired_scale_factors, 2457 desired_size_in_dip, 2458 &candidate_bitmap_indices, 2459 &score); 2460 if (score > highest_score) { 2461 highest_score = score; 2462 best_favicon_id = candidate_favicon_ids[i], 2463 best_bitmap_ids.clear(); 2464 for (size_t j = 0; j < candidate_bitmap_indices.size(); ++j) { 2465 size_t candidate_index = candidate_bitmap_indices[j]; 2466 best_bitmap_ids.push_back( 2467 bitmap_id_sizes[candidate_index].bitmap_id); 2468 } 2469 } 2470 } 2471 2472 // Construct FaviconBitmapResults from |best_favicon_id| and 2473 // |best_bitmap_ids|. 2474 GURL icon_url; 2475 IconType icon_type; 2476 if (!thumbnail_db_->GetFaviconHeader(best_favicon_id, &icon_url, 2477 &icon_type, NULL)) { 2478 return false; 2479 } 2480 2481 for (size_t i = 0; i < best_bitmap_ids.size(); ++i) { 2482 base::Time last_updated; 2483 FaviconBitmapResult bitmap_result; 2484 bitmap_result.icon_url = icon_url; 2485 bitmap_result.icon_type = icon_type; 2486 if (!thumbnail_db_->GetFaviconBitmap(best_bitmap_ids[i], 2487 &last_updated, 2488 &bitmap_result.bitmap_data, 2489 &bitmap_result.pixel_size)) { 2490 return false; 2491 } 2492 2493 bitmap_result.expired = (Time::Now() - last_updated) > 2494 TimeDelta::FromDays(kFaviconRefetchDays); 2495 if (bitmap_result.is_valid()) 2496 favicon_bitmap_results->push_back(bitmap_result); 2497 } 2498 return true; 2499} 2500 2501bool HistoryBackend::SetFaviconMappingsForPageAndRedirects( 2502 const GURL& page_url, 2503 IconType icon_type, 2504 const std::vector<FaviconID>& icon_ids) { 2505 if (!thumbnail_db_) 2506 return false; 2507 2508 // Find all the pages whose favicons we should set, we want to set it for 2509 // all the pages in the redirect chain if it redirected. 2510 history::RedirectList redirects; 2511 GetCachedRecentRedirects(page_url, &redirects); 2512 2513 bool mappings_changed = false; 2514 2515 // Save page <-> favicon associations. 2516 for (history::RedirectList::const_iterator i(redirects.begin()); 2517 i != redirects.end(); ++i) { 2518 mappings_changed |= SetFaviconMappingsForPage(*i, icon_type, icon_ids); 2519 } 2520 return mappings_changed; 2521} 2522 2523bool HistoryBackend::SetFaviconMappingsForPage( 2524 const GURL& page_url, 2525 IconType icon_type, 2526 const std::vector<FaviconID>& icon_ids) { 2527 DCHECK_LE(icon_ids.size(), kMaxFaviconsPerPage); 2528 bool mappings_changed = false; 2529 2530 // Two icon types are considered 'equivalent' if one of the icon types is 2531 // TOUCH_ICON and the other is TOUCH_PRECOMPOSED_ICON. 2532 // 2533 // Sets the icon mappings from |page_url| for |icon_type| to the favicons 2534 // with |icon_ids|. Mappings for |page_url| to favicons of type |icon_type| 2535 // whose FaviconID is not in |icon_ids| are removed. All icon mappings for 2536 // |page_url| to favicons of a type equivalent to |icon_type| are removed. 2537 // Remove any favicons which are orphaned as a result of the removal of the 2538 // icon mappings. 2539 2540 std::vector<FaviconID> unmapped_icon_ids = icon_ids; 2541 2542 std::vector<IconMapping> icon_mappings; 2543 thumbnail_db_->GetIconMappingsForPageURL(page_url, &icon_mappings); 2544 2545 for (std::vector<IconMapping>::iterator m = icon_mappings.begin(); 2546 m != icon_mappings.end(); ++m) { 2547 std::vector<FaviconID>::iterator icon_id_it = std::find( 2548 unmapped_icon_ids.begin(), unmapped_icon_ids.end(), m->icon_id); 2549 2550 // If the icon mapping already exists, avoid removing it and adding it back. 2551 if (icon_id_it != unmapped_icon_ids.end()) { 2552 unmapped_icon_ids.erase(icon_id_it); 2553 continue; 2554 } 2555 2556 if ((icon_type == TOUCH_ICON && m->icon_type == TOUCH_PRECOMPOSED_ICON) || 2557 (icon_type == TOUCH_PRECOMPOSED_ICON && m->icon_type == TOUCH_ICON) || 2558 (icon_type == m->icon_type)) { 2559 thumbnail_db_->DeleteIconMapping(m->mapping_id); 2560 2561 // Removing the icon mapping may have orphaned the associated favicon so 2562 // we must recheck it. This is not super fast, but this case will get 2563 // triggered rarely, since normally a page will always map to the same 2564 // favicon IDs. It will mostly happen for favicons we import. 2565 if (!thumbnail_db_->HasMappingFor(m->icon_id)) 2566 thumbnail_db_->DeleteFavicon(m->icon_id); 2567 mappings_changed = true; 2568 } 2569 } 2570 2571 for (size_t i = 0; i < unmapped_icon_ids.size(); ++i) { 2572 thumbnail_db_->AddIconMapping(page_url, unmapped_icon_ids[i]); 2573 mappings_changed = true; 2574 } 2575 return mappings_changed; 2576} 2577 2578void HistoryBackend::GetCachedRecentRedirects( 2579 const GURL& page_url, 2580 history::RedirectList* redirect_list) { 2581 RedirectCache::iterator iter = recent_redirects_.Get(page_url); 2582 if (iter != recent_redirects_.end()) { 2583 *redirect_list = iter->second; 2584 2585 // The redirect chain should have the destination URL as the last item. 2586 DCHECK(!redirect_list->empty()); 2587 DCHECK(redirect_list->back() == page_url); 2588 } else { 2589 // No known redirects, construct mock redirect chain containing |page_url|. 2590 redirect_list->push_back(page_url); 2591 } 2592} 2593 2594void HistoryBackend::SendFaviconChangedNotificationForPageAndRedirects( 2595 const GURL& page_url) { 2596 history::RedirectList redirect_list; 2597 GetCachedRecentRedirects(page_url, &redirect_list); 2598 2599 FaviconChangeDetails* changed_details = new FaviconChangeDetails; 2600 for (size_t i = 0; i < redirect_list.size(); ++i) 2601 changed_details->urls.insert(redirect_list[i]); 2602 2603 BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED, 2604 changed_details); 2605} 2606 2607void HistoryBackend::Commit() { 2608 if (!db_) 2609 return; 2610 2611 // Note that a commit may not actually have been scheduled if a caller 2612 // explicitly calls this instead of using ScheduleCommit. Likewise, we 2613 // may reset the flag written by a pending commit. But this is OK! It 2614 // will merely cause extra commits (which is kind of the idea). We 2615 // could optimize more for this case (we may get two extra commits in 2616 // some cases) but it hasn't been important yet. 2617 CancelScheduledCommit(); 2618 2619 db_->CommitTransaction(); 2620 DCHECK(db_->transaction_nesting() == 0) << "Somebody left a transaction open"; 2621 db_->BeginTransaction(); 2622 2623 if (thumbnail_db_) { 2624 thumbnail_db_->CommitTransaction(); 2625 DCHECK(thumbnail_db_->transaction_nesting() == 0) << 2626 "Somebody left a transaction open"; 2627 thumbnail_db_->BeginTransaction(); 2628 } 2629 2630 if (archived_db_) { 2631 archived_db_->CommitTransaction(); 2632 archived_db_->BeginTransaction(); 2633 } 2634 2635 if (text_database_) { 2636 text_database_->CommitTransaction(); 2637 text_database_->BeginTransaction(); 2638 } 2639} 2640 2641void HistoryBackend::ScheduleCommit() { 2642 if (scheduled_commit_) 2643 return; 2644 scheduled_commit_ = new CommitLaterTask(this); 2645 MessageLoop::current()->PostDelayedTask( 2646 FROM_HERE, 2647 base::Bind(&CommitLaterTask::RunCommit, scheduled_commit_.get()), 2648 base::TimeDelta::FromSeconds(kCommitIntervalSeconds)); 2649} 2650 2651void HistoryBackend::CancelScheduledCommit() { 2652 if (scheduled_commit_) { 2653 scheduled_commit_->Cancel(); 2654 scheduled_commit_ = NULL; 2655 } 2656} 2657 2658void HistoryBackend::ProcessDBTaskImpl() { 2659 if (!db_) { 2660 // db went away, release all the refs. 2661 ReleaseDBTasks(); 2662 return; 2663 } 2664 2665 // Remove any canceled tasks. 2666 while (!db_task_requests_.empty() && db_task_requests_.front()->canceled()) { 2667 db_task_requests_.front()->Release(); 2668 db_task_requests_.pop_front(); 2669 } 2670 if (db_task_requests_.empty()) 2671 return; 2672 2673 // Run the first task. 2674 HistoryDBTaskRequest* request = db_task_requests_.front(); 2675 db_task_requests_.pop_front(); 2676 if (request->value->RunOnDBThread(this, db_.get())) { 2677 // The task is done. Notify the callback. 2678 request->ForwardResult(); 2679 // We AddRef'd the request before adding, need to release it now. 2680 request->Release(); 2681 } else { 2682 // Tasks wants to run some more. Schedule it at the end of current tasks. 2683 db_task_requests_.push_back(request); 2684 // And process it after an invoke later. 2685 MessageLoop::current()->PostTask( 2686 FROM_HERE, base::Bind(&HistoryBackend::ProcessDBTaskImpl, this)); 2687 } 2688} 2689 2690void HistoryBackend::ReleaseDBTasks() { 2691 for (std::list<HistoryDBTaskRequest*>::iterator i = 2692 db_task_requests_.begin(); i != db_task_requests_.end(); ++i) { 2693 (*i)->Release(); 2694 } 2695 db_task_requests_.clear(); 2696} 2697 2698//////////////////////////////////////////////////////////////////////////////// 2699// 2700// Generic operations 2701// 2702//////////////////////////////////////////////////////////////////////////////// 2703 2704void HistoryBackend::DeleteURLs(const std::vector<GURL>& urls) { 2705 expirer_.DeleteURLs(urls); 2706 2707 db_->GetStartDate(&first_recorded_time_); 2708 // Force a commit, if the user is deleting something for privacy reasons, we 2709 // want to get it on disk ASAP. 2710 Commit(); 2711} 2712 2713void HistoryBackend::DeleteURL(const GURL& url) { 2714 expirer_.DeleteURL(url); 2715 2716 db_->GetStartDate(&first_recorded_time_); 2717 // Force a commit, if the user is deleting something for privacy reasons, we 2718 // want to get it on disk ASAP. 2719 Commit(); 2720} 2721 2722void HistoryBackend::ExpireHistoryBetween( 2723 const std::set<GURL>& restrict_urls, 2724 Time begin_time, 2725 Time end_time) { 2726 if (db_) { 2727 if (begin_time.is_null() && (end_time.is_null() || end_time.is_max()) && 2728 restrict_urls.empty()) { 2729 // Special case deleting all history so it can be faster and to reduce the 2730 // possibility of an information leak. 2731 DeleteAllHistory(); 2732 } else { 2733 // Clearing parts of history, have the expirer do the depend 2734 expirer_.ExpireHistoryBetween(restrict_urls, begin_time, end_time); 2735 2736 // Force a commit, if the user is deleting something for privacy reasons, 2737 // we want to get it on disk ASAP. 2738 Commit(); 2739 } 2740 } 2741 2742 if (begin_time <= first_recorded_time_) 2743 db_->GetStartDate(&first_recorded_time_); 2744} 2745 2746void HistoryBackend::ExpireHistoryForTimes( 2747 const std::set<base::Time>& times, 2748 base::Time begin_time, base::Time end_time) { 2749 if (times.empty() || !db_) 2750 return; 2751 2752 DCHECK(*times.begin() >= begin_time) 2753 << "Min time is before begin time: " 2754 << times.begin()->ToJsTime() << " v.s. " << begin_time.ToJsTime(); 2755 DCHECK(*times.rbegin() < end_time) 2756 << "Max time is after end time: " 2757 << times.rbegin()->ToJsTime() << " v.s. " << end_time.ToJsTime(); 2758 2759 history::QueryOptions options; 2760 options.begin_time = begin_time; 2761 options.end_time = end_time; 2762 options.duplicate_policy = QueryOptions::KEEP_ALL_DUPLICATES; 2763 QueryResults results; 2764 QueryHistoryBasic(db_.get(), db_.get(), options, &results); 2765 2766 // 1st pass: find URLs that are visited at one of |times|. 2767 std::set<GURL> urls; 2768 for (size_t i = 0; i < results.size(); ++i) { 2769 if (times.count(results[i].visit_time()) > 0) 2770 urls.insert(results[i].url()); 2771 } 2772 if (urls.empty()) 2773 return; 2774 2775 // 2nd pass: collect all visit times of those URLs. 2776 std::vector<base::Time> times_to_expire; 2777 for (size_t i = 0; i < results.size(); ++i) { 2778 if (urls.count(results[i].url())) 2779 times_to_expire.push_back(results[i].visit_time()); 2780 } 2781 2782 // Put the times in reverse chronological order and remove 2783 // duplicates (for expirer_.ExpireHistoryForTimes()). 2784 std::sort(times_to_expire.begin(), times_to_expire.end(), 2785 std::greater<base::Time>()); 2786 times_to_expire.erase( 2787 std::unique(times_to_expire.begin(), times_to_expire.end()), 2788 times_to_expire.end()); 2789 2790 // Expires by times and commit. 2791 DCHECK(!times_to_expire.empty()); 2792 expirer_.ExpireHistoryForTimes(times_to_expire); 2793 Commit(); 2794 2795 DCHECK(times_to_expire.back() >= first_recorded_time_); 2796 // Update |first_recorded_time_| if we expired it. 2797 if (times_to_expire.back() == first_recorded_time_) 2798 db_->GetStartDate(&first_recorded_time_); 2799} 2800 2801void HistoryBackend::ExpireHistory( 2802 const std::vector<history::ExpireHistoryArgs>& expire_list) { 2803 if (db_) { 2804 bool update_first_recorded_time = false; 2805 2806 for (std::vector<history::ExpireHistoryArgs>::const_iterator it = 2807 expire_list.begin(); it != expire_list.end(); ++it) { 2808 expirer_.ExpireHistoryBetween(it->urls, it->begin_time, it->end_time); 2809 2810 if (it->begin_time < first_recorded_time_) 2811 update_first_recorded_time = true; 2812 } 2813 Commit(); 2814 2815 // Update |first_recorded_time_| if any deletion might have affected it. 2816 if (update_first_recorded_time) 2817 db_->GetStartDate(&first_recorded_time_); 2818 } 2819} 2820 2821void HistoryBackend::URLsNoLongerBookmarked(const std::set<GURL>& urls) { 2822 if (!db_) 2823 return; 2824 2825 for (std::set<GURL>::const_iterator i = urls.begin(); i != urls.end(); ++i) { 2826 URLRow url_row; 2827 if (!db_->GetRowForURL(*i, &url_row)) 2828 continue; // The URL isn't in the db; nothing to do. 2829 2830 VisitVector visits; 2831 db_->GetVisitsForURL(url_row.id(), &visits); 2832 2833 if (visits.empty()) 2834 expirer_.DeleteURL(*i); // There are no more visits; nuke the URL. 2835 } 2836} 2837 2838void HistoryBackend::KillHistoryDatabase() { 2839 if (!db_) 2840 return; 2841 2842 // Rollback transaction because Raze() cannot be called from within a 2843 // transaction. 2844 db_->RollbackTransaction(); 2845 bool success = db_->Raze(); 2846 UMA_HISTOGRAM_BOOLEAN("History.KillHistoryDatabaseResult", success); 2847 2848#if defined(OS_ANDROID) 2849 // Release AndroidProviderBackend before other objects. 2850 android_provider_backend_.reset(); 2851#endif 2852 2853 // The expirer keeps tabs on the active databases. Tell it about the 2854 // databases which will be closed. 2855 expirer_.SetDatabases(NULL, NULL, NULL, NULL); 2856 2857 // Reopen a new transaction for |db_| for the sake of CloseAllDatabases(). 2858 db_->BeginTransaction(); 2859 CloseAllDatabases(); 2860} 2861 2862void HistoryBackend::ProcessDBTask( 2863 scoped_refptr<HistoryDBTaskRequest> request) { 2864 DCHECK(request); 2865 if (request->canceled()) 2866 return; 2867 2868 bool task_scheduled = !db_task_requests_.empty(); 2869 // Make sure we up the refcount of the request. ProcessDBTaskImpl will 2870 // release when done with the task. 2871 request->AddRef(); 2872 db_task_requests_.push_back(request.get()); 2873 if (!task_scheduled) { 2874 // No other tasks are scheduled. Process request now. 2875 ProcessDBTaskImpl(); 2876 } 2877} 2878 2879void HistoryBackend::BroadcastNotifications( 2880 int type, 2881 HistoryDetails* details_deleted) { 2882 // |delegate_| may be NULL if |this| is in the process of closing (closed by 2883 // HistoryService -> HistoryBackend::Closing(). 2884 if (delegate_) 2885 delegate_->BroadcastNotifications(type, details_deleted); 2886 else 2887 delete details_deleted; 2888} 2889 2890void HistoryBackend::NotifySyncURLsDeleted(bool all_history, 2891 bool archived, 2892 URLRows* rows) { 2893 if (typed_url_syncable_service_.get()) 2894 typed_url_syncable_service_->OnUrlsDeleted(all_history, archived, rows); 2895} 2896 2897// Deleting -------------------------------------------------------------------- 2898 2899void HistoryBackend::DeleteAllHistory() { 2900 // Our approach to deleting all history is: 2901 // 1. Copy the bookmarks and their dependencies to new tables with temporary 2902 // names. 2903 // 2. Delete the original tables. Since tables can not share pages, we know 2904 // that any data we don't want to keep is now in an unused page. 2905 // 3. Renaming the temporary tables to match the original. 2906 // 4. Vacuuming the database to delete the unused pages. 2907 // 2908 // Since we are likely to have very few bookmarks and their dependencies 2909 // compared to all history, this is also much faster than just deleting from 2910 // the original tables directly. 2911 2912 // Get the bookmarked URLs. 2913 std::vector<BookmarkService::URLAndTitle> starred_urls; 2914 BookmarkService* bookmark_service = GetBookmarkService(); 2915 if (bookmark_service) 2916 bookmark_service_->GetBookmarks(&starred_urls); 2917 2918 URLRows kept_urls; 2919 for (size_t i = 0; i < starred_urls.size(); i++) { 2920 URLRow row; 2921 if (!db_->GetRowForURL(starred_urls[i].url, &row)) 2922 continue; 2923 2924 // Clear the last visit time so when we write these rows they are "clean." 2925 row.set_last_visit(Time()); 2926 row.set_visit_count(0); 2927 row.set_typed_count(0); 2928 kept_urls.push_back(row); 2929 } 2930 2931 // Clear thumbnail and favicon history. The favicons for the given URLs will 2932 // be kept. 2933 if (!ClearAllThumbnailHistory(&kept_urls)) { 2934 LOG(ERROR) << "Thumbnail history could not be cleared"; 2935 // We continue in this error case. If the user wants to delete their 2936 // history, we should delete as much as we can. 2937 } 2938 2939 // ClearAllMainHistory will change the IDs of the URLs in kept_urls. Therfore, 2940 // we clear the list afterwards to make sure nobody uses this invalid data. 2941 if (!ClearAllMainHistory(kept_urls)) 2942 LOG(ERROR) << "Main history could not be cleared"; 2943 kept_urls.clear(); 2944 2945 // Delete FTS files & archived history. 2946 if (text_database_) { 2947 // We assume that the text database has one transaction on them that we need 2948 // to close & restart (the long-running history transaction). 2949 text_database_->CommitTransaction(); 2950 text_database_->DeleteAll(); 2951 text_database_->BeginTransaction(); 2952 } 2953 2954 if (archived_db_) { 2955 // Close the database and delete the file. 2956 archived_db_.reset(); 2957 base::FilePath archived_file_name = GetArchivedFileName(); 2958 file_util::Delete(archived_file_name, false); 2959 2960 // Now re-initialize the database (which may fail). 2961 archived_db_.reset(new ArchivedDatabase()); 2962 if (!archived_db_->Init(archived_file_name)) { 2963 LOG(WARNING) << "Could not initialize the archived database."; 2964 archived_db_.reset(); 2965 } else { 2966 // Open our long-running transaction on this database. 2967 archived_db_->BeginTransaction(); 2968 } 2969 } 2970 2971 db_->GetStartDate(&first_recorded_time_); 2972 2973 // Send out the notfication that history is cleared. The in-memory datdabase 2974 // will pick this up and clear itself. 2975 URLsDeletedDetails* details = new URLsDeletedDetails; 2976 details->all_history = true; 2977 NotifySyncURLsDeleted(true, false, NULL); 2978 BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_DELETED, details); 2979} 2980 2981bool HistoryBackend::ClearAllThumbnailHistory(URLRows* kept_urls) { 2982 if (!thumbnail_db_) { 2983 // When we have no reference to the thumbnail database, maybe there was an 2984 // error opening it. In this case, we just try to blow it away to try to 2985 // fix the error if it exists. This may fail, in which case either the 2986 // file doesn't exist or there's no more we can do. 2987 file_util::Delete(GetThumbnailFileName(), false); 2988 return true; 2989 } 2990 2991 // Create duplicate icon_mapping, favicon, and favicon_bitmaps tables, this 2992 // is where the favicons we want to keep will be stored. 2993 if (!thumbnail_db_->InitTemporaryTables()) 2994 return false; 2995 2996 // This maps existing favicon IDs to the ones in the temporary table. 2997 typedef std::map<FaviconID, FaviconID> FaviconMap; 2998 FaviconMap copied_favicons; 2999 3000 // Copy all unique favicons to the temporary table, and update all the 3001 // URLs to have the new IDs. 3002 for (URLRows::iterator i = kept_urls->begin(); i != kept_urls->end(); ++i) { 3003 std::vector<IconMapping> icon_mappings; 3004 if (!thumbnail_db_->GetIconMappingsForPageURL(i->url(), &icon_mappings)) 3005 continue; 3006 3007 for (std::vector<IconMapping>::iterator m = icon_mappings.begin(); 3008 m != icon_mappings.end(); ++m) { 3009 FaviconID old_id = m->icon_id; 3010 FaviconID new_id; 3011 FaviconMap::const_iterator found = copied_favicons.find(old_id); 3012 if (found == copied_favicons.end()) { 3013 new_id = thumbnail_db_->CopyFaviconAndFaviconBitmapsToTemporaryTables( 3014 old_id); 3015 copied_favicons[old_id] = new_id; 3016 } else { 3017 // We already encountered a URL that used this favicon, use the ID we 3018 // previously got. 3019 new_id = found->second; 3020 } 3021 // Add Icon mapping, and we don't care wheteher it suceeded or not. 3022 thumbnail_db_->AddToTemporaryIconMappingTable(i->url(), new_id); 3023 } 3024 } 3025#if defined(OS_ANDROID) 3026 // TODO (michaelbai): Add the unit test once AndroidProviderBackend is 3027 // avaliable in HistoryBackend. 3028 db_->ClearAndroidURLRows(); 3029#endif 3030 3031 // Drop original favicon_bitmaps, favicons, and icon mapping tables and 3032 // replace them with the duplicate tables. Recreate the other tables. This 3033 // will make the database consistent again. 3034 thumbnail_db_->CommitTemporaryTables(); 3035 3036 thumbnail_db_->RecreateThumbnailTable(); 3037 3038 // Vacuum to remove all the pages associated with the dropped tables. There 3039 // must be no transaction open on the table when we do this. We assume that 3040 // our long-running transaction is open, so we complete it and start it again. 3041 DCHECK(thumbnail_db_->transaction_nesting() == 1); 3042 thumbnail_db_->CommitTransaction(); 3043 thumbnail_db_->Vacuum(); 3044 thumbnail_db_->BeginTransaction(); 3045 return true; 3046} 3047 3048bool HistoryBackend::ClearAllMainHistory(const URLRows& kept_urls) { 3049 // Create the duplicate URL table. We will copy the kept URLs into this. 3050 if (!db_->CreateTemporaryURLTable()) 3051 return false; 3052 3053 // Insert the URLs into the temporary table, we need to keep a map of changed 3054 // IDs since the ID will be different in the new table. 3055 typedef std::map<URLID, URLID> URLIDMap; 3056 URLIDMap old_to_new; // Maps original ID to new one. 3057 for (URLRows::const_iterator i = kept_urls.begin(); i != kept_urls.end(); 3058 ++i) { 3059 URLID new_id = db_->AddTemporaryURL(*i); 3060 old_to_new[i->id()] = new_id; 3061 } 3062 3063 // Replace the original URL table with the temporary one. 3064 if (!db_->CommitTemporaryURLTable()) 3065 return false; 3066 3067 // Delete the old tables and recreate them empty. 3068 db_->RecreateAllTablesButURL(); 3069 3070 // Vacuum to reclaim the space from the dropped tables. This must be done 3071 // when there is no transaction open, and we assume that our long-running 3072 // transaction is currently open. 3073 db_->CommitTransaction(); 3074 db_->Vacuum(); 3075 db_->BeginTransaction(); 3076 db_->GetStartDate(&first_recorded_time_); 3077 3078 return true; 3079} 3080 3081BookmarkService* HistoryBackend::GetBookmarkService() { 3082 if (bookmark_service_) 3083 bookmark_service_->BlockTillLoaded(); 3084 return bookmark_service_; 3085} 3086 3087void HistoryBackend::NotifyVisitObservers(const VisitRow& visit) { 3088 BriefVisitInfo info; 3089 info.url_id = visit.url_id; 3090 info.time = visit.visit_time; 3091 info.transition = visit.transition; 3092 // If we don't have a delegate yet during setup or shutdown, we will drop 3093 // these notifications. 3094 if (delegate_) 3095 delegate_->NotifyVisitDBObserversOnAddVisit(info); 3096} 3097 3098} // namespace history 3099