bigbuffet-rw/app/soapbox/actions/preload.ts

70 lines
2.2 KiB
TypeScript
Raw Normal View History

import mapValues from 'lodash/mapValues';
import { verifyCredentials } from './auth';
import { importFetchedAccounts } from './importer';
2020-08-24 13:23:05 -07:00
import type { AppDispatch } from 'soapbox/store';
const PLEROMA_PRELOAD_IMPORT = 'PLEROMA_PRELOAD_IMPORT';
const MASTODON_PRELOAD_IMPORT = 'MASTODON_PRELOAD_IMPORT';
2020-08-24 13:23:05 -07:00
// https://git.pleroma.social/pleroma/pleroma-fe/-/merge_requests/1176/diffs
const decodeUTF8Base64 = (data: string) => {
2020-08-24 13:23:05 -07:00
const rawData = atob(data);
const array = Uint8Array.from(rawData.split('').map((char) => char.charCodeAt(0)));
const text = new TextDecoder().decode(array);
return text;
};
const decodePleromaData = (data: Record<string, any>) => {
return mapValues(data, base64string => JSON.parse(decodeUTF8Base64(base64string)));
};
const pleromaDecoder = (json: string) => decodePleromaData(JSON.parse(json));
// This will throw if it fails.
// Should be called inside a try-catch.
const decodeFromMarkup = (elementId: string, decoder: (json: string) => Record<string, any>) => {
const { textContent } = document.getElementById(elementId)!;
return decoder(textContent as string);
};
const preloadFromMarkup = (elementId: string, decoder: (json: string) => Record<string, any>, action: (data: Record<string, any>) => any) =>
(dispatch: AppDispatch) => {
try {
const data = decodeFromMarkup(elementId, decoder);
dispatch(action(data));
} catch {
// Do nothing
}
};
2020-08-24 13:23:05 -07:00
const preload = () =>
(dispatch: AppDispatch) => {
dispatch(preloadFromMarkup('initial-results', pleromaDecoder, preloadPleroma));
dispatch(preloadFromMarkup('initial-state', JSON.parse, preloadMastodon));
};
2020-08-24 13:23:05 -07:00
const preloadPleroma = (data: Record<string, any>) => ({
type: PLEROMA_PRELOAD_IMPORT,
data,
});
const preloadMastodon = (data: Record<string, any>) =>
(dispatch: AppDispatch) => {
const { me, access_token } = data.meta;
const { url } = data.accounts[me];
2021-09-22 07:23:37 -07:00
dispatch(importFetchedAccounts(Object.values(data.accounts)));
dispatch(verifyCredentials(access_token, url));
dispatch({ type: MASTODON_PRELOAD_IMPORT, data });
2020-08-24 13:23:05 -07:00
};
export {
PLEROMA_PRELOAD_IMPORT,
MASTODON_PRELOAD_IMPORT,
preload,
preloadPleroma,
preloadMastodon,
};