The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

212 lines
8.1 KiB

  1. import IntlMessageFormat from 'intl-messageformat';
  2. import locales from './web_push_locales';
  3. import { unescape } from 'lodash';
  4. const MAX_NOTIFICATIONS = 5;
  5. const GROUP_TAG = 'tag';
  6. const notify = options =>
  7. self.registration.getNotifications().then(notifications => {
  8. if (notifications.length >= MAX_NOTIFICATIONS) { // Reached the maximum number of notifications, proceed with grouping
  9. const group = {
  10. title: formatMessage('notifications.group', options.data.preferred_locale, { count: notifications.length + 1 }),
  11. body: notifications.sort((n1, n2) => n1.timestamp < n2.timestamp).map(notification => notification.title).join('\n'),
  12. badge: '/badge.png',
  13. icon: '/android-chrome-192x192.png',
  14. tag: GROUP_TAG,
  15. data: {
  16. url: (new URL('/web/notifications', self.location)).href,
  17. count: notifications.length + 1,
  18. preferred_locale: options.data.preferred_locale,
  19. },
  20. };
  21. notifications.forEach(notification => notification.close());
  22. return self.registration.showNotification(group.title, group);
  23. } else if (notifications.length === 1 && notifications[0].tag === GROUP_TAG) { // Already grouped, proceed with appending the notification to the group
  24. const group = cloneNotification(notifications[0]);
  25. group.title = formatMessage('notifications.group', options.data.preferred_locale, { count: group.data.count + 1 });
  26. group.body = `${options.title}\n${group.body}`;
  27. group.data = { ...group.data, count: group.data.count + 1 };
  28. return self.registration.showNotification(group.title, group);
  29. }
  30. return self.registration.showNotification(options.title, options);
  31. });
  32. const fetchFromApi = (path, method, accessToken) => {
  33. const url = (new URL(path, self.location)).href;
  34. return fetch(url, {
  35. headers: {
  36. 'Authorization': `Bearer ${accessToken}`,
  37. 'Content-Type': 'application/json',
  38. },
  39. method: method,
  40. credentials: 'include',
  41. }).then(res => {
  42. if (res.ok) {
  43. return res;
  44. } else {
  45. throw new Error(res.status);
  46. }
  47. }).then(res => res.json());
  48. };
  49. const cloneNotification = notification => {
  50. const clone = {};
  51. let k;
  52. // Object.assign() does not work with notifications
  53. for(k in notification) {
  54. clone[k] = notification[k];
  55. }
  56. return clone;
  57. };
  58. const formatMessage = (messageId, locale, values = {}) =>
  59. (new IntlMessageFormat(locales[locale][messageId], locale)).format(values);
  60. const htmlToPlainText = html =>
  61. unescape(html.replace(/<br\s*\/?>/g, '\n').replace(/<\/p><p>/g, '\n\n').replace(/<[^>]*>/g, ''));
  62. const handlePush = (event) => {
  63. const { access_token, notification_id, preferred_locale, title, body, icon } = event.data.json();
  64. // Placeholder until more information can be loaded
  65. event.waitUntil(
  66. notify({
  67. title,
  68. body,
  69. icon,
  70. tag: notification_id,
  71. timestamp: new Date(),
  72. badge: '/badge.png',
  73. data: { access_token, preferred_locale, url: '/web/notifications' },
  74. }).then(() => fetchFromApi(`/api/v1/notifications/${notification_id}`, 'get', access_token)).then(notification => {
  75. const options = {};
  76. options.title = formatMessage(`notification.${notification.type}`, preferred_locale, { name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
  77. options.body = notification.status && htmlToPlainText(notification.status.content);
  78. options.icon = notification.account.avatar_static;
  79. options.timestamp = notification.created_at && new Date(notification.created_at);
  80. options.tag = notification.id;
  81. options.badge = '/badge.png';
  82. options.image = notification.status && notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url || undefined;
  83. 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}` };
  84. if (notification.status && notification.status.sensitive) {
  85. options.data.hiddenBody = htmlToPlainText(notification.status.content);
  86. options.data.hiddenImage = notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url;
  87. options.body = notification.status.spoiler_text;
  88. options.image = undefined;
  89. options.actions = [actionExpand(preferred_locale)];
  90. } else if (notification.type === 'mention') {
  91. options.actions = [actionReblog(preferred_locale), actionFavourite(preferred_locale)];
  92. }
  93. return notify(options);
  94. })
  95. );
  96. };
  97. const actionExpand = preferred_locale => ({
  98. action: 'expand',
  99. icon: '/web-push-icon_expand.png',
  100. title: formatMessage('status.show_more', preferred_locale),
  101. });
  102. const actionReblog = preferred_locale => ({
  103. action: 'reblog',
  104. icon: '/web-push-icon_reblog.png',
  105. title: formatMessage('status.reblog', preferred_locale),
  106. });
  107. const actionFavourite = preferred_locale => ({
  108. action: 'favourite',
  109. icon: '/web-push-icon_favourite.png',
  110. title: formatMessage('status.favourite', preferred_locale),
  111. });
  112. const findBestClient = clients => {
  113. const focusedClient = clients.find(client => client.focused);
  114. const visibleClient = clients.find(client => client.visibilityState === 'visible');
  115. return focusedClient || visibleClient || clients[0];
  116. };
  117. const expandNotification = notification => {
  118. const newNotification = cloneNotification(notification);
  119. newNotification.body = newNotification.data.hiddenBody;
  120. newNotification.image = newNotification.data.hiddenImage;
  121. newNotification.actions = [actionReblog(notification.data.preferred_locale), actionFavourite(notification.data.preferred_locale)];
  122. return self.registration.showNotification(newNotification.title, newNotification);
  123. };
  124. const removeActionFromNotification = (notification, action) => {
  125. const newNotification = cloneNotification(notification);
  126. newNotification.actions = newNotification.actions.filter(item => item.action !== action);
  127. return self.registration.showNotification(newNotification.title, newNotification);
  128. };
  129. const openUrl = url =>
  130. self.clients.matchAll({ type: 'window' }).then(clientList => {
  131. if (clientList.length !== 0) {
  132. const webClients = clientList.filter(client => /\/web\//.test(client.url));
  133. if (webClients.length !== 0) {
  134. const client = findBestClient(webClients);
  135. const { pathname } = new URL(url);
  136. if (pathname.startsWith('/web/')) {
  137. return client.focus().then(client => client.postMessage({
  138. type: 'navigate',
  139. path: pathname.slice('/web/'.length - 1),
  140. }));
  141. }
  142. } else if ('navigate' in clientList[0]) { // Chrome 42-48 does not support navigate
  143. const client = findBestClient(clientList);
  144. return client.navigate(url).then(client => client.focus());
  145. }
  146. }
  147. return self.clients.openWindow(url);
  148. });
  149. const handleNotificationClick = (event) => {
  150. const reactToNotificationClick = new Promise((resolve, reject) => {
  151. if (event.action) {
  152. if (event.action === 'expand') {
  153. resolve(expandNotification(event.notification));
  154. } else if (event.action === 'reblog') {
  155. const { data } = event.notification;
  156. resolve(fetchFromApi(`/api/v1/statuses/${data.id}/reblog`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'reblog')));
  157. } else if (event.action === 'favourite') {
  158. const { data } = event.notification;
  159. resolve(fetchFromApi(`/api/v1/statuses/${data.id}/favourite`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'favourite')));
  160. } else {
  161. reject(`Unknown action: ${event.action}`);
  162. }
  163. } else {
  164. event.notification.close();
  165. resolve(openUrl(event.notification.data.url));
  166. }
  167. });
  168. event.waitUntil(reactToNotificationClick);
  169. };
  170. self.addEventListener('push', handlePush);
  171. self.addEventListener('notificationclick', handleNotificationClick);