Connect to websocket and start accepting messages

This commit is contained in:
Gabe Kangas 2022-05-02 22:13:36 -07:00
parent a0354d6d49
commit 15becc5121
No known key found for this signature in database
GPG key ID: 9A56337728BC81EA
11 changed files with 107 additions and 39 deletions

View file

@ -183,7 +183,7 @@ func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request)
_, _ = w.Write([]byte(events.ErrorMaxConnectionsExceeded)) _, _ = w.Write([]byte(events.ErrorMaxConnectionsExceeded))
return return
} }
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
conn, err := upgrader.Upgrade(w, r, nil) conn, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
log.Debugln(err) log.Debugln(err)

View file

@ -1,3 +1,4 @@
/* eslint-disable no-case-declarations */
import { useEffect, useLayoutEffect } from 'react'; import { useEffect, useLayoutEffect } from 'react';
import { atom, useRecoilState, useSetRecoilState } from 'recoil'; import { atom, useRecoilState, useSetRecoilState } from 'recoil';
import { makeEmptyClientConfig, ClientConfig } from '../../interfaces/client-config.model'; import { makeEmptyClientConfig, ClientConfig } from '../../interfaces/client-config.model';
@ -13,6 +14,14 @@ import {
getChatState, getChatState,
getChatVisibilityState, getChatVisibilityState,
} from '../../interfaces/application-state'; } from '../../interfaces/application-state';
import {
SocketEvent,
ConnectedClientInfoEvent,
SocketMessageType,
ChatEvent,
} from '../../interfaces/socket-events';
import handleConnectedClientInfoMessage from './eventhandlers/connectedclientinfo';
import handleChatMessage from './eventhandlers/handleChatMessage';
// The config that comes from the API. // The config that comes from the API.
export const clientConfigStateAtom = atom({ export const clientConfigStateAtom = atom({
@ -52,12 +61,14 @@ export const chatMessagesAtom = atom<ChatMessage[]>({
export function ClientConfigStore() { export function ClientConfigStore() {
const setClientConfig = useSetRecoilState<ClientConfig>(clientConfigStateAtom); const setClientConfig = useSetRecoilState<ClientConfig>(clientConfigStateAtom);
const [appState, setAppState] = useRecoilState<AppState>(appStateAtom);
const setChatVisibility = useSetRecoilState<ChatVisibilityState>(chatVisibilityAtom); const setChatVisibility = useSetRecoilState<ChatVisibilityState>(chatVisibilityAtom);
const [chatState, setChatState] = useRecoilState<ChatState>(chatStateAtom); const setChatState = useSetRecoilState<ChatState>(chatStateAtom);
const setChatMessages = useSetRecoilState<ChatMessage[]>(chatMessagesAtom); const setChatMessages = useSetRecoilState<ChatMessage[]>(chatMessagesAtom);
const [accessToken, setAccessToken] = useRecoilState<string>(accessTokenAtom);
const setChatDisplayName = useSetRecoilState<string>(chatDisplayNameAtom); const setChatDisplayName = useSetRecoilState<string>(chatDisplayNameAtom);
const [appState, setAppState] = useRecoilState<AppState>(appStateAtom);
const [accessToken, setAccessToken] = useRecoilState<string>(accessTokenAtom);
let websocketService: WebsocketService;
const updateClientConfig = async () => { const updateClientConfig = async () => {
try { try {
@ -89,8 +100,20 @@ export function ClientConfigStore() {
} }
}; };
const handleMessage = (message: SocketEvent) => {
switch (message.type) {
case SocketMessageType.CONNECTED_USER_INFO:
handleConnectedClientInfoMessage(message as ConnectedClientInfoEvent);
break;
case SocketMessageType.CHAT:
handleChatMessage(message as ChatEvent);
break;
default:
console.error('Unknown socket message type: ', message.type);
}
};
const getChatHistory = async () => { const getChatHistory = async () => {
setChatState(ChatState.Loading);
try { try {
const messages = await ChatService.getChatHistory(accessToken); const messages = await ChatService.getChatHistory(accessToken);
// console.log(`ChatService -> getChatHistory() messages: \n${JSON.stringify(messages)}`); // console.log(`ChatService -> getChatHistory() messages: \n${JSON.stringify(messages)}`);
@ -98,6 +121,16 @@ export function ClientConfigStore() {
} catch (error) { } catch (error) {
console.error(`ChatService -> getChatHistory() ERROR: \n${error}`); console.error(`ChatService -> getChatHistory() ERROR: \n${error}`);
} }
};
const startChat = async () => {
setChatState(ChatState.Loading);
try {
websocketService = new WebsocketService(accessToken, '/ws');
websocketService.handleMessage = handleMessage;
} catch (error) {
console.error(`ChatService -> startChat() ERROR: \n${error}`);
}
setChatState(ChatState.Available); setChatState(ChatState.Available);
}; };
@ -111,8 +144,8 @@ export function ClientConfigStore() {
return; return;
} }
console.log('access token changed', accessToken);
getChatHistory(); getChatHistory();
startChat();
}, [accessToken]); }, [accessToken]);
useEffect(() => { useEffect(() => {

View file

@ -0,0 +1,5 @@
import { ConnectedClientInfoEvent, SocketEvent } from '../../../interfaces/socket-events';
export default function handleConnectedClientInfoMessage(message: ConnectedClientInfoEvent) {
console.log('connected client', message);
}

View file

@ -0,0 +1,8 @@
import {
ChatEvent,
SocketEvent,
} from '../../../interfaces/socket-events';
export default function handleChatMessage(message: ChatEvent) {
console.log('chat message', message);
}

View file

@ -11,7 +11,8 @@ export default function OwncastPlayer(props) {
autoplay: false, autoplay: false,
controls: true, controls: true,
responsive: true, responsive: true,
fluid: true, fluid: false,
playsInline: true,
liveui: true, liveui: true,
preload: 'auto', preload: 'auto',
controlBar: { controlBar: {

View file

@ -1,9 +1,7 @@
import { User } from './user'; import { SocketEvent } from './socket-events';
import { User } from './user.model';
export interface ChatMessage { export interface ChatMessage extends SocketEvent {
id: string;
type: string;
timestamp: Date;
user: User; user: User;
body: string; body: string;
} }

View file

@ -0,0 +1,33 @@
import { User } from './user.model';
export enum SocketMessageType {
CHAT = 'CHAT',
PING = 'PING',
NAME_CHANGE = 'NAME_CHANGE',
PONG = 'PONG',
SYSTEM = 'SYSTEM',
USER_JOINED = 'USER_JOINED',
CHAT_ACTION = 'CHAT_ACTION',
FEDIVERSE_ENGAGEMENT_FOLLOW = 'FEDIVERSE_ENGAGEMENT_FOLLOW',
FEDIVERSE_ENGAGEMENT_LIKE = 'FEDIVERSE_ENGAGEMENT_LIKE',
FEDIVERSE_ENGAGEMENT_REPOST = 'FEDIVERSE_ENGAGEMENT_REPOST',
CONNECTED_USER_INFO = 'CONNECTED_USER_INFO',
ERROR_USER_DISABLED = 'ERROR_USER_DISABLED',
ERROR_NEEDS_REGISTRATION = 'ERROR_NEEDS_REGISTRATION',
ERROR_MAX_CONNECTIONS_EXCEEDED = 'ERROR_MAX_CONNECTIONS_EXCEEDED',
VISIBILITY_UPDATE = 'VISIBILITY-UPDATE',
}
export interface SocketEvent {
id: string;
timestamp: Date;
type: SocketMessageType;
}
export interface ConnectedClientInfoEvent extends SocketEvent {
user: User;
}
export interface ChatEvent extends SocketEvent {
user: User;
body: string;
}

View file

@ -24,8 +24,8 @@ class ChatService {
body: JSON.stringify({ displayName: username }), body: JSON.stringify({ displayName: username }),
}; };
const response = await getUnauthedData(URL_CHAT_REGISTRATION, options); const response = await getUnauthedData(URL_CHAT_REGISTRATION, options);
return response; return response;
} }
} }

View file

@ -1,22 +1,7 @@
import { message } from "antd"; import { message } from 'antd';
import { SocketMessageType } from '../interfaces/socket-events';
enum SocketMessageType {
CHAT = 'CHAT',
PING = 'PING',
NAME_CHANGE = 'NAME_CHANGE',
PONG = 'PONG',
SYSTEM = 'SYSTEM',
USER_JOINED = 'USER_JOINED',
CHAT_ACTION = 'CHAT_ACTION',
FEDIVERSE_ENGAGEMENT_FOLLOW = 'FEDIVERSE_ENGAGEMENT_FOLLOW',
FEDIVERSE_ENGAGEMENT_LIKE = 'FEDIVERSE_ENGAGEMENT_LIKE',
FEDIVERSE_ENGAGEMENT_REPOST = 'FEDIVERSE_ENGAGEMENT_REPOST',
CONNECTED_USER_INFO = 'CONNECTED_USER_INFO',
ERROR_USER_DISABLED = 'ERROR_USER_DISABLED',
ERROR_NEEDS_REGISTRATION = 'ERROR_NEEDS_REGISTRATION',
ERROR_MAX_CONNECTIONS_EXCEEDED = 'ERROR_MAX_CONNECTIONS_EXCEEDED',
VISIBILITY_UPDATE = 'VISIBILITY-UPDATE',
};
interface SocketMessage { interface SocketMessage {
type: SocketMessageType; type: SocketMessageType;
@ -32,9 +17,11 @@ export default class WebsocketService {
websocketReconnectTimer: ReturnType<typeof setTimeout>; websocketReconnectTimer: ReturnType<typeof setTimeout>;
handleMessage?: (message: SocketMessage) => void;
constructor(accessToken, path) { constructor(accessToken, path) {
this.accessToken = accessToken; this.accessToken = accessToken;
this.path = 'http://localhost:8080/ws'; this.path = path;
// this.websocketReconnectTimer = null; // this.websocketReconnectTimer = null;
// this.accessToken = accessToken; // this.accessToken = accessToken;
@ -53,9 +40,10 @@ export default class WebsocketService {
} }
createAndConnect() { createAndConnect() {
const url = new URL(this.path); const url = new URL('ws://localhost:8080/ws');
url.searchParams.append('accessToken', this.accessToken); url.searchParams.append('accessToken', this.accessToken);
console.log('connecting to ', url.toString());
const ws = new WebSocket(url.toString()); const ws = new WebSocket(url.toString());
ws.onopen = this.onOpen.bind(this); ws.onopen = this.onOpen.bind(this);
// ws.onclose = this.onClose.bind(this); // ws.onclose = this.onClose.bind(this);
@ -73,7 +61,8 @@ export default class WebsocketService {
// On ws error just close the socket and let it re-connect again for now. // On ws error just close the socket and let it re-connect again for now.
onError(e) { onError(e) {
handleNetworkingError(`Socket error: ${JSON.parse(e)}`); console.error(e)
handleNetworkingError(`Socket error: ${e}`);
this.websocket.close(); this.websocket.close();
// if (!this.isShutdown) { // if (!this.isShutdown) {
// this.scheduleReconnect(); // this.scheduleReconnect();
@ -95,6 +84,9 @@ export default class WebsocketService {
for (let i = 0; i < messages.length; i++) { for (let i = 0; i < messages.length; i++) {
try { try {
message = JSON.parse(messages[i]); message = JSON.parse(messages[i]);
if (this.handleMessage) {
this.handleMessage(message);
}
} catch (e) { } catch (e) {
console.error(e, e.data); console.error(e, e.data);
return; return;
@ -133,6 +125,6 @@ export default class WebsocketService {
function handleNetworkingError(error) { function handleNetworkingError(error) {
console.error( console.error(
`Chat has been disconnected and is likely not working for you. It's possible you were removed from chat. If this is a server configuration issue, visit troubleshooting steps to resolve. https://owncast.online/docs/troubleshooting/#chat-is-disabled: ${error}` `Chat has been disconnected and is likely not working for you. It's possible you were removed from chat. If this is a server configuration issue, visit troubleshooting steps to resolve. https://owncast.online/docs/troubleshooting/#chat-is-disabled: ${error}`,
); );
} }

View file

@ -120,8 +120,6 @@ interface FetchOptions {
auth?: boolean; auth?: boolean;
} }
export async function fetchData(url: string, options?: FetchOptions) { export async function fetchData(url: string, options?: FetchOptions) {
const { data, method = 'GET', auth = true } = options || {}; const { data, method = 'GET', auth = true } = options || {};