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

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, renames 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"
21 #include "extensions/browser/api/runtime/runtime_api_delegate.h"
30 #include "extensions/browser/event_router.h" 22 #include "extensions/browser/event_router.h"
31 #include "extensions/browser/extension_host.h" 23 #include "extensions/browser/extension_host.h"
24 #include "extensions/browser/extension_prefs.h"
32 #include "extensions/browser/extension_registry.h" 25 #include "extensions/browser/extension_registry.h"
33 #include "extensions/browser/extension_system.h" 26 #include "extensions/browser/extension_system.h"
34 #include "extensions/browser/extensions_browser_client.h" 27 #include "extensions/browser/extensions_browser_client.h"
35 #include "extensions/browser/lazy_background_task_queue.h" 28 #include "extensions/browser/lazy_background_task_queue.h"
36 #include "extensions/browser/process_manager.h" 29 #include "extensions/browser/process_manager.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."; 55 const char kPlatformInfoUnavailable[] = "Platform information unavailable.";
68 const char kUpdateFound[] = "update_available";
69 const char kUpdateNotFound[] = "no_update";
70 const char kUpdateThrottled[] = "throttled";
71 56
72 // A preference key storing the url loaded when an extension is uninstalled. 57 // A preference key storing the url loaded when an extension is uninstalled.
73 const char kUninstallUrl[] = "uninstall_url"; 58 const char kUninstallUrl[] = "uninstall_url";
74 59
75 // The name of the directory to be returned by getPackageDirectoryEntry. This 60 // 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 61 // particular value does not matter to user code, but is chosen for consistency
77 // with the equivalent Pepper API. 62 // with the equivalent Pepper API.
78 const char kPackageDirectoryPath[] = "crxfs"; 63 const char kPackageDirectoryPath[] = "crxfs";
79 64
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, 65 void DispatchOnStartupEventImpl(BrowserContext* browser_context,
89 const std::string& extension_id, 66 const std::string& extension_id,
90 bool first_call, 67 bool first_call,
91 ExtensionHost* host) { 68 ExtensionHost* host) {
92 // A NULL host from the LazyBackgroundTaskQueue means the page failed to 69 // A NULL host from the LazyBackgroundTaskQueue means the page failed to
93 // load. Give up. 70 // load. Give up.
94 if (!host && !first_call) 71 if (!host && !first_call)
95 return; 72 return;
96 73
97 // Don't send onStartup events to incognito browser contexts. 74 // Don't send onStartup events to incognito browser contexts.
98 if (browser_context->IsOffTheRecord()) 75 if (browser_context->IsOffTheRecord())
99 return; 76 return;
100 77
101 if (ExtensionsBrowserClient::Get()->IsShuttingDown() || 78 if (ExtensionsBrowserClient::Get()->IsShuttingDown() ||
102 !ExtensionsBrowserClient::Get()->IsValidContext(browser_context)) 79 !ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
103 return; 80 return;
104 ExtensionSystem* system = ExtensionSystem::Get(browser_context); 81 ExtensionSystem* system = ExtensionSystem::Get(browser_context);
105 if (!system) 82 if (!system)
106 return; 83 return;
107 84
108 // If this is a persistent background page, we want to wait for it to load 85 // 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. 86 // (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. 87 // If it fails to load the first time, don't bother trying again.
111 const Extension* extension = 88 const Extension* extension =
112 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID( 89 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID(
113 extension_id); 90 extension_id);
114 if (extension && BackgroundInfo::HasPersistentBackgroundPage(extension) && 91 if (extension && BackgroundInfo::HasPersistentBackgroundPage(extension) &&
115 first_call && 92 first_call &&
116 system->lazy_background_task_queue()-> 93 system->lazy_background_task_queue()->ShouldEnqueueTask(browser_context,
117 ShouldEnqueueTask(browser_context, extension)) { 94 extension)) {
118 system->lazy_background_task_queue()->AddPendingTask( 95 system->lazy_background_task_queue()->AddPendingTask(
119 browser_context, extension_id, 96 browser_context,
120 base::Bind(&DispatchOnStartupEventImpl, 97 extension_id,
121 browser_context, extension_id, false)); 98 base::Bind(
99 &DispatchOnStartupEventImpl, browser_context, extension_id, false));
122 return; 100 return;
123 } 101 }
124 102
125 scoped_ptr<base::ListValue> event_args(new base::ListValue()); 103 scoped_ptr<base::ListValue> event_args(new base::ListValue());
126 scoped_ptr<Event> event(new Event(runtime::OnStartup::kEventName, 104 scoped_ptr<Event> event(
127 event_args.Pass())); 105 new Event(runtime::OnStartup::kEventName, event_args.Pass()));
128 system->event_router()->DispatchEventToExtension(extension_id, event.Pass()); 106 system->event_router()->DispatchEventToExtension(extension_id, event.Pass());
129 } 107 }
130 108
131 void SetUninstallURL(ExtensionPrefs* prefs, 109 void SetUninstallURL(ExtensionPrefs* prefs,
132 const std::string& extension_id, 110 const std::string& extension_id,
133 const std::string& url_string) { 111 const std::string& url_string) {
134 prefs->UpdateExtensionPref(extension_id, 112 prefs->UpdateExtensionPref(
135 kUninstallUrl, 113 extension_id, kUninstallUrl, new base::StringValue(url_string));
136 new base::StringValue(url_string));
137 } 114 }
138 115
139 #if defined(ENABLE_EXTENSIONS) 116 #if defined(ENABLE_EXTENSIONS)
140 std::string GetUninstallURL(ExtensionPrefs* prefs, 117 std::string GetUninstallURL(ExtensionPrefs* prefs,
141 const std::string& extension_id) { 118 const std::string& extension_id) {
142 std::string url_string; 119 std::string url_string;
143 prefs->ReadPrefAsString(extension_id, kUninstallUrl, &url_string); 120 prefs->ReadPrefAsString(extension_id, kUninstallUrl, &url_string);
144 return url_string; 121 return url_string;
145 } 122 }
146 #endif // defined(ENABLE_EXTENSIONS) 123 #endif // defined(ENABLE_EXTENSIONS)
147 124
148 } // namespace 125 } // namespace
149 126
150 /////////////////////////////////////////////////////////////////////////////// 127 ///////////////////////////////////////////////////////////////////////////////
151 128
152 static base::LazyInstance<BrowserContextKeyedAPIFactory<RuntimeAPI> > 129 static base::LazyInstance<BrowserContextKeyedAPIFactory<RuntimeAPI> >
153 g_factory = LAZY_INSTANCE_INITIALIZER; 130 g_factory = LAZY_INSTANCE_INITIALIZER;
154 131
155 // static 132 // static
156 BrowserContextKeyedAPIFactory<RuntimeAPI>* RuntimeAPI::GetFactoryInstance() { 133 BrowserContextKeyedAPIFactory<RuntimeAPI>* RuntimeAPI::GetFactoryInstance() {
157 return g_factory.Pointer(); 134 return g_factory.Pointer();
158 } 135 }
159 136
160 RuntimeAPI::RuntimeAPI(content::BrowserContext* context) 137 RuntimeAPI::RuntimeAPI(content::BrowserContext* context)
161 : browser_context_(context), 138 : browser_context_(context), dispatch_chrome_updated_event_(false) {
162 dispatch_chrome_updated_event_(false), 139 registrar_.Add(this,
163 registered_for_updates_(false) { 140 chrome::NOTIFICATION_EXTENSIONS_READY,
164 registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
165 content::Source<BrowserContext>(context)); 141 content::Source<BrowserContext>(context));
166 registrar_.Add(this, 142 registrar_.Add(this,
167 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, 143 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
168 content::Source<BrowserContext>(context)); 144 content::Source<BrowserContext>(context));
169 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED, 145 registrar_.Add(this,
146 chrome::NOTIFICATION_EXTENSION_INSTALLED,
170 content::Source<BrowserContext>(context)); 147 content::Source<BrowserContext>(context));
171 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, 148 registrar_.Add(this,
149 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
172 content::Source<BrowserContext>(context)); 150 content::Source<BrowserContext>(context));
173 151
152 delegate_ = ExtensionsBrowserClient::Get()->CreateRuntimeAPIDelegate(
153 browser_context_);
154
174 // Check if registered events are up-to-date. We can only do this once 155 // 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. 156 // per browser context, since it updates internal state when called.
176 dispatch_chrome_updated_event_ = 157 dispatch_chrome_updated_event_ =
177 ExtensionsBrowserClient::Get()->DidVersionUpdate(browser_context_); 158 ExtensionsBrowserClient::Get()->DidVersionUpdate(browser_context_);
178 } 159 }
179 160
180 RuntimeAPI::~RuntimeAPI() { 161 RuntimeAPI::~RuntimeAPI() {
181 if (registered_for_updates_) { 162 delegate_->RemoveUpdateObserver(this);
182 ExtensionSystem::Get(browser_context_)->
183 extension_service()->RemoveUpdateObserver(this);
184 }
185 } 163 }
186 164
187 void RuntimeAPI::Observe(int type, 165 void RuntimeAPI::Observe(int type,
188 const content::NotificationSource& source, 166 const content::NotificationSource& source,
189 const content::NotificationDetails& details) { 167 const content::NotificationDetails& details) {
190 switch (type) { 168 switch (type) {
191 case chrome::NOTIFICATION_EXTENSIONS_READY: { 169 case chrome::NOTIFICATION_EXTENSIONS_READY: {
192 OnExtensionsReady(); 170 OnExtensionsReady();
193 break; 171 break;
194 } 172 }
(...skipping 18 matching lines...) Expand all
213 default: 191 default:
214 NOTREACHED(); 192 NOTREACHED();
215 break; 193 break;
216 } 194 }
217 } 195 }
218 196
219 void RuntimeAPI::OnExtensionsReady() { 197 void RuntimeAPI::OnExtensionsReady() {
220 // We're done restarting Chrome after an update. 198 // We're done restarting Chrome after an update.
221 dispatch_chrome_updated_event_ = false; 199 dispatch_chrome_updated_event_ = false;
222 200
223 registered_for_updates_ = true; 201 delegate_->AddUpdateObserver(this);
224
225 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
226 extension_system->extension_service()->AddUpdateObserver(this);
227 202
228 // RuntimeAPI is redirected in incognito, so |browser_context_| is never 203 // RuntimeAPI is redirected in incognito, so |browser_context_| is never
229 // incognito. We don't observe incognito ProcessManagers but that is OK 204 // incognito. We don't observe incognito ProcessManagers but that is OK
230 // because we don't send onStartup events to incognito browser contexts. 205 // because we don't send onStartup events to incognito browser contexts.
231 DCHECK(!browser_context_->IsOffTheRecord()); 206 DCHECK(!browser_context_->IsOffTheRecord());
232 // Some tests use partially constructed Profiles without a process manager. 207 // Some tests use partially constructed Profiles without a process manager.
208 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
233 if (extension_system->process_manager()) 209 if (extension_system->process_manager())
234 extension_system->process_manager()->AddObserver(this); 210 extension_system->process_manager()->AddObserver(this);
235 } 211 }
236 212
237 void RuntimeAPI::OnExtensionLoaded(const Extension* extension) { 213 void RuntimeAPI::OnExtensionLoaded(const Extension* extension) {
238 if (!dispatch_chrome_updated_event_) 214 if (!dispatch_chrome_updated_event_)
239 return; 215 return;
240 216
241 // Dispatch the onInstalled event with reason "chrome_update". 217 // Dispatch the onInstalled event with reason "chrome_update".
242 base::MessageLoop::current()->PostTask( 218 base::MessageLoop::current()->PostTask(
243 FROM_HERE, 219 FROM_HERE,
244 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, 220 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent,
245 browser_context_, 221 browser_context_,
246 extension->id(), 222 extension->id(),
247 Version(), 223 Version(),
248 true)); 224 true));
249 } 225 }
250 226
251 void RuntimeAPI::OnExtensionInstalled(const Extension* extension) { 227 void RuntimeAPI::OnExtensionInstalled(const Extension* extension) {
252 // Ephemeral apps are not considered to be installed and do not receive 228 // Ephemeral apps are not considered to be installed and do not receive
253 // the onInstalled() event. 229 // the onInstalled() event.
254 if (extension->is_ephemeral()) 230 if (extension->is_ephemeral())
255 return; 231 return;
256 232
257 // Get the previous version to check if this is an upgrade. 233 Version old_version = delegate_->GetPreviousExtensionVersion(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 234
265 // Dispatch the onInstalled event. 235 // Dispatch the onInstalled event.
266 base::MessageLoop::current()->PostTask( 236 base::MessageLoop::current()->PostTask(
267 FROM_HERE, 237 FROM_HERE,
268 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, 238 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent,
269 browser_context_, 239 browser_context_,
270 extension->id(), 240 extension->id(),
271 old_version, 241 old_version,
272 false)); 242 false));
273
274 } 243 }
275 244
276 void RuntimeAPI::OnExtensionUninstalled(const Extension* extension) { 245 void RuntimeAPI::OnExtensionUninstalled(const Extension* extension) {
277 // Ephemeral apps are not considered to be installed, so the uninstall URL 246 // Ephemeral apps are not considered to be installed, so the uninstall URL
278 // is not invoked when they are removed. 247 // is not invoked when they are removed.
279 if (extension->is_ephemeral()) 248 if (extension->is_ephemeral())
280 return; 249 return;
281 250
282 Profile* profile = Profile::FromBrowserContext(browser_context_); 251 RuntimeEventRouter::OnExtensionUninstalled(browser_context_, extension->id());
283 RuntimeEventRouter::OnExtensionUninstalled(profile, extension->id());
284 } 252 }
285 253
286 void RuntimeAPI::Shutdown() { 254 void RuntimeAPI::Shutdown() {
287 // ExtensionSystem deletes its ProcessManager during the Shutdown() phase, so 255 // ExtensionSystem deletes its ProcessManager during the Shutdown() phase, so
288 // the observer must be removed here and not in the RuntimeAPI destructor. 256 // the observer must be removed here and not in the RuntimeAPI destructor.
289 ProcessManager* process_manager = 257 ProcessManager* process_manager =
290 ExtensionSystem::Get(browser_context_)->process_manager(); 258 ExtensionSystem::Get(browser_context_)->process_manager();
291 // Some tests use partially constructed Profiles without a process manager. 259 // Some tests use partially constructed Profiles without a process manager.
292 if (process_manager) 260 if (process_manager)
293 process_manager->RemoveObserver(this); 261 process_manager->RemoveObserver(this);
294 } 262 }
295 263
296 void RuntimeAPI::OnAppUpdateAvailable(const Extension* extension) { 264 void RuntimeAPI::OnAppUpdateAvailable(const Extension* extension) {
297 Profile* profile = Profile::FromBrowserContext(browser_context_);
298 RuntimeEventRouter::DispatchOnUpdateAvailableEvent( 265 RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
299 profile, extension->id(), extension->manifest()->value()); 266 browser_context_, extension->id(), extension->manifest()->value());
300 } 267 }
301 268
302 void RuntimeAPI::OnChromeUpdateAvailable() { 269 void RuntimeAPI::OnChromeUpdateAvailable() {
303 Profile* profile = Profile::FromBrowserContext(browser_context_); 270 RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(browser_context_);
304 RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(profile);
305 } 271 }
306 272
307 void RuntimeAPI::OnBackgroundHostStartup(const Extension* extension) { 273 void RuntimeAPI::OnBackgroundHostStartup(const Extension* extension) {
308 RuntimeEventRouter::DispatchOnStartupEvent(browser_context_, extension->id()); 274 RuntimeEventRouter::DispatchOnStartupEvent(browser_context_, extension->id());
309 } 275 }
310 276
311 void RuntimeAPI::MaybeReloadExtension(const std::string& extension_id) { 277 void RuntimeAPI::ReloadExtension(const std::string& extension_id) {
312 std::pair<base::TimeTicks, int>& reload_info = 278 delegate_->ReloadExtension(extension_id);
313 last_reload_time_[extension_id]; 279 }
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 280
329 ExtensionService* service = 281 void RuntimeAPI::CheckForUpdates(
330 ExtensionSystem::Get(browser_context_)->extension_service(); 282 const std::string& extension_id,
331 if (reload_info.second >= kFastReloadCount) { 283 const RuntimeAPIDelegate::UpdateCheckCallback& callback) {
332 // Unloading an extension clears all warnings, so first terminate the 284 delegate_->CheckForUpdates(extension_id, callback);
333 // extension, and then add the warning. Since this is called from an 285 }
334 // extension function unloading the extension has to be done 286
335 // asynchronously. Fortunately PostTask guarentees FIFO order so just 287 void RuntimeAPI::OpenURL(const GURL& update_url) {
336 // post both tasks. 288 delegate_->OpenURL(update_url);
337 base::MessageLoop::current()->PostTask( 289 }
338 FROM_HERE, 290
339 base::Bind(&ExtensionService::TerminateExtension, 291 bool RuntimeAPI::GetPlatformInfo(GetPlatformInfo::Results::PlatformInfo* info) {
340 service->AsWeakPtr(), 292 return delegate_->GetPlatformInfo(info);
341 extension_id)); 293 }
342 ExtensionWarningSet warnings; 294
343 warnings.insert( 295 bool RuntimeAPI::RestartDevice(std::string* error_message) {
344 ExtensionWarning::CreateReloadTooFrequentWarning(extension_id)); 296 return delegate_->RestartDevice(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 } 297 }
361 298
362 /////////////////////////////////////////////////////////////////////////////// 299 ///////////////////////////////////////////////////////////////////////////////
363 300
364 // static 301 // static
365 void RuntimeEventRouter::DispatchOnStartupEvent( 302 void RuntimeEventRouter::DispatchOnStartupEvent(
366 content::BrowserContext* context, const std::string& extension_id) { 303 content::BrowserContext* context,
304 const std::string& extension_id) {
367 DispatchOnStartupEventImpl(context, extension_id, true, NULL); 305 DispatchOnStartupEventImpl(context, extension_id, true, NULL);
368 } 306 }
369 307
370 // static 308 // static
371 void RuntimeEventRouter::DispatchOnInstalledEvent( 309 void RuntimeEventRouter::DispatchOnInstalledEvent(
372 content::BrowserContext* context, 310 content::BrowserContext* context,
373 const std::string& extension_id, 311 const std::string& extension_id,
374 const Version& old_version, 312 const Version& old_version,
375 bool chrome_updated) { 313 bool chrome_updated) {
376 if (!ExtensionsBrowserClient::Get()->IsValidContext(context)) 314 if (!ExtensionsBrowserClient::Get()->IsValidContext(context))
377 return; 315 return;
378 ExtensionSystem* system = ExtensionSystem::Get(context); 316 ExtensionSystem* system = ExtensionSystem::Get(context);
379 if (!system) 317 if (!system)
380 return; 318 return;
381 319
382 scoped_ptr<base::ListValue> event_args(new base::ListValue()); 320 scoped_ptr<base::ListValue> event_args(new base::ListValue());
383 base::DictionaryValue* info = new base::DictionaryValue(); 321 base::DictionaryValue* info = new base::DictionaryValue();
384 event_args->Append(info); 322 event_args->Append(info);
385 if (old_version.IsValid()) { 323 if (old_version.IsValid()) {
386 info->SetString(kInstallReason, kInstallReasonUpdate); 324 info->SetString(kInstallReason, kInstallReasonUpdate);
387 info->SetString(kInstallPreviousVersion, old_version.GetString()); 325 info->SetString(kInstallPreviousVersion, old_version.GetString());
388 } else if (chrome_updated) { 326 } else if (chrome_updated) {
389 info->SetString(kInstallReason, kInstallReasonChromeUpdate); 327 info->SetString(kInstallReason, kInstallReasonChromeUpdate);
390 } else { 328 } else {
391 info->SetString(kInstallReason, kInstallReasonInstall); 329 info->SetString(kInstallReason, kInstallReasonInstall);
392 } 330 }
393 DCHECK(system->event_router()); 331 DCHECK(system->event_router());
394 scoped_ptr<Event> event(new Event(runtime::OnInstalled::kEventName, 332 scoped_ptr<Event> event(
395 event_args.Pass())); 333 new Event(runtime::OnInstalled::kEventName, event_args.Pass()));
396 system->event_router()->DispatchEventWithLazyListener(extension_id, 334 system->event_router()->DispatchEventWithLazyListener(extension_id,
397 event.Pass()); 335 event.Pass());
398 } 336 }
399 337
400 // static 338 // static
401 void RuntimeEventRouter::DispatchOnUpdateAvailableEvent( 339 void RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
402 Profile* profile, 340 content::BrowserContext* context,
403 const std::string& extension_id, 341 const std::string& extension_id,
404 const base::DictionaryValue* manifest) { 342 const base::DictionaryValue* manifest) {
405 ExtensionSystem* system = ExtensionSystem::Get(profile); 343 ExtensionSystem* system = ExtensionSystem::Get(context);
406 if (!system) 344 if (!system)
407 return; 345 return;
408 346
409 scoped_ptr<base::ListValue> args(new base::ListValue); 347 scoped_ptr<base::ListValue> args(new base::ListValue);
410 args->Append(manifest->DeepCopy()); 348 args->Append(manifest->DeepCopy());
411 DCHECK(system->event_router()); 349 DCHECK(system->event_router());
412 scoped_ptr<Event> event(new Event(runtime::OnUpdateAvailable::kEventName, 350 scoped_ptr<Event> event(
413 args.Pass())); 351 new Event(runtime::OnUpdateAvailable::kEventName, args.Pass()));
414 system->event_router()->DispatchEventToExtension(extension_id, event.Pass()); 352 system->event_router()->DispatchEventToExtension(extension_id, event.Pass());
415 } 353 }
416 354
417 // static 355 // static
418 void RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent( 356 void RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(
419 Profile* profile) { 357 content::BrowserContext* context) {
420 ExtensionSystem* system = ExtensionSystem::Get(profile); 358 ExtensionSystem* system = ExtensionSystem::Get(context);
421 if (!system) 359 if (!system)
422 return; 360 return;
423 361
424 scoped_ptr<base::ListValue> args(new base::ListValue); 362 scoped_ptr<base::ListValue> args(new base::ListValue);
425 DCHECK(system->event_router()); 363 DCHECK(system->event_router());
426 scoped_ptr<Event> event(new Event( 364 scoped_ptr<Event> event(
427 runtime::OnBrowserUpdateAvailable::kEventName, args.Pass())); 365 new Event(runtime::OnBrowserUpdateAvailable::kEventName, args.Pass()));
428 system->event_router()->BroadcastEvent(event.Pass()); 366 system->event_router()->BroadcastEvent(event.Pass());
429 } 367 }
430 368
431 // static 369 // static
432 void RuntimeEventRouter::DispatchOnRestartRequiredEvent( 370 void RuntimeEventRouter::DispatchOnRestartRequiredEvent(
433 Profile* profile, 371 content::BrowserContext* context,
434 const std::string& app_id, 372 const std::string& app_id,
435 api::runtime::OnRestartRequired::Reason reason) { 373 core_api::runtime::OnRestartRequired::Reason reason) {
436 ExtensionSystem* system = ExtensionSystem::Get(profile); 374 ExtensionSystem* system = ExtensionSystem::Get(context);
437 if (!system) 375 if (!system)
438 return; 376 return;
439 377
440 scoped_ptr<Event> event( 378 scoped_ptr<Event> event(
441 new Event(runtime::OnRestartRequired::kEventName, 379 new Event(runtime::OnRestartRequired::kEventName,
442 api::runtime::OnRestartRequired::Create(reason))); 380 core_api::runtime::OnRestartRequired::Create(reason)));
443 381
444 DCHECK(system->event_router()); 382 DCHECK(system->event_router());
445 system->event_router()->DispatchEventToExtension(app_id, event.Pass()); 383 system->event_router()->DispatchEventToExtension(app_id, event.Pass());
446 } 384 }
447 385
448 // static 386 // static
449 void RuntimeEventRouter::OnExtensionUninstalled( 387 void RuntimeEventRouter::OnExtensionUninstalled(
450 Profile* profile, 388 content::BrowserContext* context,
451 const std::string& extension_id) { 389 const std::string& extension_id) {
452 #if defined(ENABLE_EXTENSIONS) 390 #if defined(ENABLE_EXTENSIONS)
453 GURL uninstall_url(GetUninstallURL(ExtensionPrefs::Get(profile), 391 GURL uninstall_url(
454 extension_id)); 392 GetUninstallURL(ExtensionPrefs::Get(context), extension_id));
455 393
456 if (uninstall_url.is_empty()) 394 if (uninstall_url.is_empty())
457 return; 395 return;
458 396
459 Browser* browser = chrome::FindLastActiveWithProfile(profile, 397 RuntimeAPI::GetFactoryInstance()->Get(context)->OpenURL(uninstall_url);
460 chrome::GetActiveDesktop());
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) 398 #endif // defined(ENABLE_EXTENSIONS)
471 } 399 }
472 400
473 bool RuntimeGetBackgroundPageFunction::RunAsync() { 401 ExtensionFunction::ResponseAction RuntimeGetBackgroundPageFunction::Run() {
474 ExtensionSystem* system = ExtensionSystem::Get(GetProfile()); 402 ExtensionSystem* system = ExtensionSystem::Get(browser_context());
475 ExtensionHost* host = system->process_manager()-> 403 ExtensionHost* host =
476 GetBackgroundHostForExtension(extension_id()); 404 system->process_manager()->GetBackgroundHostForExtension(extension_id());
477 if (system->lazy_background_task_queue()->ShouldEnqueueTask(GetProfile(), 405 if (system->lazy_background_task_queue()->ShouldEnqueueTask(browser_context(),
478 GetExtension())) { 406 GetExtension())) {
479 system->lazy_background_task_queue()->AddPendingTask( 407 system->lazy_background_task_queue()->AddPendingTask(
480 GetProfile(), 408 browser_context(),
481 extension_id(), 409 extension_id(),
482 base::Bind(&RuntimeGetBackgroundPageFunction::OnPageLoaded, this)); 410 base::Bind(&RuntimeGetBackgroundPageFunction::OnPageLoaded, this));
483 } else if (host) { 411 } else if (host) {
484 OnPageLoaded(host); 412 OnPageLoaded(host);
485 } else { 413 } else {
486 error_ = kNoBackgroundPageError; 414 return RespondNow(Error(kNoBackgroundPageError));
not at google - send to devlin 2014/05/05 21:50:26 yay!
487 return false;
488 } 415 }
489 416
490 return true; 417 return RespondLater();
491 } 418 }
492 419
493 void RuntimeGetBackgroundPageFunction::OnPageLoaded(ExtensionHost* host) { 420 void RuntimeGetBackgroundPageFunction::OnPageLoaded(ExtensionHost* host) {
494 if (host) { 421 if (host) {
495 SendResponse(true); 422 Respond(NoArguments());
496 } else { 423 } else {
497 error_ = kPageLoadError; 424 Respond(Error(kPageLoadError));
498 SendResponse(false);
499 } 425 }
500 } 426 }
501 427
502 bool RuntimeSetUninstallURLFunction::RunSync() { 428 ExtensionFunction::ResponseAction RuntimeSetUninstallURLFunction::Run() {
503 std::string url_string; 429 std::string url_string;
504 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url_string)); 430 EXTENSION_FUNCTION_VALIDATE_TYPESAFE(args_->GetString(0, &url_string));
505 431
506 GURL url(url_string); 432 GURL url(url_string);
507 if (!url.is_valid()) { 433 if (!url.is_valid()) {
508 error_ = ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string); 434 return RespondNow(
509 return false; 435 Error(ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string)));
510 } 436 }
511
512 SetUninstallURL( 437 SetUninstallURL(
513 ExtensionPrefs::Get(GetProfile()), extension_id(), url_string); 438 ExtensionPrefs::Get(browser_context()), extension_id(), url_string);
514 return true; 439 return RespondNow(NoArguments());
515 } 440 }
516 441
517 bool RuntimeReloadFunction::RunSync() { 442 ExtensionFunction::ResponseAction RuntimeReloadFunction::Run() {
518 RuntimeAPI::GetFactoryInstance()->Get(GetProfile())->MaybeReloadExtension( 443 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->ReloadExtension(
519 extension_id()); 444 extension_id());
520 return true; 445 return RespondNow(NoArguments());
521 } 446 }
522 447
523 RuntimeRequestUpdateCheckFunction::RuntimeRequestUpdateCheckFunction() { 448 ExtensionFunction::ResponseAction RuntimeRequestUpdateCheckFunction::Run() {
524 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UPDATE_FOUND, 449 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->CheckForUpdates(
525 content::NotificationService::AllSources()); 450 extension_id(),
451 base::Bind(&RuntimeRequestUpdateCheckFunction::CheckComplete, this));
452 return RespondLater();
526 } 453 }
527 454
528 bool RuntimeRequestUpdateCheckFunction::RunAsync() { 455 void RuntimeRequestUpdateCheckFunction::CheckComplete(
529 ExtensionSystem* system = ExtensionSystem::Get(GetProfile()); 456 const RuntimeAPIDelegate::UpdateCheckResult& result) {
530 ExtensionService* service = system->extension_service(); 457 if (result.success) {
531 ExtensionUpdater* updater = service->updater(); 458 base::ListValue* results = new base::ListValue;
532 if (!updater) { 459 results->AppendString(result.response);
533 error_ = kUpdatesDisabledError; 460 base::DictionaryValue* details = new base::DictionaryValue;
534 return false; 461 results->Append(details);
535 } 462 details->SetString("version", result.version);
536 463 Respond(MultipleArguments(results));
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;
545 }
546
547 void RuntimeRequestUpdateCheckFunction::CheckComplete() {
548 if (did_reply_)
549 return;
550
551 did_reply_ = true;
552
553 // Since no UPDATE_FOUND notification was seen, this generally would mean
554 // that no update is found, but a previous update check might have already
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 { 464 } else {
563 SetResult(new base::StringValue(kUpdateNotFound)); 465 Respond(SingleArgument(new base::StringValue(result.response)));
564 }
565 SendResponse(true);
566 }
567
568 void RuntimeRequestUpdateCheckFunction::Observe(
569 int type,
570 const content::NotificationSource& source,
571 const content::NotificationDetails& details) {
572 if (did_reply_)
573 return;
574
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 } 466 }
582 } 467 }
583 468
584 void RuntimeRequestUpdateCheckFunction::ReplyUpdateFound( 469 ExtensionFunction::ResponseAction RuntimeRestartFunction::Run() {
585 const std::string& version) { 470 std::string message;
586 did_reply_ = true; 471 bool result =
587 results_.reset(new base::ListValue); 472 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->RestartDevice(
588 results_->AppendString(kUpdateFound); 473 &message);
589 base::DictionaryValue* details = new base::DictionaryValue; 474 if (!result) {
590 results_->Append(details); 475 return RespondNow(Error(message));
591 details->SetString("version", version); 476 }
592 SendResponse(true); 477 return RespondNow(NoArguments());
593 } 478 }
594 479
595 bool RuntimeRestartFunction::RunSync() { 480 ExtensionFunction::ResponseAction RuntimeGetPlatformInfoFunction::Run() {
596 #if defined(OS_CHROMEOS) 481 GetPlatformInfo::Results::PlatformInfo info;
597 if (chromeos::UserManager::Get()->IsLoggedInAsKioskApp()) { 482 if (!RuntimeAPI::GetFactoryInstance()
598 chromeos::DBusThreadManager::Get() 483 ->Get(browser_context())
599 ->GetPowerManagerClient() 484 ->GetPlatformInfo(&info)) {
600 ->RequestRestart(); 485 return RespondNow(Error(kPlatformInfoUnavailable));
601 return true;
602 } 486 }
603 #endif 487 return RespondNow(
604 SetError("Function available only for ChromeOS kiosk mode."); 488 MultipleArguments(GetPlatformInfo::Results::Create(info).release()));
605 return false;
606 } 489 }
607 490
608 bool RuntimeGetPlatformInfoFunction::RunSync() { 491 ExtensionFunction::ResponseAction
609 GetPlatformInfo::Results::PlatformInfo info; 492 RuntimeGetPackageDirectoryEntryFunction::Run() {
610
611 const char* os = chrome::OmahaQueryParams::GetOS();
612 if (strcmp(os, "mac") == 0) {
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;
627 }
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);
654 return true;
655 }
656
657 bool RuntimeGetPackageDirectoryEntryFunction::RunSync() {
658 fileapi::IsolatedContext* isolated_context = 493 fileapi::IsolatedContext* isolated_context =
659 fileapi::IsolatedContext::GetInstance(); 494 fileapi::IsolatedContext::GetInstance();
660 DCHECK(isolated_context); 495 DCHECK(isolated_context);
661 496
662 std::string relative_path = kPackageDirectoryPath; 497 std::string relative_path = kPackageDirectoryPath;
663 base::FilePath path = extension_->path(); 498 base::FilePath path = extension_->path();
664 std::string filesystem_id = isolated_context->RegisterFileSystemForPath( 499 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
665 fileapi::kFileSystemTypeNativeLocal, path, &relative_path); 500 fileapi::kFileSystemTypeNativeLocal, path, &relative_path);
666 501
667 int renderer_id = render_view_host_->GetProcess()->GetID(); 502 int renderer_id = render_view_host_->GetProcess()->GetID();
668 content::ChildProcessSecurityPolicy* policy = 503 content::ChildProcessSecurityPolicy* policy =
669 content::ChildProcessSecurityPolicy::GetInstance(); 504 content::ChildProcessSecurityPolicy::GetInstance();
670 policy->GrantReadFileSystem(renderer_id, filesystem_id); 505 policy->GrantReadFileSystem(renderer_id, filesystem_id);
671 base::DictionaryValue* dict = new base::DictionaryValue(); 506 base::DictionaryValue* dict = new base::DictionaryValue();
672 SetResult(dict);
673 dict->SetString("fileSystemId", filesystem_id); 507 dict->SetString("fileSystemId", filesystem_id);
674 dict->SetString("baseName", relative_path); 508 dict->SetString("baseName", relative_path);
675 return true; 509 return RespondNow(SingleArgument(dict));
676 } 510 }
677 511
678 } // namespace extensions 512 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698