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.

234 lines
7.7 KiB

  1. import api, { getLinks } from '../api';
  2. import IntlMessageFormat from 'intl-messageformat';
  3. import { 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 { getFiltersRegex } from '../selectors';
  16. import { usePendingItems as preferPendingItems } from 'mastodon/initial_state';
  17. import compareId from 'mastodon/compare_id';
  18. import { searchTextFromRawStatus } from 'mastodon/actions/importer/normalizer';
  19. export const NOTIFICATIONS_UPDATE = 'NOTIFICATIONS_UPDATE';
  20. export const NOTIFICATIONS_UPDATE_NOOP = 'NOTIFICATIONS_UPDATE_NOOP';
  21. export const NOTIFICATIONS_EXPAND_REQUEST = 'NOTIFICATIONS_EXPAND_REQUEST';
  22. export const NOTIFICATIONS_EXPAND_SUCCESS = 'NOTIFICATIONS_EXPAND_SUCCESS';
  23. export const NOTIFICATIONS_EXPAND_FAIL = 'NOTIFICATIONS_EXPAND_FAIL';
  24. export const NOTIFICATIONS_FILTER_SET = 'NOTIFICATIONS_FILTER_SET';
  25. export const NOTIFICATIONS_CLEAR = 'NOTIFICATIONS_CLEAR';
  26. export const NOTIFICATIONS_SCROLL_TOP = 'NOTIFICATIONS_SCROLL_TOP';
  27. export const NOTIFICATIONS_LOAD_PENDING = 'NOTIFICATIONS_LOAD_PENDING';
  28. export const NOTIFICATIONS_MOUNT = 'NOTIFICATIONS_MOUNT';
  29. export const NOTIFICATIONS_UNMOUNT = 'NOTIFICATIONS_UNMOUNT';
  30. defineMessages({
  31. mention: { id: 'notification.mention', defaultMessage: '{name} mentioned you' },
  32. group: { id: 'notifications.group', defaultMessage: '{count} notifications' },
  33. });
  34. const fetchRelatedRelationships = (dispatch, notifications) => {
  35. const accountIds = notifications.filter(item => item.type === 'follow').map(item => item.account.id);
  36. if (accountIds.length > 0) {
  37. dispatch(fetchRelationships(accountIds));
  38. }
  39. };
  40. export const loadPending = () => ({
  41. type: NOTIFICATIONS_LOAD_PENDING,
  42. });
  43. export function updateNotifications(notification, intlMessages, intlLocale) {
  44. return (dispatch, getState) => {
  45. const showInColumn = getState().getIn(['settings', 'notifications', 'shows', notification.type], true);
  46. const showAlert = getState().getIn(['settings', 'notifications', 'alerts', notification.type], true);
  47. const playSound = getState().getIn(['settings', 'notifications', 'sounds', notification.type], true);
  48. const filters = getFiltersRegex(getState(), { contextType: 'notifications' });
  49. let filtered = false;
  50. if (['mention', 'status'].includes(notification.type)) {
  51. const dropRegex = filters[0];
  52. const regex = filters[1];
  53. const searchIndex = searchTextFromRawStatus(notification.status);
  54. if (dropRegex && dropRegex.test(searchIndex)) {
  55. return;
  56. }
  57. filtered = regex && regex.test(searchIndex);
  58. }
  59. dispatch(submitMarkers());
  60. if (showInColumn) {
  61. dispatch(importFetchedAccount(notification.account));
  62. if (notification.status) {
  63. dispatch(importFetchedStatus(notification.status));
  64. }
  65. dispatch({
  66. type: NOTIFICATIONS_UPDATE,
  67. notification,
  68. usePendingItems: preferPendingItems,
  69. meta: (playSound && !filtered) ? { sound: 'boop' } : undefined,
  70. });
  71. fetchRelatedRelationships(dispatch, [notification]);
  72. } else if (playSound && !filtered) {
  73. dispatch({
  74. type: NOTIFICATIONS_UPDATE_NOOP,
  75. meta: { sound: 'boop' },
  76. });
  77. }
  78. // Desktop notifications
  79. if (typeof window.Notification !== 'undefined' && showAlert && !filtered) {
  80. const title = new IntlMessageFormat(intlMessages[`notification.${notification.type}`], intlLocale).format({ name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
  81. const body = (notification.status && notification.status.spoiler_text.length > 0) ? notification.status.spoiler_text : unescapeHTML(notification.status ? notification.status.content : '');
  82. const notify = new Notification(title, { body, icon: notification.account.avatar, tag: notification.id });
  83. notify.addEventListener('click', () => {
  84. window.focus();
  85. notify.close();
  86. });
  87. }
  88. };
  89. };
  90. const excludeTypesFromSettings = state => state.getIn(['settings', 'notifications', 'shows']).filter(enabled => !enabled).keySeq().toJS();
  91. const excludeTypesFromFilter = filter => {
  92. const allTypes = ImmutableList(['follow', 'follow_request', 'favourite', 'reblog', 'mention', 'poll']);
  93. return allTypes.filterNot(item => item === filter).toJS();
  94. };
  95. const noOp = () => {};
  96. export function expandNotifications({ maxId } = {}, done = noOp) {
  97. return (dispatch, getState) => {
  98. const activeFilter = getState().getIn(['settings', 'notifications', 'quickFilter', 'active']);
  99. const notifications = getState().get('notifications');
  100. const isLoadingMore = !!maxId;
  101. if (notifications.get('isLoading')) {
  102. done();
  103. return;
  104. }
  105. const params = {
  106. max_id: maxId,
  107. exclude_types: activeFilter === 'all'
  108. ? excludeTypesFromSettings(getState())
  109. : excludeTypesFromFilter(activeFilter),
  110. };
  111. if (!params.max_id && (notifications.get('items', ImmutableList()).size + notifications.get('pendingItems', ImmutableList()).size) > 0) {
  112. const a = notifications.getIn(['pendingItems', 0, 'id']);
  113. const b = notifications.getIn(['items', 0, 'id']);
  114. if (a && b && compareId(a, b) > 0) {
  115. params.since_id = a;
  116. } else {
  117. params.since_id = b || a;
  118. }
  119. }
  120. const isLoadingRecent = !!params.since_id;
  121. dispatch(expandNotificationsRequest(isLoadingMore));
  122. api(getState).get('/api/v1/notifications', { params }).then(response => {
  123. const next = getLinks(response).refs.find(link => link.rel === 'next');
  124. dispatch(importFetchedAccounts(response.data.map(item => item.account)));
  125. dispatch(importFetchedStatuses(response.data.map(item => item.status).filter(status => !!status)));
  126. dispatch(expandNotificationsSuccess(response.data, next ? next.uri : null, isLoadingMore, isLoadingRecent, isLoadingRecent && preferPendingItems));
  127. fetchRelatedRelationships(dispatch, response.data);
  128. dispatch(submitMarkers());
  129. }).catch(error => {
  130. dispatch(expandNotificationsFail(error, isLoadingMore));
  131. }).finally(() => {
  132. done();
  133. });
  134. };
  135. };
  136. export function expandNotificationsRequest(isLoadingMore) {
  137. return {
  138. type: NOTIFICATIONS_EXPAND_REQUEST,
  139. skipLoading: !isLoadingMore,
  140. };
  141. };
  142. export function expandNotificationsSuccess(notifications, next, isLoadingMore, isLoadingRecent, usePendingItems) {
  143. return {
  144. type: NOTIFICATIONS_EXPAND_SUCCESS,
  145. notifications,
  146. next,
  147. isLoadingRecent: isLoadingRecent,
  148. usePendingItems,
  149. skipLoading: !isLoadingMore,
  150. };
  151. };
  152. export function expandNotificationsFail(error, isLoadingMore) {
  153. return {
  154. type: NOTIFICATIONS_EXPAND_FAIL,
  155. error,
  156. skipLoading: !isLoadingMore,
  157. skipAlert: !isLoadingMore,
  158. };
  159. };
  160. export function clearNotifications() {
  161. return (dispatch, getState) => {
  162. dispatch({
  163. type: NOTIFICATIONS_CLEAR,
  164. });
  165. api(getState).post('/api/v1/notifications/clear');
  166. };
  167. };
  168. export function scrollTopNotifications(top) {
  169. return {
  170. type: NOTIFICATIONS_SCROLL_TOP,
  171. top,
  172. };
  173. };
  174. export function setFilter (filterType) {
  175. return dispatch => {
  176. dispatch({
  177. type: NOTIFICATIONS_FILTER_SET,
  178. path: ['notifications', 'quickFilter', 'active'],
  179. value: filterType,
  180. });
  181. dispatch(expandNotifications());
  182. dispatch(saveSettings());
  183. };
  184. };
  185. export const mountNotifications = () => ({
  186. type: NOTIFICATIONS_MOUNT,
  187. });
  188. export const unmountNotifications = () => ({
  189. type: NOTIFICATIONS_UNMOUNT,
  190. });