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.

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