0
owncast/webroot/js/websocket.js

140 lines
3.7 KiB
JavaScript
Raw Normal View History

import SOCKET_MESSAGE_TYPES from './utils/socket-message-types.js';
Merge of emoji + autolink + embed + etc (#108) * Add an emoji picker to chat * Update to the custom emoji picker and add first pass at using custom emoji in text box * Add custom emoji endpoint and use it in the app * Position the emoji picker * Handle events from the text input * pair down the number of party parrots * Size emoji in chat and input * Add new custom emoji * Add OMQ stickers as custom emoji * Show custom category for emoji picker by default * update omq emojis * Document basic supported markdown syntax. Closes #95 * Websocket refactor: Pull it out of the UI and support callbacks (#104) * Websocket refactor: Pull it out of the UI and support listeners * Changes required for Safari to be happy with modules * Move to explicit ad-hoc callback registration * Add an emoji picker to chat * Update to the custom emoji picker and add first pass at using custom emoji in text box * Handle events from the text input * Rebuild autolinking + embed handling for #93 * Re-enable disabling chat * Document basic supported markdown syntax. Closes #95 * Document basic supported markdown syntax. Closes #95 * Add an emoji picker to chat * Merge emoji and embeds. * Merge emoji + embed branches. Rework autolink +embeds. WIP for username highlighting for #100 * More updates to chat text formatting/embedding/linking * Fix username autocomplete to work with div instead of form elements * Post-rebase fixes + tweaks * Disable text input by setting contentEditable = false * Remove test that hardcodes pointing to public test server * Fix re-enable chat with the contentEditable input div * Style and fix the fake placeholder text in the input div * Missing file. Were did it go? * Set a height for instagram embeds * Cleanup Co-authored-by: Ginger Wong <omqmail@gmail.com>
2020-08-12 21:56:41 -07:00
const URL_WEBSOCKET = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/entry`;
const TIMER_WEBSOCKET_RECONNECT = 5000; // ms
export const CALLBACKS = {
RAW_WEBSOCKET_MESSAGE_RECEIVED: 'rawWebsocketMessageReceived',
WEBSOCKET_CONNECTED: 'websocketConnected',
WEBSOCKET_DISCONNECTED: 'websocketDisconnected',
}
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}`)
};
}
export default Websocket;