Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / extensions / activity_log / activity_log.cc
blob7fa22ae27178d251e0297f60acccb46cbc64033a
1 // Copyright (c) 2011 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/activity_log/activity_log.h"
7 #include <set>
8 #include <vector>
10 #include "base/command_line.h"
11 #include "base/json/json_string_value_serializer.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/thread_checker.h"
17 #include "chrome/browser/extensions/activity_log/activity_action_constants.h"
18 #include "chrome/browser/extensions/activity_log/counting_policy.h"
19 #include "chrome/browser/extensions/activity_log/fullstream_ui_policy.h"
20 #include "chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h"
21 #include "chrome/browser/extensions/extension_tab_util.h"
22 #include "chrome/browser/prerender/prerender_manager.h"
23 #include "chrome/browser/prerender/prerender_manager_factory.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/ui/browser.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/pref_names.h"
29 #include "components/syncable_prefs/pref_service_syncable.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/web_contents.h"
32 #include "extensions/browser/extension_registry.h"
33 #include "extensions/browser/extension_registry_factory.h"
34 #include "extensions/browser/extension_system.h"
35 #include "extensions/browser/extension_system_provider.h"
36 #include "extensions/browser/extensions_browser_client.h"
37 #include "extensions/common/extension.h"
38 #include "extensions/common/one_shot_event.h"
39 #include "third_party/re2/re2/re2.h"
40 #include "url/gurl.h"
42 namespace constants = activity_log_constants;
44 namespace extensions {
46 namespace {
48 using constants::kArgUrlPlaceholder;
49 using content::BrowserThread;
51 // If DOM API methods start with this string, we flag them as being of type
52 // DomActionType::XHR.
53 const char kDomXhrPrefix[] = "XMLHttpRequest.";
55 // Specifies a possible action to take to get an extracted URL in the ApiInfo
56 // structure below.
57 enum Transformation {
58 NONE,
59 DICT_LOOKUP,
60 LOOKUP_TAB_ID,
63 // Information about specific Chrome and DOM APIs, such as which contain
64 // arguments that should be extracted into the arg_url field of an Action.
65 struct ApiInfo {
66 // The lookup key consists of the action_type and api_name in the Action
67 // object.
68 Action::ActionType action_type;
69 const char* api_name;
71 // If non-negative, an index into args might contain a URL to be extracted
72 // into arg_url.
73 int arg_url_index;
75 // A transformation to apply to the data found at index arg_url_index in the
76 // argument list.
78 // If NONE, the data is expected to be a string which is treated as a URL.
80 // If LOOKUP_TAB_ID, the data is either an integer which is treated as a tab
81 // ID and translated (in the context of a provided Profile), or a list of tab
82 // IDs which are translated.
84 // If DICT_LOOKUP, the data is expected to be a dictionary, and
85 // arg_url_dict_path is a path (list of keys delimited by ".") where a URL
86 // string is to be found.
87 Transformation arg_url_transform;
88 const char* arg_url_dict_path;
91 static const ApiInfo kApiInfoTable[] = {
92 // Tabs APIs that require tab ID translation
93 {Action::ACTION_API_CALL, "tabs.connect", 0, LOOKUP_TAB_ID, NULL},
94 {Action::ACTION_API_CALL, "tabs.detectLanguage", 0, LOOKUP_TAB_ID, NULL},
95 {Action::ACTION_API_CALL, "tabs.duplicate", 0, LOOKUP_TAB_ID, NULL},
96 {Action::ACTION_API_CALL, "tabs.executeScript", 0, LOOKUP_TAB_ID, NULL},
97 {Action::ACTION_API_CALL, "tabs.get", 0, LOOKUP_TAB_ID, NULL},
98 {Action::ACTION_API_CALL, "tabs.insertCSS", 0, LOOKUP_TAB_ID, NULL},
99 {Action::ACTION_API_CALL, "tabs.move", 0, LOOKUP_TAB_ID, NULL},
100 {Action::ACTION_API_CALL, "tabs.reload", 0, LOOKUP_TAB_ID, NULL},
101 {Action::ACTION_API_CALL, "tabs.remove", 0, LOOKUP_TAB_ID, NULL},
102 {Action::ACTION_API_CALL, "tabs.sendMessage", 0, LOOKUP_TAB_ID, NULL},
103 {Action::ACTION_API_CALL, "tabs.update", 0, LOOKUP_TAB_ID, NULL},
104 {Action::ACTION_API_EVENT, "tabs.onUpdated", 0, LOOKUP_TAB_ID, NULL},
105 {Action::ACTION_API_EVENT, "tabs.onMoved", 0, LOOKUP_TAB_ID, NULL},
106 {Action::ACTION_API_EVENT, "tabs.onDetached", 0, LOOKUP_TAB_ID, NULL},
107 {Action::ACTION_API_EVENT, "tabs.onAttached", 0, LOOKUP_TAB_ID, NULL},
108 {Action::ACTION_API_EVENT, "tabs.onRemoved", 0, LOOKUP_TAB_ID, NULL},
109 {Action::ACTION_API_EVENT, "tabs.onReplaced", 0, LOOKUP_TAB_ID, NULL},
111 // Other APIs that accept URLs as strings
112 {Action::ACTION_API_CALL, "bookmarks.create", 0, DICT_LOOKUP, "url"},
113 {Action::ACTION_API_CALL, "bookmarks.update", 1, DICT_LOOKUP, "url"},
114 {Action::ACTION_API_CALL, "cookies.get", 0, DICT_LOOKUP, "url"},
115 {Action::ACTION_API_CALL, "cookies.getAll", 0, DICT_LOOKUP, "url"},
116 {Action::ACTION_API_CALL, "cookies.remove", 0, DICT_LOOKUP, "url"},
117 {Action::ACTION_API_CALL, "cookies.set", 0, DICT_LOOKUP, "url"},
118 {Action::ACTION_API_CALL, "downloads.download", 0, DICT_LOOKUP, "url"},
119 {Action::ACTION_API_CALL, "history.addUrl", 0, DICT_LOOKUP, "url"},
120 {Action::ACTION_API_CALL, "history.deleteUrl", 0, DICT_LOOKUP, "url"},
121 {Action::ACTION_API_CALL, "history.getVisits", 0, DICT_LOOKUP, "url"},
122 {Action::ACTION_API_CALL, "webstore.install", 0, NONE, NULL},
123 {Action::ACTION_API_CALL, "windows.create", 0, DICT_LOOKUP, "url"},
124 {Action::ACTION_DOM_ACCESS, "Document.location", 0, NONE, NULL},
125 {Action::ACTION_DOM_ACCESS, "HTMLAnchorElement.href", 0, NONE, NULL},
126 {Action::ACTION_DOM_ACCESS, "HTMLButtonElement.formAction", 0, NONE, NULL},
127 {Action::ACTION_DOM_ACCESS, "HTMLEmbedElement.src", 0, NONE, NULL},
128 {Action::ACTION_DOM_ACCESS, "HTMLFormElement.action", 0, NONE, NULL},
129 {Action::ACTION_DOM_ACCESS, "HTMLFrameElement.src", 0, NONE, NULL},
130 {Action::ACTION_DOM_ACCESS, "HTMLHtmlElement.manifest", 0, NONE, NULL},
131 {Action::ACTION_DOM_ACCESS, "HTMLIFrameElement.src", 0, NONE, NULL},
132 {Action::ACTION_DOM_ACCESS, "HTMLImageElement.longDesc", 0, NONE, NULL},
133 {Action::ACTION_DOM_ACCESS, "HTMLImageElement.src", 0, NONE, NULL},
134 {Action::ACTION_DOM_ACCESS, "HTMLImageElement.lowsrc", 0, NONE, NULL},
135 {Action::ACTION_DOM_ACCESS, "HTMLInputElement.formAction", 0, NONE, NULL},
136 {Action::ACTION_DOM_ACCESS, "HTMLInputElement.src", 0, NONE, NULL},
137 {Action::ACTION_DOM_ACCESS, "HTMLLinkElement.href", 0, NONE, NULL},
138 {Action::ACTION_DOM_ACCESS, "HTMLMediaElement.src", 0, NONE, NULL},
139 {Action::ACTION_DOM_ACCESS, "HTMLMediaElement.currentSrc", 0, NONE, NULL},
140 {Action::ACTION_DOM_ACCESS, "HTMLModElement.cite", 0, NONE, NULL},
141 {Action::ACTION_DOM_ACCESS, "HTMLObjectElement.data", 0, NONE, NULL},
142 {Action::ACTION_DOM_ACCESS, "HTMLQuoteElement.cite", 0, NONE, NULL},
143 {Action::ACTION_DOM_ACCESS, "HTMLScriptElement.src", 0, NONE, NULL},
144 {Action::ACTION_DOM_ACCESS, "HTMLSourceElement.src", 0, NONE, NULL},
145 {Action::ACTION_DOM_ACCESS, "HTMLTrackElement.src", 0, NONE, NULL},
146 {Action::ACTION_DOM_ACCESS, "HTMLVideoElement.poster", 0, NONE, NULL},
147 {Action::ACTION_DOM_ACCESS, "Location.assign", 0, NONE, NULL},
148 {Action::ACTION_DOM_ACCESS, "Location.replace", 0, NONE, NULL},
149 {Action::ACTION_DOM_ACCESS, "Window.location", 0, NONE, NULL},
150 {Action::ACTION_DOM_ACCESS, "XMLHttpRequest.open", 1, NONE, NULL}};
152 // A singleton class which provides lookups into the kApiInfoTable data
153 // structure. It inserts all data into a map on first lookup.
154 class ApiInfoDatabase {
155 public:
156 static ApiInfoDatabase* GetInstance() {
157 return base::Singleton<ApiInfoDatabase>::get();
160 // Retrieves an ApiInfo record for the given Action type. Returns either a
161 // pointer to the record, or NULL if no such record was found.
162 const ApiInfo* Lookup(Action::ActionType action_type,
163 const std::string& api_name) const {
164 std::map<std::string, const ApiInfo*>::const_iterator i =
165 api_database_.find(api_name);
166 if (i == api_database_.end())
167 return NULL;
168 if (i->second->action_type != action_type)
169 return NULL;
170 return i->second;
173 private:
174 ApiInfoDatabase() {
175 for (size_t i = 0; i < arraysize(kApiInfoTable); i++) {
176 const ApiInfo* info = &kApiInfoTable[i];
177 api_database_[info->api_name] = info;
180 virtual ~ApiInfoDatabase() {}
182 // The map is keyed by API name only, since API names aren't be repeated
183 // across multiple action types in kApiInfoTable. However, the action type
184 // should still be checked before returning a positive match.
185 std::map<std::string, const ApiInfo*> api_database_;
187 friend struct base::DefaultSingletonTraits<ApiInfoDatabase>;
188 DISALLOW_COPY_AND_ASSIGN(ApiInfoDatabase);
191 // Gets the URL for a given tab ID. Helper method for ExtractUrls. Returns
192 // true if able to perform the lookup. The URL is stored to *url, and
193 // *is_incognito is set to indicate whether the URL is for an incognito tab.
194 bool GetUrlForTabId(int tab_id,
195 Profile* profile,
196 GURL* url,
197 bool* is_incognito) {
198 content::WebContents* contents = NULL;
199 Browser* browser = NULL;
200 bool found = ExtensionTabUtil::GetTabById(
201 tab_id,
202 profile,
203 true, // Search incognito tabs, too.
204 &browser,
205 NULL,
206 &contents,
207 NULL);
209 if (found) {
210 *url = contents->GetURL();
211 *is_incognito = browser->profile()->IsOffTheRecord();
212 return true;
213 } else {
214 return false;
218 // Resolves an argument URL relative to a base page URL. If the page URL is
219 // not valid, then only absolute argument URLs are supported.
220 bool ResolveUrl(const GURL& base, const std::string& arg, GURL* arg_out) {
221 if (base.is_valid())
222 *arg_out = base.Resolve(arg);
223 else
224 *arg_out = GURL(arg);
226 return arg_out->is_valid();
229 // Performs processing of the Action object to extract URLs from the argument
230 // list and translate tab IDs to URLs, according to the API call metadata in
231 // kApiInfoTable. Mutates the Action object in place. There is a small chance
232 // that the tab id->URL translation could be wrong, if the tab has already been
233 // navigated by the time of invocation.
235 // Any extracted URL is stored into the arg_url field of the action, and the
236 // URL in the argument list is replaced with the marker value "<arg_url>". For
237 // APIs that take a list of tab IDs, extracts the first valid URL into arg_url
238 // and overwrites the other tab IDs in the argument list with the translated
239 // URL.
240 void ExtractUrls(scoped_refptr<Action> action, Profile* profile) {
241 const ApiInfo* api_info = ApiInfoDatabase::GetInstance()->Lookup(
242 action->action_type(), action->api_name());
243 if (api_info == NULL)
244 return;
246 int url_index = api_info->arg_url_index;
248 if (!action->args() || url_index < 0 ||
249 static_cast<size_t>(url_index) >= action->args()->GetSize())
250 return;
252 // Do not overwrite an existing arg_url value in the Action, so that callers
253 // have the option of doing custom arg_url extraction.
254 if (action->arg_url().is_valid())
255 return;
257 GURL arg_url;
258 bool arg_incognito = action->page_incognito();
260 switch (api_info->arg_url_transform) {
261 case NONE: {
262 // No translation needed; just extract the URL directly from a raw string
263 // or from a dictionary. Succeeds if we can find a string in the
264 // argument list and that the string resolves to a valid URL.
265 std::string url_string;
266 if (action->args()->GetString(url_index, &url_string) &&
267 ResolveUrl(action->page_url(), url_string, &arg_url)) {
268 action->mutable_args()->Set(url_index,
269 new base::StringValue(kArgUrlPlaceholder));
271 break;
274 case DICT_LOOKUP: {
275 CHECK(api_info->arg_url_dict_path);
276 // Look up the URL from a dictionary at the specified location. Succeeds
277 // if we can find a dictionary in the argument list, the dictionary
278 // contains the specified key, and the corresponding value resolves to a
279 // valid URL.
280 base::DictionaryValue* dict = NULL;
281 std::string url_string;
282 if (action->mutable_args()->GetDictionary(url_index, &dict) &&
283 dict->GetString(api_info->arg_url_dict_path, &url_string) &&
284 ResolveUrl(action->page_url(), url_string, &arg_url)) {
285 dict->SetString(api_info->arg_url_dict_path, kArgUrlPlaceholder);
287 break;
290 case LOOKUP_TAB_ID: {
291 // Translation of tab IDs to URLs has been requested. There are two
292 // cases to consider: either a single integer or a list of integers (when
293 // multiple tabs are manipulated).
294 int tab_id;
295 base::ListValue* tab_list = NULL;
296 if (action->args()->GetInteger(url_index, &tab_id)) {
297 // Single tab ID to translate.
298 GetUrlForTabId(tab_id, profile, &arg_url, &arg_incognito);
299 if (arg_url.is_valid()) {
300 action->mutable_args()->Set(
301 url_index, new base::StringValue(kArgUrlPlaceholder));
303 } else if (action->mutable_args()->GetList(url_index, &tab_list)) {
304 // A list of possible IDs to translate. Work through in reverse order
305 // so the last one translated is left in arg_url.
306 int extracted_index = -1; // Which list item is copied to arg_url?
307 for (int i = tab_list->GetSize() - 1; i >= 0; --i) {
308 if (tab_list->GetInteger(i, &tab_id) &&
309 GetUrlForTabId(tab_id, profile, &arg_url, &arg_incognito)) {
310 if (!arg_incognito)
311 tab_list->Set(i, new base::StringValue(arg_url.spec()));
312 extracted_index = i;
315 if (extracted_index >= 0) {
316 tab_list->Set(
317 extracted_index, new base::StringValue(kArgUrlPlaceholder));
320 break;
323 default:
324 NOTREACHED();
327 if (arg_url.is_valid()) {
328 action->set_arg_incognito(arg_incognito);
329 action->set_arg_url(arg_url);
333 } // namespace
335 // SET THINGS UP. --------------------------------------------------------------
337 static base::LazyInstance<BrowserContextKeyedAPIFactory<ActivityLog> >
338 g_factory = LAZY_INSTANCE_INITIALIZER;
340 BrowserContextKeyedAPIFactory<ActivityLog>* ActivityLog::GetFactoryInstance() {
341 return g_factory.Pointer();
344 // static
345 ActivityLog* ActivityLog::GetInstance(content::BrowserContext* context) {
346 return ActivityLog::GetFactoryInstance()->Get(
347 Profile::FromBrowserContext(context));
350 // Use GetInstance instead of directly creating an ActivityLog.
351 ActivityLog::ActivityLog(content::BrowserContext* context)
352 : database_policy_(NULL),
353 database_policy_type_(ActivityLogPolicy::POLICY_INVALID),
354 profile_(Profile::FromBrowserContext(context)),
355 db_enabled_(false),
356 testing_mode_(false),
357 has_threads_(true),
358 extension_registry_observer_(this),
359 watchdog_apps_active_(0) {
360 // This controls whether logging statements are printed & which policy is set.
361 testing_mode_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
362 switches::kEnableExtensionActivityLogTesting);
364 // Check if the watchdog extension is previously installed and active.
365 watchdog_apps_active_ =
366 profile_->GetPrefs()->GetInteger(prefs::kWatchdogExtensionActive);
368 observers_ = new base::ObserverListThreadSafe<Observer>;
370 // Check that the right threads exist for logging to the database.
371 // If not, we shouldn't try to do things that require them.
372 if (!BrowserThread::IsMessageLoopValid(BrowserThread::DB) ||
373 !BrowserThread::IsMessageLoopValid(BrowserThread::FILE) ||
374 !BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
375 has_threads_ = false;
378 db_enabled_ =
379 has_threads_ && (base::CommandLine::ForCurrentProcess()->HasSwitch(
380 switches::kEnableExtensionActivityLogging) ||
381 watchdog_apps_active_);
383 extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
384 ChooseDatabasePolicy();
387 void ActivityLog::SetDatabasePolicy(
388 ActivityLogPolicy::PolicyType policy_type) {
389 if (database_policy_type_ == policy_type)
390 return;
391 if (!IsDatabaseEnabled() && !IsWatchdogAppActive())
392 return;
394 // Deleting the old policy takes place asynchronously, on the database
395 // thread. Initializing a new policy below similarly happens
396 // asynchronously. Since the two operations are both queued for the
397 // database, the queue ordering should ensure that the deletion completes
398 // before database initialization occurs.
400 // However, changing policies at runtime is still not recommended, and
401 // likely only should be done for unit tests.
402 if (database_policy_)
403 database_policy_->Close();
405 switch (policy_type) {
406 case ActivityLogPolicy::POLICY_FULLSTREAM:
407 database_policy_ = new FullStreamUIPolicy(profile_);
408 break;
409 case ActivityLogPolicy::POLICY_COUNTS:
410 database_policy_ = new CountingPolicy(profile_);
411 break;
412 default:
413 NOTREACHED();
415 database_policy_->Init();
416 database_policy_type_ = policy_type;
419 ActivityLog::~ActivityLog() {
420 if (database_policy_)
421 database_policy_->Close();
424 // MAINTAIN STATUS. ------------------------------------------------------------
426 void ActivityLog::ChooseDatabasePolicy() {
427 if (!(IsDatabaseEnabled() || IsWatchdogAppActive()))
428 return;
429 if (testing_mode_)
430 SetDatabasePolicy(ActivityLogPolicy::POLICY_FULLSTREAM);
431 else
432 SetDatabasePolicy(ActivityLogPolicy::POLICY_COUNTS);
435 bool ActivityLog::IsDatabaseEnabled() {
436 // Make sure we are not enabled when there are no threads.
437 DCHECK(has_threads_ || !db_enabled_);
438 return db_enabled_;
441 bool ActivityLog::IsWatchdogAppActive() {
442 return (watchdog_apps_active_ > 0);
445 void ActivityLog::SetWatchdogAppActiveForTesting(bool active) {
446 watchdog_apps_active_ = active ? 1 : 0;
449 void ActivityLog::OnExtensionLoaded(content::BrowserContext* browser_context,
450 const Extension* extension) {
451 if (!ActivityLogAPI::IsExtensionWhitelisted(extension->id())) return;
452 if (has_threads_)
453 db_enabled_ = true;
454 watchdog_apps_active_++;
455 profile_->GetPrefs()->SetInteger(prefs::kWatchdogExtensionActive,
456 watchdog_apps_active_);
457 if (watchdog_apps_active_ == 1)
458 ChooseDatabasePolicy();
461 void ActivityLog::OnExtensionUnloaded(content::BrowserContext* browser_context,
462 const Extension* extension,
463 UnloadedExtensionInfo::Reason reason) {
464 if (!ActivityLogAPI::IsExtensionWhitelisted(extension->id())) return;
465 watchdog_apps_active_--;
466 profile_->GetPrefs()->SetInteger(prefs::kWatchdogExtensionActive,
467 watchdog_apps_active_);
468 if (watchdog_apps_active_ == 0 &&
469 !base::CommandLine::ForCurrentProcess()->HasSwitch(
470 switches::kEnableExtensionActivityLogging)) {
471 db_enabled_ = false;
475 // OnExtensionUnloaded will also be called right before this.
476 void ActivityLog::OnExtensionUninstalled(
477 content::BrowserContext* browser_context,
478 const Extension* extension,
479 extensions::UninstallReason reason) {
480 if (ActivityLogAPI::IsExtensionWhitelisted(extension->id()) &&
481 !base::CommandLine::ForCurrentProcess()->HasSwitch(
482 switches::kEnableExtensionActivityLogging) &&
483 watchdog_apps_active_ == 0) {
484 DeleteDatabase();
485 } else if (database_policy_) {
486 database_policy_->RemoveExtensionData(extension->id());
490 void ActivityLog::AddObserver(ActivityLog::Observer* observer) {
491 observers_->AddObserver(observer);
494 void ActivityLog::RemoveObserver(ActivityLog::Observer* observer) {
495 observers_->RemoveObserver(observer);
498 // static
499 void ActivityLog::RegisterProfilePrefs(
500 user_prefs::PrefRegistrySyncable* registry) {
501 registry->RegisterIntegerPref(prefs::kWatchdogExtensionActive, false);
504 // LOG ACTIONS. ----------------------------------------------------------------
506 void ActivityLog::LogAction(scoped_refptr<Action> action) {
507 if (ActivityLogAPI::IsExtensionWhitelisted(action->extension_id()))
508 return;
510 // Perform some preprocessing of the Action data: convert tab IDs to URLs and
511 // mask out incognito URLs if appropriate.
512 ExtractUrls(action, profile_);
514 // Mark DOM XHR requests as such, for easier processing later.
515 if (action->action_type() == Action::ACTION_DOM_ACCESS &&
516 base::StartsWith(action->api_name(), kDomXhrPrefix,
517 base::CompareCase::SENSITIVE) &&
518 action->other()) {
519 base::DictionaryValue* other = action->mutable_other();
520 int dom_verb = -1;
521 if (other->GetInteger(constants::kActionDomVerb, &dom_verb) &&
522 dom_verb == DomActionType::METHOD) {
523 other->SetInteger(constants::kActionDomVerb, DomActionType::XHR);
527 if (IsDatabaseEnabled() && database_policy_)
528 database_policy_->ProcessAction(action);
529 if (IsWatchdogAppActive())
530 observers_->Notify(FROM_HERE, &Observer::OnExtensionActivity, action);
531 if (testing_mode_)
532 VLOG(1) << action->PrintForDebug();
535 void ActivityLog::OnScriptsExecuted(
536 const content::WebContents* web_contents,
537 const ExecutingScriptsMap& extension_ids,
538 const GURL& on_url) {
539 Profile* profile =
540 Profile::FromBrowserContext(web_contents->GetBrowserContext());
541 ExtensionRegistry* registry = ExtensionRegistry::Get(profile);
542 for (ExecutingScriptsMap::const_iterator it = extension_ids.begin();
543 it != extension_ids.end(); ++it) {
544 const Extension* extension =
545 registry->GetExtensionById(it->first, ExtensionRegistry::ENABLED);
546 if (!extension || ActivityLogAPI::IsExtensionWhitelisted(extension->id()))
547 continue;
549 // If OnScriptsExecuted is fired because of tabs.executeScript, the list
550 // of content scripts will be empty. We don't want to log it because
551 // the call to tabs.executeScript will have already been logged anyway.
552 if (!it->second.empty()) {
553 scoped_refptr<Action> action;
554 action = new Action(extension->id(),
555 base::Time::Now(),
556 Action::ACTION_CONTENT_SCRIPT,
557 ""); // no API call here
558 action->set_page_url(on_url);
559 action->set_page_title(base::UTF16ToUTF8(web_contents->GetTitle()));
560 action->set_page_incognito(
561 web_contents->GetBrowserContext()->IsOffTheRecord());
563 const prerender::PrerenderManager* prerender_manager =
564 prerender::PrerenderManagerFactory::GetForProfile(profile);
565 if (prerender_manager &&
566 prerender_manager->IsWebContentsPrerendering(web_contents, NULL))
567 action->mutable_other()->SetBoolean(constants::kActionPrerender, true);
568 for (std::set<std::string>::const_iterator it2 = it->second.begin();
569 it2 != it->second.end();
570 ++it2) {
571 action->mutable_args()->AppendString(*it2);
573 LogAction(action);
578 void ActivityLog::OnApiEventDispatched(const std::string& extension_id,
579 const std::string& event_name,
580 scoped_ptr<base::ListValue> event_args) {
581 DCHECK_CURRENTLY_ON(BrowserThread::UI);
582 scoped_refptr<Action> action = new Action(extension_id,
583 base::Time::Now(),
584 Action::ACTION_API_EVENT,
585 event_name);
586 action->set_args(event_args.Pass());
587 LogAction(action);
590 void ActivityLog::OnApiFunctionCalled(const std::string& extension_id,
591 const std::string& api_name,
592 scoped_ptr<base::ListValue> args) {
593 DCHECK_CURRENTLY_ON(BrowserThread::UI);
594 scoped_refptr<Action> action = new Action(extension_id,
595 base::Time::Now(),
596 Action::ACTION_API_CALL,
597 api_name);
598 action->set_args(args.Pass());
599 LogAction(action);
602 // LOOKUP ACTIONS. -------------------------------------------------------------
604 void ActivityLog::GetFilteredActions(
605 const std::string& extension_id,
606 const Action::ActionType type,
607 const std::string& api_name,
608 const std::string& page_url,
609 const std::string& arg_url,
610 const int daysAgo,
611 const base::Callback
612 <void(scoped_ptr<std::vector<scoped_refptr<Action> > >)>& callback) {
613 if (database_policy_) {
614 database_policy_->ReadFilteredData(
615 extension_id, type, api_name, page_url, arg_url, daysAgo, callback);
619 // DELETE ACTIONS. -------------------------------------------------------------
621 void ActivityLog::RemoveActions(const std::vector<int64>& action_ids) {
622 if (!database_policy_)
623 return;
624 database_policy_->RemoveActions(action_ids);
627 void ActivityLog::RemoveURLs(const std::vector<GURL>& restrict_urls) {
628 if (!database_policy_)
629 return;
630 database_policy_->RemoveURLs(restrict_urls);
633 void ActivityLog::RemoveURLs(const std::set<GURL>& restrict_urls) {
634 if (!database_policy_)
635 return;
637 std::vector<GURL> urls;
638 for (std::set<GURL>::const_iterator it = restrict_urls.begin();
639 it != restrict_urls.end(); ++it) {
640 urls.push_back(*it);
642 database_policy_->RemoveURLs(urls);
645 void ActivityLog::RemoveURL(const GURL& url) {
646 if (url.is_empty())
647 return;
648 std::vector<GURL> urls;
649 urls.push_back(url);
650 RemoveURLs(urls);
653 void ActivityLog::DeleteDatabase() {
654 if (!database_policy_)
655 return;
656 database_policy_->DeleteDatabase();
659 template <>
660 void BrowserContextKeyedAPIFactory<ActivityLog>::DeclareFactoryDependencies() {
661 DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
662 DependsOn(ExtensionRegistryFactory::GetInstance());
665 } // namespace extensions