Fix timeline markers not working on Chrome (#13887)

* Periodically save timeline markers

This saves timeline markers immediately upon message arrival, but not more
than once every 5 minutes.

This does not change how the markers are saved on closing the window,
except that it avoids submitting them if there is no need for it.

* Use the Fetch API when possible instead of XHR on window unload
This commit is contained in:
ThibG 2020-05-29 16:14:16 +02:00 committed by GitHub
parent 8bbc81c71e
commit 5aff2a6957
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 115 additions and 24 deletions

View File

@ -1,30 +1,81 @@
export const submitMarkers = () => (dispatch, getState) => { import api from '../api';
import { debounce } from 'lodash';
import compareId from '../compare_id';
import { showAlertForError } from './alerts';
export const MARKERS_SUBMIT_SUCCESS = 'MARKERS_SUBMIT_SUCCESS';
export const synchronouslySubmitMarkers = () => (dispatch, getState) => {
const accessToken = getState().getIn(['meta', 'access_token'], ''); const accessToken = getState().getIn(['meta', 'access_token'], '');
const params = {}; const params = _buildParams(getState());
const lastHomeId = getState().getIn(['timelines', 'home', 'items', 0]);
const lastNotificationId = getState().getIn(['notifications', 'items', 0, 'id']);
if (lastHomeId) {
params.home = {
last_read_id: lastHomeId,
};
}
if (lastNotificationId) {
params.notifications = {
last_read_id: lastNotificationId,
};
}
if (Object.keys(params).length === 0) { if (Object.keys(params).length === 0) {
return; return;
} }
const client = new XMLHttpRequest(); if (window.fetch) {
fetch('/api/v1/markers', {
keepalive: true,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
},
body: JSON.stringify(params),
});
} else {
const client = new XMLHttpRequest();
client.open('POST', '/api/v1/markers', false); client.open('POST', '/api/v1/markers', false);
client.setRequestHeader('Content-Type', 'application/json'); client.setRequestHeader('Content-Type', 'application/json');
client.setRequestHeader('Authorization', `Bearer ${accessToken}`); client.setRequestHeader('Authorization', `Bearer ${accessToken}`);
client.send(JSON.stringify(params)); client.SUBMIT(JSON.stringify(params));
}
};
const _buildParams = (state) => {
const params = {};
const lastHomeId = state.getIn(['timelines', 'home', 'items', 0]);
const lastNotificationId = state.getIn(['notifications', 'items', 0, 'id']);
if (lastHomeId && compareId(lastHomeId, state.getIn(['markers', 'home'])) > 0) {
params.home = {
last_read_id: lastHomeId,
};
}
if (lastNotificationId && compareId(lastNotificationId, state.getIn(['markers', 'notifications'])) > 0) {
params.notifications = {
last_read_id: lastNotificationId,
};
}
return params;
};
const debouncedSubmitMarkers = debounce((dispatch, getState) => {
const params = _buildParams(getState());
if (Object.keys(params).length === 0) {
return;
}
api().post('/api/v1/markers', params).then(() => {
dispatch(submitMarkersSuccess(params));
}).catch(error => {
dispatch(showAlertForError(error));
});
}, 300000, { leading: true, trailing: true });
export function submitMarkersSuccess({ home, notifications }) {
return {
type: MARKERS_SUBMIT_SUCCESS,
home: (home || {}).last_read_id,
notifications: (notifications || {}).last_read_id,
};
};
export function submitMarkers() {
return (dispatch, getState) => debouncedSubmitMarkers(dispatch, getState);
}; };

View File

