import { h, Component } from 'https://unpkg.com/preact?module'; import htm from 'https://unpkg.com/htm?module'; const html = htm.bind(h); import { OwncastPlayer } from './components/player.js'; import SocialIcon from './components/social.js'; import UsernameForm from './components/chat/username.js'; import Chat from './components/chat/chat.js'; import Websocket from './utils/websocket.js'; import { addNewlines, classNames, clearLocalStorage, debounce, generateAvatar, generateUsername, getLocalStorage, pluralize, setLocalStorage, } from './utils/helpers.js'; import { HEIGHT_SHORT_WIDE, KEY_AVATAR, KEY_CHAT_DISPLAYED, KEY_USERNAME, MESSAGE_OFFLINE, MESSAGE_ONLINE, TEMP_IMAGE, TIMER_DISABLE_CHAT_AFTER_OFFLINE, TIMER_STATUS_UPDATE, TIMER_STREAM_DURATION_COUNTER, URL_CONFIG, URL_OWNCAST, URL_STATUS, WIDTH_SINGLE_COL, } from './utils/constants.js'; export default class App extends Component { constructor(props, context) { super(props, context); this.state = { websocket: new Websocket(), displayChat: getLocalStorage(KEY_CHAT_DISPLAYED), // chat panel state chatEnabled: false, // chat input box state username: getLocalStorage(KEY_USERNAME) || generateUsername(), userAvatarImage: getLocalStorage(KEY_AVATAR) || generateAvatar(`${this.username}${Date.now()}`), configData: {}, extraUserContent: '', playerActive: false, // player object is active streamOnline: false, // stream is active/online // status streamStatusMessage: MESSAGE_OFFLINE, viewerCount: '', sessionMaxViewerCount: '', overallMaxViewerCount: '', // dom windowWidth: window.innerWidth, windowHeight: window.innerHeight, }; // timers this.playerRestartTimer = null; this.offlineTimer = null; this.statusTimer = null; this.disableChatTimer = null; this.streamDurationTimer = null; // misc dom events this.handleChatPanelToggle = this.handleChatPanelToggle.bind(this); this.handleUsernameChange = this.handleUsernameChange.bind(this); this.handleWindowResize = debounce(this.handleWindowResize.bind(this), 400); this.handleOfflineMode = this.handleOfflineMode.bind(this); this.handleOnlineMode = this.handleOnlineMode.bind(this); this.disableChatInput = this.disableChatInput.bind(this); // player events this.handlePlayerReady = this.handlePlayerReady.bind(this); this.handlePlayerPlaying = this.handlePlayerPlaying.bind(this); this.handlePlayerEnded = this.handlePlayerEnded.bind(this); this.handlePlayerError = this.handlePlayerError.bind(this); // fetch events this.getConfig = this.getConfig.bind(this); this.getStreamStatus = this.getStreamStatus.bind(this); this.getExtraUserContent = this.getExtraUserContent.bind(this); } componentDidMount() { this.getConfig(); window.addEventListener('resize', this.handleWindowResize); this.player = new OwncastPlayer(); this.player.setupPlayerCallbacks({ onReady: this.handlePlayerReady, onPlaying: this.handlePlayerPlaying, onEnded: this.handlePlayerEnded, onError: this.handlePlayerError, }); this.player.init(); } componentWillUnmount() { // clear all the timers clearInterval(this.playerRestartTimer); clearInterval(this.offlineTimer); clearInterval(this.statusTimer); clearTimeout(this.disableChatTimer); clearInterval(this.streamDurationTimer); window.removeEventListener('resize', this.handleWindowResize); } // fetch /config data getConfig() { fetch(URL_CONFIG) .then(response => { if (!response.ok) { throw new Error(`Network response was not ok ${response.ok}`); } return response.json(); }) .then(json => { this.setConfigData(json); }) .catch(error => { this.handleNetworkingError(`Fetch config: ${error}`); }); } // fetch stream status getStreamStatus() { fetch(URL_STATUS) .then(response => { if (!response.ok) { throw new Error(`Network response was not ok ${response.ok}`); } return response.json(); }) .then(json => { this.updateStreamStatus(json); }) .catch(error => { this.handleOfflineMode(); this.handleNetworkingError(`Stream status: ${error}`); }); } // fetch content.md getExtraUserContent(path) { fetch(path) .then(response => { if (!response.ok) { throw new Error(`Network response was not ok ${response.ok}`); } return response.text(); }) .then(text => { this.setState({ extraUserContent: new showdown.Converter().makeHtml(text), }); }) .catch(error => { this.handleNetworkingError(`Fetch extra content: ${error}`); }); } setConfigData(data = {}) { const { title, extraUserInfoFileName, summary } = data; window.document.title = title; if (extraUserInfoFileName) { this.getExtraUserContent(extraUserInfoFileName); } this.setState({ configData: { ...data, summary: summary && addNewlines(summary), }, }); } // handle UI things from stream status result updateStreamStatus(status = {}) { const { streamOnline: curStreamOnline } = this.state; if (!status) { return; } const { viewerCount, sessionMaxViewerCount, overallMaxViewerCount, online, } = status; this.lastDisconnectTime = status.lastDisconnectTime; if (status.online && !curStreamOnline) { // stream has just come online. this.handleOnlineMode(); } else if (!status.online && curStreamOnline) { // stream has just flipped offline. this.handleOfflineMode(); } if (status.online) { // only do this if video is paused, so no unnecessary img fetches if (this.player.vjsPlayer && this.player.vjsPlayer.paused()) { this.player.setPoster(); } } this.setState({ viewerCount, sessionMaxViewerCount, overallMaxViewerCount, streamOnline: online, }); } // when videojs player is ready, start polling for stream handlePlayerReady() { this.getStreamStatus(); this.statusTimer = setInterval(this.getStreamStatus, TIMER_STATUS_UPDATE); } handlePlayerPlaying() { // do something? } // likely called some time after stream status has gone offline. // basically hide video and show underlying "poster" handlePlayerEnded() { this.setState({ playerActive: false, }); } handlePlayerError() { // do something? this.handleOfflineMode(); this.handlePlayerEnded(); } // stop status timer and disable chat after some time. handleOfflineMode() { clearInterval(this.streamDurationTimer); const remainingChatTime = TIMER_DISABLE_CHAT_AFTER_OFFLINE - (Date.now() - new Date(this.lastDisconnectTime)); const countdown = (remainingChatTime < 0) ? 0 : remainingChatTime; this.disableChatTimer = setTimeout(this.disableChatInput, countdown); this.setState({ streamOnline: false, streamStatusMessage: MESSAGE_OFFLINE, }); } // play video! handleOnlineMode() { this.player.startPlayer(); clearTimeout(this.disableChatTimer); this.disableChatTimer = null; this.streamDurationTimer = setInterval(this.setCurrentStreamDuration, TIMER_STREAM_DURATION_COUNTER); this.setState({ playerActive: true, streamOnline: true, chatEnabled: true, streamStatusMessage: MESSAGE_ONLINE, }); } handleUsernameChange(newName, newAvatar) { this.setState({ username: newName, userAvatarImage: newAvatar, }); } handleChatPanelToggle() { const { displayChat: curDisplayed } = this.state; const displayChat = !curDisplayed; if (displayChat) { setLocalStorage(KEY_CHAT_DISPLAYED, displayChat); } else { clearLocalStorage(KEY_CHAT_DISPLAYED); } this.setState({ displayChat, }); } disableChatInput() { this.setState({ chatEnabled: false, }); } handleNetworkingError(error) { console.log(`>>> App Error: ${error}`); } handleWindowResize() { this.setState({ windowWidth: window.innerWidth, windowHeight: window.innerHeight, }); } render(props, state) { const { chatEnabled, configData, displayChat, extraUserContent, overallMaxViewerCount, playerActive, sessionMaxViewerCount, streamOnline, streamStatusMessage, userAvatarImage, username, viewerCount, websocket, windowHeight, windowWidth, } = state; const { version: appVersion, logo = {}, socialHandles = [], name: streamerName, summary, tags = [], title, } = configData; const { small: smallLogo = TEMP_IMAGE, large: largeLogo = TEMP_IMAGE } = logo; const bgLogo = { backgroundImage: `url(${smallLogo})` }; const bgLogoLarge = { backgroundImage: `url(${largeLogo})` }; const tagList = !tags.length ? null : tags.map((tag, index) => html`
  • ${tag}
  • `); const socialIconsList = !socialHandles.length ? null : socialHandles.map((item, index) => html`
  • <${SocialIcon} platform=${item.platform} url=${item.url} />
  • `); const mainClass = playerActive ? 'online' : ''; const streamInfoClass = streamOnline ? 'online' : ''; // need? const shortHeight = windowHeight <= HEIGHT_SHORT_WIDE; const singleColMode = windowWidth <= WIDTH_SINGLE_COL && !shortHeight; const extraAppClasses = classNames({ 'chat': displayChat, 'no-chat': !displayChat, 'single-col': singleColMode, 'bg-gray-800': singleColMode && displayChat, 'short-wide': shortHeight, }) return ( html`

    ${title}

    <${UsernameForm} username=${username} userAvatarImage=${userAvatarImage} handleUsernameChange=${this.handleUsernameChange} />
    ${streamStatusMessage} ${viewerCount} ${pluralize('viewer', viewerCount)}. Max ${pluralize('viewer', sessionMaxViewerCount)}. ${overallMaxViewerCount} overall.

    About ${streamerName}

      ${tagList}
    <${Chat} websocket=${websocket} username=${username} userAvatarImage=${userAvatarImage} chatEnabled //=${chatEnabled} />
    ` ); } }