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.

285 lines
9.1 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. import { requestNotificationPermission } from '../utils/notifications';
  20. export const NOTIFICATIONS_UPDATE = 'NOTIFICATIONS_UPDATE';
  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 => item.type === 'follow').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 showInColumn = getState().getIn(['settings', 'notifications', 'shows', notification.type], true);
  50. const showAlert = getState().getIn(['settings', 'notifications', 'alerts', notification.type], true);
  51. const playSound = getState().getIn(['settings', 'notifications', 'sounds', notification.type], true);
  52. const filters = getFiltersRegex(getState(), { contextType: 'notifications' });
  53. let filtered = false;
  54. if (['mention', 'status'].includes(notification.type)) {
  55. const dropRegex = filters[0];
  56. const regex = filters[1];
  57. const searchIndex = searchTextFromRawStatus(notification.status);
  58. if (dropRegex && dropRegex.test(searchIndex)) {
  59. return;
  60. }
  61. filtered = regex && regex.test(searchIndex);
  62. }
  63. dispatch(submitMarkers());
  64. if (showInColumn) {
  65. dispatch(importFetchedAccount(notification.account));
  66. if (notification.status) {
  67. dispatch(importFetchedStatus(notification.status));
  68. }
  69. dispatch({
  70. type: NOTIFICATIONS_UPDATE,
  71. notification,
  72. usePendingItems: preferPendingItems,
  73. meta: (playSound && !filtered) ? { sound: 'boop' } : undefined,
  74. });
  75. fetchRelatedRelationships(dispatch, [notification]);
  76. } else if (playSound && !filtered) {
  77. dispatch({
  78. type: NOTIFICATIONS_UPDATE_NOOP,
  79. meta: { sound: 'boop' },
  80. });
  81. }
  82. // Desktop notifications
  83. if (typeof window.Notification !== 'undefined' && showAlert && !filtered) {
  84. const title = new IntlMessageFormat(intlMessages[`notification.${notification.type}`], intlLocale).format({ name: notification.account.display_name.length > 0 ? notification.account.display_name : notification.account.username });
  85. const body = (notification.status && notification.status.spoiler_text.length > 0) ? notification.status.spoiler_text : unescapeHTML(notification.status ? notification.status.content : '');
  86. const notify = new Notification(title, { body, icon: notification.account.avatar, tag: notification.id });
  87. notify.addEventListener('click', () => {
  88. window.focus();
  89. notify.close();
  90. });
  91. }
  92. };
  93. };
  94. const excludeTypesFromSettings = state => state.getIn(['settings', 'notifications', 'shows']).filter(enabled => !enabled).keySeq().toJS();
  95. const excludeTypesFromFilter = filter => {
  96. const allTypes = ImmutableList(['follow', 'follow_request', 'favourite', 'reblog', 'mention', 'poll']);
  97. return allTypes.filterNot(item => item === filter).toJS();
  98. };
  99. const noOp = () => {};
  100. export function expandNotifications({ maxId } = {}, done = noOp) {
  101. return (dispatch, getState) => {
  102. const activeFilter = getState().getIn(['settings', 'notifications', 'quickFilter', 'active']);
  103. const notifications = getState().get('notifications');
  104. const isLoadingMore = !!maxId;
  105. if (notifications.get('isLoading')) {
  106. done();
  107. return;
  108. }
  109. const params = {
  110. max_id: maxId,
  111. exclude_types: activeFilter === 'all'
  112. ? excludeTypesFromSettings(getState())
  113. : excludeTypesFromFilter(activeFilter),
  114. };
  115. if (!params.max_id && (notifications.get('items', ImmutableList()).size + notifications.get('pendingItems', ImmutableList()).size) > 0) {
  116. const a = notifications.getIn(['pendingItems', 0, 'id']);
  117. const b = notifications.getIn(['items', 0, 'id']);
  118. if (a && b && compareId(a, b) > 0) {
  119. params.since_id = a;
  120. } else {
  121. params.since_id = b || a;
  122. }
  123. }
  124. const isLoadingRecent = !!params.since_id;
  125. dispatch(expandNotificationsRequest(isLoadingMore));
  126. api(getState).get('/api/v1/notifications', { params }).then(response => {
  127. const next = getLinks(response).refs.find(link => link.rel === 'next');
  128. dispatch(importFetchedAccounts(response.data.map(item => item.account)));
  129. dispatch(importFetchedStatuses(response.data.map(item => item.status).filter(status => !!status)));
  130. dispatch(expandNotificationsSuccess(response.data, next ? next.uri : null, isLoadingMore, isLoadingRecent, isLoadingRecent && preferPendingItems));
  131. fetchRelatedRelationships(dispatch, response.data);
  132. dispatch(submitMarkers());
  133. }).catch(error => {
  134. dispatch(expandNotificationsFail(error, isLoadingMore));
  135. }).finally(() => {
  136. done();
  137. });
  138. };
  139. };
  140. export function expandNotificationsRequest(isLoadingMore) {
  141. return {
  142. type: NOTIFICATIONS_EXPAND_REQUEST,
  143. skipLoading: !isLoadingMore,
  144. };
  145. };
  146. export function expandNotificationsSuccess(notifications, next, isLoadingMore, isLoadingRecent, usePendingItems) {
  147. return {
  148. type: NOTIFICATIONS_EXPAND_SUCCESS,
  149. notifications,
  150. next,
  151. isLoadingRecent: isLoadingRecent,
  152. usePendingItems,
  153. skipLoading: !isLoadingMore,
  154. };
  155. };
  156. export function expandNotificationsFail(error, isLoadingMore) {
  157. return {
  158. type: NOTIFICATIONS_EXPAND_FAIL,
  159. error,
  160. skipLoading: !isLoadingMore,
  161. skipAlert: !isLoadingMore,
  162. };
  163. };
  164. export function clearNotifications() {
  165. return (dispatch, getState) => {
  166. dispatch({
  167. type: NOTIFICATIONS_CLEAR,
  168. });
  169. api(getState).post('/api/v1/notifications/clear');
  170. };
  171. };
  172. export function scrollTopNotifications(top) {
  173. return {
  174. type: NOTIFICATIONS_SCROLL_TOP,
  175. top,
  176. };
  177. };
  178. export function setFilter (filterType) {
  179. return dispatch => {
  180. dispatch({
  181. type: NOTIFICATIONS_FILTER_SET,
  182. path: ['notifications', 'quickFilter', 'active'],
  183. value: filterType,
  184. });
  185. dispatch(expandNotifications());
  186. dispatch(saveSettings());
  187. };
  188. };
  189. export const mountNotifications = () => ({
  190. type: NOTIFICATIONS_MOUNT,
  191. });
  192. export const unmountNotifications = () => ({
  193. type: NOTIFICATIONS_UNMOUNT,
  194. });
  195. export const markNotificationsAsRead = () => ({
  196. type: NOTIFICATIONS_MARK_AS_READ,
  197. });
  198. // Browser support
  199. export function setupBrowserNotifications() {
  200. return dispatch => {
  201. dispatch(setBrowserSupport('Notification' in window));
  202. if ('Notification' in window) {
  203. dispatch(setBrowserPermission(Notification.permission));
  204. }
  205. if ('Notification' in window && 'permissions' in navigator) {
  206. navigator.permissions.query({ name: 'notifications' }).then((status) => {
  207. status.onchange = () => dispatch(setBrowserPermission(Notification.permission));
  208. }).catch(console.warn);
  209. }
  210. };
  211. }
  212. export function requestBrowserPermission(callback = noOp) {
  213. return dispatch => {
  214. requestNotificationPermission((permission) => {
  215. dispatch(setBrowserPermission(permission));
  216. callback(permission);
  217. });
  218. };
  219. };
  220. export function setBrowserSupport (value) {
  221. return {
  222. type: NOTIFICATIONS_SET_BROWSER_SUPPORT,
  223. value,
  224. };
  225. }
  226. export function setBrowserPermission (value) {
  227. return {
  228. type: NOTIFICATIONS_SET_BROWSER_PERMISSION,
  229. value,
  230. };
  231. }