summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/api/notifications/notifications_api.cc
blob: 597cc8a7772b7ac4b665aece8db866d9ab9e266f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/notifications/notifications_api.h"

#include "base/callback.h"
#include "base/strings/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/features/feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "googleurl/src/gurl.h"
#include "ui/message_center/message_center_util.h"

namespace extensions {

namespace {

const char kResultKey[] = "result";

// Given an extension id and another id, returns an id that is unique
// relative to other extensions.
std::string CreateScopedIdentifier(const std::string& extension_id,
                                   const std::string& id) {
  return extension_id + "-" + id;
}

// Removes the unique internal identifier to send the ID as the
// extension expects it.
std::string StripScopeFromIdentifier(const std::string& extension_id,
                                     const std::string& id) {
  size_t index_of_separator = extension_id.length() + 1;
  DCHECK_LT(index_of_separator, id.length());

  return id.substr(index_of_separator);
}

class NotificationsApiDelegate : public NotificationDelegate {
 public:
  NotificationsApiDelegate(ApiFunction* api_function,
                           Profile* profile,
                           const std::string& extension_id,
                           const std::string& id)
      : api_function_(api_function),
        profile_(profile),
        extension_id_(extension_id),
        id_(id),
        scoped_id_(CreateScopedIdentifier(extension_id, id)),
        process_id_(-1) {
    DCHECK(api_function_);
    if (api_function_->render_view_host())
      process_id_ = api_function->render_view_host()->GetProcess()->GetID();
  }

  virtual void Display() OVERRIDE { }

  virtual void Error() OVERRIDE {
    scoped_ptr<ListValue> args(CreateBaseEventArgs());
    SendEvent(event_names::kOnNotificationError, args.Pass());
  }

  virtual void Close(bool by_user) OVERRIDE {
    scoped_ptr<ListValue> args(CreateBaseEventArgs());
    args->Append(Value::CreateBooleanValue(by_user));
    SendEvent(event_names::kOnNotificationClosed, args.Pass());
  }

  virtual void Click() OVERRIDE {
    scoped_ptr<ListValue> args(CreateBaseEventArgs());
    SendEvent(event_names::kOnNotificationClicked, args.Pass());
  }

  virtual bool HasClickedListener() OVERRIDE {
    return ExtensionSystem::Get(profile_)->event_router()->HasEventListener(
        event_names::kOnNotificationClicked);
  }

  virtual void ButtonClick(int index) OVERRIDE {
    scoped_ptr<ListValue> args(CreateBaseEventArgs());
    args->Append(Value::CreateIntegerValue(index));
    SendEvent(event_names::kOnNotificationButtonClicked, args.Pass());
  }

  virtual std::string id() const OVERRIDE {
    return scoped_id_;
  }

  virtual int process_id() const OVERRIDE {
    return process_id_;
  }

  virtual content::RenderViewHost* GetRenderViewHost() const OVERRIDE {
    // We're holding a reference to api_function_, so we know it'll be valid
    // until ReleaseRVH is called, and api_function_ (as a
    // UIThreadExtensionFunction) will zero out its copy of render_view_host
    // when the RVH goes away.
    if (!api_function_)
      return NULL;
    return api_function_->render_view_host();
  }

  virtual void ReleaseRenderViewHost() OVERRIDE {
    api_function_ = NULL;
  }

 private:
  virtual ~NotificationsApiDelegate() {}

  void SendEvent(const std::string& name, scoped_ptr<ListValue> args) {
    scoped_ptr<Event> event(new Event(name, args.Pass()));
    ExtensionSystem::Get(profile_)->event_router()->DispatchEventToExtension(
        extension_id_, event.Pass());
  }

  scoped_ptr<ListValue> CreateBaseEventArgs() {
    scoped_ptr<ListValue> args(new ListValue());
    args->Append(Value::CreateStringValue(id_));
    return args.Pass();
  }

  scoped_refptr<ApiFunction> api_function_;
  Profile* profile_;
  const std::string extension_id_;
  const std::string id_;
  const std::string scoped_id_;
  int process_id_;

