This repository has been archived on 2023-11-06. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-overlay/pages/overlay.js

404 lines
10 KiB
JavaScript
Raw Normal View History

2022-10-14 19:00:47 +00:00
import { Link } from "@nextui-org/react";
import { Component } from "react";
import PlayerStats from "../src/components/PlayerStats";
import ScoreStats from "../src/components/ScoreStats";
2022-10-10 08:34:38 +00:00
import SongInfo from "../src/components/SongInfo";
2022-10-14 19:00:47 +00:00
import Utils from "../src/utils/utils";
import styles from "../styles/overlay.module.css";
2022-10-10 08:34:38 +00:00
2022-10-10 12:14:25 +00:00
export default class Overlay extends Component {
2022-10-10 08:34:38 +00:00
#_beatSaverURL = "";
constructor(props) {
super(props);
this.state = {
loading: true,
2022-10-11 13:22:01 +00:00
isConnectedToSocket: false,
2022-10-10 08:34:38 +00:00
id: undefined,
isValidSteamId: true,
websiteType: "ScoreSaber",
data: undefined,
showPlayerStats: true,
showScore: false,
showSongInfo: false,
textColor: undefined,
2022-10-10 08:34:38 +00:00
socket: undefined,
isVisible: false,
songInfo: undefined,
beatSaverData: undefined,
currentSongTime: 0,
paused: true,
currentScore: 0,
percentage: "100.00%",
failed: false,
leftHand: {
2022-10-14 19:00:47 +00:00
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
2022-10-10 08:34:38 +00:00
},
rightHand: {
2022-10-14 19:00:47 +00:00
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
},
};
2022-10-10 08:34:38 +00:00
this.setupTimer();
}
// I'd love if HTTP Status just gave this data lmao
// HttpSiraStatus(https://github.com/denpadokei/HttpSiraStatus) does give this data.
isCurrentSongTimeProvided = false;
// we don't need to reset this to false because it is highly unlikely for a player to swap mods within a browser session
/**
* Setup the timer for the song time
*/
setupTimer() {
setInterval(() => {
if (this.isCurrentSongTimeProvided) {
2022-10-14 19:00:47 +00:00
return;
2022-10-10 08:34:38 +00:00
}
if (!this.state.paused && this.state.beatSaverData !== undefined) {
2022-10-14 19:00:47 +00:00
this.setState({ currentSongTime: this.state.currentSongTime + 1 });
2022-10-10 08:34:38 +00:00
}
}, 1000);
}
/**
* Update the current song time
2022-10-14 19:00:47 +00:00
*
2022-10-10 08:34:38 +00:00
* @param {[]} data The song data
*/
handleCurrentSongTime(data) {
try {
2022-10-14 19:00:47 +00:00
const time = data.status.performance.currentSongTime;
2022-10-10 08:34:38 +00:00
if (time !== undefined && time != null) {
2022-10-14 19:00:47 +00:00
this.isCurrentSongTimeProvided = true;
this.setState({ currentSongTime: time });
2022-10-10 08:34:38 +00:00
}
} catch (e) {
// do nothing
}
}
async componentDidMount() {
2022-10-14 19:00:47 +00:00
console.log("Initializing...");
this.#_beatSaverURL =
document.location.origin + "/api/beatsaver/map?hash=%s";
2022-10-10 08:34:38 +00:00
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
2022-10-10 17:38:06 +00:00
// Check what website the player wants to use
2022-10-14 19:00:47 +00:00
if (params.beatleader === "true") {
2022-10-10 08:34:38 +00:00
this.setState({ websiteType: "BeatLeader" });
}
const id = params.id;
2022-10-14 19:00:47 +00:00
if (!id) {
// Check if the id param is valid
2022-10-10 08:34:38 +00:00
this.setState({ loading: false, isValidSteamId: false });
return;
}
// Check if the player wants to disable their stats (pp, global pos, etc)
2022-10-14 19:00:47 +00:00
if (params.showPlayerStats === "false" || params.playerstats === "false") {
2022-10-10 08:34:38 +00:00
this.setState({ showPlayerStats: false });
}
setTimeout(async () => {
await this.updateData(id);
}, 10); // 10ms
let shouldConnectSocket = false;
// Check if the player wants to show their current score information
2022-10-14 19:00:47 +00:00
if (params.showScoreInfo === "true" || params.scoreinfo === "true") {
2022-10-10 08:34:38 +00:00
this.setState({ showScore: true });
shouldConnectSocket = true;
}
// Check if the player wants to show the current song
2022-10-14 19:00:47 +00:00
if (params.showSongInfo === "true" || params.songinfo === "true") {
2022-10-10 08:34:38 +00:00
this.setState({ showSongInfo: true });
shouldConnectSocket = true;
}
2022-10-14 19:00:47 +00:00
// Mainly used for the preview
2022-10-10 18:50:02 +00:00
if (params.textColor) {
this.setState({ textColor: params.textColor });
2022-10-10 17:38:06 +00:00
}
2022-10-10 08:34:38 +00:00
if (shouldConnectSocket) {
2022-10-11 13:22:01 +00:00
if (this.state.isConnectedToSocket) return;
2022-10-10 08:34:38 +00:00
this.connectSocket(params.socketaddress);
}
}
/**
* Fetch and update the data from the respective platform
2022-10-14 19:00:47 +00:00
*
2022-10-10 08:34:38 +00:00
* @param {string} id The steam id of the player
2022-10-14 19:00:47 +00:00
* @returns
2022-10-10 08:34:38 +00:00
*/
2022-10-14 19:00:47 +00:00
async updateData(id) {
const data = await fetch(
new Utils()
.getWebsiteApi(id == "test" ? "Test" : this.state.websiteType)
.ApiUrl.replace("%s", id),
{
mode: "cors",
}
);
2022-10-10 08:34:38 +00:00
const json = await data.json();
2022-10-14 19:00:47 +00:00
if (json.errorMessage) {
// Invalid account
2022-10-10 08:34:38 +00:00
this.setState({ loading: false, isValidSteamId: false });
return;
}
this.setState({ loading: false, id: id, data: json });
}
/**
* Setup the HTTP Status connection
*/
connectSocket(socketAddress) {
2022-10-14 19:00:47 +00:00
socketAddress =
(socketAddress === undefined
? "ws://localhost"
: `ws://${socketAddress}`) + ":6557/socket";
2022-10-11 13:22:01 +00:00
if (this.state.isConnectedToSocket) return;
if (this.state.isVisible) {
this.resetData(false);
}
2022-10-10 08:34:38 +00:00
console.log(`Connecting to ${socketAddress}`);
const socket = new WebSocket(socketAddress);
2022-10-14 19:00:47 +00:00
socket.addEventListener("open", () => {
console.log(`Connected to ${socketAddress}`);
2022-10-11 13:22:01 +00:00
this.setState({ isConnectedToSocket: true });
2022-10-14 19:00:47 +00:00
});
socket.addEventListener("close", () => {
console.log(
"Attempting to re-connect to the HTTP Status socket in 10 seconds."
);
2022-10-11 13:22:01 +00:00
this.setState({ isConnectedToSocket: false });
2022-10-10 12:14:25 +00:00
setTimeout(() => this.connectSocket(), 10_000);
2022-10-10 08:34:38 +00:00
});
2022-10-14 19:00:47 +00:00
socket.addEventListener("message", (message) => {
2022-10-10 08:34:38 +00:00
const json = JSON.parse(message.data);
2022-10-14 19:00:47 +00:00
this.handleCurrentSongTime(json);
2022-10-10 08:34:38 +00:00
if (!this.handlers[json.event]) {
console.log("Unhandled message from HTTP Status. (" + json.event + ")");
return;
}
this.handlers[json.event](json || []);
2022-10-14 19:00:47 +00:00
});
2022-10-10 08:34:38 +00:00
this.setState({ socket: socket });
}
/**
* Set the current songs beat saver url in {@link #_beatSaverURL}
2022-10-14 19:00:47 +00:00
*
* @param {[]} songData
2022-10-10 08:34:38 +00:00
*/
async setBeatSaver(songData) {
2022-10-14 19:00:47 +00:00
console.log("Updating BeatSaver info");
const data = await fetch(
this.#_beatSaverURL.replace("%s", songData.levelId)
);
2022-10-10 08:34:38 +00:00
const json = await data.json();
2022-10-14 19:00:47 +00:00
this.setState({ beatSaverData: json });
2022-10-10 08:34:38 +00:00
}
/**
* Cleanup the data and get ready for the next song
2022-10-14 19:00:47 +00:00
*
2022-10-10 08:34:38 +00:00
* @param {boolean} visible Whether to show info other than the player stats
*/
async resetData(visible) {
setTimeout(async () => {
2022-10-10 12:21:10 +00:00
await this.updateData(this.state.id);
2022-10-10 08:34:38 +00:00
}, 250);
this.setState({
leftHand: {
2022-10-14 19:00:47 +00:00
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
2022-10-10 08:34:38 +00:00
},
rightHand: {
2022-10-14 19:00:47 +00:00
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
2022-10-10 08:34:38 +00:00
},
songInfo: undefined,
beatSaverData: undefined,
currentSongTime: 0,
currentScore: 0,
percentage: "100.00%",
2022-10-14 19:00:47 +00:00
isVisible: visible,
2022-10-10 08:34:38 +00:00
});
}
// The HTTP Status handlers
handlers = {
2022-10-14 19:00:47 +00:00
hello: (data) => {
2022-10-10 08:34:38 +00:00
console.log("Hello from HTTP Status!");
if (data.status) {
2022-10-14 19:00:47 +00:00
this.setState({ songData: data });
2022-10-10 08:34:38 +00:00
if (data.status.beatmap) {
this.setBeatSaver(data.status.beatmap);
}
}
},
2022-10-14 19:00:47 +00:00
scoreChanged: (data) => {
2022-10-10 08:34:38 +00:00
const { status } = data;
const { score, currentMaxScore } = status.performance;
2022-10-14 19:00:47 +00:00
const percent =
currentMaxScore > 0
? (((score / currentMaxScore) * 1000) / 10).toFixed(2)
: 0.0;
2022-10-10 08:34:38 +00:00
this.setState({
currentScore: score,
2022-10-14 19:00:47 +00:00
percentage: this.state.failed ? percent * 2 : percent + "%",
});
2022-10-10 08:34:38 +00:00
},
2022-10-14 19:00:47 +00:00
noteFullyCut: (data) => {
2022-10-10 08:34:38 +00:00
const { noteCut } = data;
2022-10-14 19:00:47 +00:00
console.log(noteCut);
2022-10-10 08:34:38 +00:00
// Left Saber
2022-10-14 19:00:47 +00:00
if (noteCut.saberType === "SaberA") {
2022-10-10 08:34:38 +00:00
const data = this.state.leftHand;
if (data.averageCut.includes(15) && data.averageCut.length === 1) {
data.averageCut = [];
}
2022-10-14 19:00:47 +00:00
if (
data.averagePreSwing.includes(70) &&
data.averagePreSwing.length === 1
) {
2022-10-10 08:34:38 +00:00
data.averagePreSwing = [];
}
2022-10-14 19:00:47 +00:00
if (
data.averagePostSwing.includes(30) &&
data.averagePostSwing.length === 1
) {
2022-10-10 08:34:38 +00:00
data.averagePostSwing = [];
}
data.averagePreSwing.push(noteCut.beforeSwingRating * 70);
data.averagePostSwing.push(noteCut.afterSwingRating * 30);
2022-10-10 08:34:38 +00:00
data.averageCut.push(noteCut.cutDistanceScore);
this.setState({ leftHand: data });
}
// Left Saber
2022-10-14 19:00:47 +00:00
if (noteCut.saberType === "SaberB") {
2022-10-10 08:34:38 +00:00
const data = this.state.rightHand;
if (data.averageCut.includes(15) && data.averageCut.length === 1) {
data.averageCut = [];
}
2022-10-14 19:00:47 +00:00
if (
data.averagePreSwing.includes(70) &&
data.averagePreSwing.length === 1
) {
2022-10-10 08:34:38 +00:00
data.averagePreSwing = [];
}
2022-10-14 19:00:47 +00:00
if (
data.averagePostSwing.includes(30) &&
data.averagePostSwing.length === 1
) {
2022-10-10 08:34:38 +00:00
data.averagePostSwing = [];
}
data.averagePreSwing.push(noteCut.beforeSwingRating * 70);
data.averagePostSwing.push(noteCut.afterSwingRating * 30);
2022-10-10 08:34:38 +00:00
data.averageCut.push(noteCut.cutDistanceScore);
this.setState({ rightHand: data });
}
},
2022-10-14 19:00:47 +00:00
songStart: (data) => {
console.log("Going into level, resetting data.");
2022-10-10 08:34:38 +00:00
this.resetData(true);
2022-10-14 19:00:47 +00:00
this.setState({ songData: data, paused: false });
2022-10-10 08:34:38 +00:00
this.setBeatSaver(data.status.beatmap);
},
2022-10-14 19:00:47 +00:00
finished: () => {
2022-10-10 08:34:38 +00:00
this.resetData(false);
},
2022-10-14 19:00:47 +00:00
softFail: () => {
2022-10-10 08:34:38 +00:00
this.setState({ failed: true });
},
2022-10-14 19:00:47 +00:00
pause: () => {
2022-10-10 08:34:38 +00:00
this.setState({ paused: true });
},
2022-10-14 19:00:47 +00:00
resume: () => {
2022-10-10 08:34:38 +00:00
this.setState({ paused: false });
},
2022-10-14 19:00:47 +00:00
menu: () => {
2022-10-10 08:34:38 +00:00
this.resetData(false);
},
2022-10-14 19:00:47 +00:00
noteCut: () => {},
noteMissed: () => {},
noteSpawned: () => {},
bombMissed: () => {},
beatmapEvent: () => {},
energyChanged: () => {},
};
2022-10-10 08:34:38 +00:00
render() {
const { loading, isValidSteamId, data, websiteType } = this.state;
2022-10-14 19:00:47 +00:00
if (this.state.textColor !== undefined) {
const element = document.querySelector("." + styles.main);
element.style.color = this.state.textColor;
}
2022-10-10 17:38:06 +00:00
2022-10-14 19:00:47 +00:00
return (
<div className={styles.main}>
{loading ? (
<div className={styles.loading}>
<h2>Loading...</h2>
</div>
) : !isValidSteamId ? (
<div className={styles.invalidPlayer}>
<h1>Invalid player, please visit the main page.</h1>
<Link href="/">
<a>Go Home</a>
</Link>
</div>
) : (
<div className={styles.overlay}>
{this.state.showPlayerStats ? (
<PlayerStats
pp={data.pp.toLocaleString()}
globalPos={data.rank.toLocaleString()}
country={data.country}
countryRank={data.countryRank.toLocaleString()}
websiteType={websiteType}
avatar={data.profilePicture || data.avatar}
/>
) : (
<></>
)}
{this.state.showScore && this.state.isVisible ? (
<ScoreStats data={this.state} />
) : (
<></>
)}
{this.state.showSongInfo &&
this.state.beatSaverData !== undefined &&
this.state.isVisible ? (
<SongInfo data={this.state} />
) : (
<></>
)}
</div>
)}
2022-10-10 08:34:38 +00:00
</div>
2022-10-14 19:00:47 +00:00
);
2022-10-10 08:34:38 +00:00
}
2022-10-14 19:00:47 +00:00
}