Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(394)

Side by Side Diff: extensions/browser/api/runtime/runtime_api.cc

Issue 264743014: Move chrome.runtime to //extensions. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/runtime/runtime_api.h" 5 #include "extensions/browser/api/runtime/runtime_api.h"
6 6
7 #include <utility> 7 #include <utility>
8 8
9 #include "base/lazy_instance.h" 9 #include "base/lazy_instance.h"
10 #include "base/logging.h" 10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h" 11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram.h" 12 #include "base/metrics/histogram.h"
13 #include "base/values.h" 13 #include "base/values.h"
14 #include "chrome/browser/browser_process.h" 14 #include "base/version.h"
15 #include "chrome/browser/chrome_notification_types.h" 15 #include "chrome/browser/chrome_notification_types.h"
16 #include "chrome/browser/extensions/extension_service.h" 16 #include "content/public/browser/browser_context.h"
17 #include "chrome/browser/extensions/extension_warning_service.h"
18 #include "chrome/browser/extensions/updater/extension_updater.h"
19 #include "chrome/browser/omaha_query_params/omaha_query_params.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/profiles/profile_manager.h"
22 #include "chrome/browser/ui/browser_finder.h"
23 #include "chrome/browser/ui/browser_navigator.h"
24 #include "chrome/browser/ui/browser_window.h"
25 #include "chrome/common/extensions/api/runtime.h"
26 #include "content/public/browser/child_process_security_policy.h" 17 #include "content/public/browser/child_process_security_policy.h"
27 #include "content/public/browser/notification_service.h" 18 #include "content/public/browser/notification_service.h"
28 #include "content/public/browser/render_process_host.h" 19 #include "content/public/browser/render_process_host.h"
29 #include "content/public/browser/render_view_host.h" 20 #include "content/public/browser/render_view_host.h"
30 #include "extensions/browser/event_router.h" 21 #include "extensions/browser/event_router.h"
31 #include "extensions/browser/extension_host.h" 22 #include "extensions/browser/extension_host.h"
23 #include "extensions/browser/extension_prefs.h"
32 #include "extensions/browser/extension_registry.h" 24 #include "extensions/browser/extension_registry.h"
33 #include "extensions/browser/extension_system.h" 25 #include "extensions/browser/extension_system.h"
34 #include "extensions/browser/extensions_browser_client.h" 26 #include "extensions/browser/extensions_browser_client.h"
35 #include "extensions/browser/lazy_background_task_queue.h" 27 #include "extensions/browser/lazy_background_task_queue.h"
36 #include "extensions/browser/process_manager.h" 28 #include "extensions/browser/process_manager.h"
29 #include "extensions/browser/runtime_api_delegate.h"
30 #include "extensions/common/api/runtime.h"
37 #include "extensions/common/error_utils.h" 31 #include "extensions/common/error_utils.h"
38 #include "extensions/common/extension.h" 32 #include "extensions/common/extension.h"
39 #include "extensions/common/manifest_handlers/background_info.h" 33 #include "extensions/common/manifest_handlers/background_info.h"
40 #include "url/gurl.h" 34 #include "url/gurl.h"
41 #include "webkit/browser/fileapi/isolated_context.h" 35 #include "webkit/browser/fileapi/isolated_context.h"
42 36
43 #if defined(OS_CHROMEOS)
44 #include "chrome/browser/chromeos/login/user_manager.h"
45 #include "chromeos/dbus/dbus_thread_manager.h"
46 #include "chromeos/dbus/power_manager_client.h"
47 #endif
48
49 using content::BrowserContext; 37 using content::BrowserContext;
50 38
51 namespace GetPlatformInfo = extensions::api::runtime::GetPlatformInfo; 39 namespace GetPlatformInfo = extensions::core_api::runtime::GetPlatformInfo;
52 40
53 namespace extensions { 41 namespace extensions {
54 42
55 namespace runtime = api::runtime; 43 namespace runtime = core_api::runtime;
56 44
57 namespace { 45 namespace {
58 46
59 const char kNoBackgroundPageError[] = "You do not have a background page."; 47 const char kNoBackgroundPageError[] = "You do not have a background page.";
60 const char kPageLoadError[] = "Background page failed to load."; 48 const char kPageLoadError[] = "Background page failed to load.";
61 const char kInstallReason[] = "reason"; 49 const char kInstallReason[] = "reason";
62 const char kInstallReasonChromeUpdate[] = "chrome_update"; 50 const char kInstallReasonChromeUpdate[] = "chrome_update";
63 const char kInstallReasonUpdate[] = "update"; 51 const char kInstallReasonUpdate[] = "update";
64 const char kInstallReasonInstall[] = "install"; 52 const char kInstallReasonInstall[] = "install";
65 const char kInstallPreviousVersion[] = "previousVersion"; 53 const char kInstallPreviousVersion[] = "previousVersion";
66 const char kInvalidUrlError[] = "Invalid URL."; 54 const char kInvalidUrlError[] = "Invalid URL.";
67 const char kUpdatesDisabledError[] = "Autoupdate is not enabled.";
68 const char kUpdateFound[] = "update_available";
69 const char kUpdateNotFound[] = "no_update";
70 const char kUpdateThrottled[] = "throttled";
71 55
72 // A preference key storing the url loaded when an extension is uninstalled. 56 // A preference key storing the url loaded when an extension is uninstalled.
73 const char kUninstallUrl[] = "uninstall_url"; 57 const char kUninstallUrl[] = "uninstall_url";
74 58
75 // The name of the directory to be returned by getPackageDirectoryEntry. This 59 // The name of the directory to be returned by getPackageDirectoryEntry. This
76 // particular value does not matter to user code, but is chosen for consistency 60 // particular value does not matter to user code, but is chosen for consistency
77 // with the equivalent Pepper API. 61 // with the equivalent Pepper API.
78 const char kPackageDirectoryPath[] = "crxfs"; 62 const char kPackageDirectoryPath[] = "crxfs";
79 63
80 // If an extension reloads itself within this many miliseconds of reloading
81 // itself, the reload is considered suspiciously fast.
82 const int kFastReloadTime = 10000;
83
84 // After this many suspiciously fast consecutive reloads, an extension will get
85 // disabled.
86 const int kFastReloadCount = 5;
87
88 void DispatchOnStartupEventImpl(BrowserContext* browser_context, 64 void DispatchOnStartupEventImpl(BrowserContext* browser_context,
89 const std::string& extension_id, 65 const std::string& extension_id,
90 bool first_call, 66 bool first_call,
91 ExtensionHost* host) { 67 ExtensionHost* host) {
92 // A NULL host from the LazyBackgroundTaskQueue means the page failed to 68 // A NULL host from the LazyBackgroundTaskQueue means the page failed to
93 // load. Give up. 69 // load. Give up.
94 if (!host && !first_call) 70 if (!host && !first_call)
95 return; 71 return;
96 72
97 // Don't send onStartup events to incognito browser contexts. 73 // Don't send onStartup events to incognito browser contexts.
98 if (browser_context->IsOffTheRecord()) 74 if (browser_context->IsOffTheRecord())
99 return; 75 return;
100 76
101 if (ExtensionsBrowserClient::Get()->IsShuttingDown() || 77 if (ExtensionsBrowserClient::Get()->IsShuttingDown() ||
102 !ExtensionsBrowserClient::Get()->IsValidContext(browser_context)) 78 !ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
103 return; 79 return;
104 ExtensionSystem* system = ExtensionSystem::Get(browser_context); 80 ExtensionSystem* system = ExtensionSystem::Get(browser_context);
105 if (!system) 81 if (!system)
106 return; 82 return;
107 83
108 // If this is a persistent background page, we want to wait for it to load 84 // If this is a persistent background page, we want to wait for it to load
109 // (it might not be ready, since this is startup). But only enqueue once. 85 // (it might not be ready, since this is startup). But only enqueue once.
110 // If it fails to load the first time, don't bother trying again. 86 // If it fails to load the first time, don't bother trying again.
111 const Extension* extension = 87 const Extension* extension =
112 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID( 88 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID(
113 extension_id); 89 extension_id);
114 if (extension && BackgroundInfo::HasPersistentBackgroundPage(extension) && 90 if (extension && BackgroundInfo::HasPersistentBackgroundPage(extension) &&
115 first_call && 91 first_call &&
116 system->lazy_background_task_queue()-> 92 system->lazy_background_task_queue()->ShouldEnqueueTask(browser_context,
117 ShouldEnqueueTask(browser_context, extension)) { 93 extension)) {
118 system->lazy_background_task_queue()->AddPendingTask( 94 system->lazy_background_task_queue()->AddPendingTask(
119 browser_context, extension_id, 95 browser_context,
120 base::Bind(&DispatchOnStartupEventImpl, 96 extension_id,
121 browser_context, extension_id, false)); 97 base::Bind(
98 &DispatchOnStartupEventImpl, browser_context, extension_id, false));
122 return; 99 return;
123 } 100 }
124 101
125 scoped_ptr<base::ListValue> event_args(new base::ListValue()); 102 scoped_ptr<base::ListValue> event_args(new base::ListValue());
126 scoped_ptr<Event> event(new Event(runtime::OnStartup::kEventName, 103 scoped_ptr<Event> event(
127 event_args.Pass())); 104 new Event(runtime::OnStartup::kEventName, event_args.Pass()));
128 system->event_router()->DispatchEventToExtension(extension_id, event.Pass()); 105 system->event_router()->DispatchEventToExtension(extension_id, event.Pass());
129 } 106 }
130 107
131 void SetUninstallURL(ExtensionPrefs* prefs, 108 void SetUninstallURL(ExtensionPrefs* prefs,
132 const std::string& extension_id, 109 const std::string& extension_id,
133 const std::string& url_string) { 110 const std::string& url_string) {
134 prefs->UpdateExtensionPref(extension_id, 111 prefs->UpdateExtensionPref(
135 kUninstallUrl, 112 extension_id, kUninstallUrl, new base::StringValue(url_string));
136 new base::StringValue(url_string));
137 } 113 }
138 114
139 #if defined(ENABLE_EXTENSIONS) 115 #if defined(ENABLE_EXTENSIONS)
140 std::string GetUninstallURL(ExtensionPrefs* prefs, 116 std::string GetUninstallURL(ExtensionPrefs* prefs,
141 const std::string& extension_id) { 117 const std::string& extension_id) {
142 std::string url_string; 118 std::string url_string;
143 prefs->ReadPrefAsString(extension_id, kUninstallUrl, &url_string); 119 prefs->ReadPrefAsString(extension_id, kUninstallUrl, &url_string);
144 return url_string; 120 return url_string;
145 } 121 }
146 #endif // defined(ENABLE_EXTENSIONS) 122 #endif // defined(ENABLE_EXTENSIONS)
147 123
148 } // namespace 124 } // namespace
149 125
150 /////////////////////////////////////////////////////////////////////////////// 126 ///////////////////////////////////////////////////////////////////////////////
151 127
152 static base::LazyInstance<BrowserContextKeyedAPIFactory<RuntimeAPI> > 128 static base::LazyInstance<BrowserContextKeyedAPIFactory<RuntimeAPI> >
153 g_factory = LAZY_INSTANCE_INITIALIZER; 129 g_factory = LAZY_INSTANCE_INITIALIZER;
154 130
155 // static 131 // static
156 BrowserContextKeyedAPIFactory<RuntimeAPI>* RuntimeAPI::GetFactoryInstance() { 132 BrowserContextKeyedAPIFactory<RuntimeAPI>* RuntimeAPI::GetFactoryInstance() {
157 return g_factory.Pointer(); 133 return g_factory.Pointer();
158 } 134 }
159 135
136 RuntimeAPI::UpdateCheckResult::UpdateCheckResult(bool success,
137 const std::string& response,
138 const std::string& version)
139 : success(success), response(response), version(version) {
140 }
141
160 RuntimeAPI::RuntimeAPI(content::BrowserContext* context) 142 RuntimeAPI::RuntimeAPI(content::BrowserContext* context)
161 : browser_context_(context), 143 : browser_context_(context), dispatch_chrome_updated_event_(false) {
162 dispatch_chrome_updated_event_(false), 144 registrar_.Add(this,
163 registered_for_updates_(false) { 145 chrome::NOTIFICATION_EXTENSIONS_READY,
164 registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
165 content::Source<BrowserContext>(context)); 146 content::Source<BrowserContext>(context));
166 registrar_.Add(this, 147 registrar_.Add(this,
167 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, 148 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
168 content::Source<BrowserContext>(context)); 149 content::Source<BrowserContext>(context));
169 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED, 150 registrar_.Add(this,
151 chrome::NOTIFICATION_EXTENSION_INSTALLED,
170 content::Source<BrowserContext>(context)); 152 content::Source<BrowserContext>(context));
171 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, 153 registrar_.Add(this,
154 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
172 content::Source<BrowserContext>(context)); 155 content::Source<BrowserContext>(context));
173 156
157 delegate_ = ExtensionsBrowserClient::Get()->CreateRuntimeAPIDelegate(
158 browser_context_);
159
174 // Check if registered events are up-to-date. We can only do this once 160 // Check if registered events are up-to-date. We can only do this once
175 // per browser context, since it updates internal state when called. 161 // per browser context, since it updates internal state when called.
176 dispatch_chrome_updated_event_ = 162 dispatch_chrome_updated_event_ =
177 ExtensionsBrowserClient::Get()->DidVersionUpdate(browser_context_); 163 ExtensionsBrowserClient::Get()->DidVersionUpdate(browser_context_);
178 } 164 }
179 165
180 RuntimeAPI::~RuntimeAPI() { 166 RuntimeAPI::~RuntimeAPI() {
181 if (registered_for_updates_) { 167 delegate_->UnregisterUpdateObserver(this);
182 ExtensionSystem::Get(browser_context_)->
183 extension_service()->RemoveUpdateObserver(this);
184 }
185 } 168 }
186 169
187 void RuntimeAPI::Observe(int type, 170 void RuntimeAPI::Observe(int type,
188 const content::NotificationSource& source, 171 const content::NotificationSource& source,
189 const content::NotificationDetails& details) { 172 const content::NotificationDetails& details) {
190 switch (type) { 173 switch (type) {
191 case chrome::NOTIFICATION_EXTENSIONS_READY: { 174 case chrome::NOTIFICATION_EXTENSIONS_READY: {
192 OnExtensionsReady(); 175 OnExtensionsReady();
193 break; 176 break;
194 } 177 }
(...skipping 18 matching lines...) Expand all
213 default: 196 default:
214 NOTREACHED(); 197 NOTREACHED();
215 break; 198 break;
216 } 199 }
217 } 200 }
218 201
219 void RuntimeAPI::OnExtensionsReady() { 202 void RuntimeAPI::OnExtensionsReady() {
220 // We're done restarting Chrome after an update. 203 // We're done restarting Chrome after an update.
221 dispatch_chrome_updated_event_ = false; 204 dispatch_chrome_updated_event_ = false;
222 205
223 registered_for_updates_ = true; 206 delegate_->RegisterUpdateObserver(this);
224
225 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
226 extension_system->extension_service()->AddUpdateObserver(this);
227 207
228 // RuntimeAPI is redirected in incognito, so |browser_context_| is never 208 // RuntimeAPI is redirected in incognito, so |browser_context_| is never
229 // incognito. We don't observe incognito ProcessManagers but that is OK 209 // incognito. We don't observe incognito ProcessManagers but that is OK
230 // because we don't send onStartup events to incognito browser contexts. 210 // because we don't send onStartup events to incognito browser contexts.
231 DCHECK(!browser_context_->IsOffTheRecord()); 211 DCHECK(!browser_context_->IsOffTheRecord());
232 // Some tests use partially constructed Profiles without a process manager. 212 // Some tests use partially constructed Profiles without a process manager.
213 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
233 if (extension_system->process_manager()) 214 if (extension_system->process_manager())
234 extension_system->process_manager()->AddObserver(this); 215 extension_system->process_manager()->AddObserver(this);
235 } 216 }
236 217
237 void RuntimeAPI::OnExtensionLoaded(const Extension* extension) { 218 void RuntimeAPI::OnExtensionLoaded(const Extension* extension) {
238 if (!dispatch_chrome_updated_event_) 219 if (!dispatch_chrome_updated_event_)
239 return; 220 return;
240 221
241 // Dispatch the onInstalled event with reason "chrome_update". 222 // Dispatch the onInstalled event with reason "chrome_update".
242 base::MessageLoop::current()->PostTask( 223 base::MessageLoop::current()->PostTask(
243 FROM_HERE, 224 FROM_HERE,
244 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, 225 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent,
245 browser_context_, 226 browser_context_,
246 extension->id(), 227 extension->id(),
247 Version(), 228 Version(),
248 true)); 229 true));
249 } 230 }
250 231
251 void RuntimeAPI::OnExtensionInstalled(const Extension* extension) { 232 void RuntimeAPI::OnExtensionInstalled(const Extension* extension) {
252 // Ephemeral apps are not considered to be installed and do not receive 233 // Ephemeral apps are not considered to be installed and do not receive
253 // the onInstalled() event. 234 // the onInstalled() event.
254 if (extension->is_ephemeral()) 235 if (extension->is_ephemeral())
255 return; 236 return;
256 237
257 // Get the previous version to check if this is an upgrade. 238 Version old_version = delegate_->GetOldExtensionVersion(extension);
258 ExtensionService* service = ExtensionSystem::Get(
259 browser_context_)->extension_service();
260 const Extension* old = service->GetExtensionById(extension->id(), true);
261 Version old_version;
262 if (old)
263 old_version = *old->version();
264 239
265 // Dispatch the onInstalled event. 240 // Dispatch the onInstalled event.
266 base::MessageLoop::current()->PostTask( 241 base::MessageLoop::current()->PostTask(
267 FROM_HERE, 242 FROM_HERE,
268 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, 243 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent,
269 browser_context_, 244 browser_context_,
270 extension->id(), 245 extension->id(),
271 old_version, 246 old_version,
272 false)); 247 false));
273
274 } 248 }
275 249
276 void RuntimeAPI::OnExtensionUninstalled(const Extension* extension) { 250 void RuntimeAPI::OnExtensionUninstalled(const Extension* extension) {
277 // Ephemeral apps are not considered to be installed, so the uninstall URL 251 // Ephemeral apps are not considered to be installed, so the uninstall URL
278 // is not invoked when they are removed. 252 // is not invoked when they are removed.
279 if (extension->is_ephemeral()) 253 if (extension->is_ephemeral())
280 return; 254 return;
281 255
282 Profile* profile = Profile::FromBrowserContext(browser_context_); 256 RuntimeEventRouter::OnExtensionUninstalled(browser_context_, extension->id());
283 RuntimeEventRouter::OnExtensionUninstalled(profile, extension->id());
284 } 257 }
285 258
286 void RuntimeAPI::Shutdown() { 259 void RuntimeAPI::Shutdown() {
287 // ExtensionSystem deletes its ProcessManager during the Shutdown() phase, so 260 // ExtensionSystem deletes its ProcessManager during the Shutdown() phase, so
288 // the observer must be removed here and not in the RuntimeAPI destructor. 261 // the observer must be removed here and not in the RuntimeAPI destructor.
289 ProcessManager* process_manager = 262 ProcessManager* process_manager =
290 ExtensionSystem::Get(browser_context_)->process_manager(); 263 ExtensionSystem::Get(browser_context_)->process_manager();
291 // Some tests use partially constructed Profiles without a process manager. 264 // Some tests use partially constructed Profiles without a process manager.
292 if (process_manager) 265 if (process_manager)
293 process_manager->RemoveObserver(this); 266 process_manager->RemoveObserver(this);
294 } 267 }
295 268
296 void RuntimeAPI::OnAppUpdateAvailable(const Extension* extension) { 269 void RuntimeAPI::OnAppUpdateAvailable(const Extension* extension) {
297 Profile* profile = Profile::FromBrowserContext(browser_context_);
298 RuntimeEventRouter::DispatchOnUpdateAvailableEvent( 270 RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
299 profile, extension->id(), extension->manifest()->value()); 271 browser_context_, extension->id(), extension->manifest()->value());
300 } 272 }
301 273
302 void RuntimeAPI::OnChromeUpdateAvailable() { 274 void RuntimeAPI::OnChromeUpdateAvailable() {
303 Profile* profile = Profile::FromBrowserContext(browser_context_); 275 RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(browser_context_);
304 RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(profile);
305 } 276 }
306 277
307 void RuntimeAPI::OnBackgroundHostStartup(const Extension* extension) { 278 void RuntimeAPI::OnBackgroundHostStartup(const Extension* extension) {
308 RuntimeEventRouter::DispatchOnStartupEvent(browser_context_, extension->id()); 279 RuntimeEventRouter::DispatchOnStartupEvent(browser_context_, extension->id());
309 } 280 }
310 281
311 void RuntimeAPI::MaybeReloadExtension(const std::string& extension_id) { 282 void RuntimeAPI::MaybeReloadExtension(const std::string& extension_id) {
312 std::pair<base::TimeTicks, int>& reload_info = 283 delegate_->MaybeReloadExtension(extension_id);
313 last_reload_time_[extension_id]; 284 }
314 base::TimeTicks now = base::TimeTicks::Now();
315 if (reload_info.first.is_null() ||
316 (now - reload_info.first).InMilliseconds() > kFastReloadTime) {
317 reload_info.second = 0;
318 } else {
319 reload_info.second++;
320 }
321 if (!reload_info.first.is_null()) {
322 UMA_HISTOGRAM_LONG_TIMES("Extensions.RuntimeReloadTime",
323 now - reload_info.first);
324 }
325 UMA_HISTOGRAM_COUNTS_100("Extensions.RuntimeReloadFastCount",
326 reload_info.second);
327 reload_info.first = now;
328 285
329 ExtensionService* service = 286 void RuntimeAPI::RequestUpdateCheck(const std::string& extension_id,
330 ExtensionSystem::Get(browser_context_)->extension_service(); 287 const UpdateCheckCallback& callback) {
331 if (reload_info.second >= kFastReloadCount) { 288 delegate_->RequestUpdateCheck(extension_id, callback);
332 // Unloading an extension clears all warnings, so first terminate the 289 }
333 // extension, and then add the warning. Since this is called from an 290
334 // extension function unloading the extension has to be done 291 void RuntimeAPI::HandleUninstall(const std::string& extension_id,
335 // asynchronously. Fortunately PostTask guarentees FIFO order so just 292 const GURL& update_url) {
336 // post both tasks. 293 delegate_->HandleUninstall(extension_id, update_url);
337 base::MessageLoop::current()->PostTask( 294 }
338 FROM_HERE, 295
339 base::Bind(&ExtensionService::TerminateExtension, 296 bool RuntimeAPI::GetPlatformInfo(GetPlatformInfo::Results::PlatformInfo* info) {
340 service->AsWeakPtr(), 297 return delegate_->GetPlatformInfo(info);
341 extension_id)); 298 }
342 ExtensionWarningSet warnings; 299
343 warnings.insert( 300 bool RuntimeAPI::RequestRestart(std::string* error_message) {
344 ExtensionWarning::CreateReloadTooFrequentWarning(extension_id)); 301 return delegate_->RequestRestart(error_message);
345 base::MessageLoop::current()->PostTask(
346 FROM_HERE,
347 base::Bind(&ExtensionWarningService::NotifyWarningsOnUI,
348 browser_context_,
349 warnings));
350 } else {
351 // We can't call ReloadExtension directly, since when this method finishes
352 // it tries to decrease the reference count for the extension, which fails
353 // if the extension has already been reloaded; so instead we post a task.
354 base::MessageLoop::current()->PostTask(
355 FROM_HERE,
356 base::Bind(&ExtensionService::ReloadExtension,
357 service->AsWeakPtr(),
358 extension_id));
359 }
360 } 302 }
361 303
362 /////////////////////////////////////////////////////////////////////////////// 304 ///////////////////////////////////////////////////////////////////////////////
363 305
364 // static 306 // static
365 void RuntimeEventRouter::DispatchOnStartupEvent( 307 void RuntimeEventRouter::DispatchOnStartupEvent(
366 content::BrowserContext* context, const std::string& extension_id) { 308 content::BrowserContext* context,
309 const std::string& extension_id) {
367 DispatchOnStartupEventImpl(context, extension_id, true, NULL); 310 DispatchOnStartupEventImpl(context, extension_id, true, NULL);
368 } 311 }
369 312
370 // static 313 // static
371 void RuntimeEventRouter::DispatchOnInstalledEvent( 314 void RuntimeEventRouter::DispatchOnInstalledEvent(
372 content::BrowserContext* context, 315 content::BrowserContext* context,
373 const std::string& extension_id, 316 const std::string& extension_id,
374 const Version& old_version, 317 const Version& old_version,
375 bool chrome_updated) { 318 bool chrome_updated) {
376 if (!ExtensionsBrowserClient::Get()->IsValidContext(context)) 319 if (!ExtensionsBrowserClient::Get()->IsValidContext(context))
377 return; 320 return;
378 ExtensionSystem* system = ExtensionSystem::Get(context); 321 ExtensionSystem* system = ExtensionSystem::Get(context);
379 if (!system) 322 if (!system)
380 return; 323 return;
381 324
382 scoped_ptr<base::ListValue> event_args(new base::ListValue()); 325 scoped_ptr<base::ListValue> event_args(new base::ListValue());
383 base::DictionaryValue* info = new base::DictionaryValue(); 326 base::DictionaryValue* info = new base::DictionaryValue();
384 event_args->Append(info); 327 event_args->Append(info);
385 if (old_version.IsValid()) { 328 if (old_version.IsValid()) {
386 info->SetString(kInstallReason, kInstallReasonUpdate); 329 info->SetString(kInstallReason, kInstallReasonUpdate);
387 info->SetString(kInstallPreviousVersion, old_version.GetString()); 330 info->SetString(kInstallPreviousVersion, old_version.GetString());
388 } else if (chrome_updated) { 331 } else if (chrome_updated) {
389 info->SetString(kInstallReason, kInstallReasonChromeUpdate); 332 info->SetString(kInstallReason, kInstallReasonChromeUpdate);
390 } else { 333 } else {
391 info->SetString(kInstallReason, kInstallReasonInstall); 334 info->SetString(kInstallReason, kInstallReasonInstall);
392 } 335 }
393 DCHECK(system->event_router()); 336 DCHECK(system->event_router());
394 scoped_ptr<Event> event(new Event(runtime::OnInstalled::kEventName, 337 scoped_ptr<Event> event(
395 event_args.Pass())); 338 new Event(runtime::OnInstalled::kEventName, event_args.Pass()));
396 system->event_router()->DispatchEventWithLazyListener(extension_id, 339 system->event_router()->DispatchEventWithLazyListener(extension_id,
397 event.Pass()); 340 event.Pass());
398 } 341 }
399 342
400 // static 343 // static
401 void RuntimeEventRouter::DispatchOnUpdateAvailableEvent( 344 void RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
402 Profile* profile, 345 content::BrowserContext* context,
403 const std::string& extension_id, 346 const std::string& extension_id,
404 const base::DictionaryValue* manifest) { 347 const base::DictionaryValue* manifest) {
405 ExtensionSystem* system = ExtensionSystem::Get(profile); 348 ExtensionSystem* system = ExtensionSystem::Get(context);
406 if (!system) 349 if (!system)
407 return; 350 return;
408 351
409 scoped_ptr<base::ListValue> args(new base::ListValue); 352 scoped_ptr<base::ListValue> args(new base::ListValue);
410 args->Append(manifest->DeepCopy()); 353 args->Append(manifest->DeepCopy());
411 DCHECK(system->event_router()); 354 DCHECK(system->event_router());
412 scoped_ptr<Event> event(new Event(runtime::OnUpdateAvailable::kEventName, 355 scoped_ptr<Event> event(
413 args.Pass())); 356 new Event(runtime::OnUpdateAvailable::kEventName, args.Pass()));
414 system->event_router()->DispatchEventToExtension(extension_id, event.Pass()); 357 system->event_router()->DispatchEventToExtension(extension_id, event.Pass());
415 } 358 }
416 359
417 // static 360 // static
418 void RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent( 361 void RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(
419 Profile* profile) { 362 content::BrowserContext* context) {
420 ExtensionSystem* system = ExtensionSystem::Get(profile); 363 ExtensionSystem* system = ExtensionSystem::Get(context);
421 if (!system) 364 if (!system)
422 return; 365 return;
423 366
424 scoped_ptr<base::ListValue> args(new base::ListValue); 367 scoped_ptr<base::ListValue> args(new base::ListValue);
425 DCHECK(system->event_router()); 368 DCHECK(system->event_router());
426 scoped_ptr<Event> event(new Event( 369 scoped_ptr<Event> event(
427 runtime::OnBrowserUpdateAvailable::kEventName, args.Pass())); 370 new Event(runtime::OnBrowserUpdateAvailable::kEventName, args.Pass()));
428 system->event_router()->BroadcastEvent(event.Pass()); 371 system->event_router()->BroadcastEvent(event.Pass());
429 } 372 }
430 373
431 // static 374 // static
432 void RuntimeEventRouter::DispatchOnRestartRequiredEvent( 375 void RuntimeEventRouter::DispatchOnRestartRequiredEvent(
433 Profile* profile, 376 content::BrowserContext* context,
434 const std::string& app_id, 377 const std::string& app_id,
435 api::runtime::OnRestartRequired::Reason reason) { 378 core_api::runtime::OnRestartRequired::Reason reason) {
436 ExtensionSystem* system = ExtensionSystem::Get(profile); 379 ExtensionSystem* system = ExtensionSystem::Get(context);
437 if (!system) 380 if (!system)
438 return; 381 return;
439 382
440 scoped_ptr<Event> event( 383 scoped_ptr<Event> event(
441 new Event(runtime::OnRestartRequired::kEventName, 384 new Event(runtime::OnRestartRequired::kEventName,
442 api::runtime::OnRestartRequired::Create(reason))); 385 core_api::runtime::OnRestartRequired::Create(reason)));
443 386
444 DCHECK(system->event_router()); 387 DCHECK(system->event_router());
445 system->event_router()->DispatchEventToExtension(app_id, event.Pass()); 388 system->event_router()->DispatchEventToExtension(app_id, event.Pass());
446 } 389 }
447 390
448 // static 391 // static
449 void RuntimeEventRouter::OnExtensionUninstalled( 392 void RuntimeEventRouter::OnExtensionUninstalled(
450 Profile* profile, 393 content::BrowserContext* context,
451 const std::string& extension_id) { 394 const std::string& extension_id) {
452 #if defined(ENABLE_EXTENSIONS) 395 #if defined(ENABLE_EXTENSIONS)
453 GURL uninstall_url(GetUninstallURL(ExtensionPrefs::Get(profile), 396 GURL uninstall_url(
454 extension_id)); 397 GetUninstallURL(ExtensionPrefs::Get(context), extension_id));
455 398
456 if (uninstall_url.is_empty()) 399 if (uninstall_url.is_empty())
457 return; 400 return;
458 401
459 Browser* browser = chrome::FindLastActiveWithProfile(profile, 402 RuntimeAPI::GetFactoryInstance()->Get(context)->HandleUninstall(
460 chrome::GetActiveDesktop()); 403 extension_id, uninstall_url);
461 if (!browser)
462 browser = new Browser(Browser::CreateParams(profile,
463 chrome::GetActiveDesktop()));
464
465 chrome::NavigateParams params(browser, uninstall_url,
466 content::PAGE_TRANSITION_CLIENT_REDIRECT);
467 params.disposition = NEW_FOREGROUND_TAB;
468 params.user_gesture = false;
469 chrome::Navigate(&params);
470 #endif // defined(ENABLE_EXTENSIONS) 404 #endif // defined(ENABLE_EXTENSIONS)
471 } 405 }
472 406
473 bool RuntimeGetBackgroundPageFunction::RunAsync() { 407 bool RuntimeGetBackgroundPageFunction::RunAsync() {
474 ExtensionSystem* system = ExtensionSystem::Get(GetProfile()); 408 ExtensionSystem* system = ExtensionSystem::Get(browser_context());
475 ExtensionHost* host = system->process_manager()-> 409 ExtensionHost* host =
476 GetBackgroundHostForExtension(extension_id()); 410 system->process_manager()->GetBackgroundHostForExtension(extension_id());
477 if (system->lazy_background_task_queue()->ShouldEnqueueTask(GetProfile(), 411 if (system->lazy_background_task_queue()->ShouldEnqueueTask(browser_context(),
478 GetExtension())) { 412 GetExtension())) {
479 system->lazy_background_task_queue()->AddPendingTask( 413 system->lazy_background_task_queue()->AddPendingTask(
480 GetProfile(), 414 browser_context(),
481 extension_id(), 415 extension_id(),
482 base::Bind(&RuntimeGetBackgroundPageFunction::OnPageLoaded, this)); 416 base::Bind(&RuntimeGetBackgroundPageFunction::OnPageLoaded, this));
483 } else if (host) { 417 } else if (host) {
484 OnPageLoaded(host); 418 OnPageLoaded(host);
485 } else { 419 } else {
486 error_ = kNoBackgroundPageError; 420 error_ = kNoBackgroundPageError;
487 return false; 421 return false;
488 } 422 }
489 423
490 return true; 424 return true;
(...skipping 12 matching lines...) Expand all
503 std::string url_string; 437 std::string url_string;
504 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url_string)); 438 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url_string));
505 439
506 GURL url(url_string); 440 GURL url(url_string);
507 if (!url.is_valid()) { 441 if (!url.is_valid()) {
508 error_ = ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string); 442 error_ = ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string);
509 return false; 443 return false;
510 } 444 }
511 445
512 SetUninstallURL( 446 SetUninstallURL(
513 ExtensionPrefs::Get(GetProfile()), extension_id(), url_string); 447 ExtensionPrefs::Get(browser_context()), extension_id(), url_string);
514 return true; 448 return true;
515 } 449 }
516 450
517 bool RuntimeReloadFunction::RunSync() { 451 bool RuntimeReloadFunction::RunSync() {
518 RuntimeAPI::GetFactoryInstance()->Get(GetProfile())->MaybeReloadExtension( 452 RuntimeAPI::GetFactoryInstance()
519 extension_id()); 453 ->Get(browser_context())
454 ->MaybeReloadExtension(extension_id());
520 return true; 455 return true;
521 } 456 }
522 457
523 RuntimeRequestUpdateCheckFunction::RuntimeRequestUpdateCheckFunction() {
524 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UPDATE_FOUND,
525 content::NotificationService::AllSources());
526 }
527
528 bool RuntimeRequestUpdateCheckFunction::RunAsync() { 458 bool RuntimeRequestUpdateCheckFunction::RunAsync() {
529 ExtensionSystem* system = ExtensionSystem::Get(GetProfile()); 459 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->RequestUpdateCheck(
530 ExtensionService* service = system->extension_service(); 460 extension_id(),
531 ExtensionUpdater* updater = service->updater(); 461 base::Bind(&RuntimeRequestUpdateCheckFunction::CheckComplete, this));
532 if (!updater) {
533 error_ = kUpdatesDisabledError;
534 return false;
535 }
536
537 did_reply_ = false;
538 if (!updater->CheckExtensionSoon(extension_id(), base::Bind(
539 &RuntimeRequestUpdateCheckFunction::CheckComplete, this))) {
540 did_reply_ = true;
541 SetResult(new base::StringValue(kUpdateThrottled));
542 SendResponse(true);
543 }
544 return true; 462 return true;
545 } 463 }
546 464
547 void RuntimeRequestUpdateCheckFunction::CheckComplete() { 465 void RuntimeRequestUpdateCheckFunction::CheckComplete(
548 if (did_reply_) 466 const RuntimeAPI::UpdateCheckResult& result) {
549 return; 467 if (result.success) {
550 468 results_.reset(new base::ListValue);
551 did_reply_ = true; 469 results_->AppendString(result.response);
552 470 base::DictionaryValue* details = new base::DictionaryValue;
553 // Since no UPDATE_FOUND notification was seen, this generally would mean 471 results_->Append(details);
554 // that no update is found, but a previous update check might have already 472 details->SetString("version", result.version);
555 // queued up an update, so check for that here to make sure we return the
556 // right value.
557 ExtensionSystem* system = ExtensionSystem::Get(GetProfile());
558 ExtensionService* service = system->extension_service();
559 const Extension* update = service->GetPendingExtensionUpdate(extension_id());
560 if (update) {
561 ReplyUpdateFound(update->VersionString());
562 } else { 473 } else {
563 SetResult(new base::StringValue(kUpdateNotFound)); 474 SetResult(new base::StringValue(result.response));
564 } 475 }
565 SendResponse(true); 476 SendResponse(true);
566 } 477 }
567 478
568 void RuntimeRequestUpdateCheckFunction::Observe( 479 bool RuntimeRestartFunction::RunSync() {
569 int type, 480 std::string message;
570 const content::NotificationSource& source, 481 bool result =
571 const content::NotificationDetails& details) { 482 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->RequestRestart(
572 if (did_reply_) 483 &message);
573 return; 484 if (!result) {
574 485 SetError(message);
575 DCHECK(type == chrome::NOTIFICATION_EXTENSION_UPDATE_FOUND);
576 typedef const std::pair<std::string, Version> UpdateDetails;
577 const std::string& id = content::Details<UpdateDetails>(details)->first;
578 const Version& version = content::Details<UpdateDetails>(details)->second;
579 if (id == extension_id()) {
580 ReplyUpdateFound(version.GetString());
581 } 486 }
582 } 487 return result;
583
584 void RuntimeRequestUpdateCheckFunction::ReplyUpdateFound(
585 const std::string& version) {
586 did_reply_ = true;
587 results_.reset(new base::ListValue);
588 results_->AppendString(kUpdateFound);
589 base::DictionaryValue* details = new base::DictionaryValue;
590 results_->Append(details);
591 details->SetString("version", version);
592 SendResponse(true);
593 }
594
595 bool RuntimeRestartFunction::RunSync() {
596 #if defined(OS_CHROMEOS)
597 if (chromeos::UserManager::Get()->IsLoggedInAsKioskApp()) {
598 chromeos::DBusThreadManager::Get()
599 ->GetPowerManagerClient()
600 ->RequestRestart();
601 return true;
602 }
603 #endif
604 SetError("Function available only for ChromeOS kiosk mode.");
605 return false;
606 } 488 }
607 489
608 bool RuntimeGetPlatformInfoFunction::RunSync() { 490 bool RuntimeGetPlatformInfoFunction::RunSync() {
609 GetPlatformInfo::Results::PlatformInfo info; 491 GetPlatformInfo::Results::PlatformInfo info;
610 492 if (!RuntimeAPI::GetFactoryInstance()
611 const char* os = chrome::OmahaQueryParams::GetOS(); 493 ->Get(browser_context())
612 if (strcmp(os, "mac") == 0) { 494 ->GetPlatformInfo(&info)) {
613 info.os = GetPlatformInfo::Results::PlatformInfo::OS_MAC_;
614 } else if (strcmp(os, "win") == 0) {
615 info.os = GetPlatformInfo::Results::PlatformInfo::OS_WIN_;
616 } else if (strcmp(os, "android") == 0) {
617 info.os = GetPlatformInfo::Results::PlatformInfo::OS_ANDROID_;
618 } else if (strcmp(os, "cros") == 0) {
619 info.os = GetPlatformInfo::Results::PlatformInfo::OS_CROS_;
620 } else if (strcmp(os, "linux") == 0) {
621 info.os = GetPlatformInfo::Results::PlatformInfo::OS_LINUX_;
622 } else if (strcmp(os, "openbsd") == 0) {
623 info.os = GetPlatformInfo::Results::PlatformInfo::OS_OPENBSD_;
624 } else {
625 NOTREACHED();
626 return false; 495 return false;
627 } 496 }
628
629 const char* arch = chrome::OmahaQueryParams::GetArch();
630 if (strcmp(arch, "arm") == 0) {
631 info.arch = GetPlatformInfo::Results::PlatformInfo::ARCH_ARM;
632 } else if (strcmp(arch, "x86") == 0) {
633 info.arch = GetPlatformInfo::Results::PlatformInfo::ARCH_X86_32;
634 } else if (strcmp(arch, "x64") == 0) {
635 info.arch = GetPlatformInfo::Results::PlatformInfo::ARCH_X86_64;
636 } else {
637 NOTREACHED();
638 return false;
639 }
640
641 const char* nacl_arch = chrome::OmahaQueryParams::GetNaclArch();
642 if (strcmp(nacl_arch, "arm") == 0) {
643 info.nacl_arch = GetPlatformInfo::Results::PlatformInfo::NACL_ARCH_ARM;
644 } else if (strcmp(nacl_arch, "x86-32") == 0) {
645 info.nacl_arch = GetPlatformInfo::Results::PlatformInfo::NACL_ARCH_X86_32;
646 } else if (strcmp(nacl_arch, "x86-64") == 0) {
647 info.nacl_arch = GetPlatformInfo::Results::PlatformInfo::NACL_ARCH_X86_64;
648 } else {
649 NOTREACHED();
650 return false;
651 }
652
653 results_ = GetPlatformInfo::Results::Create(info); 497 results_ = GetPlatformInfo::Results::Create(info);
654 return true; 498 return true;
655 } 499 }
656 500
657 bool RuntimeGetPackageDirectoryEntryFunction::RunSync() { 501 bool RuntimeGetPackageDirectoryEntryFunction::RunSync() {
658 fileapi::IsolatedContext* isolated_context = 502 fileapi::IsolatedContext* isolated_context =
659 fileapi::IsolatedContext::GetInstance(); 503 fileapi::IsolatedContext::GetInstance();
660 DCHECK(isolated_context); 504 DCHECK(isolated_context);
661 505
662 std::string relative_path = kPackageDirectoryPath; 506 std::string relative_path = kPackageDirectoryPath;
663 base::FilePath path = extension_->path(); 507 base::FilePath path = extension_->path();
664 std::string filesystem_id = isolated_context->RegisterFileSystemForPath( 508 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
665 fileapi::kFileSystemTypeNativeLocal, path, &relative_path); 509 fileapi::kFileSystemTypeNativeLocal, path, &relative_path);
666 510
667 int renderer_id = render_view_host_->GetProcess()->GetID(); 511 int renderer_id = render_view_host_->GetProcess()->GetID();
668 content::ChildProcessSecurityPolicy* policy = 512 content::ChildProcessSecurityPolicy* policy =
669 content::ChildProcessSecurityPolicy::GetInstance(); 513 content::ChildProcessSecurityPolicy::GetInstance();
670 policy->GrantReadFileSystem(renderer_id, filesystem_id); 514 policy->GrantReadFileSystem(renderer_id, filesystem_id);
671 base::DictionaryValue* dict = new base::DictionaryValue(); 515 base::DictionaryValue* dict = new base::DictionaryValue();
672 SetResult(dict); 516 SetResult(dict);
673 dict->SetString("fileSystemId", filesystem_id); 517 dict->SetString("fileSystemId", filesystem_id);
674 dict->SetString("baseName", relative_path); 518 dict->SetString("baseName", relative_path);
675 return true; 519 return true;
676 } 520 }
677 521
678 } // namespace extensions 522 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698