notifications.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import {
  2. NOTIFICATIONS_UPDATE,
  3. NOTIFICATIONS_EXPAND_SUCCESS,
  4. NOTIFICATIONS_EXPAND_REQUEST,
  5. NOTIFICATIONS_EXPAND_FAIL,
  6. NOTIFICATIONS_FILTER_SET,
  7. NOTIFICATIONS_CLEAR,
  8. NOTIFICATIONS_SCROLL_TOP,
  9. NOTIFICATIONS_LOAD_PENDING,
  10. NOTIFICATIONS_MOUNT,
  11. NOTIFICATIONS_UNMOUNT,
  12. NOTIFICATIONS_MARK_AS_READ,
  13. NOTIFICATIONS_SET_BROWSER_SUPPORT,
  14. NOTIFICATIONS_SET_BROWSER_PERMISSION,
  15. } from '../actions/notifications';
  16. import {
  17. ACCOUNT_BLOCK_SUCCESS,
  18. ACCOUNT_MUTE_SUCCESS,
  19. FOLLOW_REQUEST_AUTHORIZE_SUCCESS,
  20. FOLLOW_REQUEST_REJECT_SUCCESS,
  21. } from '../actions/accounts';
  22. import {
  23. MARKERS_FETCH_SUCCESS,
  24. } from '../actions/markers';
  25. import {
  26. APP_FOCUS,
  27. APP_UNFOCUS,
  28. } from '../actions/app';
  29. import { DOMAIN_BLOCK_SUCCESS } from 'mastodon/actions/domain_blocks';
  30. import { TIMELINE_DELETE, TIMELINE_DISCONNECT } from '../actions/timelines';
  31. import { fromJS, Map as ImmutableMap, List as ImmutableList } from 'immutable';
  32. import compareId from '../compare_id';
  33. const initialState = ImmutableMap({
  34. pendingItems: ImmutableList(),
  35. items: ImmutableList(),
  36. hasMore: true,
  37. top: false,
  38. mounted: 0,
  39. unread: 0,
  40. lastReadId: '0',
  41. readMarkerId: '0',
  42. isTabVisible: true,
  43. isLoading: 0,
  44. browserSupport: false,
  45. browserPermission: 'default',
  46. });
  47. const notificationToMap = notification => ImmutableMap({
  48. id: notification.id,
  49. type: notification.type,
  50. account: notification.account.id,
  51. created_at: notification.created_at,
  52. status: notification.status ? notification.status.id : null,
  53. report: notification.report ? fromJS(notification.report) : null,
  54. });
  55. const normalizeNotification = (state, notification, usePendingItems) => {
  56. const top = state.get('top');
  57. // Under currently unknown conditions, the client may receive duplicates from the server
  58. if (state.get('pendingItems').some((item) => item?.get('id') === notification.id) || state.get('items').some((item) => item?.get('id') === notification.id)) {
  59. return state;
  60. }
  61. if (usePendingItems || !state.get('pendingItems').isEmpty()) {
  62. return state.update('pendingItems', list => list.unshift(notificationToMap(notification))).update('unread', unread => unread + 1);
  63. }
  64. if (shouldCountUnreadNotifications(state)) {
  65. state = state.update('unread', unread => unread + 1);
  66. } else {
  67. state = state.set('lastReadId', notification.id);
  68. }
  69. return state.update('items', list => {
  70. if (top && list.size > 40) {
  71. list = list.take(20);
  72. }
  73. return list.unshift(notificationToMap(notification));
  74. });
  75. };
  76. const expandNormalizedNotifications = (state, notifications, next, isLoadingMore, isLoadingRecent, usePendingItems) => {
  77. // This method is pretty tricky because:
  78. // - existing notifications might be out of order
  79. // - the existing notifications may have gaps, most often explicitly noted with a `null` item
  80. // - ideally, we don't want it to reorder existing items
  81. // - `notifications` may include items that are already included
  82. // - this function can be called either to fill in a gap, or load newer items
  83. const lastReadId = state.get('lastReadId');
  84. const newItems = ImmutableList(notifications.map(notificationToMap));
  85. return state.withMutations(mutable => {
  86. if (!newItems.isEmpty()) {
  87. usePendingItems = isLoadingRecent && (usePendingItems || !mutable.get('pendingItems').isEmpty());
  88. mutable.update(usePendingItems ? 'pendingItems' : 'items', oldItems => {
  89. // If called to poll *new* notifications, we just need to add them on top without duplicates
  90. if (isLoadingRecent) {
  91. const idsToCheck = oldItems.map(item => item?.get('id')).toSet();
  92. const insertedItems = newItems.filterNot(item => idsToCheck.includes(item.get('id')));
  93. return insertedItems.concat(oldItems);
  94. }
  95. // If called to expand more (presumably older than any known to the WebUI), we just have to
  96. // add them to the bottom without duplicates
  97. if (isLoadingMore) {
  98. const idsToCheck = oldItems.map(item => item?.get('id')).toSet();
  99. const insertedItems = newItems.filterNot(item => idsToCheck.includes(item.get('id')));
  100. return oldItems.concat(insertedItems);
  101. }
  102. // Now this gets tricky, as we don't necessarily know for sure where the gap to fill is,
  103. // and some items in the timeline may not be properly ordered.
  104. // However, we know that `newItems.last()` is the oldest item that was requested and that
  105. // there is no “hole” between `newItems.last()` and `newItems.first()`.
  106. // First, find the furthest (if properly sorted, oldest) item in the notifications that is
  107. // newer than the oldest fetched one, as it's most likely that it delimits the gap.
  108. // Start the gap *after* that item.
  109. const lastIndex = oldItems.findLastIndex(item => item !== null && compareId(item.get('id'), newItems.last().get('id')) >= 0) + 1;
  110. // Then, try to find the furthest (if properly sorted, oldest) item in the notifications that
  111. // is newer than the most recent fetched one, as it delimits a section comprised of only
  112. // items older or within `newItems` (or that were deleted from the server, so should be removed
  113. // anyway).
  114. // Stop the gap *after* that item.
  115. const firstIndex = oldItems.take(lastIndex).findLastIndex(item => item !== null && compareId(item.get('id'), newItems.first().get('id')) > 0) + 1;
  116. // At this point:
  117. // - no `oldItems` after `firstIndex` is newer than any of the `newItems`
  118. // - all `oldItems` after `lastIndex` are older than every of the `newItems`
  119. // - it is possible for items in the replaced slice to be older than every `newItems`
  120. // - it is possible for items before `firstIndex` to be in the `newItems` range
  121. // Therefore:
  122. // - to avoid losing items, items from the replaced slice that are older than `newItems`
  123. // should be added in the back.
  124. // - to avoid duplicates, `newItems` should be checked the first `firstIndex` items of
  125. // `oldItems`
  126. const idsToCheck = oldItems.take(firstIndex).map(item => item?.get('id')).toSet();
  127. const insertedItems = newItems.filterNot(item => idsToCheck.includes(item.get('id')));
  128. const olderItems = oldItems.slice(firstIndex, lastIndex).filter(item => item !== null && compareId(item.get('id'), newItems.last().get('id')) < 0);
  129. return oldItems.take(firstIndex).concat(
  130. insertedItems,
  131. olderItems,
  132. oldItems.skip(lastIndex),
  133. );
  134. });
  135. }
  136. if (!next) {
  137. mutable.set('hasMore', false);
  138. }
  139. if (shouldCountUnreadNotifications(state)) {
  140. mutable.set('unread', mutable.get('pendingItems').count(item => item !== null) + mutable.get('items').count(item => item && compareId(item.get('id'), lastReadId) > 0));
  141. } else {
  142. const mostRecent = newItems.find(item => item !== null);
  143. if (mostRecent && compareId(lastReadId, mostRecent.get('id')) < 0) {
  144. mutable.set('lastReadId', mostRecent.get('id'));
  145. }
  146. }
  147. mutable.update('isLoading', (nbLoading) => nbLoading - 1);
  148. });
  149. };
  150. const filterNotifications = (state, accountIds, type) => {
  151. const helper = list => list.filterNot(item => item !== null && accountIds.includes(item.get('account')) && (type === undefined || type === item.get('type')));
  152. return state.update('items', helper).update('pendingItems', helper);
  153. };
  154. const clearUnread = (state) => {
  155. state = state.set('unread', state.get('pendingItems').size);
  156. const lastNotification = state.get('items').find(item => item !== null);
  157. return state.set('lastReadId', lastNotification ? lastNotification.get('id') : '0');
  158. };
  159. const updateTop = (state, top) => {
  160. state = state.set('top', top);
  161. if (!shouldCountUnreadNotifications(state)) {
  162. state = clearUnread(state);
  163. }
  164. return state;
  165. };
  166. const deleteByStatus = (state, statusId) => {
  167. const lastReadId = state.get('lastReadId');
  168. if (shouldCountUnreadNotifications(state)) {
  169. const deletedUnread = state.get('items').filter(item => item !== null && item.get('status') === statusId && compareId(item.get('id'), lastReadId) > 0);
  170. state = state.update('unread', unread => unread - deletedUnread.size);
  171. }
  172. const helper = list => list.filterNot(item => item !== null && item.get('status') === statusId);
  173. const deletedUnread = state.get('pendingItems').filter(item => item !== null && item.get('status') === statusId && compareId(item.get('id'), lastReadId) > 0);
  174. state = state.update('unread', unread => unread - deletedUnread.size);
  175. return state.update('items', helper).update('pendingItems', helper);
  176. };
  177. const updateMounted = (state) => {
  178. state = state.update('mounted', count => count + 1);
  179. if (!shouldCountUnreadNotifications(state, state.get('mounted') === 1)) {
  180. state = state.set('readMarkerId', state.get('lastReadId'));
  181. state = clearUnread(state);
  182. }
  183. return state;
  184. };
  185. const updateVisibility = (state, visibility) => {
  186. state = state.set('isTabVisible', visibility);
  187. if (!shouldCountUnreadNotifications(state)) {
  188. state = state.set('readMarkerId', state.get('lastReadId'));
  189. state = clearUnread(state);
  190. }
  191. return state;
  192. };
  193. const shouldCountUnreadNotifications = (state, ignoreScroll = false) => {
  194. const isTabVisible = state.get('isTabVisible');
  195. const isOnTop = state.get('top');
  196. const isMounted = state.get('mounted') > 0;
  197. const lastReadId = state.get('lastReadId');
  198. const lastItem = state.get('items').findLast(item => item !== null);
  199. const lastItemReached = !state.get('hasMore') || lastReadId === '0' || (lastItem && compareId(lastItem.get('id'), lastReadId) <= 0);
  200. return !(isTabVisible && (ignoreScroll || isOnTop) && isMounted && lastItemReached);
  201. };
  202. const recountUnread = (state, last_read_id) => {
  203. return state.withMutations(mutable => {
  204. if (compareId(last_read_id, mutable.get('lastReadId')) > 0) {
  205. mutable.set('lastReadId', last_read_id);
  206. }
  207. if (compareId(last_read_id, mutable.get('readMarkerId')) > 0) {
  208. mutable.set('readMarkerId', last_read_id);
  209. }
  210. if (state.get('unread') > 0 || shouldCountUnreadNotifications(state)) {
  211. mutable.set('unread', mutable.get('pendingItems').count(item => item !== null) + mutable.get('items').count(item => item && compareId(item.get('id'), last_read_id) > 0));
  212. }
  213. });
  214. };
  215. export default function notifications(state = initialState, action) {
  216. switch(action.type) {
  217. case MARKERS_FETCH_SUCCESS:
  218. return action.markers.notifications ? recountUnread(state, action.markers.notifications.last_read_id) : state;
  219. case NOTIFICATIONS_MOUNT:
  220. return updateMounted(state);
  221. case NOTIFICATIONS_UNMOUNT:
  222. return state.update('mounted', count => count - 1);
  223. case APP_FOCUS:
  224. return updateVisibility(state, true);
  225. case APP_UNFOCUS:
  226. return updateVisibility(state, false);
  227. case NOTIFICATIONS_LOAD_PENDING:
  228. return state.update('items', list => state.get('pendingItems').concat(list.take(40))).set('pendingItems', ImmutableList()).set('unread', 0);
  229. case NOTIFICATIONS_EXPAND_REQUEST:
  230. return state.update('isLoading', (nbLoading) => nbLoading + 1);
  231. case NOTIFICATIONS_EXPAND_FAIL:
  232. return state.update('isLoading', (nbLoading) => nbLoading - 1);
  233. case NOTIFICATIONS_FILTER_SET:
  234. return state.set('items', ImmutableList()).set('pendingItems', ImmutableList()).set('hasMore', true);
  235. case NOTIFICATIONS_SCROLL_TOP:
  236. return updateTop(state, action.top);
  237. case NOTIFICATIONS_UPDATE:
  238. return normalizeNotification(state, action.notification, action.usePendingItems);
  239. case NOTIFICATIONS_EXPAND_SUCCESS:
  240. return expandNormalizedNotifications(state, action.notifications, action.next, action.isLoadingMore, action.isLoadingRecent, action.usePendingItems);
  241. case ACCOUNT_BLOCK_SUCCESS:
  242. return filterNotifications(state, [action.relationship.id]);
  243. case ACCOUNT_MUTE_SUCCESS:
  244. return action.relationship.muting_notifications ? filterNotifications(state, [action.relationship.id]) : state;
  245. case DOMAIN_BLOCK_SUCCESS:
  246. return filterNotifications(state, action.accounts);
  247. case FOLLOW_REQUEST_AUTHORIZE_SUCCESS:
  248. case FOLLOW_REQUEST_REJECT_SUCCESS:
  249. return filterNotifications(state, [action.id], 'follow_request');
  250. case NOTIFICATIONS_CLEAR:
  251. return state.set('items', ImmutableList()).set('pendingItems', ImmutableList()).set('hasMore', false);
  252. case TIMELINE_DELETE:
  253. return deleteByStatus(state, action.id);
  254. case TIMELINE_DISCONNECT:
  255. return action.timeline === 'home' ?
  256. state.update(action.usePendingItems ? 'pendingItems' : 'items', items => items.first() ? items.unshift(null) : items) :
  257. state;
  258. case NOTIFICATIONS_MARK_AS_READ:
  259. const lastNotification = state.get('items').find(item => item !== null);
  260. return lastNotification ? recountUnread(state, lastNotification.get('id')) : state;
  261. case NOTIFICATIONS_SET_BROWSER_SUPPORT:
  262. return state.set('browserSupport', action.value);
  263. case NOTIFICATIONS_SET_BROWSER_PERMISSION:
  264. return state.set('browserPermission', action.value);
  265. default:
  266. return state;
  267. }
  268. };