reorganize js files
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
import { addNewlines } from '../utils.js';
|
||||
|
||||
export const KEY_USERNAME = 'owncast_username';
|
||||
export const KEY_AVATAR = 'owncast_avatar';
|
||||
export const KEY_CHAT_DISPLAYED = 'owncast_chat';
|
||||
export const KEY_CHAT_FIRST_MESSAGE_SENT = 'owncast_first_message_sent';
|
||||
export const CHAT_INITIAL_PLACEHOLDER_TEXT = 'Type here to chat, no account necessary.';
|
||||
export const CHAT_PLACEHOLDER_TEXT = 'Message';
|
||||
export const CHAT_PLACEHOLDER_OFFLINE = 'Chat is offline.';
|
||||
import { addNewlines } from './helpers.js';
|
||||
import {
|
||||
KEY_USERNAME,
|
||||
KEY_AVATAR,
|
||||
KEY_CHAT_DISPLAYED,
|
||||
KEY_CHAT_FIRST_MESSAGE_SENT,
|
||||
CHAT_INITIAL_PLACEHOLDER_TEXT,
|
||||
CHAT_PLACEHOLDER_TEXT,
|
||||
CHAT_PLACEHOLDER_OFFLINE,
|
||||
} from './constants.js';
|
||||
|
||||
export function formatMessageText(message, username) {
|
||||
showdown.setFlavor('github');
|
||||
|
||||
29
webroot/js/utils/constants.js
Normal file
29
webroot/js/utils/constants.js
Normal file
@@ -0,0 +1,29 @@
|
||||
// misc constants used throughout the app
|
||||
|
||||
export const URL_STATUS = `/status`;
|
||||
export const URL_CHAT_HISTORY = `/chat`;
|
||||
export const URL_CUSTOM_EMOJIS = `/emoji`;
|
||||
export const URL_CONFIG = `/config`;
|
||||
|
||||
// TODO: This directory is customizable in the config. So we should expose this via the config API.
|
||||
export const URL_STREAM = `/hls/stream.m3u8`;
|
||||
export const URL_WEBSOCKET = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/entry`;
|
||||
|
||||
export const TIMER_STATUS_UPDATE = 5000; // ms
|
||||
export const TIMER_DISABLE_CHAT_AFTER_OFFLINE = 5 * 60 * 1000; // 5 mins
|
||||
export const TIMER_STREAM_DURATION_COUNTER = 1000;
|
||||
export const TEMP_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
|
||||
|
||||
export const MESSAGE_OFFLINE = 'Stream is offline.';
|
||||
export const MESSAGE_ONLINE = 'Stream is online';
|
||||
|
||||
export const URL_OWNCAST = 'https://github.com/gabek/owncast'; // used in footer
|
||||
|
||||
|
||||
export const KEY_USERNAME = 'owncast_username';
|
||||
export const KEY_AVATAR = 'owncast_avatar';
|
||||
export const KEY_CHAT_DISPLAYED = 'owncast_chat';
|
||||
export const KEY_CHAT_FIRST_MESSAGE_SENT = 'owncast_first_message_sent';
|
||||
export const CHAT_INITIAL_PLACEHOLDER_TEXT = 'Type here to chat, no account necessary.';
|
||||
export const CHAT_PLACEHOLDER_TEXT = 'Message';
|
||||
export const CHAT_PLACEHOLDER_OFFLINE = 'Chat is offline.';
|
||||
130
webroot/js/utils/helpers.js
Normal file
130
webroot/js/utils/helpers.js
Normal file
@@ -0,0 +1,130 @@
|
||||
export function getLocalStorage(key) {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch (e) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function setLocalStorage(key, value) {
|
||||
try {
|
||||
if (value !== "" && value !== null) {
|
||||
localStorage.setItem(key, value);
|
||||
} else {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
return true;
|
||||
} catch (e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function clearLocalStorage(key) {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
|
||||
// jump down to the max height of a div, with a slight delay
|
||||
export function jumpToBottom(element) {
|
||||
if (!element) return;
|
||||
|
||||
setTimeout(() => {
|
||||
element.scrollTo({
|
||||
top: element.scrollHeight,
|
||||
left: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 50, element);
|
||||
}
|
||||
|
||||
// convert newlines to <br>s
|
||||
export function addNewlines(str) {
|
||||
return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
|
||||
}
|
||||
|
||||
export function pluralize(string, count) {
|
||||
if (count === 1) {
|
||||
return string;
|
||||
} else {
|
||||
return string + "s";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Trying to determine if browser is mobile/tablet.
|
||||
// Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
|
||||
export function hasTouchScreen() {
|
||||
let hasTouch = false;
|
||||
if ("maxTouchPoints" in navigator) {
|
||||
hasTouch = navigator.maxTouchPoints > 0;
|
||||
} else if ("msMaxTouchPoints" in navigator) {
|
||||
hasTouch = navigator.msMaxTouchPoints > 0;
|
||||
} else {
|
||||
var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
|
||||
if (mQ && mQ.media === "(pointer:coarse)") {
|
||||
hasTouch = !!mQ.matches;
|
||||
} else if ('orientation' in window) {
|
||||
hasTouch = true; // deprecated, but good fallback
|
||||
} else {
|
||||
// Only as a last resort, fall back to user agent sniffing
|
||||
var UA = navigator.userAgent;
|
||||
hasTouch = (
|
||||
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
|
||||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
|
||||
);
|
||||
}
|
||||
}
|
||||
return hasTouch;
|
||||
}
|
||||
|
||||
// generate random avatar from https://robohash.org
|
||||
export function generateAvatar(hash) {
|
||||
const avatarSource = 'https://robohash.org/';
|
||||
const optionSize = '?size=80x80';
|
||||
const optionSet = '&set=set2';
|
||||
const optionBg = ''; // or &bgset=bg1 or bg2
|
||||
|
||||
return avatarSource + hash + optionSize + optionSet + optionBg;
|
||||
}
|
||||
|
||||
export function generateUsername() {
|
||||
return `User ${(Math.floor(Math.random() * 42) + 1)}`;
|
||||
}
|
||||
|
||||
export function secondsToHMMSS(seconds = 0) {
|
||||
const finiteSeconds = Number.isFinite(+seconds) ? Math.abs(seconds) : 0;
|
||||
|
||||
const hours = Math.floor(finiteSeconds / 3600);
|
||||
const hoursString = hours ? `${hours}:` : '';
|
||||
|
||||
const mins = Math.floor((finiteSeconds / 60) % 60);
|
||||
const minString = mins < 10 ? `0${mins}:` : `${mins}:`;
|
||||
|
||||
const secs = Math.floor(finiteSeconds % 60);
|
||||
const secsString = secs < 10 ? `0${secs}` : `${secs}`;
|
||||
|
||||
return hoursString + minString + secsString;
|
||||
}
|
||||
|
||||
export function setVHvar() {
|
||||
var vh = window.innerHeight * 0.01;
|
||||
// Then we set the value in the --vh custom property to the root of the document
|
||||
document.documentElement.style.setProperty('--vh', `${vh}px`);
|
||||
console.log("== new vh", vh)
|
||||
}
|
||||
|
||||
export function doesObjectSupportFunction(object, functionName) {
|
||||
return typeof object[functionName] === "function";
|
||||
}
|
||||
|
||||
// return a string of css classes
|
||||
export function classNames(json) {
|
||||
const classes = [];
|
||||
|
||||
Object.entries(json).map(function(item) {
|
||||
const [ key, value ] = item;
|
||||
if (value) {
|
||||
classes.push(key);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return classes.join(' ');
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
// x, y pixel psitions of /img/social.gif image.
|
||||
export const SOCIAL_PLATFORMS = {
|
||||
default: {
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
/**
|
||||
* These are the types of messages that we can handle with the websocket.
|
||||
* Mostly used by `websocket.js` but if other components need to handle
|
||||
* different types then it can import this file.
|
||||
*/
|
||||
export default {
|
||||
CHAT: 'CHAT',
|
||||
PING: 'PING',
|
||||
NAME_CHANGE: 'NAME_CHANGE',
|
||||
PONG: 'PONG'
|
||||
};
|
||||
145
webroot/js/utils/websocket.js
Normal file
145
webroot/js/utils/websocket.js
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* These are the types of messages that we can handle with the websocket.
|
||||
* Mostly used by `websocket.js` but if other components need to handle
|
||||
* different types then it can import this file.
|
||||
*/
|
||||
export const SOCKET_MESSAGE_TYPES = {
|
||||
CHAT: 'CHAT',
|
||||
PING: 'PING',
|
||||
NAME_CHANGE: 'NAME_CHANGE',
|
||||
PONG: 'PONG'
|
||||
};
|
||||
|
||||
export const CALLBACKS = {
|
||||
RAW_WEBSOCKET_MESSAGE_RECEIVED: 'rawWebsocketMessageReceived',
|
||||
WEBSOCKET_CONNECTED: 'websocketConnected',
|
||||
WEBSOCKET_DISCONNECTED: 'websocketDisconnected',
|
||||
}
|
||||
|
||||
const URL_WEBSOCKET = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/entry`;
|
||||
const TIMER_WEBSOCKET_RECONNECT = 5000; // ms
|
||||
|
||||
export default class Websocket {
|
||||
constructor() {
|
||||
this.websocket = null;
|
||||
this.websocketReconnectTimer = null;
|
||||
|
||||
this.websocketConnectedListeners = [];
|
||||
this.websocketDisconnectListeners = [];
|
||||
this.rawMessageListeners = [];
|
||||
|
||||
this.send = this.send.bind(this);
|
||||
|
||||
const ws = new WebSocket(URL_WEBSOCKET);
|
||||
ws.onopen = this.onOpen.bind(this);
|
||||
ws.onclose = this.onClose.bind(this);
|
||||
ws.onerror = this.onError.bind(this);
|
||||
ws.onmessage = this.onMessage.bind(this);
|
||||
|
||||
this.websocket = ws;
|
||||
}
|
||||
|
||||
// Other components should register for websocket callbacks.
|
||||
addListener(type, callback) {
|
||||
if (type == CALLBACKS.WEBSOCKET_CONNECTED) {
|
||||
this.websocketConnectedListeners.push(callback);
|
||||
} else if (type == CALLBACKS.WEBSOCKET_DISCONNECTED) {
|
||||
this.websocketDisconnectListeners.push(callback);
|
||||
} else if (type == CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED) {
|
||||
this.rawMessageListeners.push(callback);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Interface with other components
|
||||
|
||||
// Outbound: Other components can pass an object to `send`.
|
||||
send(message) {
|
||||
// Sanity check that what we're sending is a valid type.
|
||||
if (!message.type || !SOCKET_MESSAGE_TYPES[message.type]) {
|
||||
console.warn(`Outbound message: Unknown socket message type: "${message.type}" sent.`);
|
||||
}
|
||||
|
||||
const messageJSON = JSON.stringify(message);
|
||||
this.websocket.send(messageJSON);
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
// Fire the callbacks of the listeners.
|
||||
|
||||
notifyWebsocketConnectedListeners(message) {
|
||||
this.websocketConnectedListeners.forEach(function (callback) {
|
||||
callback(message);
|
||||
});
|
||||
}
|
||||
|
||||
notifyWebsocketDisconnectedListeners(message) {
|
||||
this.websocketDisconnectListeners.forEach(function (callback) {
|
||||
callback(message);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
notifyRawMessageListeners(message) {
|
||||
this.rawMessageListeners.forEach(function (callback) {
|
||||
callback(message);
|
||||
});
|
||||
}
|
||||
|
||||
// Internal websocket callbacks
|
||||
|
||||
onOpen(e) {
|
||||
if (this.websocketReconnectTimer) {
|
||||
clearTimeout(this.websocketReconnectTimer);
|
||||
}
|
||||
|
||||
this.notifyWebsocketConnectedListeners();
|
||||
}
|
||||
|
||||
onClose(e) {
|
||||
// connection closed, discard old websocket and create a new one in 5s
|
||||
this.websocket = null;
|
||||
this.notifyWebsocketDisconnectedListeners();
|
||||
this.handleNetworkingError('Websocket closed.');
|
||||
this.websocketReconnectTimer = setTimeout(this.setupWebsocket, TIMER_WEBSOCKET_RECONNECT);
|
||||
}
|
||||
|
||||
// On ws error just close the socket and let it re-connect again for now.
|
||||
onError(e) {
|
||||
this.handleNetworkingError(`Socket error: ${JSON.parse(e)}`);
|
||||
this.websocket.close();
|
||||
}
|
||||
|
||||
/*
|
||||
onMessage is fired when an inbound object comes across the websocket.
|
||||
If the message is of type `PING` we send a `PONG` back and do not
|
||||
pass it along to listeners.
|
||||
*/
|
||||
onMessage(e) {
|
||||
try {
|
||||
var model = JSON.parse(e.data);
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
|
||||
// Send PONGs
|
||||
if (model.type === SOCKET_MESSAGE_TYPES.PING) {
|
||||
this.sendPong();
|
||||
return;
|
||||
}
|
||||
|
||||
// Notify any of the listeners via the raw socket message callback.
|
||||
this.notifyRawMessageListeners(model);
|
||||
}
|
||||
|
||||
// Reply to a PING as a keep alive.
|
||||
sendPong() {
|
||||
const pong = { type: SOCKET_MESSAGE_TYPES.PONG };
|
||||
this.send(pong);
|
||||
}
|
||||
|
||||
handleNetworkingError(error) {
|
||||
console.error(`Websocket Error: ${error}`)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user