about summary refs log tree commit diff
path: root/app/javascript/mastodon/service_worker/web_push_notifications.js
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2018-05-19 14:46:47 +0200
committerGitHub <noreply@github.com>2018-05-19 14:46:47 +0200
commit4b94e9c65efd227c58f8be9b3db6b667d403ed3c (patch)
tree32c3e4f22fa78fb6d74062e192ea8cc7c59f135b /app/javascript/mastodon/service_worker/web_push_notifications.js
parent1951ff41b33b264fd8179998648c3cbbf2834cd5 (diff)
Improve payload format of Web Push API now that it's open (#7521)
> Good lord what is happening in there

Previously the contents of the Web Push API payloads closely resembled the structure of JavaScript's [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification). But now that the API is open to non-browser apps, and given that there is no required coupling between contents of the payload and a Notification object, here is how I changed the payload:

```json
{ 
  "access_token": "...",
  "preferred_locale": "en",
  "notification_id": "12345",
  "notification_type": "follow",
  "title": "So and so followed you",
  "body": "This is my bio",
  "icon": "https://example.com/avatar.png"
}
```

The title, body and icon attributes are included as a fallback so you can construct a minimal notification if you cannot perform a network request to the API to get more data.
Diffstat (limited to 'app/javascript/mastodon/service_worker/web_push_notifications.js')
-rw-r--r--app/javascript/mastodon/service_worker/web_push_notifications.js178
1 files changed, 107 insertions, 71 deletions
diff --git a/app/javascript/mastodon/service_worker/web_push_notifications.js b/app/javascript/mastodon/service_worker/web_push_notifications.js
index f63cff335..16eaefcbb 100644
--- a/app/javascript/mastodon/service_worker/web_push_notifications.js
+++ b/app/javascript/mastodon/service_worker/web_push_notifications.js
@@ -1,36 +1,32 @@
+import IntlMessageFormat from 'intl-messageformat';
+import locales from './web_push_locales';
+
 const MAX_NOTIFICATIONS = 5;
 const GROUP_TAG = 'tag';
 
