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