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.
5 #include "chrome/browser/extensions/api/history/history_api.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/command_line.h"
11 #include "base/json/json_writer.h"
12 #include "base/lazy_instance.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/task/cancelable_task_tracker.h"
19 #include "base/time/time.h"
20 #include "base/values.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/activity_log/activity_log.h"
23 #include "chrome/browser/history/history_service.h"
24 #include "chrome/browser/history/history_service_factory.h"
25 #include "chrome/browser/history/history_types.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/extensions/api/history.h"
29 #include "chrome/common/pref_names.h"
30 #include "content/public/browser/notification_details.h"
31 #include "content/public/browser/notification_source.h"
32 #include "extensions/browser/event_router.h"
33 #include "extensions/browser/extension_system_provider.h"
34 #include "extensions/browser/extensions_browser_client.h"
36 namespace extensions {
38 using api::history::HistoryItem;
39 using api::history::VisitItem;
40 using extensions::ActivityLog;
42 typedef std::vector<linked_ptr<api::history::HistoryItem> >
44 typedef std::vector<linked_ptr<api::history::VisitItem> >
47 namespace AddUrl = api::history::AddUrl;
48 namespace DeleteUrl = api::history::DeleteUrl;
49 namespace DeleteRange = api::history::DeleteRange;
50 namespace GetVisits = api::history::GetVisits;
51 namespace OnVisited = api::history::OnVisited;
52 namespace OnVisitRemoved = api::history::OnVisitRemoved;
53 namespace Search = api::history::Search;
57 const char kInvalidUrlError[] = "Url is invalid.";
58 const char kDeleteProhibitedError[] = "Browsing history is not allowed to be "
61 double MilliSecondsFromTime(const base::Time& time) {
62 return 1000 * time.ToDoubleT();
65 scoped_ptr<HistoryItem> GetHistoryItem(const history::URLRow& row) {
66 scoped_ptr<HistoryItem> history_item(new HistoryItem());
68 history_item->id = base::Int64ToString(row.id());
69 history_item->url.reset(new std::string(row.url().spec()));
70 history_item->title.reset(new std::string(base::UTF16ToUTF8(row.title())));
71 history_item->last_visit_time.reset(
72 new double(MilliSecondsFromTime(row.last_visit())));
73 history_item->typed_count.reset(new int(row.typed_count()));
74 history_item->visit_count.reset(new int(row.visit_count()));
76 return history_item.Pass();
79 scoped_ptr<VisitItem> GetVisitItem(const history::VisitRow& row) {
80 scoped_ptr<VisitItem> visit_item(new VisitItem());
82 visit_item->id = base::Int64ToString(row.url_id);
83 visit_item->visit_id = base::Int64ToString(row.visit_id);
84 visit_item->visit_time.reset(
85 new double(MilliSecondsFromTime(row.visit_time)));
86 visit_item->referring_visit_id = base::Int64ToString(row.referring_visit);
88 VisitItem::Transition transition = VisitItem::TRANSITION_LINK;
89 switch (row.transition & content::PAGE_TRANSITION_CORE_MASK) {
90 case content::PAGE_TRANSITION_LINK:
91 transition = VisitItem::TRANSITION_LINK;
93 case content::PAGE_TRANSITION_TYPED:
94 transition = VisitItem::TRANSITION_TYPED;
96 case content::PAGE_TRANSITION_AUTO_BOOKMARK:
97 transition = VisitItem::TRANSITION_AUTO_BOOKMARK;
99 case content::PAGE_TRANSITION_AUTO_SUBFRAME:
100 transition = VisitItem::TRANSITION_AUTO_SUBFRAME;
102 case content::PAGE_TRANSITION_MANUAL_SUBFRAME:
103 transition = VisitItem::TRANSITION_MANUAL_SUBFRAME;
105 case content::PAGE_TRANSITION_GENERATED:
106 transition = VisitItem::TRANSITION_GENERATED;
108 case content::PAGE_TRANSITION_AUTO_TOPLEVEL:
109 transition = VisitItem::TRANSITION_AUTO_TOPLEVEL;
111 case content::PAGE_TRANSITION_FORM_SUBMIT:
112 transition = VisitItem::TRANSITION_FORM_SUBMIT;
114 case content::PAGE_TRANSITION_RELOAD:
115 transition = VisitItem::TRANSITION_RELOAD;
117 case content::PAGE_TRANSITION_KEYWORD:
118 transition = VisitItem::TRANSITION_KEYWORD;
120 case content::PAGE_TRANSITION_KEYWORD_GENERATED:
121 transition = VisitItem::TRANSITION_KEYWORD_GENERATED;
127 visit_item->transition = transition;
129 return visit_item.Pass();
134 HistoryEventRouter::HistoryEventRouter(Profile* profile) {
135 const content::Source<Profile> source = content::Source<Profile>(profile);
137 chrome::NOTIFICATION_HISTORY_URL_VISITED,
140 chrome::NOTIFICATION_HISTORY_URLS_DELETED,
144 HistoryEventRouter::~HistoryEventRouter() {}
146 void HistoryEventRouter::Observe(int type,
147 const content::NotificationSource& source,
148 const content::NotificationDetails& details) {
150 case chrome::NOTIFICATION_HISTORY_URL_VISITED:
152 content::Source<Profile>(source).ptr(),
153 content::Details<const history::URLVisitedDetails>(details).ptr());
155 case chrome::NOTIFICATION_HISTORY_URLS_DELETED:
157 content::Source<Profile>(source).ptr(),
158 content::Details<const history::URLsDeletedDetails>(details).ptr());
165 void HistoryEventRouter::HistoryUrlVisited(
167 const history::URLVisitedDetails* details) {
168 scoped_ptr<HistoryItem> history_item = GetHistoryItem(details->row);
169 scoped_ptr<base::ListValue> args = OnVisited::Create(*history_item);
171 DispatchEvent(profile, api::history::OnVisited::kEventName, args.Pass());
174 void HistoryEventRouter::HistoryUrlsRemoved(
176 const history::URLsDeletedDetails* details) {
177 OnVisitRemoved::Removed removed;
178 removed.all_history = details->all_history;
180 std::vector<std::string>* urls = new std::vector<std::string>();
181 for (history::URLRows::const_iterator iterator = details->rows.begin();
182 iterator != details->rows.end(); ++iterator) {
183 urls->push_back(iterator->url().spec());
185 removed.urls.reset(urls);
187 scoped_ptr<base::ListValue> args = OnVisitRemoved::Create(removed);
188 DispatchEvent(profile, api::history::OnVisitRemoved::kEventName, args.Pass());
191 void HistoryEventRouter::DispatchEvent(
193 const std::string& event_name,
194 scoped_ptr<base::ListValue> event_args) {
195 if (profile && extensions::EventRouter::Get(profile)) {
196 scoped_ptr<extensions::Event> event(new extensions::Event(
197 event_name, event_args.Pass()));
198 event->restrict_to_browser_context = profile;
199 extensions::EventRouter::Get(profile)->BroadcastEvent(event.Pass());
203 HistoryAPI::HistoryAPI(content::BrowserContext* context)
204 : browser_context_(context) {
205 EventRouter* event_router = EventRouter::Get(browser_context_);
206 event_router->RegisterObserver(this, api::history::OnVisited::kEventName);
207 event_router->RegisterObserver(this,
208 api::history::OnVisitRemoved::kEventName);
211 HistoryAPI::~HistoryAPI() {
214 void HistoryAPI::Shutdown() {
215 EventRouter::Get(browser_context_)->UnregisterObserver(this);
218 static base::LazyInstance<BrowserContextKeyedAPIFactory<HistoryAPI> >
219 g_factory = LAZY_INSTANCE_INITIALIZER;
222 BrowserContextKeyedAPIFactory<HistoryAPI>* HistoryAPI::GetFactoryInstance() {
223 return g_factory.Pointer();
227 void BrowserContextKeyedAPIFactory<HistoryAPI>::DeclareFactoryDependencies() {
228 DependsOn(ActivityLog::GetFactoryInstance());
229 DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
232 void HistoryAPI::OnListenerAdded(const EventListenerInfo& details) {
233 history_event_router_.reset(
234 new HistoryEventRouter(Profile::FromBrowserContext(browser_context_)));
235 EventRouter::Get(browser_context_)->UnregisterObserver(this);
238 bool HistoryFunction::ValidateUrl(const std::string& url_string, GURL* url) {
239 GURL temp_url(url_string);
240 if (!temp_url.is_valid()) {
241 error_ = kInvalidUrlError;
244 url->Swap(&temp_url);
248 bool HistoryFunction::VerifyDeleteAllowed() {
249 PrefService* prefs = GetProfile()->GetPrefs();
250 if (!prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
251 error_ = kDeleteProhibitedError;
257 base::Time HistoryFunction::GetTime(double ms_from_epoch) {
258 // The history service has seconds resolution, while javascript Date() has
259 // milliseconds resolution.
260 double seconds_from_epoch = ms_from_epoch / 1000.0;
261 // Time::FromDoubleT converts double time 0 to empty Time object. So we need
262 // to do special handling here.
263 return (seconds_from_epoch == 0) ?
264 base::Time::UnixEpoch() : base::Time::FromDoubleT(seconds_from_epoch);
267 HistoryFunctionWithCallback::HistoryFunctionWithCallback() {
270 HistoryFunctionWithCallback::~HistoryFunctionWithCallback() {
273 bool HistoryFunctionWithCallback::RunAsync() {
274 AddRef(); // Balanced in SendAysncRepose() and below.
275 bool retval = RunAsyncImpl();
281 void HistoryFunctionWithCallback::SendAsyncResponse() {
282 base::MessageLoop::current()->PostTask(
284 base::Bind(&HistoryFunctionWithCallback::SendResponseToCallback, this));
287 void HistoryFunctionWithCallback::SendResponseToCallback() {
289 Release(); // Balanced in RunAsync().
292 bool HistoryGetVisitsFunction::RunAsyncImpl() {
293 scoped_ptr<GetVisits::Params> params(GetVisits::Params::Create(*args_));
294 EXTENSION_FUNCTION_VALIDATE(params.get());
297 if (!ValidateUrl(params->details.url, &url))
300 HistoryService* hs = HistoryServiceFactory::GetForProfile(
301 GetProfile(), Profile::EXPLICIT_ACCESS);
303 true, // Retrieve full history of a URL.
304 &cancelable_consumer_,
305 base::Bind(&HistoryGetVisitsFunction::QueryComplete,
306 base::Unretained(this)));
311 void HistoryGetVisitsFunction::QueryComplete(
312 HistoryService::Handle request_service,
314 const history::URLRow* url_row,
315 history::VisitVector* visits) {
316 VisitItemList visit_item_vec;
317 if (visits && !visits->empty()) {
318 for (history::VisitVector::iterator iterator = visits->begin();
319 iterator != visits->end();
321 visit_item_vec.push_back(make_linked_ptr(
322 GetVisitItem(*iterator).release()));
326 results_ = GetVisits::Results::Create(visit_item_vec);
330 bool HistorySearchFunction::RunAsyncImpl() {
331 scoped_ptr<Search::Params> params(Search::Params::Create(*args_));
332 EXTENSION_FUNCTION_VALIDATE(params.get());
334 base::string16 search_text = base::UTF8ToUTF16(params->query.text);
336 history::QueryOptions options;
337 options.SetRecentDayRange(1);
338 options.max_count = 100;
340 if (params->query.start_time.get())
341 options.begin_time = GetTime(*params->query.start_time);
342 if (params->query.end_time.get())
343 options.end_time = GetTime(*params->query.end_time);
344 if (params->query.max_results.get())
345 options.max_count = *params->query.max_results;
347 HistoryService* hs = HistoryServiceFactory::GetForProfile(
348 GetProfile(), Profile::EXPLICIT_ACCESS);
349 hs->QueryHistory(search_text, options, &cancelable_consumer_,
350 base::Bind(&HistorySearchFunction::SearchComplete,
351 base::Unretained(this)));
356 void HistorySearchFunction::SearchComplete(
357 HistoryService::Handle request_handle,
358 history::QueryResults* results) {
359 HistoryItemList history_item_vec;
360 if (results && !results->empty()) {
361 for (history::QueryResults::URLResultVector::const_iterator iterator =
363 iterator != results->end();
365 history_item_vec.push_back(make_linked_ptr(
366 GetHistoryItem(**iterator).release()));
369 results_ = Search::Results::Create(history_item_vec);
373 bool HistoryAddUrlFunction::RunAsync() {
374 scoped_ptr<AddUrl::Params> params(AddUrl::Params::Create(*args_));
375 EXTENSION_FUNCTION_VALIDATE(params.get());
378 if (!ValidateUrl(params->details.url, &url))
381 HistoryService* hs = HistoryServiceFactory::GetForProfile(
382 GetProfile(), Profile::EXPLICIT_ACCESS);
383 hs->AddPage(url, base::Time::Now(), history::SOURCE_EXTENSION);
389 bool HistoryDeleteUrlFunction::RunAsync() {
390 scoped_ptr<DeleteUrl::Params> params(DeleteUrl::Params::Create(*args_));
391 EXTENSION_FUNCTION_VALIDATE(params.get());
393 if (!VerifyDeleteAllowed())
397 if (!ValidateUrl(params->details.url, &url))
400 HistoryService* hs = HistoryServiceFactory::GetForProfile(
401 GetProfile(), Profile::EXPLICIT_ACCESS);
404 // Also clean out from the activity log. If the activity log testing flag is
405 // set then don't clean so testers can see what potentially malicious
406 // extensions have been trying to clean from their logs.
407 if (!CommandLine::ForCurrentProcess()->HasSwitch(
408 switches::kEnableExtensionActivityLogTesting)) {
409 ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
410 DCHECK(activity_log);
411 activity_log->RemoveURL(url);
418 bool HistoryDeleteRangeFunction::RunAsyncImpl() {
419 scoped_ptr<DeleteRange::Params> params(DeleteRange::Params::Create(*args_));
420 EXTENSION_FUNCTION_VALIDATE(params.get());
422 if (!VerifyDeleteAllowed())
425 base::Time start_time = GetTime(params->range.start_time);
426 base::Time end_time = GetTime(params->range.end_time);
428 std::set<GURL> restrict_urls;
429 HistoryService* hs = HistoryServiceFactory::GetForProfile(
430 GetProfile(), Profile::EXPLICIT_ACCESS);
431 hs->ExpireHistoryBetween(
435 base::Bind(&HistoryDeleteRangeFunction::DeleteComplete,
436 base::Unretained(this)),
439 // Also clean from the activity log unless in testing mode.
440 if (!CommandLine::ForCurrentProcess()->HasSwitch(
441 switches::kEnableExtensionActivityLogTesting)) {
442 ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
443 DCHECK(activity_log);
444 activity_log->RemoveURLs(restrict_urls);
450 void HistoryDeleteRangeFunction::DeleteComplete() {
454 bool HistoryDeleteAllFunction::RunAsyncImpl() {
455 if (!VerifyDeleteAllowed())
458 std::set<GURL> restrict_urls;
459 HistoryService* hs = HistoryServiceFactory::GetForProfile(
460 GetProfile(), Profile::EXPLICIT_ACCESS);
461 hs->ExpireHistoryBetween(
463 base::Time(), // Unbounded beginning...
464 base::Time(), // ...and the end.
465 base::Bind(&HistoryDeleteAllFunction::DeleteComplete,
466 base::Unretained(this)),
469 // Also clean from the activity log unless in testing mode.
470 if (!CommandLine::ForCurrentProcess()->HasSwitch(
471 switches::kEnableExtensionActivityLogTesting)) {
472 ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
473 DCHECK(activity_log);
474 activity_log->RemoveURLs(restrict_urls);
480 void HistoryDeleteAllFunction::DeleteComplete() {
484 } // namespace extensions