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.
 
 
 
 

214 rivejä
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. fetchFromApi(`/api/v1/notifications/${notification_id}`, 'get', access_token).then(notification => {
  67. const options = {};
  68. options.title = formatMessage(`notification.${notification.type}`, preferred_locale, { name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
  69. options.body = notification.status && htmlToPlainText(notification.status.content);
  70. options.icon = notification.account.avatar_static;
  71. options.timestamp = notification.created_at && new Date(notification.created_at);
  72. options.tag = notification.id;
  73. options.badge = '/badge.png';
  74. options.image = notification.status && notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url || undefined;
  75. 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}` };
  76. if (notification.status && notification.status.sensitive) {
  77. options.data.hiddenBody = htmlToPlainText(notification.status.content);
  78. options.data.hiddenImage = notification.status.media_attachments.length > 0 && notification.status.media_attachments[0].preview_url;
  79. options.body = notification.status.spoiler_text;
  80. options.image = undefined;
  81. options.actions = [actionExpand(preferred_locale)];
  82. } else if (notification.type === 'mention') {
  83. options.actions = [actionReblog(preferred_locale), actionFavourite(preferred_locale)];
  84. }
  85. return notify(options);
  86. }).catch(() => {
  87. return notify({
  88. title,
  89. body,
  90. icon,
  91. tag: notification_id,
  92. timestamp: new Date(),
  93. badge: '/badge.png',
  94. data: { access_token, preferred_locale, url: '/web/notifications' },
  95. });
  96. })
  97. );
  98. };
  99. const actionExpand = preferred_locale => ({
  100. action: 'expand',
  101. icon: '/web-push-icon_expand.png',
  102. title: formatMessage('status.show_more', preferred_locale),
  103. });
  104. const actionReblog = preferred_locale => ({
  105. action: 'reblog',
  106. icon: '/web-push-icon_reblog.png',
  107. title: formatMessage('status.reblog', preferred_locale),
  108. });
  109. const actionFavourite = preferred_locale => ({
  110. action: 'favourite',
  111. icon: '/web-push-icon_favourite.png',
  112. title: formatMessage('status.favourite', preferred_locale),
  113. });
  114. const findBestClient = clients => {
  115. const focusedClient = clients.find(client => client.focused);
  116. const visibleClient = clients.find(client => client.visibilityState === 'visible');
  117. return focusedClient || visibleClient || clients[0];
  118. };
  119. const expandNotification = notification => {
  120. const newNotification = cloneNotification(notification);
  121. newNotification.body = newNotification.data.hiddenBody;
  122. newNotification.image = newNotification.data.hiddenImage;
  123. newNotification.actions = [actionReblog(notification.data.preferred_locale), actionFavourite(notification.data.preferred_locale)];
  124. return self.registration.showNotification(newNotification.title, newNotification);
  125. };
  126. const removeActionFromNotification = (notification, action) => {
  127. const newNotification = cloneNotification(notification);
  128. newNotification.actions = newNotification.actions.filter(item => item.action !== action);
  129. return self.registration.showNotification(newNotification.title, newNotification);
  130. };
  131. const openUrl = url =>
  132. self.clients.matchAll({ type: 'window' }).then(clientList => {
  133. if (clientList.length !== 0) {
  134. const webClients = clientList.filter(client => /\/web\//.test(client.url));
  135. if (webClients.length !== 0) {
  136. const client = findBestClient(webClients);
  137. const { pathname } = new URL(url);
  138. if (pathname.startsWith('/web/')) {
  139. return client.focus().then(client => client.postMessage({
  140. type: 'navigate',
  141. path: pathname.slice('/web/'.length - 1),
  142. }));
  143. }
  144. } else if ('navigate' in clientList[0]) { // Chrome 42-48 does not support navigate
  145. const client = findBestClient(clientList);
  146. return client.navigate(url).then(client => client.focus());
  147. }
  148. }
  149. return self.clients.openWindow(url);
  150. });
  151. const handleNotificationClick = (event) => {
  152. const reactToNotificationClick = new Promise((resolve, reject) => {
  153. if (event.action) {
  154. if (event.action === 'expand') {
  155. resolve(expandNotification(event.notification));
  156. } else if (event.action === 'reblog') {
  157. const { data } = event.notification;
  158. resolve(fetchFromApi(`/api/v1/statuses/${data.id}/reblog`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'reblog')));
  159. } else if (event.action === 'favourite') {
  160. const { data } = event.notification;
  161. resolve(fetchFromApi(`/api/v1/statuses/${data.id}/favourite`, 'post', data.access_token).then(() => removeActionFromNotification(event.notification, 'favourite')));
  162. } else {
  163. reject(`Unknown action: ${event.action}`);
  164. }
  165. } else {
  166. event.notification.close();
  167. resolve(openUrl(event.notification.data.url));
  168. }
  169. });
  170. event.waitUntil(reactToNotificationClick);
  171. };
  172. self.addEventListener('push', handlePush);
  173. self.addEventListener('notificationclick', handleNotificationClick);