start a video-only page; fix some styles

This commit is contained in:
Ginger Wong 2020-08-23 21:23:16 -07:00
parent a07ad8d693
commit 22e16b67d7
10 changed files with 681 additions and 687 deletions

View file

@ -11,16 +11,16 @@
</head>
<body class="messages-only">
<body>
<div id="chat-container"></div>
<div id="messages-only"></div>
<script type="module">
import { render, html } from "https://unpkg.com/htm/preact/index.mjs?module";
import StandaloneChat from './js/app-standalong-chat.js';
import StandaloneChat from './js/app-standalone-chat.js';
(function () {
render(html`<${StandaloneChat} messagesOnly />`, document.getElementById("chat-container"));
render(html`<${StandaloneChat} messagesOnly />`, document.getElementById("messages-only"));
})();
</script>
</body>

View file

@ -0,0 +1,31 @@
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
<link href="//unpkg.com/video.js@7.9.2/dist/video-js.css" rel="stylesheet">
<link href="https://unpkg.com/@videojs/themes@1/dist/fantasy/index.css" rel="stylesheet" />
<script src="//unpkg.com/video.js@7.9.2/dist/video.js"></script>
<link href="./styles/video.css" rel="stylesheet" />
<link href="./styles/video-only.css" rel="stylesheet" />
<script src="//unpkg.com/showdown/dist/showdown.min.js"></script>
</head>
<body>
<div id="video-only"></div>
<script type="module">
import { render, html } from "https://unpkg.com/htm/preact/index.mjs?module";
import VideoOnly from './js/app-video-only.js';
(function () {
render(html`<${VideoOnly} />`, document.getElementById("video-only"));
})();
</script>
</body>
</html>

View file

@ -33,6 +33,7 @@
<link href="//unpkg.com/video.js@7.9.2/dist/video-js.css" rel="stylesheet">
<link href="https://unpkg.com/@videojs/themes@1/dist/fantasy/index.css" rel="stylesheet" />
<script src="//unpkg.com/video.js@7.9.2/dist/video.js"></script>
<!-- markdown renderer -->
<script src="//unpkg.com/showdown/dist/showdown.min.js"></script>
<link href="./styles/app.css" rel="stylesheet" />
@ -48,7 +49,7 @@
<script type="module">
import { render, html } from "https://unpkg.com/htm/preact/index.mjs?module";
import App from './js/app2.js';
import App from './js/app.js';
(function () {
render(html`<${App} />`, document.getElementById("app"));

View file

@ -0,0 +1,265 @@
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 {
addNewlines,
pluralize,
} from './utils/helpers.js';
import {
URL_CONFIG,
URL_STATUS,
TIMER_STATUS_UPDATE,
TIMER_STREAM_DURATION_COUNTER,
TEMP_IMAGE,
MESSAGE_OFFLINE,
MESSAGE_ONLINE,
} from './utils/constants.js';
export default class VideoOnly extends Component {
constructor(props, context) {
super(props, context);
this.state = {
configData: {},
playerActive: false, // player object is active
streamOnline: false, // stream is active/online
//status
streamStatusMessage: MESSAGE_OFFLINE,
viewerCount: '',
sessionMaxViewerCount: '',
overallMaxViewerCount: '',
};
// timers
this.playerRestartTimer = null;
this.offlineTimer = null;
this.statusTimer = null;
this.streamDurationTimer = null;
this.handleOfflineMode = this.handleOfflineMode.bind(this);
this.handleOnlineMode = this.handleOnlineMode.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);
}
componentDidMount() {
this.getConfig();
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);
clearInterval(this.streamDurationTimer);
}
// 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}`);
});
}
setConfigData(data = {}) {
const { title, summary } = data;
window.document.title = title;
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);
this.setState({
streamOnline: false,
streamStatusMessage: MESSAGE_OFFLINE,
});
}
// play video!
handleOnlineMode() {
this.player.startPlayer();
this.streamDurationTimer =
setInterval(this.setCurrentStreamDuration, TIMER_STREAM_DURATION_COUNTER);
this.setState({
playerActive: true,
streamOnline: true,
streamStatusMessage: MESSAGE_ONLINE,
});
}
handleNetworkingError(error) {
console.log(`>>> App Error: ${error}`);
}
render(props, state) {
const {
configData,
viewerCount,
sessionMaxViewerCount,
overallMaxViewerCount,
playerActive,
streamOnline,
streamStatusMessage,
} = state;
const {
version: appVersion,
logo = {},
socialHandles = [],
name: streamerName,
summary,
tags = [],
title,
} = configData;
const { small: smallLogo = TEMP_IMAGE, large: largeLogo = TEMP_IMAGE } = logo;
const bgLogoLarge = { backgroundImage: `url(${largeLogo})` };
const mainClass = playerActive ? 'online' : '';
return (
html`
<main class=${mainClass}>
<div
id="video-container"
class="flex owncast-video-container bg-black w-full bg-center bg-no-repeat flex flex-col items-center justify-start"
style=${bgLogoLarge}
>
<video
class="video-js vjs-big-play-centered display-block w-full h-full"
id="video"
preload="auto"
controls
playsinline
></video>
</div>
<section id="stream-info" aria-label="Stream status" class="flex text-center flex-row justify-between items-center font-mono py-2 px-8 bg-gray-900 text-indigo-200">
<span>${streamStatusMessage}</span>
<span>${viewerCount} ${pluralize('viewer', viewerCount)}.</span>
<span>Max ${pluralize('viewer', sessionMaxViewerCount)}.</span>
<span>${overallMaxViewerCount} overall.</span>
</section>
</main>
`);
}
}

