notifications.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { IntlMessageFormat } from 'intl-messageformat';
  2. import { defineMessages } from 'react-intl';
  3. import { List as ImmutableList } from 'immutable';
  4. import { compareId } from 'mastodon/compare_id';
  5. import { usePendingItems as preferPendingItems } from 'mastodon/initial_state';
  6. import api, { getLinks } from '../api';
  7. import { unescapeHTML } from '../utils/html';
  8. import { requestNotificationPermission } from '../utils/notifications';
  9. import { fetchFollowRequests, fetchRelationships } from './accounts';
  10. import {
  11. importFetchedAccount,
  12. importFetchedAccounts,
  13. importFetchedStatus,
  14. importFetchedStatuses,
  15. } from './importer';
  16. import { submitMarkers } from './markers';
  17. import { notificationsUpdate } from "./notifications_typed";
  18. import { register as registerPushNotifications } from './push_notifications';
  19. import { saveSettings } from './settings';
  20. export * from "./notifications_typed";
  21. export const NOTIFICATIONS_UPDATE_NOOP = 'NOTIFICATIONS_UPDATE_NOOP';
  22. export const NOTIFICATIONS_EXPAND_REQUEST = 'NOTIFICATIONS_EXPAND_REQUEST';
  23. export const NOTIFICATIONS_EXPAND_SUCCESS = 'NOTIFICATIONS_EXPAND_SUCCESS';
  24. export const NOTIFICATIONS_EXPAND_FAIL = 'NOTIFICATIONS_EXPAND_FAIL';
  25. export const NOTIFICATIONS_FILTER_SET = 'NOTIFICATIONS_FILTER_SET';
  26. export const NOTIFICATIONS_CLEAR = 'NOTIFICATIONS_CLEAR';
  27. export const NOTIFICATIONS_SCROLL_TOP = 'NOTIFICATIONS_SCROLL_TOP';
  28. export const NOTIFICATIONS_LOAD_PENDING = 'NOTIFICATIONS_LOAD_PENDING';
  29. export const NOTIFICATIONS_MOUNT = 'NOTIFICATIONS_MOUNT';
  30. export const NOTIFICATIONS_UNMOUNT = 'NOTIFICATIONS_UNMOUNT';
  31. export const NOTIFICATIONS_MARK_AS_READ = 'NOTIFICATIONS_MARK_AS_READ';
  32. export const NOTIFICATIONS_SET_BROWSER_SUPPORT = 'NOTIFICATIONS_SET_BROWSER_SUPPORT';
  33. export const NOTIFICATIONS_SET_BROWSER_PERMISSION = 'NOTIFICATIONS_SET_BROWSER_PERMISSION';
  34. defineMessages({
  35. mention: { id: 'notification.mention', defaultMessage: '{name} mentioned you' },
  36. group: { id: 'notifications.group', defaultMessage: '{count} notifications' },
  37. });
  38. const fetchRelatedRelationships = (dispatch, notifications) => {
  39. const accountIds = notifications.filter(item => ['follow', 'follow_request', 'admin.sign_up'].indexOf(item.type) !== -1).map(item => item.account.id);
  40. if (accountIds.length > 0) {
  41. dispatch(fetchRelationships(accountIds));
  42. }
  43. };
  44. export const loadPending = () => ({
  45. type: NOTIFICATIONS_LOAD_PENDING,
  46. });
  47. export function updateNotifications(notification, intlMessages, intlLocale) {
  48. return (dispatch, getState) => {
  49. const activeFilter = getState().getIn(['settings', 'notifications', 'quickFilter', 'active']);
  50. const showInColumn = activeFilter === 'all' ? getState().getIn(['settings', 'notifications', 'shows', notification.type], true) : activeFilter === notification.type;
  51. const showAlert = getState().getIn(['settings', 'notifications', 'alerts', notification.type], true);
  52. const playSound = getState().getIn(['settings', 'notifications', 'sounds', notification.type], true);
  53. let filtered = false;
  54. if (['mention', 'status'].includes(notification.type) && notification.status.filtered) {
  55. const filters = notification.status.filtered.filter(result => result.filter.context.includes('notifications'));
  56. if (filters.some(result => result.filter.filter_action === 'hide')) {
  57. return;
  58. }
  59. filtered = filters.length > 0;
  60. }
  61. if (['follow_request'].includes(notification.type)) {
  62. dispatch(fetchFollowRequests());
  63. }
  64. dispatch(submitMarkers());
  65. if (showInColumn) {
  66. dispatch(importFetchedAccount(notification.account));
  67. if (notification.status) {
  68. dispatch(importFetchedStatus(notification.status));
  69. }
  70. if (notification.report) {
  71. dispatch(importFetchedAccount(notification.report.target_account));
  72. }
  73. dispatch(notificationsUpdate({ notification, preferPendingItems, playSound: playSound && !filtered}));
  74. fetchRelatedRelationships(dispatch, [notification]);
  75. } else if (playSound && !filtered) {
  76. dispatch({
  77. type: NOTIFICATIONS_UPDATE_NOOP,
  78. meta: { sound: 'boop' },
  79. });
  80. }
  81. // Desktop notifications
  82. if (typeof window.Notification !== 'undefined' && showAlert && !filtered) {
  83. const title = new IntlMessageFormat(intlMessages[`notification.${notification.type}`], intlLocale).format({ name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
  84. const body = (notification.status && notification.status.spoiler_text.length > 0) ? notification.status.spoiler_text : unescapeHTML(notification.status ? notification.status.content : '');
  85. const notify = new Notification(title, { body, icon: notification.account.avatar, tag: notification.id });
  86. notify.addEventListener('click', () => {
  87. window.focus();
  88. notify.close();
  89. });
  90. }
  91. };
  92. }
  93. const excludeTypesFromSettings = state => state.getIn(['settings', 'notifications', 'shows']).filter(enabled => !enabled).keySeq().toJS();
  94. const excludeTypesFromFilter = filter => {
  95. const allTypes = ImmutableList([
  96. 'follow',
  97. 'follow_request',
  98. 'favourite',
  99. 'reblog',
  100. 'mention',
  101. 'poll',
  102. 'status',
  103. 'update',
  104. 'admin.sign_up',
  105. 'admin.report',
  106. ]);
  107. return allTypes.filterNot(item => item === filter).toJS();
  108. };
  109. const noOp = () => {};
  110. let expandNotificationsController = new AbortController();
  111. export function expandNotifications({ maxId, forceLoad } = {}, done = noOp) {
  112. return (dispatch, getState) => {
  113. const activeFilter = getState().getIn(['settings', 'notifications', 'quickFilter', 'active']);
  114. const notifications = getState().get('notifications');
  115. const isLoadingMore = !!maxId;
  116. if (notifications.get('isLoading')) {
  117. if (forceLoad) {
  118. expandNotificationsController.abort();
  119. expandNotificationsController = new AbortController();
  120. } else {
  121. done();
  122. return;
  123. }
  124. }
  125. const params = {
  126. max_id: maxId,
  127. exclude_types: activeFilter === 'all'
  128. ? excludeTypesFromSettings(getState())
  129. : excludeTypesFromFilter(activeFilter),
  130. };
  131. if (!params.max_id && (notifications.get('items', ImmutableList()).size + notifications.get('pendingItems', ImmutableList()).size) > 0) {
  132. const a = notifications.getIn(['pendingItems', 0, 'id']);
  133. const b = notifications.getIn(['items', 0, 'id']);
  134. if (a && b && compareId(a, b) > 0) {
  135. params.since_id = a;
  136. } else {
  137. params.since_id = b || a;
  138. }
  139. }
  140. const isLoadingRecent = !!params.since_id;
  141. dispatch(expandNotificationsRequest(isLoadingMore));
  142. api(getState).get('/api/v1/notifications', { params, signal: expandNotificationsController.signal }).then(response => {
  143. const next = getLinks(response).refs.find(link => link.rel === 'next');
  144. dispatch(importFetchedAccounts(response.data.map(item => item.account)));
  145. dispatch(importFetchedStatuses(response.data.map(item => item.status).filter(status => !!status)));
  146. dispatch(importFetchedAccounts(response.data.filter(item => item.report).map(item => item.report.target_account)));
  147. dispatch(expandNotificationsSuccess(response.data, next ? next.uri : null, isLoadingMore, isLoadingRecent, isLoadingRecent && preferPendingItems));
  148. fetchRelatedRelationships(dispatch, response.data);
  149. dispatch(submitMarkers());
  150. }).catch(error => {
  151. dispatch(expandNotificationsFail(error, isLoadingMore));
  152. }).finally(() => {
  153. done();
  154. });
  155. };
  156. }
  157. export function expandNotificationsRequest(isLoadingMore) {
  158. return {
  159. type: NOTIFICATIONS_EXPAND_REQUEST,
  160. skipLoading: !isLoadingMore,
  161. };
  162. }
  163. export function expandNotificationsSuccess(notifications, next, isLoadingMore, isLoadingRecent, usePendingItems) {
  164. return {
  165. type: NOTIFICATIONS_EXPAND_SUCCESS,
  166. notifications,
  167. next,
  168. isLoadingRecent: isLoadingRecent,
  169. usePendingItems,
  170. skipLoading: !isLoadingMore,
  171. };
  172. }
  173. export function expandNotificationsFail(error, isLoadingMore) {
  174. return {
  175. type: NOTIFICATIONS_EXPAND_FAIL,
  176. error,
  177. skipLoading: !isLoadingMore,
  178. skipAlert: !isLoadingMore || error.name === 'AbortError',
  179. };
  180. }
  181. export function clearNotifications() {
  182. return (dispatch, getState) => {
  183. dispatch({
  184. type: NOTIFICATIONS_CLEAR,
  185. });
  186. api(getState).post('/api/v1/notifications/clear');
  187. };
  188. }
  189. export function scrollTopNotifications(top) {
  190. return {
  191. type: NOTIFICATIONS_SCROLL_TOP,
  192. top,
  193. };
  194. }
  195. export function setFilter (filterType) {
  196. return dispatch => {
  197. dispatch({
  198. type: NOTIFICATIONS_FILTER_SET,
  199. path: ['notifications', 'quickFilter', 'active'],
  200. value: filterType,
  201. });
  202. dispatch(expandNotifications({ forceLoad: true }));
  203. dispatch(saveSettings());
  204. };
  205. }
  206. export const mountNotifications = () => ({
  207. type: NOTIFICATIONS_MOUNT,
  208. });
  209. export const unmountNotifications = () => ({
  210. type: NOTIFICATIONS_UNMOUNT,
  211. });
  212. export const markNotificationsAsRead = () => ({
  213. type: NOTIFICATIONS_MARK_AS_READ,
  214. });
  215. // Browser support
  216. export function setupBrowserNotifications() {
  217. return dispatch => {
  218. dispatch(setBrowserSupport('Notification' in window));
  219. if ('Notification' in window) {
  220. dispatch(setBrowserPermission(Notification.permission));
  221. }
  222. if ('Notification' in window && 'permissions' in navigator) {
  223. navigator.permissions.query({ name: 'notifications' }).then((status) => {
  224. status.onchange = () => dispatch(setBrowserPermission(Notification.permission));
  225. }).catch(console.warn);
  226. }
  227. };
  228. }
  229. export function requestBrowserPermission(callback = noOp) {
  230. return dispatch => {
  231. requestNotificationPermission((permission) => {
  232. dispatch(setBrowserPermission(permission));
  233. callback(permission);
  234. if (permission === 'granted') {
  235. dispatch(registerPushNotifications());
  236. }
  237. });
  238. };
  239. }
  240. export function setBrowserSupport (value) {
  241. return {
  242. type: NOTIFICATIONS_SET_BROWSER_SUPPORT,
  243. value,
  244. };
  245. }
  246. export function setBrowserPermission (value) {
  247. return {
  248. type: NOTIFICATIONS_SET_BROWSER_PERMISSION,
  249. value,
  250. };
  251. }