owncast/web/utils/server-status-context.tsx

126 lines
2.8 KiB
TypeScript
Raw Normal View History

2021-01-17 09:40:46 +01:00
// TODO: add a notication after updating info that changes will take place either on a new stream or server restart. may be different for each field.
import React, { useState, useEffect } from 'react';
2021-01-29 19:26:55 +01:00
import PropTypes from 'prop-types';
import { STATUS, fetchData, FETCH_INTERVAL, SERVER_CONFIG } from './apis';
import { ConfigDetails, UpdateArgs } from '../types/config-section';
2021-01-10 11:37:22 +01:00
import { DEFAULT_VARIANT_STATE } from '../pages/components/config/constants';
export const initialServerConfigState: ConfigDetails = {
streamKey: '',
instanceDetails: {
extraPageContent: '',
logo: '',
name: '',
nsfw: false,
2021-01-19 19:34:06 +01:00
socialHandles: [],
streamTitle: '',
summary: '',
tags: [],
title: '',
},
ffmpegPath: '',
rtmpServerPort: '',
webServerPort: '',
s3: {},
yp: {
enabled: false,
instanceUrl: '',
},
videoSettings: {
latencyLevel: 4,
2021-01-10 11:37:22 +01:00
videoQualityVariants: [DEFAULT_VARIANT_STATE],
}
};
const initialServerStatusState = {
broadcastActive: false,
broadcaster: null,
online: false,
viewerCount: 0,
sessionMaxViewerCount: 0,
sessionPeakViewerCount: 0,
overallPeakViewerCount: 0,
disableUpgradeChecks: true,
versionNumber: '0.0.0',
};
export const ServerStatusContext = React.createContext({
...initialServerStatusState,
serverConfig: initialServerConfigState,
2020-12-27 03:04:23 +01:00
2021-01-29 19:26:55 +01:00
setFieldInConfigState: (args: UpdateArgs) => { return args },
});
const ServerStatusProvider = ({ children }) => {
const [status, setStatus] = useState(initialServerStatusState);
const [config, setConfig] = useState(initialServerConfigState);
const getStatus = async () => {
try {
const result = await fetchData(STATUS);
setStatus({ ...result });
} catch (error) {
// todo
}
};
const getConfig = async () => {
try {
const result = await fetchData(SERVER_CONFIG);
setConfig(result);
} catch (error) {
// todo
}
};
2021-01-03 10:54:04 +01:00
const setFieldInConfigState = ({ fieldName, value, path }: UpdateArgs) => {
const updatedConfig = path ?
{
...config,
[path]: {
...config[path],
[fieldName]: value,
},
} :
{
2020-12-27 03:04:23 +01:00
...config,
[fieldName]: value,
};
setConfig(updatedConfig);
};
2020-12-27 03:04:23 +01:00
useEffect(() => {
let getStatusIntervalId = null;
getStatus();
getStatusIntervalId = setInterval(getStatus, FETCH_INTERVAL);
getConfig();
// returned function will be called on component unmount
return () => {
clearInterval(getStatusIntervalId);
}
}, []);
const providerValue = {
...status,
serverConfig: config,
2020-12-27 03:04:23 +01:00
2021-01-03 10:54:04 +01:00
setFieldInConfigState,
};
return (
<ServerStatusContext.Provider value={providerValue}>
{children}
</ServerStatusContext.Provider>
);
}
ServerStatusProvider.propTypes = {
children: PropTypes.element.isRequired,
};
export default ServerStatusProvider;