View file

@ -1,28 +1,60 @@
import Websocket from './websocket.js';
import { MessagingInterface, Message } from './message.js';
import SOCKET_MESSAGE_TYPES from './utils/socket-message-types.js';
import { OwncastPlayer } from './player.js';
import { h, Component } from 'https://unpkg.com/preact?module';
import htm from 'https://unpkg.com/htm?module';
const html = htm.bind(h);
const MESSAGE_OFFLINE = 'Stream is offline.';
const MESSAGE_ONLINE = 'Stream is online';
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';
const TEMP_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
import {
getLocalStorage,
setLocalStorage,
clearLocalStorage,
generateAvatar,
generateUsername,
addNewlines,
pluralize,
} from './utils/helpers.js';
import {
URL_OWNCAST,
URL_CONFIG,
URL_STATUS,
TIMER_STATUS_UPDATE,
TIMER_DISABLE_CHAT_AFTER_OFFLINE,
TIMER_STREAM_DURATION_COUNTER,
TEMP_IMAGE,
MESSAGE_OFFLINE,
MESSAGE_ONLINE,
KEY_USERNAME,
KEY_AVATAR,
KEY_CHAT_DISPLAYED,
} from './utils/constants.js';
const URL_CONFIG = `/config`;
const URL_STATUS = `/status`;
const URL_CHAT_HISTORY = `/chat`;
export default class App extends Component {
constructor(props, context) {
super(props, context);
const TIMER_STATUS_UPDATE = 5000; // ms
const TIMER_DISABLE_CHAT_AFTER_OFFLINE = 5 * 60 * 1000; // 5 mins
const TIMER_STREAM_DURATION_COUNTER = 1000;
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()}`),
class Owncast {
constructor() {
this.player;
configData: {},
extraUserContent: '',
this.configData;
this.vueApp;
this.messagingInterface = null;
playerActive: false, // player object is active
streamOnline: false, // stream is active/online
//status
streamStatusMessage: MESSAGE_OFFLINE,
viewerCount: '',
sessionMaxViewerCount: '',
overallMaxViewerCount: '',
};
// timers
this.playerRestartTimer = null;
@ -31,67 +63,30 @@ class Owncast {
this.disableChatTimer = null;
this.streamDurationTimer = null;
// misc
this.streamStatus = null;
// misc dom events
this.handleChatPanelToggle = this.handleChatPanelToggle.bind(this);
this.handleUsernameChange = this.handleUsernameChange.bind(this);
Vue.filter('plural', pluralize);
// bindings
this.vueAppMounted = this.vueAppMounted.bind(this);
this.setConfigData = this.setConfigData.bind(this);
this.getStreamStatus = this.getStreamStatus.bind(this);
this.getExtraUserContent = this.getExtraUserContent.bind(this);
this.updateStreamStatus = this.updateStreamStatus.bind(this);
this.handleNetworkingError = this.handleNetworkingError.bind(this);
this.handleOfflineMode = this.handleOfflineMode.bind(this);
this.handleOnlineMode = this.handleOnlineMode.bind(this);
this.handleNetworkingError = this.handleNetworkingError.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);
this.setCurrentStreamDuration = this.setCurrentStreamDuration.bind(this);
// fetch events
this.getConfig = this.getConfig.bind(this);
this.getStreamStatus = this.getStreamStatus.bind(this);
this.getExtraUserContent = this.getExtraUserContent.bind(this);
}
init() {
this.messagingInterface = new MessagingInterface();
this.setupWebsocket();
this.vueApp = new Vue({
el: '#app-container',
data: {
playerOn: false,
messages: [],
overallMaxViewerCount: 0,
sessionMaxViewerCount: 0,
streamStatus: MESSAGE_OFFLINE, // Default state.
viewerCount: 0,
isOnline: false,
// from config
appVersion: '',
extraUserContent: '',
logo: TEMP_IMAGE,
logoLarge: TEMP_IMAGE,
socialHandles: [],
streamerName: '',
summary: '',
tags: [],
title: '',
},
watch: {
messages: {
deep: true,
handler: this.messagingInterface.onReceivedMessages,
},
},
mounted: this.vueAppMounted,
});
}
// do all these things after Vue.js has mounted, else we'll get weird DOM issues.
vueAppMounted() {
componentDidMount() {
this.getConfig();
this.messagingInterface.init();
this.player = new OwncastPlayer();
this.player.setupPlayerCallbacks({
@ -101,50 +96,15 @@ class Owncast {
onError: this.handlePlayerError,
});
this.player.init();
this.getChatHistory();
};
setConfigData(data) {
this.vueApp.appVersion = data.version;
this.vueApp.logo = data.logo.small;
this.vueApp.logoLarge = data.logo.large;
this.vueApp.socialHandles = data.socialHandles;
this.vueApp.streamerName = data.name;
this.vueApp.summary = data.summary && addNewlines(data.summary);
this.vueApp.tags = data.tags;
this.vueApp.title = data.title;
window.document.title = data.title;
this.getExtraUserContent(`${data.extraUserInfoFileName}`);
this.configData = data;
}
// websocket for messaging
setupWebsocket() {
this.websocket = new Websocket();
this.websocket.addListener('rawWebsocketMessageReceived', this.receivedWebsocketMessage.bind(this));
this.messagingInterface.send = this.websocket.send;
};
receivedWebsocketMessage(model) {
if (model.type === SOCKET_MESSAGE_TYPES.CHAT) {
const message = new Message(model);
this.addMessage(message);
} else if (model.type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) {
this.addMessage(model);
}
}
addMessage(message) {
const existing = this.vueApp.messages.filter(function (item) {
return item.id === message.id;
})
if (existing.length === 0 || !existing) {
this.vueApp.messages = [...this.vueApp.messages, message];
}
componentWillUnmount() {
// clear all the timers
clearInterval(this.playerRestartTimer);
clearInterval(this.offlineTimer);
clearInterval(this.statusTimer);
clearTimeout(this.disableChatTimer);
clearInterval(this.streamDurationTimer);
}
// fetch /config data
@ -180,7 +140,7 @@ class Owncast {
this.handleOfflineMode();
this.handleNetworkingError(`Stream status: ${error}`);
});
};
}
// fetch content.md
getExtraUserContent(path) {
@ -192,141 +152,304 @@ class Owncast {
return response.text();
})
.then(text => {
const descriptionHTML = new showdown.Converter().makeHtml(text);
this.vueApp.extraUserContent = descriptionHTML;
this.setState({
extraUserContent: new showdown.Converter().makeHtml(text),
});
})
.catch(error => {
this.handleNetworkingError(`Fetch extra content: ${error}`);
});
};
// fetch chat history
getChatHistory() {
fetch(URL_CHAT_HISTORY)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok ${response.ok}`);
}
return response.json();
})
.then(data => {
const formattedMessages = data.map(function (message) {
return new Message(message);
})
this.vueApp.messages = formattedMessages.concat(this.vueApp.messages);
})
.catch(error => {
this.handleNetworkingError(`Fetch getChatHistory: ${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;
}
// update UI
this.vueApp.viewerCount = status.viewerCount;
this.vueApp.sessionMaxViewerCount = status.sessionMaxViewerCount;
this.vueApp.overallMaxViewerCount = status.overallMaxViewerCount;
const {
viewerCount,
sessionMaxViewerCount,
overallMaxViewerCount,
online,
} = status;
this.lastDisconnectTime = status.lastDisconnectTime;
if (!this.streamStatus) {
// display offline mode the first time we get status, and it's offline.
if (!status.online) {
this.handleOfflineMode();
} else {
this.handleOnlineMode();
}
} else {
if (status.online && !this.streamStatus.online) {
if (status.online && !curStreamOnline) {
// stream has just come online.
this.handleOnlineMode();
} else if (!status.online && this.streamStatus.online) {
} else if (!status.online && curStreamOnline) {
// stream has just flipped offline.
this.handleOfflineMode();
}
}
// keep a local copy
this.streamStatus = status;
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();
}
}
};
// update vueApp.streamStatus text when online
setCurrentStreamDuration() {
// Default to something
let streamDurationString = '';
if (this.streamStatus.lastConnectTime) {
const diff = (Date.now() - Date.parse(this.streamStatus.lastConnectTime)) / 1000;
streamDurationString = secondsToHMMSS(diff);
}
this.vueApp.streamStatus = `${MESSAGE_ONLINE} ${streamDurationString}.`
}
handleNetworkingError(error) {
console.log(`>>> App Error: ${error}`)
};
// stop status timer and disable chat after some time.
handleOfflineMode() {
this.vueApp.isOnline = false;
clearInterval(this.streamDurationTimer);
this.vueApp.streamStatus = MESSAGE_OFFLINE;
if (this.streamStatus) {
const remainingChatTime = TIMER_DISABLE_CHAT_AFTER_OFFLINE - (Date.now() - new Date(this.lastDisconnectTime));
const countdown = (remainingChatTime < 0) ? 0 : remainingChatTime;
this.disableChatTimer = setTimeout(this.messagingInterface.disableChat, countdown);
}
};
// play video!
handleOnlineMode() {
this.vueApp.playerOn = true;
this.vueApp.isOnline = true;
this.vueApp.streamStatus = MESSAGE_ONLINE;
this.player.startPlayer();
clearTimeout(this.disableChatTimer);
this.disableChatTimer = null;
this.messagingInterface.enableChat();
this.streamDurationTimer =
setInterval(this.setCurrentStreamDuration, TIMER_STREAM_DURATION_COUNTER);
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.vueApp.playerOn = false;
};
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}`);
}
render(props, state) {
const {
username,
userAvatarImage,
websocket,
configData,
extraUserContent,
displayChat,
viewerCount,
sessionMaxViewerCount,
overallMaxViewerCount,
playerActive,
streamOnline,
streamStatusMessage,
chatEnabled,
} = 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`
<li key="tag${index}" class="tag rounded-sm text-gray-100 bg-gray-700 text-xs uppercase mr-3 p-2 whitespace-no-wrap">${tag}</li>
`);
const socialIconsList =
!socialHandles.length ?
null :
socialHandles.map((item, index) => html`
<li key="social${index}">
<${SocialIcon} platform=${item.platform} url=${item.url} />
</li>
`);
const chatClass = displayChat ? 'chat' : 'no-chat';
const mainClass = playerActive ? 'online' : '';
const streamInfoClass = streamOnline ? 'online' : '';
return (
html`
<div id="app-container" class="flex w-full flex-col justify-start relative ${chatClass}">
<div id="top-content">
<header class="flex border-b border-gray-900 border-solid shadow-md fixed z-10 w-full top-0 left-0 flex flex-row justify-between flex-no-wrap">
<h1 class="flex flex-row items-center justify-start p-2 uppercase text-gray-400 text-xl font-thin tracking-wider overflow-hidden whitespace-no-wrap">
<span
id="logo-container"
class="inline-block rounded-full bg-white w-8 min-w-8 min-h-8 h-8 p-1 mr-2 bg-no-repeat bg-center"
style=${bgLogo}
>
<img class="logo visually-hidden" src=${smallLogo} alt=""/>
</span>
<span class="instance-title overflow-hidden truncate">${title}</span>
</h1>
<div id="user-options-container" class="flex flex-row justify-end items-center flex-no-wrap">
<${UsernameForm}
username=${username}
userAvatarImage=${userAvatarImage}
handleUsernameChange=${this.handleUsernameChange}
/>
<button type="button" id="chat-toggle" onClick=${this.handleChatPanelToggle} class="flex cursor-pointer text-center justify-center items-center min-w-12 h-full bg-gray-800 hover:bg-gray-700">💬</button>
</div>
</header>
</div>
<main class=${mainClass}>
<div
id="video-container"
class="flex owncast-video-container bg-black w-full bg-center bg-no-repeat flex flex-col items-center justify-start"
style=${bgLogoLarge}
>
<video
class="video-js vjs-big-play-centered display-block w-full h-full"
id="video"
preload="auto"
controls
playsinline
></video>
</div>
<section id="stream-info" aria-label="Stream status" class="flex text-center flex-row justify-between font-mono py-2 px-8 bg-gray-900 text-indigo-200 shadow-md border-b border-gray-100 border-solid ${streamInfoClass}">
<span>${streamStatusMessage}</span>
<span>${viewerCount} ${pluralize('viewer', viewerCount)}.</span>
<span>Max ${pluralize('viewer', sessionMaxViewerCount)}.</span>
<span>${overallMaxViewerCount} overall.</span>
</section>
</main>
<section id="user-content" aria-label="User information" class="p-8">
<div class="user-content flex flex-row p-8">
<div
class="user-image rounded-full bg-white p-4 mr-8 bg-no-repeat bg-center"
style=${bgLogoLarge}
>
<img
class="logo visually-hidden"
alt="Logo"
src=${largeLogo}/>
</div>
<div class="user-content-header border-b border-gray-500 border-solid">
<h2 class="font-semibold text-5xl">
About <span class="streamer-name text-indigo-600">${streamerName}</span>
</h2>
<ul id="social-list" class="social-list flex flex-row items-center justify-start flex-wrap">
<span class="follow-label text-xs font-bold mr-2 uppercase">Follow me: </span>
${socialIconsList}
</ul>
<div id="stream-summary" class="stream-summary my-4" dangerouslySetInnerHTML=${{ __html: summary }}></div>
<ul id="tag-list" class="tag-list flex flex-row my-4">
${tagList}
</ul>
</div>
</div>
<div
id="extra-user-content"
class="extra-user-content px-8"
dangerouslySetInnerHTML=${{ __html: extraUserContent }}
></div>
</section>
<footer class="flex flex-row justify-start p-8 opacity-50 text-xs">
<span class="mx-1 inline-block">
<a href="${URL_OWNCAST}" target="_blank">About Owncast</a>
</span>
<span class="mx-1 inline-block">Version ${appVersion}</span>
</footer>
<${Chat}
websocket=${websocket}
username=${username}
userAvatarImage=${userAvatarImage}
chatEnabled=${chatEnabled}
/>
</div>
`);
}
}
export default Owncast;

