045a0a2afd
* Support webfinger requests for the live account. Closes https://github.com/owncast/owncast/issues/1193 * Support for actor requests. Returns response for live actor. Closes https://github.com/owncast/owncast/issues/1203 * Handle follow and unfollow requests. Closes https://github.com/owncast/owncast/issues/1191 and https://github.com/owncast/owncast/issues/1205 and https://github.com/owncast/owncast/issues/1206 and https://github.com/owncast/owncast/issues/1194 * Add basic support for sending out text activities. For https://github.com/owncast/owncast/issues/1192 * Some error handling and passing of dynamic local account names. * Add hardcoded example image attachment to test post * Centralize the map of accounts and inboxes * No longer disable the preview generator based on YP toggle * Send a federated message to followers when stream starts. For https://github.com/owncast/owncast/issues/1192 * Placeholder for attaching tags * Add image description * Save and get to outbox persistence. Return using outbox endpoint for actor * Pass payloads to be handled through the gochan * Handle undo follow requests explitly, not all undo requests * Add API for manually sending simple federated messages. Closes #1215 * Verify inbox requests. Closes #1321 * Add route to fetch a single AP object by ID. For #1329 * Add responses to fediverse nodeinfo requests * Set and get federation config values for admin * Handle host-meta requests * Do not send out message if disabled. Use saved go live message. * Require AP-compatible content types for AP-related requests * Rename ap models to apmodels for clarity * Change how content type matching takes place. * io -> ioutil * Add stub delete activity callback * Handle likes and announces to surface engagement in chat. Part of #1229 * Append url to go live posts * Do not require specific content types for nodeinfo requests * Add follow engagement chat message via AP * add owncast user-agent to requests * Set note visibility to public (for now) * Fix saving/fetching a single object * Add support for x-nodeinfo2 responses * Point to the dev admin branch for ap * Bundle in dev admin for testing * Add error logging * Add AP middleware back * Point to the new external compatible logo endpoint * Clean up more AP logging to help testing * Tweak go live text and link hashtags * Fix bug in fetching init time * Send update actor activities when server details/profile is updated * Add federation config overview to web client config * Add additional actor properties * Make the AP middleware checking more flexible when looking at types * First pass at remote fediverse follow flow. For #1371 * Added a basic AP actor followers endpoint * WIP client followers API * Add profile-page reference to webfinger response * Add aliases to webfinger response * Fix content-type returned to be expected activitypub+json * First pass at followers api * Point at local dev copy of go-fed/activity * Add custom toot Hashtag objects to posts * Store additional user details to followers table * Fix AP followers endpoint. Closes #1204 * Add owncast hashtag as an invisible tag to go live posts * Reject AP requests when it is disabled * Add actor util for generating full account user from person object * Verify inbox requests before performing any other work * Accept actor update requests * Fix linter errors in federation branch * Migrate AP SQL to sqlc for type safe queries * Use the @unclearParadigm REST parameter helper * Fix verifying post ID on AP engagement * WIP privacy/request approval * Style the remote follow modal * First pass at a followers list component w/ mock data. #1370 * Revert "Use the @unclearParadigm REST parameter helper" This reverts commit c8af8a413f6f53e7d1a15a7d823ff28be2db3c23. * Fix get followers API * Add support for requiring approval. Closes https://github.com/owncast/owncast/issues/1208 * Handle Applications as Actors partly for PeerTube support * add temp todo list * check route on load, this might change later * style followers * account for just 1 tab case * Remove mock data. Allow showing follow button even when there are no external actions defined * Point to actual followers API * Support fallback img for follower views * Remove duplicate verification. Add some additional verbose logging * Bundle dev admin * Add type to host-meta webfinger template response * Tweak remote follow modal content * WIP federation followers refactor * Do not send pointer to middleware * Update admin * Add setting for toggling displaying fediverse engagement. Closes #1404 * Add in-development admin * Do not enable cors on admin followers api * Add db migration for updating messages table * Enable empty string go live messages to disable * Remove debug messages * Rework some ActivityPub handling. Create new Actor->Person handling. Create new Actor->Service handling. Add engagement handlers to send chat events and store event objects. Store inbound activities to new ap_inbound_activities table. * Support federated engagement events. Store them in the messages table and surface them via chat events. * Support federated event engatement in the chat * Tweak web UI followers handling * Point go.mod at remote fork instead of local * Update admin * Merged in develop. Couple fixes * Update dev admin * Update fedi engagement posts. - Fix incorrect action text. - Add action icons. * Set public as to instead of cc for ap msg * Updated styling for federated actions in chat * Add support for blocking federated domains. Closes #1209 * Force checking of https in verify step * Update dev admin * Return user scopes in chat history api. Closes #1586 * Update dev admin * Add AP outbound request worker pool. Closes #1571 * Disable (temporarily?) owncast tag on AP posts * Consolidate creating activity+notes in outbound AP messages * Add inbox worker pool. Closes #1570 * Update dev admin bundle * Clean up some logs * Re-enable inbound verfication * Save full IRI to outbox instead of path * Reject if full IRI is not found in outbox * Use full ActivityPub user account in chat event * Fix and expand follower APIs - Add missing IDs to AP follower endpoints - Split AP follower endpoints into initial request and pages. - Support pagination in AP requests. * Include IRI in error message * Hide chat toggle when chat is hidden. Closes #1606 * Updates to followers pagination * Set default go live message * Remove log * indirect -> direct import * Updates for inbound federated event handling. - Keep track of existing events and reject duplicates. - Change what is sent to chat for surfing federated engagement. - Keep track if outbound events are automated "go live" events or not. * Update chat federated engagement. * Update dev admin. * Move from being a person to a bot (service). Closes #1619 * Only set server init date if not already set * Only save notes to outbox able * Rework private-mode followers/approvals * API for returning a list of federated actions for #1573 * Fix too-small follower cells and jumpy tabs. Closes #1616 and closes #1516 * Fix shortcuts getting fired on inputs. Fixes #1489 and #1201 * Add spinner, autoclose + other fixes to follow modal. Fixes #1593 * Fix fetching a single object by IRI * SendFederationMessage -> SendFederatedMessage * Autolink and create tag objects from manual posts. Closes #1620 * Update dev admin bundle * Handle engagement from non-automated/live posts * Reject federated engagement actions if they do not match a local post * Update dev admin bundle * A bunch of cleanup * Fix unused assignments and logic * Remove unused function * Add content warning and sentive content flag if stream is NSFW. Closes #1624 * Disable fetching objects by IRI when in private mode. Closes #1623 * Update the error message of the remote follow dialog. closes #1622 * Update dev admin * Fix NREs throwing in test content * Fix query that wasn't properly filtering out hidden messages * Test against user being disabled instead of message visibility * Fix automated test NRE * Update comment * Adjust federated engagement chat views. Closes #1617 * Add additional index to users table * Add support for removing followers/requests. Closes #1630 * Reject federated actions from blocked actors. #1631 * Use fallback avatar if it fails to load. Closes #1635 * Fix styling of follower list. Closes #1636 * Add basic blurb stating they should follow the server. Closes #1641 * Update dev admin * Set default go live message in migration. Closes #1642 * Reset the messages table on 0.0.11 schema migration * Fix js error with moderation actions. Closes #1621 * Add a bit more clarification on follow modal. Closes #1599 * Remove todos * Split out actor and domain blocking checks * Check for errors on default values being set * Clean up actor rejection due to being blocked * Update dev admin * Add colon to error to make it easier to read * Remove markdown rendering of go live message. Reorganize text. Remove content warning. Closes #1645 * Break out the sort+render messages logic so it can be fired on visibility change. Closes #1643 * Do not send profile updates if federation is disabled * Save follow references to inbound activities table * Update dev admin * Add blocked actor test * Remove the overloaded term of Follow from social links * Fix test running in memory only * Remove "just" in engagement messags * Replace star with heart for like action. * Update dev admin * Explicitly set cc as public * Remove overly using the stream name in fediverse engagement messages * Some federated/follow UI tweaks * Remove explicit cc and bcc as they are not required * Explicitly set the audience * Remove extra margin * Add Join Fediverse button to follow modal. Closes #1651 * Do not allow multiple follows to send multiple events. Closes #1650 * Give events a min height * Do not allow old posts to be liked/shared. Closes #1652 * Remove value from log message * Alert followers on private mode toggle * Ignore clicks to follow button if disabled * Remove underline from action buttons * Add moderator icon to join message * Update admin * Post-merge remove unused var * Remove pointing at feature branch Co-authored-by: Ginger Wong <omqmail@gmail.com>
975 lines
27 KiB
JavaScript
975 lines
27 KiB
JavaScript
import { h, Component } from '/js/web_modules/preact.js';
|
|
import htm from '/js/web_modules/htm.js';
|
|
const html = htm.bind(h);
|
|
|
|
import { OwncastPlayer } from './components/player.js';
|
|
import SocialIconsList from './components/platform-logos-list.js';
|
|
import UsernameForm from './components/chat/username.js';
|
|
import VideoPoster from './components/video-poster.js';
|
|
import Followers from './components/federation/followers.js';
|
|
|
|
import Chat from './components/chat/chat.js';
|
|
import Websocket, {
|
|
CALLBACKS,
|
|
SOCKET_MESSAGE_TYPES,
|
|
} from './utils/websocket.js';
|
|
import { registerChat } from './chat/register.js';
|
|
|
|
import ExternalActionModal, {
|
|
ExternalActionButton,
|
|
} from './components/external-action-modal.js';
|
|
|
|
import FediverseFollowModal, {
|
|
FediverseFollowButton,
|
|
} from './components/fediverse-follow-modal.js';
|
|
|
|
import {
|
|
addNewlines,
|
|
checkUrlPathForDisplay,
|
|
classNames,
|
|
debounce,
|
|
getLocalStorage,
|
|
getOrientation,
|
|
hasTouchScreen,
|
|
makeLastOnlineString,
|
|
parseSecondsToDurationString,
|
|
pluralize,
|
|
ROUTE_RECORDINGS,
|
|
setLocalStorage,
|
|
} from './utils/helpers.js';
|
|
import {
|
|
CHAT_MAX_MESSAGE_LENGTH,
|
|
EST_SOCKET_PAYLOAD_BUFFER,
|
|
HEIGHT_SHORT_WIDE,
|
|
KEY_ACCESS_TOKEN,
|
|
KEY_CHAT_DISPLAYED,
|
|
KEY_USERNAME,
|
|
MESSAGE_OFFLINE,
|
|
MESSAGE_ONLINE,
|
|
ORIENTATION_PORTRAIT,
|
|
OWNCAST_LOGO_LOCAL,
|
|
TEMP_IMAGE,
|
|
TIMER_DISABLE_CHAT_AFTER_OFFLINE,
|
|
TIMER_STATUS_UPDATE,
|
|
TIMER_STREAM_DURATION_COUNTER,
|
|
URL_CONFIG,
|
|
URL_OWNCAST,
|
|
URL_STATUS,
|
|
URL_VIEWER_PING,
|
|
WIDTH_SINGLE_COL,
|
|
} from './utils/constants.js';
|
|
import { checkIsModerator } from './utils/chat.js';
|
|
import TabBar from './components/tab-bar.js';
|
|
|
|
export default class App extends Component {
|
|
constructor(props, context) {
|
|
super(props, context);
|
|
|
|
const chatStorage = getLocalStorage(KEY_CHAT_DISPLAYED);
|
|
this.hasTouchScreen = hasTouchScreen();
|
|
this.windowBlurred = false;
|
|
|
|
this.state = {
|
|
websocket: null,
|
|
canChat: false, // all of chat functionality (panel + username)
|
|
displayChatPanel: chatStorage === null ? true : chatStorage === 'true', // just the chat panel
|
|
chatInputEnabled: false, // chat input box state
|
|
accessToken: null,
|
|
username: getLocalStorage(KEY_USERNAME),
|
|
isModerator: false,
|
|
|
|
isRegistering: false,
|
|
touchKeyboardActive: false,
|
|
|
|
configData: {
|
|
loading: true,
|
|
},
|
|
extraPageContent: '',
|
|
|
|
playerActive: false, // player object is active
|
|
streamOnline: null, // stream is active/online
|
|
isPlaying: false, // player is actively playing video
|
|
|
|
// status
|
|
streamStatusMessage: MESSAGE_OFFLINE,
|
|
viewerCount: '',
|
|
lastDisconnectTime: null,
|
|
|
|
// dom
|
|
windowWidth: window.innerWidth,
|
|
windowHeight: window.innerHeight,
|
|
orientation: getOrientation(this.hasTouchScreen),
|
|
|
|
// modals
|
|
externalActionModalData: null,
|
|
fediverseModalData: null,
|
|
|
|
// routing & tabbing
|
|
section: '',
|
|
sectionId: '',
|
|
};
|
|
|
|
// timers
|
|
this.playerRestartTimer = null;
|
|
this.offlineTimer = null;
|
|
this.statusTimer = null;
|
|
this.disableChatInputTimer = null;
|
|
this.streamDurationTimer = null;
|
|
|
|
// misc dom events
|
|
this.handleChatPanelToggle = this.handleChatPanelToggle.bind(this);
|
|
this.handleUsernameChange = this.handleUsernameChange.bind(this);
|
|
this.handleFormFocus = this.handleFormFocus.bind(this);
|
|
this.handleFormBlur = this.handleFormBlur.bind(this);
|
|
this.handleWindowBlur = this.handleWindowBlur.bind(this);
|
|
this.handleWindowFocus = this.handleWindowFocus.bind(this);
|
|
this.handleWindowResize = debounce(this.handleWindowResize.bind(this), 250);
|
|
|
|
this.handleOfflineMode = this.handleOfflineMode.bind(this);
|
|
this.handleOnlineMode = this.handleOnlineMode.bind(this);
|
|
this.disableChatInput = this.disableChatInput.bind(this);
|
|
this.setCurrentStreamDuration = this.setCurrentStreamDuration.bind(this);
|
|
|
|
this.handleKeyPressed = this.handleKeyPressed.bind(this);
|
|
this.displayExternalAction = this.displayExternalAction.bind(this);
|
|
this.closeExternalActionModal = this.closeExternalActionModal.bind(this);
|
|
this.displayFediverseFollowModal =
|
|
this.displayFediverseFollowModal.bind(this);
|
|
this.closeFediverseFollowModal = this.closeFediverseFollowModal.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);
|
|
|
|
// user events
|
|
this.handleWebsocketMessage = this.handleWebsocketMessage.bind(this);
|
|
|
|
// chat
|
|
this.hasConfiguredChat = false;
|
|
this.setupChatAuth = this.setupChatAuth.bind(this);
|
|
this.disableChat = this.disableChat.bind(this);
|
|
}
|
|
|
|
componentDidMount() {
|
|
this.getConfig();
|
|
if (!this.hasTouchScreen) {
|
|
window.addEventListener('resize', this.handleWindowResize);
|
|
}
|
|
window.addEventListener('blur', this.handleWindowBlur);
|
|
window.addEventListener('focus', this.handleWindowFocus);
|
|
if (this.hasTouchScreen) {
|
|
window.addEventListener('orientationchange', this.handleWindowResize);
|
|
}
|
|
window.addEventListener('keypress', this.handleKeyPressed);
|
|
this.player = new OwncastPlayer();
|
|
this.player.setupPlayerCallbacks({
|
|
onReady: this.handlePlayerReady,
|
|
onPlaying: this.handlePlayerPlaying,
|
|
onEnded: this.handlePlayerEnded,
|
|
onError: this.handlePlayerError,
|
|
});
|
|
this.player.init();
|
|
|
|
// check routing
|
|
this.getRoute();
|
|
}
|
|
|
|
componentWillUnmount() {
|
|
// clear all the timers
|
|
clearInterval(this.playerRestartTimer);
|
|
clearInterval(this.offlineTimer);
|
|
clearInterval(this.statusTimer);
|
|
clearTimeout(this.disableChatInputTimer);
|
|
clearInterval(this.streamDurationTimer);
|
|
window.removeEventListener('resize', this.handleWindowResize);
|
|
window.removeEventListener('blur', this.handleWindowBlur);
|
|
window.removeEventListener('focus', this.handleWindowFocus);
|
|
window.removeEventListener('keypress', this.handleKeyPressed);
|
|
if (this.hasTouchScreen) {
|
|
window.removeEventListener('orientationchange', this.handleWindowResize);
|
|
}
|
|
}
|
|
|
|
getRoute() {
|
|
const routeInfo = checkUrlPathForDisplay();
|
|
this.setState({
|
|
...routeInfo,
|
|
});
|
|
}
|
|
|
|
// 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}`);
|
|
});
|
|
|
|
// Ping the API to let them know we're an active viewer
|
|
fetch(URL_VIEWER_PING).catch((error) => {
|
|
this.handleOfflineMode();
|
|
this.handleNetworkingError(`Viewer PING error: ${error}`);
|
|
});
|
|
}
|
|
|
|
setConfigData(data = {}) {
|
|
const { name, summary, chatDisabled } = data;
|
|
window.document.title = name;
|
|
|
|
// If this is the first time setting the config
|
|
// then setup chat if it's enabled.
|
|
if (!this.hasConfiguredChat && !chatDisabled) {
|
|
this.setupChatAuth();
|
|
}
|
|
|
|
this.hasConfiguredChat = true;
|
|
|
|
this.setState({
|
|
canChat: !chatDisabled,
|
|
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,
|
|
online,
|
|
lastConnectTime,
|
|
streamTitle,
|
|
lastDisconnectTime,
|
|
} = status;
|
|
|
|
this.setState({
|
|
viewerCount,
|
|
lastConnectTime,
|
|
streamOnline: online,
|
|
streamTitle,
|
|
lastDisconnectTime,
|
|
});
|
|
|
|
if (status.online !== curStreamOnline) {
|
|
if (status.online) {
|
|
// stream has just come online.
|
|
this.handleOnlineMode();
|
|
} else {
|
|
// stream has just flipped offline or app just got loaded and stream is offline.
|
|
this.handleOfflineMode(lastDisconnectTime);
|
|
}
|
|
}
|
|
}
|
|
|
|
// when videojs player is ready, start polling for stream
|
|
handlePlayerReady() {
|
|
this.getStreamStatus();
|
|
this.statusTimer = setInterval(this.getStreamStatus, TIMER_STATUS_UPDATE);
|
|
}
|
|
|
|
handlePlayerPlaying() {
|
|
this.setState({
|
|
isPlaying: true,
|
|
});
|
|
}
|
|
|
|
// likely called some time after stream status has gone offline.
|
|
// basically hide video and show underlying "poster"
|
|
handlePlayerEnded() {
|
|
this.setState({
|
|
playerActive: false,
|
|
isPlaying: false,
|
|
});
|
|
}
|
|
|
|
handlePlayerError() {
|
|
// do something?
|
|
this.handleOfflineMode();
|
|
this.handlePlayerEnded();
|
|
}
|
|
|
|
// stop status timer and disable chat after some time.
|
|
handleOfflineMode(lastDisconnectTime) {
|
|
clearInterval(this.streamDurationTimer);
|
|
|
|
if (lastDisconnectTime) {
|
|
const remainingChatTime =
|
|
TIMER_DISABLE_CHAT_AFTER_OFFLINE -
|
|
(Date.now() - new Date(lastDisconnectTime));
|
|
const countdown = remainingChatTime < 0 ? 0 : remainingChatTime;
|
|
if (countdown > 0) {
|
|
this.setState({
|
|
chatInputEnabled: true,
|
|
});
|
|
}
|
|
this.disableChatInputTimer = setTimeout(this.disableChatInput, countdown);
|
|
}
|
|
|
|
this.setState({
|
|
streamOnline: false,
|
|
streamStatusMessage: MESSAGE_OFFLINE,
|
|
});
|
|
|
|
if (this.player.vjsPlayer && this.player.vjsPlayer.paused()) {
|
|
this.handlePlayerEnded();
|
|
}
|
|
|
|
if (this.windowBlurred) {
|
|
document.title = ` 🔴 ${
|
|
this.state.configData && this.state.configData.name
|
|
}`;
|
|
}
|
|
}
|
|
|
|
// play video!
|
|
handleOnlineMode() {
|
|
this.player.startPlayer();
|
|
clearTimeout(this.disableChatInputTimer);
|
|
this.disableChatInputTimer = null;
|
|
|
|
this.streamDurationTimer = setInterval(
|
|
this.setCurrentStreamDuration,
|
|
TIMER_STREAM_DURATION_COUNTER
|
|
);
|
|
|
|
this.setState({
|
|
playerActive: true,
|
|
streamOnline: true,
|
|
chatInputEnabled: true,
|
|
streamTitle: '',
|
|
streamStatusMessage: MESSAGE_ONLINE,
|
|
});
|
|
|
|
if (this.windowBlurred) {
|
|
document.title = ` 🟢 ${
|
|
this.state.configData && this.state.configData.name
|
|
}`;
|
|
}
|
|
}
|
|
|
|
setCurrentStreamDuration() {
|
|
let streamDurationString = '';
|
|
if (this.state.lastConnectTime) {
|
|
const diff = (Date.now() - Date.parse(this.state.lastConnectTime)) / 1000;
|
|
streamDurationString = parseSecondsToDurationString(diff);
|
|
}
|
|
this.setState({
|
|
streamStatusMessage: `${MESSAGE_ONLINE} ${streamDurationString}`,
|
|
});
|
|
}
|
|
|
|
handleUsernameChange(newName) {
|
|
this.setState({
|
|
username: newName,
|
|
});
|
|
|
|
this.sendUsernameChange(newName);
|
|
}
|
|
|
|
handleFormFocus() {
|
|
if (this.hasTouchScreen) {
|
|
this.setState({
|
|
touchKeyboardActive: true,
|
|
});
|
|
}
|
|
}
|
|
|
|
handleFormBlur() {
|
|
if (this.hasTouchScreen) {
|
|
this.setState({
|
|
touchKeyboardActive: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
handleChatPanelToggle() {
|
|
const { displayChatPanel: curDisplayed } = this.state;
|
|
|
|
const displayChat = !curDisplayed;
|
|
setLocalStorage(KEY_CHAT_DISPLAYED, displayChat);
|
|
this.setState({
|
|
displayChatPanel: displayChat,
|
|
});
|
|
}
|
|
|
|
disableChatInput() {
|
|
this.setState({
|
|
chatInputEnabled: false,
|
|
});
|
|
}
|
|
|
|
handleNetworkingError(error) {
|
|
console.error(`>>> App Error: ${error}`);
|
|
}
|
|
|
|
handleWindowResize() {
|
|
this.setState({
|
|
windowWidth: window.innerWidth,
|
|
windowHeight: window.innerHeight,
|
|
orientation: getOrientation(this.hasTouchScreen),
|
|
});
|
|
}
|
|
|
|
handleWindowBlur() {
|
|
this.windowBlurred = true;
|
|
}
|
|
|
|
handleWindowFocus() {
|
|
this.windowBlurred = false;
|
|
window.document.title = this.state.configData && this.state.configData.name;
|
|
}
|
|
|
|
handleSpaceBarPressed(e) {
|
|
e.preventDefault();
|
|
if (this.state.isPlaying) {
|
|
this.setState({
|
|
isPlaying: false,
|
|
});
|
|
try {
|
|
this.player.vjsPlayer.pause();
|
|
} catch (err) {
|
|
console.warn(err);
|
|
}
|
|
} else {
|
|
this.setState({
|
|
isPlaying: true,
|
|
});
|
|
this.player.vjsPlayer.play();
|
|
}
|
|
}
|
|
|
|
handleMuteKeyPressed() {
|
|
const muted = this.player.vjsPlayer.muted();
|
|
const volume = this.player.vjsPlayer.volume();
|
|
|
|
try {
|
|
if (volume === 0) {
|
|
this.player.vjsPlayer.volume(0.5);
|
|
this.player.vjsPlayer.muted(false);
|
|
} else {
|
|
this.player.vjsPlayer.muted(!muted);
|
|
}
|
|
} catch (err) {
|
|
console.warn(err);
|
|
}
|
|
}
|
|
|
|
handleFullScreenKeyPressed() {
|
|
if (this.player.vjsPlayer.isFullscreen()) {
|
|
this.player.vjsPlayer.exitFullscreen();
|
|
} else {
|
|
this.player.vjsPlayer.requestFullscreen();
|
|
}
|
|
}
|
|
|
|
handleVolumeSet(factor) {
|
|
this.player.vjsPlayer.volume(this.player.vjsPlayer.volume() + factor);
|
|
}
|
|
|
|
handleKeyPressed(e) {
|
|
// Only handle shortcuts if the focus is on the general page body,
|
|
// not a specific input field.
|
|
if (e.target !== document.getElementById('app-body')) {
|
|
return;
|
|
}
|
|
|
|
if (this.state.streamOnline) {
|
|
switch (e.code) {
|
|
case 'MediaPlayPause':
|
|
case 'KeyP':
|
|
case 'Space':
|
|
this.handleSpaceBarPressed(e);
|
|
break;
|
|
case 'KeyM':
|
|
this.handleMuteKeyPressed(e);
|
|
break;
|
|
case 'KeyF':
|
|
this.handleFullScreenKeyPressed(e);
|
|
break;
|
|
case 'KeyC':
|
|
this.handleChatPanelToggle();
|
|
break;
|
|
case 'Digit9':
|
|
this.handleVolumeSet(-0.1);
|
|
break;
|
|
case 'Digit0':
|
|
this.handleVolumeSet(0.1);
|
|
}
|
|
}
|
|
}
|
|
|
|
displayExternalAction(action) {
|
|
const { username } = this.state;
|
|
if (!action) {
|
|
return;
|
|
}
|
|
const { url: actionUrl, openExternally } = action || {};
|
|
let url = new URL(actionUrl);
|
|
// Append url and username to params so the link knows where we came from and who we are.
|
|
url.searchParams.append('username', username);
|
|
url.searchParams.append('instance', window.location);
|
|
|
|
const fullUrl = url.toString();
|
|
|
|
if (openExternally) {
|
|
var win = window.open(fullUrl, '_blank');
|
|
win.focus();
|
|
return;
|
|
}
|
|
this.setState({
|
|
externalActionModalData: {
|
|
...action,
|
|
url: fullUrl,
|
|
},
|
|
});
|
|
}
|
|
closeExternalActionModal() {
|
|
this.setState({
|
|
externalActionModalData: null,
|
|
});
|
|
}
|
|
|
|
displayFediverseFollowModal(data) {
|
|
this.setState({ fediverseModalData: data });
|
|
}
|
|
closeFediverseFollowModal() {
|
|
this.setState({ fediverseModalData: null });
|
|
}
|
|
|
|
handleWebsocketMessage(e) {
|
|
if (e.type === SOCKET_MESSAGE_TYPES.ERROR_USER_DISABLED) {
|
|
// User has been actively disabled on the backend. Turn off chat for them.
|
|
this.handleBlockedChat();
|
|
} else if (
|
|
e.type === SOCKET_MESSAGE_TYPES.ERROR_NEEDS_REGISTRATION &&
|
|
!this.isRegistering
|
|
) {
|
|
// User needs an access token, so start the user auth flow.
|
|
this.state.websocket.shutdown();
|
|
this.setState({ websocket: null });
|
|
this.setupChatAuth(true);
|
|
} else if (e.type === SOCKET_MESSAGE_TYPES.ERROR_MAX_CONNECTIONS_EXCEEDED) {
|
|
// Chat server cannot support any more chat clients. Turn off chat for them.
|
|
this.disableChat();
|
|
} else if (e.type === SOCKET_MESSAGE_TYPES.CONNECTED_USER_INFO) {
|
|
// When connected the user will return an event letting us know what our
|
|
// user details are so we can display them properly.
|
|
const { user } = e;
|
|
const { displayName } = user;
|
|
|
|
this.setState({
|
|
username: displayName,
|
|
isModerator: checkIsModerator(e),
|
|
});
|
|
}
|
|
}
|
|
|
|
handleBlockedChat() {
|
|
this.disableChat();
|
|
}
|
|
|
|
disableChat() {
|
|
this.state.websocket.shutdown();
|
|
this.setState({ websocket: null, canChat: false });
|
|
}
|
|
|
|
async setupChatAuth(force) {
|
|
var accessToken = getLocalStorage(KEY_ACCESS_TOKEN);
|
|
var username = getLocalStorage(KEY_USERNAME);
|
|
|
|
if (!accessToken || force) {
|
|
try {
|
|
this.isRegistering = true;
|
|
const registration = await registerChat(this.state.username);
|
|
accessToken = registration.accessToken;
|
|
username = registration.displayName;
|
|
|
|
setLocalStorage(KEY_ACCESS_TOKEN, accessToken);
|
|
setLocalStorage(KEY_USERNAME, username);
|
|
|
|
this.isRegistering = false;
|
|
} catch (e) {
|
|
console.error('registration error:', e);
|
|
}
|
|
}
|
|
|
|
if (this.state.websocket) {
|
|
this.state.websocket.shutdown();
|
|
this.setState({
|
|
websocket: null,
|
|
});
|
|
}
|
|
|
|
// Without a valid access token he websocket connection will be rejected.
|
|
const websocket = new Websocket(accessToken);
|
|
websocket.addListener(
|
|
CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED,
|
|
this.handleWebsocketMessage
|
|
);
|
|
|
|
this.setState({
|
|
username,
|
|
websocket,
|
|
accessToken,
|
|
});
|
|
}
|
|
|
|
sendUsernameChange(newName) {
|
|
const nameChange = {
|
|
type: SOCKET_MESSAGE_TYPES.NAME_CHANGE,
|
|
newName,
|
|
};
|
|
this.state.websocket.send(nameChange);
|
|
}
|
|
|
|
render(props, state) {
|
|
const {
|
|
chatInputEnabled,
|
|
configData,
|
|
displayChatPanel,
|
|
canChat,
|
|
isModerator,
|
|
|
|
isPlaying,
|
|
orientation,
|
|
playerActive,
|
|
streamOnline,
|
|
streamStatusMessage,
|
|
streamTitle,
|
|
touchKeyboardActive,
|
|
username,
|
|
viewerCount,
|
|
websocket,
|
|
windowHeight,
|
|
windowWidth,
|
|
fediverseModalData,
|
|
externalActionModalData,
|
|
lastDisconnectTime,
|
|
section,
|
|
sectionId,
|
|
} = state;
|
|
|
|
const {
|
|
version: appVersion,
|
|
logo = TEMP_IMAGE,
|
|
socialHandles = [],
|
|
summary,
|
|
tags = [],
|
|
name,
|
|
extraPageContent,
|
|
chatDisabled,
|
|
externalActions,
|
|
customStyles,
|
|
maxSocketPayloadSize,
|
|
federation = {},
|
|
} = configData;
|
|
|
|
const bgUserLogo = { backgroundImage: `url(${logo})` };
|
|
|
|
const tagList = tags !== null && tags.length > 0 && tags.join(' #');
|
|
|
|
let viewerCountMessage = '';
|
|
if (streamOnline && viewerCount > 0) {
|
|
viewerCountMessage = html`${viewerCount}
|
|
${pluralize(' viewer', viewerCount)}`;
|
|
} else if (lastDisconnectTime) {
|
|
viewerCountMessage = makeLastOnlineString(lastDisconnectTime);
|
|
}
|
|
|
|
const mainClass = playerActive ? 'online' : '';
|
|
const isPortrait =
|
|
this.hasTouchScreen && orientation === ORIENTATION_PORTRAIT;
|
|
const shortHeight = windowHeight <= HEIGHT_SHORT_WIDE && !isPortrait;
|
|
const singleColMode = windowWidth <= WIDTH_SINGLE_COL && !shortHeight;
|
|
|
|
const noVideoContent =
|
|
!playerActive || (section === ROUTE_RECORDINGS && sectionId !== '');
|
|
const shouldDisplayChat =
|
|
displayChatPanel && !chatDisabled && !noVideoContent;
|
|
const usernameStyle = chatDisabled ? 'none' : 'flex';
|
|
// const shouldDisplayChat = displayChatPanel && canChat && !chatDisabled;
|
|
|
|
const extraAppClasses = classNames({
|
|
'config-loading': configData.loading,
|
|
|
|
chat: shouldDisplayChat,
|
|
'no-chat': !shouldDisplayChat,
|
|
'no-video': noVideoContent,
|
|
'chat-hidden': !displayChatPanel && canChat && !chatDisabled, // hide panel
|
|
'chat-disabled': !canChat || chatDisabled,
|
|
'single-col': singleColMode,
|
|
'bg-gray-800': singleColMode && shouldDisplayChat,
|
|
'short-wide': shortHeight && windowWidth > WIDTH_SINGLE_COL,
|
|
'touch-screen': this.hasTouchScreen,
|
|
'touch-keyboard-active': touchKeyboardActive,
|
|
});
|
|
|
|
const poster = isPlaying
|
|
? null
|
|
: html` <${VideoPoster} offlineImage=${logo} active=${streamOnline} /> `;
|
|
|
|
// modal buttons
|
|
const externalActionButtons = html`<div
|
|
id="external-actions-container"
|
|
class="flex flex-row flex-wrap justify-end"
|
|
>
|
|
${externalActions &&
|
|
externalActions.map(
|
|
function (action) {
|
|
return html`<${ExternalActionButton}
|
|
onClick=${this.displayExternalAction}
|
|
action=${action}
|
|
/>`;
|
|
}.bind(this)
|
|
)}
|
|
|
|
<!-- fediverse follow button -->
|
|
${federation.enabled &&
|
|
html`<${FediverseFollowButton}
|
|
onClick=${this.displayFediverseFollowModal}
|
|
federationInfo=${federation}
|
|
serverName=${name}
|
|
/>`}
|
|
</div>`;
|
|
|
|
// modal component
|
|
const externalActionModal =
|
|
externalActionModalData &&
|
|
html`<${ExternalActionModal}
|
|
action=${externalActionModalData}
|
|
onClose=${this.closeExternalActionModal}
|
|
/>`;
|
|
|
|
const fediverseFollowModal =
|
|
fediverseModalData &&
|
|
html`
|
|
<${ExternalActionModal}
|
|
onClose=${this.closeFediverseFollowModal}
|
|
action=${fediverseModalData}
|
|
useIframe=${false}
|
|
customContent=${html`<${FediverseFollowModal}
|
|
name=${name}
|
|
logo=${logo}
|
|
federationInfo=${federation}
|
|
onClose=${this.closeFediverseFollowModal}
|
|
/>`}
|
|
/>
|
|
`;
|
|
|
|
const chat = this.state.websocket
|
|
? html`
|
|
<${Chat}
|
|
websocket=${websocket}
|
|
username=${username}
|
|
chatInputEnabled=${chatInputEnabled && !chatDisabled}
|
|
instanceTitle=${name}
|
|
accessToken=${this.state.accessToken}
|
|
inputMaxBytes=${maxSocketPayloadSize - EST_SOCKET_PAYLOAD_BUFFER ||
|
|
CHAT_MAX_MESSAGE_LENGTH}
|
|
/>
|
|
`
|
|
: null;
|
|
|
|
const TAB_CONTENT = [
|
|
{
|
|
label: 'About',
|
|
content: html`
|
|
<div>
|
|
<div
|
|
id="stream-summary"
|
|
class="stream-summary my-4"
|
|
dangerouslySetInnerHTML=${{ __html: summary }}
|
|
></div>
|
|
<div id="tag-list" class="tag-list text-gray-600 mb-3">
|
|
${tagList && `#${tagList}`}
|
|
</div>
|
|
<div
|
|
id="extra-user-content"
|
|
class="extra-user-content"
|
|
dangerouslySetInnerHTML=${{ __html: extraPageContent }}
|
|
></div>
|
|
</div>
|
|
`,
|
|
},
|
|
];
|
|
|
|
if (federation.enabled) {
|
|
TAB_CONTENT.push({
|
|
label: 'Followers',
|
|
content: html`<${Followers} />`,
|
|
});
|
|
}
|
|
|
|
return html`
|
|
<div
|
|
id="app-container"
|
|
class="flex w-full flex-col justify-start relative ${extraAppClasses}"
|
|
>
|
|
<style>
|
|
${customStyles}
|
|
</style>
|
|
|
|
<div id="top-content" class="z-50">
|
|
<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 mr-2 bg-no-repeat bg-center"
|
|
>
|
|
<img
|
|
class="logo visually-hidden"
|
|
src=${OWNCAST_LOGO_LOCAL}
|
|
alt="owncast logo"
|
|
/>
|
|
</span>
|
|
<span class="instance-title overflow-hidden truncate"
|
|
>${streamOnline && streamTitle ? streamTitle : name}</span
|
|
>
|
|
</h1>
|
|
<div
|
|
id="user-options-container"
|
|
class="flex flex-row justify-end items-center flex-no-wrap"
|
|
>
|
|
<${UsernameForm}
|
|
username=${username}
|
|
isModerator=${isModerator}
|
|
onUsernameChange=${this.handleUsernameChange}
|
|
onFocus=${this.handleFormFocus}
|
|
onBlur=${this.handleFormBlur}
|
|
/>
|
|
<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"
|
|
style=${{
|
|
display: chatDisabled || noVideoContent ? 'none' : 'block',
|
|
}}
|
|
>
|
|
💬
|
|
</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"
|
|
>
|
|
<video
|
|
class="video-js vjs-big-play-centered display-block w-full h-full"
|
|
id="video"
|
|
preload="auto"
|
|
controls
|
|
playsinline
|
|
></video>
|
|
${poster}
|
|
</div>
|
|
|
|
<section
|
|
id="stream-info"
|
|
aria-label="Stream status"
|
|
class="flex text-center flex-row justify-between font-mono py-2 px-4 bg-gray-900 text-indigo-200 shadow-md border-b border-gray-100 border-solid"
|
|
>
|
|
<span class="text-xs">${streamStatusMessage}</span>
|
|
<span id="stream-viewer-count" class="text-xs text-right"
|
|
>${viewerCountMessage}</span
|
|
>
|
|
</section>
|
|
</main>
|
|
|
|
<section
|
|
id="user-content"
|
|
aria-label="Owncast server information"
|
|
class="p-2"
|
|
>
|
|
${externalActionButtons && html`${externalActionButtons}`}
|
|
|
|
<div class="user-content flex flex-row p-8">
|
|
<div
|
|
class="user-logo-icons flex flex-col items-center justify-start mr-8"
|
|
>
|
|
<div
|
|
class="user-image rounded-full bg-white p-4 bg-no-repeat bg-center"
|
|
style=${bgUserLogo}
|
|
>
|
|
<img class="logo visually-hidden" alt="" src=${logo} />
|
|
</div>
|
|
<div class="social-actions">
|
|
<${SocialIconsList} handles=${socialHandles} />
|
|
</div>
|
|
</div>
|
|
|
|
<div class="user-content-header">
|
|
<h2 class="server-name font-semibold text-5xl">
|
|
<span class="streamer-name text-indigo-600">${name}</span>
|
|
</h2>
|
|
<h3 class="font-semibold text-3xl">
|
|
${streamOnline && streamTitle}
|
|
</h3>
|
|
|
|
<!-- tab bar -->
|
|
<div class="${TAB_CONTENT.length > 1 ? 'my-8' : 'my-3'}">
|
|
<${TabBar} tabs=${TAB_CONTENT} ariaLabel="User Content" />
|
|
</div>
|
|
</div>
|
|
</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}" rel="noopener noreferrer" target="_blank"
|
|
>${appVersion}</a
|
|
>
|
|
</span>
|
|
</footer>
|
|
|
|
${chat} ${externalActionModal} ${fediverseFollowModal}
|
|
</div>
|
|
`;
|
|
}
|
|
}
|