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.

94 lines
2.6 KiB

  1. import createStream from '../stream';
  2. import {
  3. updateTimeline,
  4. deleteFromTimelines,
  5. refreshHomeTimeline,
  6. connectTimeline,
  7. disconnectTimeline,
  8. } from './timelines';
  9. import { updateNotifications, refreshNotifications } from './notifications';
  10. import { getLocale } from '../locales';
  11. const { messages } = getLocale();
  12. export function connectTimelineStream (timelineId, path, pollingRefresh = null) {
  13. return (dispatch, getState) => {
  14. const streamingAPIBaseURL = getState().getIn(['meta', 'streaming_api_base_url']);
  15. const accessToken = getState().getIn(['meta', 'access_token']);
  16. const locale = getState().getIn(['meta', 'locale']);
  17. let polling = null;
  18. const setupPolling = () => {
  19. polling = setInterval(() => {
  20. pollingRefresh(dispatch);
  21. }, 20000);
  22. };
  23. const clearPolling = () => {
  24. if (polling) {
  25. clearInterval(polling);
  26. polling = null;
  27. }
  28. };
  29. const subscription = createStream(streamingAPIBaseURL, accessToken, path, {
  30. connected () {
  31. if (pollingRefresh) {
  32. clearPolling();
  33. }
  34. dispatch(connectTimeline(timelineId));
  35. },
  36. disconnected () {
  37. if (pollingRefresh) {
  38. setupPolling();
  39. }
  40. dispatch(disconnectTimeline(timelineId));
  41. },
  42. received (data) {
  43. switch(data.event) {
  44. case 'update':
  45. dispatch(updateTimeline(timelineId, JSON.parse(data.payload)));
  46. break;
  47. case 'delete':
  48. dispatch(deleteFromTimelines(data.payload));
  49. break;
  50. case 'notification':
  51. dispatch(updateNotifications(JSON.parse(data.payload), messages, locale));
  52. break;
  53. }
  54. },
  55. reconnected () {
  56. if (pollingRefresh) {
  57. clearPolling();
  58. pollingRefresh(dispatch);
  59. }
  60. dispatch(connectTimeline(timelineId));
  61. },
  62. });
  63. const disconnect = () => {
  64. if (subscription) {
  65. subscription.close();
  66. }
  67. clearPolling();
  68. };
  69. return disconnect;
  70. };
  71. }
  72. function refreshHomeTimelineAndNotification (dispatch) {
  73. dispatch(refreshHomeTimeline());
  74. dispatch(refreshNotifications());
  75. }
  76. export const connectUserStream = () => connectTimelineStream('home', 'user', refreshHomeTimelineAndNotification);
  77. export const connectCommunityStream = () => connectTimelineStream('community', 'public:local');
  78. export const connectMediaStream = () => connectTimelineStream('community', 'public:local');
  79. export const connectPublicStream = () => connectTimelineStream('public', 'public');
  80. export const connectHashtagStream = (tag) => connectTimelineStream(`hashtag:${tag}`, `hashtag&tag=${tag}`);