View file

@ -1,455 +0,0 @@
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 {
getLocalStorage,
setLocalStorage,
clearLocalStorage,
generateAvatar,
generateUsername,
addNewlines,
pluralize,
} from './utils/helpers.js';
import {
URL_OWNCAST,
URL_CONFIG,
URL_STATUS,
TIMER_STATUS_UPDATE,
TIMER_DISABLE_CHAT_AFTER_OFFLINE,
TIMER_STREAM_DURATION_COUNTER,
TEMP_IMAGE,
MESSAGE_OFFLINE,
MESSAGE_ONLINE,
KEY_USERNAME,
KEY_AVATAR,
KEY_CHAT_DISPLAYED,
} 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: '',
};
// 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.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();
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);
}
// 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}`);
}
render(props, state) {
const {
username,
userAvatarImage,
websocket,
configData,
extraUserContent,
displayChat,
viewerCount,
sessionMaxViewerCount,
overallMaxViewerCount,
playerActive,
streamOnline,
streamStatusMessage,
chatEnabled,
} = 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`
<li key="tag${index}" class="tag rounded-sm text-gray-100 bg-gray-700 text-xs uppercase mr-3 p-2 whitespace-no-wrap">${tag}</li>
`);
const socialIconsList =
!socialHandles.length ?
null :
socialHandles.map((item, index) => html`
<li key="social${index}">
<${SocialIcon} platform=${item.platform} url=${item.url} />
</li>
`);
const chatClass = displayChat ? 'chat' : 'no-chat';
const mainClass = playerActive ? 'online' : '';
const streamInfoClass = streamOnline ? 'online' : '';
return (
html`
<div id="app-container" class="flex w-full flex-col justify-start relative ${chatClass}">
<div id="top-content">
<header class="flex border-b border-gray-900 border-solid shadow-md fixed z-10 w-full top-0 left-0 flex flex-row justify-between flex-no-wrap">
<h1 class="flex flex-row items-center justify-start p-2 uppercase text-gray-400 text-xl font-thin tracking-wider overflow-hidden whitespace-no-wrap">
<span
id="logo-container"
class="inline-block rounded-full bg-white w-8 min-w-8 min-h-8 h-8 p-1 mr-2 bg-no-repeat bg-center"
style=${bgLogo}
>
<img class="logo visually-hidden" src=${smallLogo} alt=""/>
</span>
<span class="instance-title overflow-hidden truncate">${title}</span>
</h1>
<div id="user-options-container" class="flex flex-row justify-end items-center flex-no-wrap">
<${UsernameForm}
username=${username}
userAvatarImage=${userAvatarImage}
handleUsernameChange=${this.handleUsernameChange}
/>
<button type="button" id="chat-toggle" onClick=${this.handleChatPanelToggle} class="flex cursor-pointer text-center justify-center items-center min-w-12 h-full bg-gray-800 hover:bg-gray-700">💬</button>
</div>
</header>
</div>
<main class=${mainClass}>
<div
id="video-container"
class="flex owncast-video-container bg-black w-full bg-center bg-no-repeat flex flex-col items-center justify-start"
style=${bgLogoLarge}
>
<video
class="video-js vjs-big-play-centered display-block w-full h-full"
id="video"
preload="auto"
controls
playsinline
></video>
</div>
<section id="stream-info" aria-label="Stream status" class="flex text-center flex-row justify-between font-mono py-2 px-8 bg-gray-900 text-indigo-200 shadow-md border-b border-gray-100 border-solid ${streamInfoClass}">
<span>${streamStatusMessage}</span>
<span>${viewerCount} ${pluralize('viewer', viewerCount)}.</span>
<span>Max ${pluralize('viewer', sessionMaxViewerCount)}.</span>
<span>${overallMaxViewerCount} overall.</span>
</section>
</main>
<section id="user-content" aria-label="User information" class="p-8">
<div class="user-content flex flex-row p-8">
<div
class="user-image rounded-full bg-white p-4 mr-8 bg-no-repeat bg-center"
style=${bgLogoLarge}
>
<img
class="logo visually-hidden"
alt="Logo"
src=${largeLogo}/>
</div>
<div class="user-content-header border-b border-gray-500 border-solid">
<h2 class="font-semibold text-5xl">
About <span class="streamer-name text-indigo-600">${streamerName}</span>
</h2>
<ul id="social-list" class="social-list flex flex-row items-center justify-start flex-wrap">
<span class="follow-label text-xs font-bold mr-2 uppercase">Follow me: </span>
${socialIconsList}
</ul>
<div id="stream-summary" class="stream-summary my-4" dangerouslySetInnerHTML=${{ __html: summary }}></div>
<ul id="tag-list" class="tag-list flex flex-row my-4">
${tagList}
</ul>
</div>
</div>
<div
id="extra-user-content"
class="extra-user-content px-8"
dangerouslySetInnerHTML=${{ __html: extraUserContent }}
></div>
</section>
<footer class="flex flex-row justify-start p-8 opacity-50 text-xs">
<span class="mx-1 inline-block">
<a href="${URL_OWNCAST}" target="_blank">About Owncast</a>
</span>
<span class="mx-1 inline-block">Version ${appVersion}</span>
</footer>
<${Chat}
websocket=${websocket}
username=${username}
userAvatarImage=${userAvatarImage}
chatEnabled=${chatEnabled}
/>
</div>
`);
}
}