@ -7,6 +7,7 @@ import {
importFetchedStatus, importFetchedStatus,
importFetchedStatuses, importFetchedStatuses,
} from './importer'; } from './importer';
import { submitMarkers } from './markers';
import { saveSettings } from './settings'; import { saveSettings } from './settings';
import { defineMessages } from 'react-intl'; import { defineMessages } from 'react-intl';
import { List as ImmutableList } from 'immutable'; import { List as ImmutableList } from 'immutable';
@ -70,6 +71,8 @@ export function updateNotifications(notification, intlMessages, intlLocale) {
filtered = regex && regex.test(searchIndex); filtered = regex && regex.test(searchIndex);
} }
dispatch(submitMarkers());
if (showInColumn) { if (showInColumn) {
dispatch(importFetchedAccount(notification.account)); dispatch(importFetchedAccount(notification.account));
@ -157,6 +160,7 @@ export function expandNotifications({ maxId } = {}, done = noOp) {
dispatch(expandNotificationsSuccess(response.data, next ? next.uri : null, isLoadingMore, isLoadingRecent, isLoadingRecent && preferPendingItems)); dispatch(expandNotificationsSuccess(response.data, next ? next.uri : null, isLoadingMore, isLoadingRecent, isLoadingRecent && preferPendingItems));
fetchRelatedRelationships(dispatch, response.data); fetchRelatedRelationships(dispatch, response.data);
dispatch(submitMarkers());
}).catch(error => { }).catch(error => {
dispatch(expandNotificationsFail(error, isLoadingMore)); dispatch(expandNotificationsFail(error, isLoadingMore));
}).finally(() => { }).finally(() => {

View File

@ -1,4 +1,5 @@
import { importFetchedStatus, importFetchedStatuses } from './importer'; import { importFetchedStatus, importFetchedStatuses } from './importer';
import { submitMarkers } from './markers';
import api, { getLinks } from 'mastodon/api'; import api, { getLinks } from 'mastodon/api';
import { Map as ImmutableMap, List as ImmutableList } from 'immutable'; import { Map as ImmutableMap, List as ImmutableList } from 'immutable';
import compareId from 'mastodon/compare_id'; import compareId from 'mastodon/compare_id';
@ -36,6 +37,10 @@ export function updateTimeline(timeline, status, accept) {
status, status,
usePendingItems: preferPendingItems, usePendingItems: preferPendingItems,
}); });
if (timeline === 'home') {
dispatch(submitMarkers());
}
}; };
}; };
@ -98,6 +103,10 @@ export function expandTimeline(timelineId, path, params = {}, done = noOp) {
const next = getLinks(response).refs.find(link => link.rel === 'next'); const next = getLinks(response).refs.find(link => link.rel === 'next');
dispatch(importFetchedStatuses(response.data)); dispatch(importFetchedStatuses(response.data));
dispatch(expandTimelineSuccess(timelineId, response.data, next ? next.uri : null, response.status === 206, isLoadingRecent, isLoadingMore, isLoadingRecent && preferPendingItems)); dispatch(expandTimelineSuccess(timelineId, response.data, next ? next.uri : null, response.status === 206, isLoadingRecent, isLoadingMore, isLoadingRecent && preferPendingItems));
if (timelineId === 'home') {
dispatch(submitMarkers());
}
}).catch(error => { }).catch(error => {
dispatch(expandTimelineFail(timelineId, error, isLoadingMore)); dispatch(expandTimelineFail(timelineId, error, isLoadingMore));
}).finally(() => { }).finally(() => {

View File

@ -16,7 +16,7 @@ import { expandNotifications } from '../../actions/notifications';
import { fetchFilters } from '../../actions/filters'; import { fetchFilters } from '../../actions/filters';
import { clearHeight } from '../../actions/height_cache'; import { clearHeight } from '../../actions/height_cache';
import { focusApp, unfocusApp } from 'mastodon/actions/app'; import { focusApp, unfocusApp } from 'mastodon/actions/app';
import { submitMarkers } from 'mastodon/actions/markers'; import { synchronouslySubmitMarkers } from 'mastodon/actions/markers';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers'; import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area'; import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container'; import ColumnsAreaContainer from './containers/columns_area_container';
@ -251,7 +251,7 @@ class UI extends React.PureComponent {
handleBeforeUnload = e => { handleBeforeUnload = e => {
const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props; const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props;
dispatch(submitMarkers()); dispatch(synchronouslySubmitMarkers());
if (isComposing && (hasComposingText || hasMediaAttachments)) { if (isComposing && (hasComposingText || hasMediaAttachments)) {
// Setting returnValue to any string causes confirmation dialog. // Setting returnValue to any string causes confirmation dialog.

View File

@ -35,6 +35,7 @@ import identity_proofs from './identity_proofs';
import trends from './trends'; import trends from './trends';
import missed_updates from './missed_updates'; import missed_updates from './missed_updates';
import announcements from './announcements'; import announcements from './announcements';
import markers from './markers';
const reducers = { const reducers = {
announcements, announcements,
@ -73,6 +74,7 @@ const reducers = {
polls, polls,
trends, trends,
missed_updates, missed_updates,
markers,
}; };
export default combineReducers(reducers); export default combineReducers(reducers);

View File

@ -0,0 +1,25 @@
import {
MARKERS_SUBMIT_SUCCESS,
} from '../actions/notifications';
const initialState = ImmutableMap({
home: '0',
notifications: '0',
});
import { Map as ImmutableMap } from 'immutable';
export default function markers(state = initialState, action) {
switch(action.type) {
case MARKERS_SUBMIT_SUCCESS:
if (action.home) {
state = state.set('home', action.home);
}
if (action.notifications) {
state = state.set('notifications', action.notifications);
}
return state;
default:
return state;
}
};