  DISALLOW_COPY_AND_ASSIGN(NotificationsApiDelegate);
};

}  // namespace

bool NotificationsApiFunction::IsNotificationsApiAvailable() {
  // We need to check this explicitly rather than letting
  // _permission_features.json enforce it, because we're sharing the
  // chrome.notifications permissions namespace with WebKit notifications.
  return GetExtension()->is_platform_app() || GetExtension()->is_extension();
}

NotificationsApiFunction::NotificationsApiFunction() {
}

NotificationsApiFunction::~NotificationsApiFunction() {
}

void NotificationsApiFunction::CreateNotification(
    const std::string& id,
    api::notifications::NotificationOptions* options) {
  // If older notification runtime is used, use simpler bridge.
  if (!message_center::IsRichNotificationEnabled()) {
    message_center::NotificationType type =
        MapApiTemplateTypeToType(options->type);
    GURL icon_url(UTF8ToUTF16(options->icon_url));
    string16 title(UTF8ToUTF16(options->title));
    string16 message(UTF8ToUTF16(options->message));

    // Ignore options if running on the old notification runtime.
    scoped_ptr<DictionaryValue> optional_fields(new DictionaryValue());

    NotificationsApiDelegate* api_delegate(new NotificationsApiDelegate(
        this,
        profile(),
        extension_->id(),
        id));  // ownership is passed to Notification
    Notification notification(type, extension_->url(), icon_url, title, message,
                              WebKit::WebTextDirectionDefault,
                              UTF8ToUTF16(extension_->name()),
                              UTF8ToUTF16(api_delegate->id()),
                              optional_fields.get(), api_delegate);

    g_browser_process->notification_ui_manager()->Add(notification, profile());
    return;
  }

  message_center::NotificationType type =
      MapApiTemplateTypeToType(options->type);
  GURL icon_url(UTF8ToUTF16(options->icon_url));
  string16 title(UTF8ToUTF16(options->title));
  string16 message(UTF8ToUTF16(options->message));

  scoped_ptr<DictionaryValue> optional_fields(new DictionaryValue());

  // For all notification types.
  if (options->priority.get())
    optional_fields->SetInteger(message_center::kPriorityKey,
                                *options->priority);
  if (options->event_time.get())
    optional_fields->SetDouble(message_center::kTimestampKey,
                               *options->event_time);
  if (options->buttons.get()) {
    if (options->buttons->size() > 0) {
      linked_ptr<api::notifications::NotificationButton> button =
          (*options->buttons)[0];
      optional_fields->SetString(message_center::kButtonOneTitleKey,
                                 UTF8ToUTF16(button->title));
      if (button->icon_url.get())
        optional_fields->SetString(message_center::kButtonOneIconUrlKey,
                                   UTF8ToUTF16(*button->icon_url));
    }
    if (options->buttons->size() > 1) {
      linked_ptr<api::notifications::NotificationButton> button =
          (*options->buttons)[1];
      optional_fields->SetString(message_center::kButtonTwoTitleKey,
                                 UTF8ToUTF16(button->title));
      if (button->icon_url.get())
        optional_fields->SetString(message_center::kButtonTwoIconUrlKey,
                                   UTF8ToUTF16(*button->icon_url));
    }
  }
  if (options->expanded_message.get())
    optional_fields->SetString(message_center::kExpandedMessageKey,
                               UTF8ToUTF16(*options->expanded_message));

  // For image notifications (type == 'image').
  // TODO(dharcourt): Fail if (type == 'image' && !options->image_url.get())
  // TODO(dharcourt): Fail if (type != 'image' && options->image_url.get())
  if (options->image_url.get())
    optional_fields->SetString(message_center::kImageUrlKey,
                               UTF8ToUTF16(*options->image_url));

  // For list notifications (type == 'multiple').
  // TODO(dharcourt): Fail if (type == 'multiple' && !options->items.get())
  // TODO(dharcourt): Fail if (type != 'multiple' && options->items.get())
  if (options->items.get()) {
    base::ListValue* items = new base::ListValue();
    std::vector<
      linked_ptr<
        api::notifications::NotificationItem> >::iterator i;
    for (i = options->items->begin(); i != options->items->end(); ++i) {
      base::DictionaryValue* item = new base::DictionaryValue();
      item->SetString(message_center::kItemTitleKey,
                      UTF8ToUTF16(i->get()->title));
      item->SetString(message_center::kItemMessageKey,
                      UTF8ToUTF16(i->get()->message));
      items->Append(item);
    }
    optional_fields->Set(message_center::kItemsKey, items);
  }

  NotificationsApiDelegate* api_delegate(new NotificationsApiDelegate(
      this,
      profile(),
      extension_->id(),
      id));  // ownership is passed to Notification
  Notification notification(type, extension_->url(), icon_url, title, message,
                            WebKit::WebTextDirectionDefault,
                            UTF8ToUTF16(extension_->name()),
                            UTF8ToUTF16(api_delegate->id()),
                            optional_fields.get(), api_delegate);

  g_browser_process->notification_ui_manager()->Add(notification, profile());
}

bool NotificationsApiFunction::IsNotificationsApiEnabled() {
  DesktopNotificationService* service =
      DesktopNotificationServiceFactory::GetForProfile(profile());
  return service->IsExtensionEnabled(extension_->id());
}

bool NotificationsApiFunction::RunImpl() {
  if (IsNotificationsApiAvailable() && IsNotificationsApiEnabled()) {
    return RunNotificationsApi();
  } else {
    SendResponse(false);
    return true;
  }
}

message_center::NotificationType
NotificationsApiFunction::MapApiTemplateTypeToType(
    api::notifications::TemplateType type) {
  switch (type) {
    case api::notifications::TEMPLATE_TYPE_NONE:
    case api::notifications::TEMPLATE_TYPE_BASIC:
      return message_center::NOTIFICATION_TYPE_BASE_FORMAT;
    case api::notifications::TEMPLATE_TYPE_IMAGE:
      return message_center::NOTIFICATION_TYPE_IMAGE;
    case api::notifications::TEMPLATE_TYPE_LIST:
      return message_center::NOTIFICATION_TYPE_MULTIPLE;
    default:
      // Gracefully handle newer application code that is running on an older
      // runtime that doesn't recognize the requested template.
      return message_center::NOTIFICATION_TYPE_BASE_FORMAT;
  }
}

const char kNotificationPrefix[] = "extensions.api.";

static uint64 next_id_ = 0;

NotificationsCreateFunction::NotificationsCreateFunction() {
}

NotificationsCreateFunction::~NotificationsCreateFunction() {
}

bool NotificationsCreateFunction::RunNotificationsApi() {
  params_ = api::notifications::Create::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  // If the caller provided a notificationId, use that. Otherwise, generate
  // one. Note that there's nothing stopping an app developer from passing in
  // arbitrary "extension.api.999" notificationIds that will collide with
  // future generated IDs. It doesn't seem necessary to try to prevent this; if
  // developers want to hurt themselves, we'll let them.
  const std::string extension_id(extension_->id());
  std::string notification_id;
  if (!params_->notification_id.empty())
    notification_id = params_->notification_id;
  else
    notification_id = kNotificationPrefix + base::Uint64ToString(next_id_++);

  CreateNotification(notification_id, &params_->options);

  SetResult(Value::CreateStringValue(notification_id));

  SendResponse(true);

  return true;
}

NotificationsUpdateFunction::NotificationsUpdateFunction() {
}

NotificationsUpdateFunction::~NotificationsUpdateFunction() {
}

bool NotificationsUpdateFunction::RunNotificationsApi() {
  params_ = api::notifications::Update::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  if (g_browser_process->notification_ui_manager()->DoesIdExist(
          CreateScopedIdentifier(extension_->id(), params_->notification_id))) {
    CreateNotification(params_->notification_id, &params_->options);
    SetResult(Value::CreateBooleanValue(true));
  } else {
    SetResult(Value::CreateBooleanValue(false));
  }

  SendResponse(true);

  return true;
}

NotificationsClearFunction::NotificationsClearFunction() {
}

NotificationsClearFunction::~NotificationsClearFunction() {
}

bool NotificationsClearFunction::RunNotificationsApi() {
  params_ = api::notifications::Clear::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  bool cancel_result = g_browser_process->notification_ui_manager()->CancelById(
      CreateScopedIdentifier(extension_->id(), params_->notification_id));

  SetResult(Value::CreateBooleanValue(cancel_result));
  SendResponse(true);

  return true;
}

NotificationsGetAllFunction::NotificationsGetAllFunction() {}

NotificationsGetAllFunction::~NotificationsGetAllFunction() {}

bool NotificationsGetAllFunction::RunNotificationsApi() {
  NotificationUIManager* notification_ui_manager =
      g_browser_process->notification_ui_manager();
  std::set<std::string> notification_ids =
      notification_ui_manager->GetAllIdsByProfileAndSourceOrigin(
          profile_, extension_->url());

  scoped_ptr<DictionaryValue> result(new DictionaryValue());

  for (std::set<std::string>::iterator iter = notification_ids.begin();
       iter != notification_ids.end(); iter++) {
    result->SetBooleanWithoutPathExpansion(
        StripScopeFromIdentifier(extension_->id(), *iter), true);
  }

  SetResult(result.release());
  SendResponse(true);

  return true;
}

}  // namespace extensions