View file

@ -63,17 +63,16 @@ export default class UsernameForm extends Component {
const { displayForm } = state;
const narrowSpace = document.body.clientWidth < 640;
const formDisplayStyle = narrowSpace ? 'inline-block' : 'flex';
const styles = {
info: {
display: displayForm || narrowSpace ? 'none' : 'flex',
},
form: {
display: displayForm ? 'flex' : 'none',
display: displayForm ? formDisplayStyle : 'none',
},
};
if (narrowSpace) {
styles.form.display = 'inline-block';
}
return (
html`
<div id="user-info">

View file

@ -7,7 +7,7 @@ Spefici styles for app layout
:root {
--header-height: 3.5em;
--right-col-width: 24em;
--video-container-height: 55vh;
--video-container-height: calc((9 / 16) * 100vw);
--header-bg-color: rgba(20,0,40,1);
--user-image-width: 10em;
}
@ -70,6 +70,10 @@ header {
#video-container {
height: calc(var(--video-container-height));
margin-top: var(--header-height);
position: relative;
width: 100%;
/* height: calc((9 / 16) * 100vw); */
min-height: 480px;
background-size: 30%;
}
#video-container #video {

View file

@ -1,37 +1,33 @@
/*
The styles in this file mostly ovveride those coming from chat.css
*/
.messages-only {
/* modify this px number if you want things to be relatively bigger or smaller 8*/
/* modify this px number if you want things to be relatively bigger or smaller */
#messages-only {
font-size: 16px;
}
.messages-only .message-content {
#messages-only .message-content {
text-shadow: 1px 1px 0px rgba(0,0,0,0.25);
}
.message-avatar {
#messages-only .message-avatar {
display: none;
box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.25);
}
.message-avatar img {
#messages-only .message-avatar img {
height: 1.8em;
width: 1.8em;
}
.messages-only .message {
#messages-only .message {
padding: .5em;
}
.messages-only .message-text {
#messages-only .message-text {
font-weight: 400;
color: white;
}
.messages-only .message-text a {
#messages-only .message-text a {
color: #fc0;
}
.messages-only .message-author {
#messages-only .message-author {
color: rgba(20,0,40,1);
}

View file

@ -0,0 +1,30 @@
/*
The styles in this file mostly ovveride those coming from chat.css
*/
/* modify this px number if you want things to be relatively bigger or smaller */
#video-only {
font-size: 16px;
position: relative;
}
#video-only #video-container {
background-size: 30%;
width: 100%;
height: calc((9 / 16) * 100vw);
}
#video-only #video-container #video {
transition: opacity .5s;
opacity: 0;
pointer-events: none;
}
#video-only .online #video-container #video {
opacity: 1;
pointer-events: auto;
}
#video-only #stream-info {
height: 3rem;
}