notifications.js 9.6 KB

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