-// Avoid loading intl-messageformat and dealing with locales in the ServiceWorker
-const formatGroupTitle = (message, count) => message.replace('%{count}', count);
-
 const notify = options =>
   self.registration.getNotifications().then(notifications => {
-    if (notifications.length === MAX_NOTIFICATIONS) {
-      // Reached the maximum number of notifications, proceed with grouping
+    if (notifications.length >= MAX_NOTIFICATIONS) { // Reached the maximum number of notifications, proceed with grouping
       const group = {
-        title: formatGroupTitle(options.data.message, notifications.length + 1),
-        body: notifications
-          .sort((n1, n2) => n1.timestamp < n2.timestamp)
-          .map(notification => notification.title).join('\n'),
+        title: formatMessage('notifications.group', options.data.preferred_locale, { count: notifications.length + 1 }),
+        body: notifications.sort((n1, n2) => n1.timestamp < n2.timestamp).map(notification => notification.title).join('\n'),
         badge: '/badge.png',
         icon: '/android-chrome-192x192.png',
         tag: GROUP_TAG,
         data: {
           url: (new URL('/web/notifications', self.location)).href,
           count: notifications.length + 1,
-          message: options.data.message,
+          preferred_locale: options.data.preferred_locale,
         },
       };
 
       notifications.forEach(notification => notification.close());
 
       return self.registration.showNotification(group.title, group);
-    } else if (notifications.length === 1 && notifications[0].tag === GROUP_TAG) {
-      // Already grouped, proceed with appending the notification to the group
-      const group = cloneNotification(notifications[0]);
+    } else if (notifications.length === 1 && notifications[0].tag === GROUP_TAG) { // Already grouped, proceed with appending the notification to the group
+      const group = { ...notifications[0] };
 
-      group.title = formatGroupTitle(group.data.message, group.data.count + 1);
+      group.title = formatMessage('notifications.group', options.data.preferred_locale, { count: group.data.count + 1 });
       group.body  = `${options.title}\n${group.body}`;
       group.data  = { ...group.data, count: group.data.count + 1 };
 
@@ -40,57 +36,87 @@ const notify = options =>
     return self.registration.showNotification(options.title, options);
   });
 
-const handlePush = (event) => {
-  const options = event.data.json();
-
-  options.body      = options.data.nsfw || options.data.content;
-  options.dir       = options.data.dir;
-  options.image     = options.image || undefined; // Null results in a network request (404)
-  options.timestamp = options.timestamp && new Date(options.timestamp);
-
-  const expandAction = options.data.actions.find(action => action.todo === 'expand');
+const fetchFromApi = (path, method, accessToken) => {
+  const url = (new URL(path, self.location)).href;
 
-  if (expandAction) {
-    options.actions          = [expandAction];
-    options.hiddenActions    = options.data.actions.filter(action => action !== expandAction);
-    options.data.hiddenImage = options.image;
-    options.image            = undefined;
-  } else {
-    options.actions = options.data.actions;
-  }
+  return fetch(url, {
+    headers: {
+      'Authorization': `Bearer ${accessToken}`,
+      'Content-Type': 'application/json',
+    },
 
-  event.waitUntil(notify(options));
+    method: method,
+    credentials: 'include',
+  }).then(res => {
+    if (res.ok) {
+      return res;
+    } else {
+      throw new Error(res.status);
+    }
+  }).then(res => res.json());
 };
 
-const cloneNotification = (notification) => {
-  const clone = {  };
+const formatMessage = (messageId, locale, values = {}) =>
+  (new IntlMessageFormat(locales[locale][messageId], locale)).format(values);
 
-  for(var k in notification) {
-    clone[k] = notification[k];
-  }
+const handlePush = (event) => {
+  const { access_token, notification_id, preferred_locale, title, body, icon } = event.data.json();
+
+  // Placeholder until more information can be loaded
+  event.waitUntil(
+    notify({
+      title,
+      body,
+      icon,
+      tag: notification_id,
+      timestamp: new Date(),
+      badge: '/badge.png',
+      data: { access_token, preferred_locale, url: '/web/notifications' },
+    }).then(() => fetchFromApi(`/api/v1/notifications/${notification_id}`, 'get', access_token)).then(notification => {
+      const options = {};
+
+      options.title     = formatMessage(`notification.${notification.type}`, preferred_locale, { name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
+      options.body      = notification.status && notification.status.content;
+      options.icon      = notification.account.avatar_static;
+      options.timestamp = notification.created_at && new Date(notification.created_at);
+      options.tag       = notification.id;
+      options.badge     = '/badge.png';
+      options.image     = notification.status && notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url || undefined;
+      options.data      = { access_token, preferred_locale, id: notification.status ? notification.status.id : notification.account.id, url: notification.status ? `/web/statuses/${notification.status.id}` : `/web/accounts/${notification.account.id}` };
+
+      if (notification.status && notification.status.sensitive) {
+        options.data.hiddenBody  = notification.status.content;
+        options.data.hiddenImage = notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url;
+
+        options.body    = undefined;
+        options.image   = undefined;
+        options.actions = [actionExpand(preferred_locale)];
+      } else if (notification.status) {
+        options.actions = [actionReblog(preferred_locale), actionFavourite(preferred_locale)];
+      }
 
-  return clone;
+      return notify(options);
+    })
+  );
 };
 
-const expandNotification = (notification) => {
-  const nextNotification = cloneNotification(notification);
+const actionExpand = preferred_locale => ({
+  action: 'expand',
+  icon: '/web-push-icon_expand.png',
+  title: formatMessage('status.show_more', preferred_locale),
+});
 
-  nextNotification.body    = notification.data.content;
-  nextNotification.image   = notification.data.hiddenImage;
-  nextNotification.actions = notification.data.actions.filter(action => action.todo !== 'expand');
+const actionReblog = preferred_locale => ({
+  action: 'reblog',
+  icon: '/web-push-icon_reblog.png',
+  title: formatMessage('status.reblog', preferred_locale),
+});
 
-  return self.registration.showNotification(nextNotification.title, nextNotification);
-};
-
-const makeRequest = (notification, action) =>
-  fetch(action.action, {
-    headers: {
-      'Authorization': `Bearer ${notification.data.access_token}`,
-      'Content-Type': 'application/json',
-    },
-    method: action.method,
-    credentials: 'include',
-  });
+const actionFavourite = preferred_locale => ({
+  action: 'favourite',
+  icon: '/web-push-icon_favourite.png',
+  title: formatMessage('status.favourite', preferred_locale),
+});
 
 const findBestClient = clients => {
   const focusedClient = clients.find(client => client.focused);
@@ -99,6 +125,24 @@ const findBestClient = clients => {
   return focusedClient || visibleClient || clients[0];
 };
 
+const expandNotification = notification => {
+  const newNotification = { ...notification };
+
+  newNotification.body    = newNotification.data.hiddenBody;
+  newNotification.image   = newNotification.data.hiddenImage;
+  newNotification.actions = [actionReblog(notification.data.preferred_locale), actionFavourite(notification.data.preferred_locale)];
+
+  return self.registration.showNotification(newNotification.title, newNotification);
+};
+
+const removeActionFromNotification = (notification, action) => {
+  const newNotification = { ...notification };
+
+  newNotification.actions = newNotification.actions.filter(item => item.action !== action);
+
+  return self.registration.showNotification(newNotification.title, newNotification);
+};
+
 const openUrl = url =>
   self.clients.matchAll({ type: 'window' }).then(clientList => {
     if (clientList.length !== 0) {
@@ -124,27 +168,19 @@ const openUrl = url =>
     return self.clients.openWindow(url);
   });
 
-const removeActionFromNotification = (notification, action) => {
-  const actions          = notification.actions.filter(act => act.action !== action.action);
-  const nextNotification = cloneNotification(notification);
-
-  nextNotification.actions = actions;
-
-  return self.registration.showNotification(nextNotification.title, nextNotification);
-};
-
 const handleNotificationClick = (event) => {
   const reactToNotificationClick = new Promise((resolve, reject) => {
     if (event.action) {
-      const action = event.notification.data.actions.find(({ action }) => action === event.action);
-
-      if (action.todo === 'expand') {
+      if (event.action === 'expand') {
         resolve(expandNotification(event.notification));
-      } else if (action.todo === 'request') {
-        resolve(makeRequest(event.notification, action)
-          .then(() => removeActionFromNotification(event.notification, action)));
+      } else if (event.action === 'reblog') {
+        const { data } = event.notification;
+        resolve(fetchFromApi(`/api/v1/statuses/${data.id}/reblog`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'reblog')));
+      } else if (event.action === 'favourite') {
+        const { data } = event.notification;
+        resolve(fetchFromApi(`/api/v1/statuses/${data.id}/favourite`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'favourite')));
       } else {
-        reject(`Unknown action: ${action.todo}`);
+        reject(`Unknown action: ${event.action}`);
       }
     } else {
       event.notification.close();