desktop_notification_service.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/notifications/desktop_notification_service.h"
6
7#include "base/metrics/histogram.h"
8#include "base/strings/utf_string_conversions.h"
9#include "base/threading/thread.h"
10#include "chrome/browser/browser_process.h"
11#include "chrome/browser/chrome_notification_types.h"
12#include "chrome/browser/content_settings/content_settings_details.h"
13#include "chrome/browser/content_settings/content_settings_provider.h"
14#include "chrome/browser/content_settings/host_content_settings_map.h"
15#include "chrome/browser/extensions/extension_info_map.h"
16#include "chrome/browser/extensions/extension_service.h"
17#include "chrome/browser/extensions/extension_system.h"
18#include "chrome/browser/infobars/confirm_infobar_delegate.h"
19#include "chrome/browser/infobars/infobar_service.h"
20#include "chrome/browser/notifications/desktop_notification_service_factory.h"
21#include "chrome/browser/notifications/notification.h"
22#include "chrome/browser/notifications/notification_object_proxy.h"
23#include "chrome/browser/notifications/notification_ui_manager.h"
24#include "chrome/browser/notifications/sync_notifier/chrome_notifier_service.h"
25#include "chrome/browser/notifications/sync_notifier/chrome_notifier_service_factory.h"
26#include "chrome/browser/prefs/scoped_user_pref_update.h"
27#include "chrome/browser/profiles/profile.h"
28#include "chrome/browser/ui/browser.h"
29#include "chrome/common/content_settings.h"
30#include "chrome/common/content_settings_pattern.h"
31#include "chrome/common/pref_names.h"
32#include "chrome/common/url_constants.h"
33#include "components/user_prefs/pref_registry_syncable.h"
34#include "content/public/browser/browser_thread.h"
35#include "content/public/browser/notification_service.h"
36#include "content/public/browser/render_view_host.h"
37#include "content/public/browser/web_contents.h"
38#include "content/public/common/show_desktop_notification_params.h"
39#include "extensions/common/constants.h"
40#include "grit/browser_resources.h"
41#include "grit/chromium_strings.h"
42#include "grit/generated_resources.h"
43#include "grit/theme_resources.h"
44#include "net/base/escape.h"
45#include "ui/base/l10n/l10n_util.h"
46#include "ui/base/resource/resource_bundle.h"
47#include "ui/base/webui/web_ui_util.h"
48#include "ui/message_center/message_center_util.h"
49#include "ui/message_center/notifier_settings.h"
50
51#if defined(OS_CHROMEOS)
52#include "ash/system/system_notifier.h"
53#endif
54
55using content::BrowserThread;
56using content::RenderViewHost;
57using content::WebContents;
58using message_center::NotifierId;
59using WebKit::WebNotificationPresenter;
60using WebKit::WebTextDirection;
61
62
63// NotificationPermissionInfoBarDelegate --------------------------------------
64
65// The delegate for the infobar shown when an origin requests notification
66// permissions.
67class NotificationPermissionInfoBarDelegate : public ConfirmInfoBarDelegate {
68 public:
69  // Creates a notification permission infobar delegate and adds it to
70  // |infobar_service|.
71  static void Create(InfoBarService* infobar_service,
72                     DesktopNotificationService* notification_service,
73                     const GURL& origin,
74                     const string16& display_name,
75                     int process_id,
76                     int route_id,
77                     int callback_context);
78
79 private:
80  NotificationPermissionInfoBarDelegate(
81      InfoBarService* infobar_service,
82      DesktopNotificationService* notification_service,
83      const GURL& origin,
84      const string16& display_name,
85      int process_id,
86      int route_id,
87      int callback_context);
88  virtual ~NotificationPermissionInfoBarDelegate();
89
90  // ConfirmInfoBarDelegate:
91  virtual int GetIconID() const OVERRIDE;
92  virtual Type GetInfoBarType() const OVERRIDE;
93  virtual string16 GetMessageText() const OVERRIDE;
94  virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
95  virtual bool Accept() OVERRIDE;
96  virtual bool Cancel() OVERRIDE;
97
98  // The origin we are asking for permissions on.
99  GURL origin_;
100
101  // The display name for the origin to be displayed.  Will be different from
102  // origin_ for extensions.
103  string16 display_name_;
104
105  // The notification service to be used.
106  DesktopNotificationService* notification_service_;
107
108  // The callback information that tells us how to respond to javascript via
109  // the correct RenderView.
110  int process_id_;
111  int route_id_;
112  int callback_context_;
113
114  // Whether the user clicked one of the buttons.
115  bool action_taken_;
116
117  DISALLOW_COPY_AND_ASSIGN(NotificationPermissionInfoBarDelegate);
118};
119
120// static
121void NotificationPermissionInfoBarDelegate::Create(
122    InfoBarService* infobar_service,
123    DesktopNotificationService* notification_service,
124    const GURL& origin,
125    const string16& display_name,
126    int process_id,
127    int route_id,
128    int callback_context) {
129  infobar_service->AddInfoBar(scoped_ptr<InfoBarDelegate>(
130      new NotificationPermissionInfoBarDelegate(
131          infobar_service, notification_service, origin, display_name,
132          process_id, route_id, callback_context)));
133}
134
135NotificationPermissionInfoBarDelegate::NotificationPermissionInfoBarDelegate(
136    InfoBarService* infobar_service,
137    DesktopNotificationService* notification_service,
138    const GURL& origin,
139    const string16& display_name,
140    int process_id,
141    int route_id,
142    int callback_context)
143    : ConfirmInfoBarDelegate(infobar_service),
144      origin_(origin),
145      display_name_(display_name),
146      notification_service_(notification_service),
147      process_id_(process_id),
148      route_id_(route_id),
149      callback_context_(callback_context),
150      action_taken_(false) {
151}
152
153NotificationPermissionInfoBarDelegate::
154    ~NotificationPermissionInfoBarDelegate() {
155  if (!action_taken_)
156    UMA_HISTOGRAM_COUNTS("NotificationPermissionRequest.Ignored", 1);
157
158  RenderViewHost* host = RenderViewHost::FromID(process_id_, route_id_);
159  if (host)
160    host->DesktopNotificationPermissionRequestDone(callback_context_);
161}
162
163int NotificationPermissionInfoBarDelegate::GetIconID() const {
164  return IDR_INFOBAR_DESKTOP_NOTIFICATIONS;
165}
166
167InfoBarDelegate::Type
168    NotificationPermissionInfoBarDelegate::GetInfoBarType() const {
169  return PAGE_ACTION_TYPE;
170}
171
172string16 NotificationPermissionInfoBarDelegate::GetMessageText() const {
173  return l10n_util::GetStringFUTF16(IDS_NOTIFICATION_PERMISSIONS,
174                                    display_name_);
175}
176
177string16 NotificationPermissionInfoBarDelegate::GetButtonLabel(
178    InfoBarButton button) const {
179  return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
180      IDS_NOTIFICATION_PERMISSION_YES : IDS_NOTIFICATION_PERMISSION_NO);
181}
182
183bool NotificationPermissionInfoBarDelegate::Accept() {
184  UMA_HISTOGRAM_COUNTS("NotificationPermissionRequest.Allowed", 1);
185  notification_service_->GrantPermission(origin_);
186  action_taken_ = true;
187  return true;
188}
189
190bool NotificationPermissionInfoBarDelegate::Cancel() {
191  UMA_HISTOGRAM_COUNTS("NotificationPermissionRequest.Denied", 1);
192  notification_service_->DenyPermission(origin_);
193  action_taken_ = true;
194  return true;
195}
196
197
198// DesktopNotificationService -------------------------------------------------
199
200// static
201void DesktopNotificationService::RegisterProfilePrefs(
202    user_prefs::PrefRegistrySyncable* registry) {
203  registry->RegisterListPref(
204      prefs::kMessageCenterDisabledExtensionIds,
205      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
206  registry->RegisterListPref(
207      prefs::kMessageCenterDisabledSystemComponentIds,
208      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
209  registry->RegisterListPref(
210      prefs::kMessageCenterEnabledSyncNotifierIds,
211      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
212  registry->RegisterBooleanPref(
213      prefs::kWelcomeNotificationDismissed,
214      false,
215      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
216}
217
218// static
219string16 DesktopNotificationService::CreateDataUrl(
220    const GURL& icon_url, const string16& title, const string16& body,
221    WebTextDirection dir) {
222  int resource;
223  std::vector<std::string> subst;
224  if (icon_url.is_valid()) {
225    resource = IDR_NOTIFICATION_ICON_HTML;
226    subst.push_back(icon_url.spec());
227    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(title)));
228    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(body)));
229    // icon float position
230    subst.push_back(dir == WebKit::WebTextDirectionRightToLeft ?
231                    "right" : "left");
232  } else if (title.empty() || body.empty()) {
233    resource = IDR_NOTIFICATION_1LINE_HTML;
234    string16 line = title.empty() ? body : title;
235    // Strings are div names in the template file.
236    string16 line_name = title.empty() ? ASCIIToUTF16("description")
237                                       : ASCIIToUTF16("title");
238    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(line_name)));
239    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(line)));
240  } else {
241    resource = IDR_NOTIFICATION_2LINE_HTML;
242    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(title)));
243    subst.push_back(net::EscapeForHTML(UTF16ToUTF8(body)));
244  }
245  // body text direction
246  subst.push_back(dir == WebKit::WebTextDirectionRightToLeft ?
247                  "rtl" : "ltr");
248
249  return CreateDataUrl(resource, subst);
250}
251
252// static
253string16 DesktopNotificationService::CreateDataUrl(
254    int resource, const std::vector<std::string>& subst) {
255  const base::StringPiece template_html(
256      ResourceBundle::GetSharedInstance().GetRawDataResource(
257          resource));
258
259  if (template_html.empty()) {
260    NOTREACHED() << "unable to load template. ID: " << resource;
261    return string16();
262  }
263
264  std::string data = ReplaceStringPlaceholders(template_html, subst, NULL);
265  return UTF8ToUTF16("data:text/html;charset=utf-8," +
266                      net::EscapeQueryParamValue(data, false));
267}
268
269// static
270std::string DesktopNotificationService::AddNotification(
271    const GURL& origin_url,
272    const string16& title,
273    const string16& message,
274    const GURL& icon_url,
275    const string16& replace_id,
276    NotificationDelegate* delegate,
277    Profile* profile) {
278  if (message_center::IsRichNotificationEnabled()) {
279    // For message center create a non-HTML notification with |icon_url|.
280    Notification notification(origin_url, icon_url, title, message,
281                              WebKit::WebTextDirectionDefault,
282                              string16(), replace_id, delegate);
283    g_browser_process->notification_ui_manager()->Add(notification, profile);
284    return notification.notification_id();
285  }
286
287  // Generate a data URL embedding the icon URL, title, and message.
288  GURL content_url(CreateDataUrl(
289      icon_url, title, message, WebKit::WebTextDirectionDefault));
290  Notification notification(
291      GURL(), content_url, string16(), replace_id, delegate);
292  g_browser_process->notification_ui_manager()->Add(notification, profile);
293  return notification.notification_id();
294}
295
296// static
297std::string DesktopNotificationService::AddIconNotification(
298    const GURL& origin_url,
299    const string16& title,
300    const string16& message,
301    const gfx::Image& icon,
302    const string16& replace_id,
303    NotificationDelegate* delegate,
304    Profile* profile) {
305  if (message_center::IsRichNotificationEnabled()) {
306    // For message center create a non-HTML notification with |icon|.
307    Notification notification(origin_url, icon, title, message,
308                              WebKit::WebTextDirectionDefault,
309                              string16(), replace_id, delegate);
310    g_browser_process->notification_ui_manager()->Add(notification, profile);
311    return notification.notification_id();
312  }
313
314  GURL icon_url;
315  if (!icon.IsEmpty())
316    icon_url = GURL(webui::GetBitmapDataUrl(*icon.ToSkBitmap()));
317  return AddNotification(
318      origin_url, title, message, icon_url, replace_id, delegate, profile);
319}
320
321// static
322void DesktopNotificationService::RemoveNotification(
323    const std::string& notification_id) {
324    g_browser_process->notification_ui_manager()->CancelById(notification_id);
325}
326
327DesktopNotificationService::DesktopNotificationService(
328    Profile* profile,
329    NotificationUIManager* ui_manager)
330    : profile_(profile),
331      ui_manager_(ui_manager) {
332  OnStringListPrefChanged(
333      prefs::kMessageCenterDisabledExtensionIds, &disabled_extension_ids_);
334  OnStringListPrefChanged(
335      prefs::kMessageCenterDisabledSystemComponentIds,
336      &disabled_system_component_ids_);
337  OnStringListPrefChanged(
338      prefs::kMessageCenterEnabledSyncNotifierIds, &enabled_sync_notifier_ids_);
339  disabled_extension_id_pref_.Init(
340      prefs::kMessageCenterDisabledExtensionIds,
341      profile_->GetPrefs(),
342      base::Bind(
343          &DesktopNotificationService::OnStringListPrefChanged,
344          base::Unretained(this),
345          base::Unretained(prefs::kMessageCenterDisabledExtensionIds),
346          base::Unretained(&disabled_extension_ids_)));
347  disabled_system_component_id_pref_.Init(
348      prefs::kMessageCenterDisabledSystemComponentIds,
349      profile_->GetPrefs(),
350      base::Bind(
351          &DesktopNotificationService::OnStringListPrefChanged,
352          base::Unretained(this),
353          base::Unretained(prefs::kMessageCenterDisabledSystemComponentIds),
354          base::Unretained(&disabled_system_component_ids_)));
355  enabled_sync_notifier_id_pref_.Init(
356      prefs::kMessageCenterEnabledSyncNotifierIds,
357      profile_->GetPrefs(),
358      base::Bind(
359          &DesktopNotificationService::OnStringListPrefChanged,
360          base::Unretained(this),
361          base::Unretained(prefs::kMessageCenterEnabledSyncNotifierIds),
362          base::Unretained(&enabled_sync_notifier_ids_)));
363  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
364                 content::Source<Profile>(profile_));
365}
366
367DesktopNotificationService::~DesktopNotificationService() {
368}
369
370void DesktopNotificationService::GrantPermission(const GURL& origin) {
371  ContentSettingsPattern primary_pattern =
372      ContentSettingsPattern::FromURLNoWildcard(origin);
373  profile_->GetHostContentSettingsMap()->SetContentSetting(
374      primary_pattern,
375      ContentSettingsPattern::Wildcard(),
376      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
377      NO_RESOURCE_IDENTIFIER,
378      CONTENT_SETTING_ALLOW);
379}
380
381void DesktopNotificationService::DenyPermission(const GURL& origin) {
382  ContentSettingsPattern primary_pattern =
383      ContentSettingsPattern::FromURLNoWildcard(origin);
384  profile_->GetHostContentSettingsMap()->SetContentSetting(
385      primary_pattern,
386      ContentSettingsPattern::Wildcard(),
387      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
388      NO_RESOURCE_IDENTIFIER,
389      CONTENT_SETTING_BLOCK);
390}
391
392ContentSetting DesktopNotificationService::GetDefaultContentSetting(
393    std::string* provider_id) {
394  return profile_->GetHostContentSettingsMap()->GetDefaultContentSetting(
395      CONTENT_SETTINGS_TYPE_NOTIFICATIONS, provider_id);
396}
397
398void DesktopNotificationService::SetDefaultContentSetting(
399    ContentSetting setting) {
400  profile_->GetHostContentSettingsMap()->SetDefaultContentSetting(
401      CONTENT_SETTINGS_TYPE_NOTIFICATIONS, setting);
402}
403
404void DesktopNotificationService::ResetToDefaultContentSetting() {
405  profile_->GetHostContentSettingsMap()->SetDefaultContentSetting(
406      CONTENT_SETTINGS_TYPE_NOTIFICATIONS, CONTENT_SETTING_DEFAULT);
407}
408
409void DesktopNotificationService::GetNotificationsSettings(
410    ContentSettingsForOneType* settings) {
411  profile_->GetHostContentSettingsMap()->GetSettingsForOneType(
412      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
413      NO_RESOURCE_IDENTIFIER,
414      settings);
415}
416
417void DesktopNotificationService::ClearSetting(
418    const ContentSettingsPattern& pattern) {
419  profile_->GetHostContentSettingsMap()->SetContentSetting(
420      pattern,
421      ContentSettingsPattern::Wildcard(),
422      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
423      NO_RESOURCE_IDENTIFIER,
424      CONTENT_SETTING_DEFAULT);
425}
426
427void DesktopNotificationService::ResetAllOrigins() {
428  profile_->GetHostContentSettingsMap()->ClearSettingsForOneType(
429      CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
430}
431
432ContentSetting DesktopNotificationService::GetContentSetting(
433    const GURL& origin) {
434  return profile_->GetHostContentSettingsMap()->GetContentSetting(
435      origin,
436      origin,
437      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
438      NO_RESOURCE_IDENTIFIER);
439}
440
441void DesktopNotificationService::RequestPermission(
442    const GURL& origin, int process_id, int route_id, int callback_context,
443    WebContents* contents) {
444  // If |origin| hasn't been seen before and the default content setting for
445  // notifications is "ask", show an infobar.
446  // The cache can only answer queries on the IO thread once it's initialized,
447  // so don't ask the cache.
448  ContentSetting setting = GetContentSetting(origin);
449  if (setting == CONTENT_SETTING_ASK) {
450    // Show an info bar requesting permission.
451    InfoBarService* infobar_service =
452        InfoBarService::FromWebContents(contents);
453    // |infobar_service| may be NULL, e.g., if this request originated in a
454    // browser action popup, extension background page, or any HTML that runs
455    // outside of a tab.
456    if (infobar_service) {
457      NotificationPermissionInfoBarDelegate::Create(
458          infobar_service,
459          DesktopNotificationServiceFactory::GetForProfile(
460              Profile::FromBrowserContext(contents->GetBrowserContext())),
461          origin, DisplayNameForOriginInProcessId(origin, process_id),
462          process_id, route_id, callback_context);
463      return;
464    }
465  }
466
467  // Notify renderer immediately.
468  RenderViewHost* host = RenderViewHost::FromID(process_id, route_id);
469  if (host)
470    host->DesktopNotificationPermissionRequestDone(callback_context);
471}
472
473#if !defined(OS_WIN)
474void DesktopNotificationService::ShowNotification(
475    const Notification& notification) {
476  GetUIManager()->Add(notification, profile_);
477}
478
479bool DesktopNotificationService::CancelDesktopNotification(
480    int process_id, int route_id, int notification_id) {
481  scoped_refptr<NotificationObjectProxy> proxy(
482      new NotificationObjectProxy(process_id, route_id, notification_id,
483                                  false));
484  return GetUIManager()->CancelById(proxy->id());
485}
486#endif  // OS_WIN
487
488bool DesktopNotificationService::ShowDesktopNotification(
489    const content::ShowDesktopNotificationHostMsgParams& params,
490    int process_id, int route_id, DesktopNotificationSource source) {
491  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
492  const GURL& origin = params.origin;
493  NotificationObjectProxy* proxy =
494      new NotificationObjectProxy(process_id, route_id,
495                                  params.notification_id,
496                                  source == WorkerNotification);
497
498  string16 display_source = DisplayNameForOriginInProcessId(origin, process_id);
499  if (params.is_html) {
500    ShowNotification(Notification(origin, params.contents_url, display_source,
501        params.replace_id, proxy));
502  } else {
503    Notification notification(origin, params.icon_url, params.title,
504        params.body, params.direction, display_source, params.replace_id,
505        proxy);
506    // The webkit notification doesn't timeout.
507    notification.set_never_timeout(true);
508    ShowNotification(notification);
509  }
510  return true;
511}
512
513string16 DesktopNotificationService::DisplayNameForOriginInProcessId(
514    const GURL& origin, int process_id) {
515  // If the source is an extension, lookup the display name.
516  // Message center prefers to use extension name if the notification
517  // is allowed by an extension.
518  if (NotificationUIManager::DelegatesToMessageCenter() ||
519      origin.SchemeIs(extensions::kExtensionScheme)) {
520    ExtensionInfoMap* extension_info_map =
521        extensions::ExtensionSystem::Get(profile_)->info_map();
522    if (extension_info_map) {
523      ExtensionSet extensions;
524      extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
525          origin, process_id, extensions::APIPermission::kNotification,
526          &extensions);
527      for (ExtensionSet::const_iterator iter = extensions.begin();
528           iter != extensions.end(); ++iter) {
529        NotifierId notifier_id(NotifierId::APPLICATION, (*iter)->id());
530        if (IsNotifierEnabled(notifier_id))
531          return UTF8ToUTF16((*iter)->name());
532      }
533    }
534  }
535  return UTF8ToUTF16(origin.host());
536}
537
538void DesktopNotificationService::NotifySettingsChange() {
539  content::NotificationService::current()->Notify(
540      chrome::NOTIFICATION_DESKTOP_NOTIFICATION_SETTINGS_CHANGED,
541      content::Source<DesktopNotificationService>(this),
542      content::NotificationService::NoDetails());
543}
544
545NotificationUIManager* DesktopNotificationService::GetUIManager() {
546  // We defer setting ui_manager_ to the global singleton until we need it
547  // in order to avoid UI dependent construction during startup.
548  if (!ui_manager_)
549    ui_manager_ = g_browser_process->notification_ui_manager();
550  return ui_manager_;
551}
552
553bool DesktopNotificationService::IsNotifierEnabled(
554    const NotifierId& notifier_id) {
555  switch (notifier_id.type) {
556    case NotifierId::APPLICATION:
557      return disabled_extension_ids_.find(notifier_id.id) ==
558          disabled_extension_ids_.end();
559    case NotifierId::WEB_PAGE:
560      return GetContentSetting(notifier_id.url) == CONTENT_SETTING_ALLOW;
561    case NotifierId::SYSTEM_COMPONENT:
562#if defined(OS_CHROMEOS)
563      return disabled_system_component_ids_.find(
564          ash::system_notifier::SystemComponentTypeToString(
565              static_cast<ash::system_notifier::AshSystemComponentNotifierType>(
566                  notifier_id.system_component_type)))
567          == disabled_system_component_ids_.end();
568#else
569      return false;
570#endif
571    case NotifierId::SYNCED_NOTIFICATION_SERVICE:
572      return enabled_sync_notifier_ids_.find(notifier_id.id) !=
573          enabled_sync_notifier_ids_.end();
574  }
575
576  NOTREACHED();
577  return false;
578}
579
580void DesktopNotificationService::SetNotifierEnabled(
581    const NotifierId& notifier_id,
582    bool enabled) {
583  DCHECK_NE(NotifierId::WEB_PAGE, notifier_id.type);
584
585  bool add_new_item = false;
586  const char* pref_name = NULL;
587  scoped_ptr<base::StringValue> id;
588  switch (notifier_id.type) {
589    case NotifierId::APPLICATION:
590      pref_name = prefs::kMessageCenterDisabledExtensionIds;
591      add_new_item = !enabled;
592      id.reset(new base::StringValue(notifier_id.id));
593      break;
594    case NotifierId::SYSTEM_COMPONENT:
595#if defined(OS_CHROMEOS)
596      pref_name = prefs::kMessageCenterDisabledSystemComponentIds;
597      add_new_item = !enabled;
598      id.reset(new base::StringValue(
599          ash::system_notifier::SystemComponentTypeToString(
600              static_cast<ash::system_notifier::AshSystemComponentNotifierType>(
601                  notifier_id.system_component_type))));
602#else
603      return;
604#endif
605      break;
606    case NotifierId::SYNCED_NOTIFICATION_SERVICE:
607      pref_name = prefs::kMessageCenterEnabledSyncNotifierIds;
608      // Adding a new item if |enabled| == true, since synced notification
609      // services are opt-in.
610      add_new_item = enabled;
611      id.reset(new base::StringValue(notifier_id.id));
612      break;
613    default:
614      NOTREACHED();
615  }
616  DCHECK(pref_name != NULL);
617
618  ListPrefUpdate update(profile_->GetPrefs(), pref_name);
619  base::ListValue* const list = update.Get();
620  if (add_new_item) {
621    // AppendIfNotPresent will delete |adding_value| when the same value
622    // already exists.
623    list->AppendIfNotPresent(id.release());
624  } else {
625    list->Remove(*id, NULL);
626  }
627}
628
629void DesktopNotificationService::OnStringListPrefChanged(
630    const char* pref_name, std::set<std::string>* ids_field) {
631  ids_field->clear();
632  const base::ListValue* pref_list = profile_->GetPrefs()->GetList(pref_name);
633  for (size_t i = 0; i < pref_list->GetSize(); ++i) {
634    std::string element;
635    if (pref_list->GetString(i, &element) && !element.empty())
636      ids_field->insert(element);
637    else
638      LOG(WARNING) << i << "-th element is not a string for " << pref_name;
639  }
640}
641
642WebKit::WebNotificationPresenter::Permission
643    DesktopNotificationService::HasPermission(const GURL& origin) {
644  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
645  HostContentSettingsMap* host_content_settings_map =
646      profile_->GetHostContentSettingsMap();
647  ContentSetting setting = host_content_settings_map->GetContentSetting(
648      origin,
649      origin,
650      CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
651      NO_RESOURCE_IDENTIFIER);
652
653  if (setting == CONTENT_SETTING_ALLOW)
654    return WebKit::WebNotificationPresenter::PermissionAllowed;
655  if (setting == CONTENT_SETTING_BLOCK)
656    return WebKit::WebNotificationPresenter::PermissionDenied;
657  if (setting == CONTENT_SETTING_ASK)
658    return WebKit::WebNotificationPresenter::PermissionNotAllowed;
659  NOTREACHED() << "Invalid notifications settings value: " << setting;
660  return WebKit::WebNotificationPresenter::PermissionNotAllowed;
661}
662
663void DesktopNotificationService::Observe(
664    int type,
665    const content::NotificationSource& source,
666    const content::NotificationDetails& details) {
667  DCHECK_EQ(chrome::NOTIFICATION_EXTENSION_UNINSTALLED, type);
668
669  extensions::Extension* extension =
670      content::Details<extensions::Extension>(details).ptr();
671  NotifierId notifier_id(NotifierId::APPLICATION, extension->id());
672  if (IsNotifierEnabled(notifier_id))
673    return;
674
675  SetNotifierEnabled(notifier_id, true);
676}
677