0
0
Fork 0

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.
This commit is contained in:
Eugen Rochko 2018-05-19 14:46:47 +02:00 committed by GitHub
parent 1951ff41b3
commit 4b94e9c65e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
76 changed files with 217 additions and 623 deletions

View file

@ -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();
const fetchFromApi = (path, method, accessToken) => {
const url = (new URL(path, self.location)).href;
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');
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;
}
event.waitUntil(notify(options));
};
const cloneNotification = (notification) => {
const clone = { };
for(var k in notification) {
clone[k] = notification[k];
}
return clone;
};
const expandNotification = (notification) => {
const nextNotification = cloneNotification(notification);
nextNotification.body = notification.data.content;
nextNotification.image = notification.data.hiddenImage;
nextNotification.actions = notification.data.actions.filter(action => action.todo !== 'expand');
return self.registration.showNotification(nextNotification.title, nextNotification);
};
const makeRequest = (notification, action) =>
fetch(action.action, {
return fetch(url, {
headers: {
'Authorization': `Bearer ${notification.data.access_token}`,
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
method: action.method,
method: method,
credentials: 'include',
});
}).then(res => {
if (res.ok) {
return res;
} else {
throw new Error(res.status);
}
}).then(res => res.json());
};
const formatMessage = (messageId, locale, values = {}) =>
(new IntlMessageFormat(locales[locale][messageId], locale)).format(values);
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 notify(options);
})
);
};
const actionExpand = preferred_locale => ({
action: 'expand',
icon: '/web-push-icon_expand.png',
title: formatMessage('status.show_more', preferred_locale),
});
const actionReblog = preferred_locale => ({
action: 'reblog',
icon: '/web-push-icon_reblog.png',
title: formatMessage('status.reblog', preferred_locale),
});
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();