Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Align web socket commands with LiveView server #397

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 35 additions & 57 deletions src/ui/TimerView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import AutoRefreshLayout from "../layout/AutoRefreshLayout";
import LiveSplitIcon from "../assets/icon_small.png";

import "../css/TimerView.scss";
import { WebSocketManager } from "../util/WebSocketManager";

export interface Props {
isDesktop: boolean,
Expand Down Expand Up @@ -40,11 +41,31 @@ interface Callbacks {
}

export class TimerView extends React.Component<Props, State> {
private connection: Option<WebSocket>;
private connection: WebSocketManager;

constructor(props: Props) {
super(props);

this.connection = new WebSocketManager({
start: () => this.start(),
split: () => this.split(),
splitOrStart: () => this.splitOrStart(),
reset: () => this.reset(),
undoSplit: () => this.undoSplit(),
skip: () => this.skipSplit(),
initGameTime: () => this.initializeGameTime(),
setGameTime: (time: string) => this.setGameTime(time),
setLoadingTimes: (loadTime: string) => this.setLoadingTimes(loadTime),
pauseGameTime: () => this.pauseGameTime(),
resumeGameTime: () => this.resumeGameTime(),
getCurrentTime: (cb: (totalSeconds: number) => void) => this.getTime(cb),
getCurrentPhase: (cb: (currentPhase: number) => void) => this.getCurrentPhase(cb),
togglePause: () => this.togglePauseOrStart(),
},
{
info: toast.info,
error: toast.error
});
this.state = {
comparison: null,
timingMethod: null,
Expand Down Expand Up @@ -168,7 +189,7 @@ export class TimerView extends React.Component<Props, State> {
<button onClick={(_) => this.connectToServerOrDisconnect()}>
{
(() => {
const connectionState = this.connection?.readyState ?? WebSocket.CLOSED;
const connectionState = this.connection.connectionState();
switch (connectionState) {
case WebSocket.OPEN:
return <div>
Expand Down Expand Up @@ -219,61 +240,18 @@ export class TimerView extends React.Component<Props, State> {
}

private connectToServerOrDisconnect() {
if (this.connection) {
if (this.connection.readyState === WebSocket.OPEN) {
this.connection.close();
this.forceUpdate();
}
return;
}
const url = prompt("Specify the WebSocket URL:");
if (!url) {
return;
}
try {
this.connection = new WebSocket(url);
} catch (e) {
toast.error(`Failed to connect: ${e}`);
throw e;
}
this.forceUpdate();
let wasConnected = false;
this.connection.onopen = (_) => {
wasConnected = true;
toast.info("Connected to server");
this.forceUpdate();
};
this.connection.onerror = (e) => {
toast.error(e);
};
this.connection.onmessage = (e) => {
// FIXME: Clone the Shared Timer. This assumes that `this` is always
// mounted.
if (typeof e.data === "string") {
const [command, ...args] = e.data.split(" ");
switch (command) {
case "start": this.start(); break;
case "split": this.split(); break;
case "splitorstart": this.splitOrStart(); break;
case "reset": this.reset(); break;
case "togglepause": this.togglePauseOrStart(); break;
case "undo": this.undoSplit(); break;
case "skip": this.skipSplit(); break;
case "initgametime": this.initializeGameTime(); break;
case "setgametime": this.setGameTime(args[0]); break;
case "setloadingtimes": this.setLoadingTimes(args[0]); break;
case "pausegametime": this.pauseGameTime(); break;
case "resumegametime": this.resumeGameTime(); break;
}
}
};
this.connection.onclose = (_) => {
if (wasConnected) {
toast.info("Closed connection to server");
}
this.connection = null;
this.forceUpdate();
};
const connectionState = this.connection.connectionState();
connectionState === WebSocket.OPEN ? this.connection.disconnect() : this.connection.connectToServer();
}

private getTime(cb: (totalSeconds: number) => void) {
this.readWith((t) => {
cb(t.currentTime().realTime()!.totalSeconds());
});
}

private getCurrentPhase(cb: (phase: number) => void) {
this.readWith((t) => cb(t.currentPhase()));
}

private writeWith<T>(action: (timer: TimerRefMut) => T): T {
Expand Down
121 changes: 121 additions & 0 deletions src/util/WebSocketManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { expect } from './OptionUtil';
import { ToastContent } from 'react-toastify';

type TimerActions = {
start: () => void,
split: () => void,
splitOrStart: () => void,
reset: () => void,
undoSplit: () => void,
skip: () => void,
initGameTime: () => void,
setGameTime: (gameTime: string) => void,
setLoadingTimes: (loadingTime: string) => void,
pauseGameTime: () => void,
resumeGameTime: () => void,
getCurrentTime: (valueCallback: ((totalSeconds: number) => void)) => void,
getCurrentPhase: (valueCallback: ((phase: number) => void)) => void,
togglePause: () => void
};

type UIActions = {
info: (message: string | ToastContent) => void,
error: (message: string | ToastContent) => void
};

export class WebSocketManager {

ws: WebSocket | null = null;
actions!: TimerActions;
uiActions!: UIActions;

public constructor(actions: TimerActions, uiActions: UIActions) {
this.actions = actions;
this.uiActions = uiActions;
return this;
}

public connectToServer() {
const url = prompt("Enter Websocket server address");
if (url) {
this.setupWebSocket(url);
}
}

private setupWebSocket(url: string) {
this.ws = new WebSocket(url);
this.ws.onopen = () => this.uiActions.info("Connected to websocket");
this.ws.onmessage = this.handleCommand.bind(this);
this.ws.onclose = () => {
this.disconnect();
};
this.ws.onerror = (e: Event) => this.uiActions.error(e);
}

public disconnect() {
this.uiActions.error("Disconnected from websocket");
this.ws = null;
}

public connectionState() {
return this.ws?.readyState ?? WebSocket.CLOSED;
}

private handleCommand(e: MessageEvent) {
if (typeof e.data === "string") {
const [command, ...args] = e.data.split(" ");
switch (command) {
case "starttimer": this.actions.start(); break;
case "getcurrenttime": this.getAndSendCurrentTime(); break;
case "getcurrenttimerphase": this.getAndSendCurrentPhase(); break;
case "split": this.actions.split(); break;
case "splitorstart": this.actions.splitOrStart(); break;
case "reset": this.actions.reset(); break;
case "pause":
case "resume":
case "togglepause": this.actions.togglePause(); break; // These are different aliases for the same command
case "unsplit": this.actions.undoSplit(); break;
case "skipsplit": this.actions.skip(); break;
case "initgametime": this.actions.initGameTime(); break;
case "setgametime": this.actions.setGameTime(args[0]); break;
case "setloadingtimes": this.actions.setLoadingTimes(args[0]); break;
case "pausegametime": this.actions.pauseGameTime(); break;
case "resumegametime": this.actions.resumeGameTime(); break;
}
}
}

private getAndSendCurrentTime() {
this.actions.getCurrentTime((time) => {
this.sendResponse(this.formatTimeForServer(time));
});
}

private getAndSendCurrentPhase() {
this.actions.getCurrentPhase((phase) => {
this.sendResponse(this.mapPhaseEnumToString(phase));
});
}

private sendResponse(value: string) {
this.ws?.send(value);
}

private mapPhaseEnumToString(phase: number) : string {
const phases = ["NotRunning", "Running", "Ended", "Paused"];
return expect(phases[phase], "Invalid Phase");
}

private formatTimeForServer(totalSeconds: number): string {
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
const twoDigitString = (n: number) => n.toLocaleString('en-gb', { minimumIntegerDigits: 2});
const secondsWithMilliseconds = (n: number) => n.toLocaleString('en-gb', {minimumIntegerDigits: 2, minimumFractionDigits: 2, maximumFractionDigits: 2});
if (hours > 0) {
return `${twoDigitString(hours)}:${twoDigitString(minutes)}:${secondsWithMilliseconds(seconds)}`;
}
return `${twoDigitString(minutes)}:${secondsWithMilliseconds(seconds)}`;
}
}