Formatted code

This commit is contained in:
Liam 2022-10-14 20:00:47 +01:00
parent 5b1c408fb9
commit 7c713a99ab
22 changed files with 759 additions and 586 deletions

@ -1,11 +1,11 @@
// 1. import `NextUIProvider` component
import { NextUIProvider } from '@nextui-org/react';
import { NextSeo } from 'next-seo';
import Head from 'next/head'
import { NextUIProvider } from "@nextui-org/react";
import { NextSeo } from "next-seo";
import Head from "next/head";
import Config from '../config.json';
import Config from "../config.json";
import '../styles/globals.css';
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return (
@ -22,9 +22,9 @@ function MyApp({ Component, pageProps }) {
images: [
{
url: "https://cdn.fascinated.cc/YrATaLjUOP.png?raw=true",
alt: "Site Example"
}
]
alt: "Site Example",
},
],
}}
twitter={{
cardType: "summary_large_image",
@ -33,13 +33,19 @@ function MyApp({ Component, pageProps }) {
/>
<Head>
<meta name="theme-color" content= {Config.color} />
<meta property="og:keywords" content="BeatSaber,Overlay,OBS,Twitch,YouTube,BeatSaber Overlay,Github," />
<meta name="theme-color" content={Config.color} />
<meta
property="og:keywords"
content="BeatSaber,Overlay,OBS,Twitch,YouTube,BeatSaber Overlay,Github,"
/>
<noscript>
<img src="https://analytics.fascinated.cc/ingress/4bc413fa-a126-4860-9a6a-22d10d5cf2fb/pixel.gif" />
</noscript>
<script defer src="https://analytics.fascinated.cc/ingress/4bc413fa-a126-4860-9a6a-22d10d5cf2fb/script.js"></script>
<script
defer
src="https://analytics.fascinated.cc/ingress/4bc413fa-a126-4860-9a6a-22d10d5cf2fb/script.js"
></script>
</Head>
<Component {...pageProps} />
</NextUIProvider>

@ -1,13 +1,13 @@
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { CssBaseline } from '@nextui-org/react';
import { CssBaseline } from "@nextui-org/react";
import Document, { Head, Html, Main, NextScript } from "next/document";
import React from "react";
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: React.Children.toArray([initialProps.styles])
styles: React.Children.toArray([initialProps.styles]),
};
}

@ -1,7 +1,7 @@
import fs from 'fs';
import path from 'path';
import sharp from 'sharp';
import fetch from 'node-fetch';
import fs from "fs";
import fetch from "node-fetch";
import path from "path";
import sharp from "sharp";
const cacheDir = process.cwd() + path.sep + "cache";
if (!fs.existsSync(cacheDir)) {
@ -20,12 +20,12 @@ export default async function handler(req, res) {
let buffer = await data.buffer();
buffer = await sharp(buffer).resize(150, 150).toBuffer();
fs.writeFileSync(imagePath, buffer);
res.setHeader('Content-Type', 'image/' + ext);
res.setHeader("Content-Type", "image/" + ext);
res.send(buffer);
console.log("Song Art Cache - Added song \"" + mapHash + "\"");
console.log('Song Art Cache - Added song "' + mapHash + '"');
return;
}
const buffer = fs.readFileSync(imagePath);
res.setHeader('Content-Type', 'image/jpg' + ext);
res.setHeader("Content-Type", "image/jpg" + ext);
res.send(buffer);
}

@ -1,16 +1,23 @@
import Utils from '../../../utils/utils';
import Utils from "../../../utils/utils";
export default async function handler(req, res) {
const mapHash = req.query.hash;
const mapData = await Utils.getMapData(mapHash.replace("custom_level_", ""));
if (mapData === undefined) { // Check if a map hash was provided
if (mapData === undefined) {
// Check if a map hash was provided
return res.json({ error: true, message: "Unknown map" });
}
const data = { // The maps data from the provided map hash
const data = {
// The maps data from the provided map hash
bsr: mapData.id,
songArt: "http://" + req.headers.host + "/api/beatsaver/art/" + mapHash + "?ext=" + mapData.versions[0].coverURL
.split("/")[3].split(".")[1]
songArt:
"http://" +
req.headers.host +
"/api/beatsaver/art/" +
mapHash +
"?ext=" +
mapData.versions[0].coverURL.split("/")[3].split(".")[1],
};
res.json({ error: false, data: data });
}

@ -1,9 +1,10 @@
export default async function handler(req, res) {
res.json({
"avatar": "https://avatars.akamai.steamstatic.com/4322d8d20cb6dbdd1d891b4efa9952a9679c9a76_full.jpg",
"country": "GB",
"pp": 0,
"rank": 0,
"countryRank": 0,
avatar:
"https://avatars.akamai.steamstatic.com/4322d8d20cb6dbdd1d891b4efa9952a9679c9a76_full.jpg",
country: "GB",
pp: 0,
rank: 0,
countryRank: 0,
});
}

@ -1,14 +1,24 @@
import { Button, Card, Container, Grid, Input, Link, Modal, Spacer, Switch, Text, textTransforms } from '@nextui-org/react';
import { Component } from 'react';
import NavBar from '../src/components/Navbar';
import {
Button,
Card,
Container,
Grid,
Input,
Link,
Modal,
Spacer,
Switch,
Text,
} from "@nextui-org/react";
import { Component } from "react";
import NavBar from "../src/components/Navbar";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import styles from '../styles/main.module.css';
import styles from "../styles/main.module.css";
export default class Home extends Component {
constructor(props) {
super(props);
@ -26,7 +36,7 @@ export default class Home extends Component {
showScoreInfo: false,
showSongInfo: false,
},
}
};
}
async componentDidMount() {
@ -34,29 +44,35 @@ export default class Home extends Component {
const params = Object.fromEntries(urlSearchParams.entries());
if (params.id) {
document.location.href = "/overlay/"+ window.location.search
document.location.href = "/overlay/" + window.location.search;
return;
}
if (localStorage.getItem('values') == undefined) {
localStorage.setItem('values', JSON.stringify({
if (localStorage.getItem("values") == undefined) {
localStorage.setItem(
"values",
JSON.stringify({
steamId: this.state.steamId,
values: this.state.values
}));
values: this.state.values,
})
);
} else {
const json = JSON.parse(localStorage.getItem('values'))
const json = JSON.parse(localStorage.getItem("values"));
this.setState({ steamId: json.steamId, values: json.values });
}
this.setState({ loading: false });
}
loadPreview() {
this.setState({ isPreviewVisible: true, previewUrl: this.generateUrl(true) });
this.setState({
isPreviewVisible: true,
previewUrl: this.generateUrl(true),
});
}
generateUrl(withTc = false) {
let values = "";
Object.entries(this.state.values).forEach(value => {
Object.entries(this.state.values).forEach((value) => {
if (value[1] === undefined) {
return;
}
@ -67,7 +83,13 @@ export default class Home extends Component {
values += `&${value[0]}=${value[1]}`;
});
return window.location.origin + "/overlay?id=" + this.state.steamId + values + (withTc ? "&textColor=black" : "");
return (
window.location.origin +
"/overlay?id=" +
this.state.steamId +
values +
(withTc ? "&textColor=black" : "")
);
}
updateValue(key, value) {
@ -79,25 +101,31 @@ export default class Home extends Component {
updateStorage() {
setTimeout(() => {
localStorage.setItem('values', JSON.stringify({
localStorage.setItem(
"values",
JSON.stringify({
steamId: this.state.steamId,
values: this.state.values
}));
values: this.state.values,
})
);
}, 5);
}
render() {
return this.state.loading ? <h1>Loading...</h1> :
return this.state.loading ? (
<h1>Loading...</h1>
) : (
<div className={styles.main}>
<NavBar></NavBar>
<Container css={{
marginTop: '$8'
}}>
<Container
css={{
marginTop: "$8",
}}
>
{/* Preview */}
{
this.state.isPreviewVisible ? <Modal
{this.state.isPreviewVisible ? (
<Modal
closeButton
open={this.state.isPreviewVisible}
width={"100%"}
@ -105,23 +133,29 @@ export default class Home extends Component {
onClose={() => this.setState({ isPreviewVisible: false })}
>
<Modal.Header>
<Text size={18}>
Overlay Preview
</Text>
<Text size={18}>Overlay Preview</Text>
</Modal.Header>
<Modal.Body>
<iframe height={600} src={this.state.previewUrl}></iframe>
</Modal.Body>
</Modal> : <></>
}
</Modal>
) : (
<></>
)}
<Grid.Container gap={2} justify='center'>
<Grid xs={12} css={{
color: 'black'
}} justify='center'>
<div style={{
textAlign: 'center',
}}>
<Grid.Container gap={2} justify="center">
<Grid
xs={12}
css={{
color: "black",
}}
justify="center"
>
<div
style={{
textAlign: "center",
}}
>
<Text h1>BeatSaber Overlay</Text>
<Text h4>Welcome to the Setup panel</Text>
</div>
@ -137,7 +171,10 @@ export default class Home extends Component {
labelPlaceholder="Ip Address (Only set if you stream on multiple devices)"
initialValue="localhost"
value={this.state.values.socketAddr}
onChange={event => this.updateValue("socketAddr", event.target.value)} checked={true}
onChange={(event) =>
this.updateValue("socketAddr", event.target.value)
}
checked={true}
/>
<Spacer y={2} />
<Input
@ -145,49 +182,96 @@ export default class Home extends Component {
labelPlaceholder="Steam Id"
initialValue=""
value={this.state.steamId}
onChange={event => {
onChange={(event) => {
this.setState({ steamId: event.target.value });
this.updateStorage();
}}
/>
<Spacer y={1} />
<Text>Do you want to use BeatLeader rather than ScoreSaber?</Text>
<Switch onChange={event => this.updateValue("useBeatLeader", event.target.checked)} checked={this.state.values.useBeatLeader} size="md" />
<Text>Do you want to show Player Stats (Current PP, global pos, etc)</Text>
<Switch onChange={event => this.updateValue("showPlayerStats", event.target.checked)} checked={this.state.values.showPlayerStats} size="md" />
<Text>Do you want to show Score Info (Current swing values, total score, etc)</Text>
<Switch onChange={event => this.updateValue("showScoreInfo", event.target.checked)} checked={this.state.values.showScoreInfo} size="md" />
<Text>Do you want to show Song Info (Song name, bsr, song art, etc)</Text>
<Switch onChange={event => this.updateValue("showSongInfo", event.target.checked)} checked={this.state.values.showSongInfo} size="md" />
<Text>
Do you want to use BeatLeader rather than ScoreSaber?
</Text>
<Switch
onChange={(event) =>
this.updateValue("useBeatLeader", event.target.checked)
}
checked={this.state.values.useBeatLeader}
size="md"
/>
<Text>
Do you want to show Player Stats (Current PP, global pos,
etc)
</Text>
<Switch
onChange={(event) =>
this.updateValue("showPlayerStats", event.target.checked)
}
checked={this.state.values.showPlayerStats}
size="md"
/>
<Text>
Do you want to show Score Info (Current swing values, total
score, etc)
</Text>
<Switch
onChange={(event) =>
this.updateValue("showScoreInfo", event.target.checked)
}
checked={this.state.values.showScoreInfo}
size="md"
/>
<Text>
Do you want to show Song Info (Song name, bsr, song art,
etc)
</Text>
<Switch
onChange={(event) =>
this.updateValue("showSongInfo", event.target.checked)
}
checked={this.state.values.showSongInfo}
size="md"
/>
<Spacer y={1} />
<Button.Group>
<Button flat auto onClick={() => {
<Button
flat
auto
onClick={() => {
if (!this.state.steamId) {
toast.error("Please provide a Steam ID");
return;
}
window.open(this.generateUrl(), "_blank");
}}>Open Overlay</Button>
<Button flat auto onClick={() => {
}}
>
Open Overlay
</Button>
<Button
flat
auto
onClick={() => {
if (!this.state.steamId) {
toast.error("Please provide a Steam ID");
return;
}
this.loadPreview();
}}>Preview</Button>
}}
>
Preview
</Button>
</Button.Group>
{
this.state.overlayUrl !== undefined ?
{this.state.overlayUrl !== undefined ? (
<>
<Text b>
Url
</Text>
<Link href={this.state.overlayUrl}>{this.state.overlayUrl}</Link>
<Text b>Url</Text>
<Link href={this.state.overlayUrl}>
{this.state.overlayUrl}
</Link>
</>
: <></>
}
) : (
<></>
)}
</Card.Body>
</Card>
</Grid>
@ -196,5 +280,6 @@ export default class Home extends Component {
<ToastContainer />
</div>
}
);
}
}

@ -1,14 +1,13 @@
import { Link } from '@nextui-org/react';
import {Component} from 'react'
import PlayerStats from '../src/components/PlayerStats';
import ScoreStats from '../src/components/ScoreStats';
import { Link } from "@nextui-org/react";
import { Component } from "react";
import PlayerStats from "../src/components/PlayerStats";
import ScoreStats from "../src/components/ScoreStats";
import SongInfo from "../src/components/SongInfo";
import Utils from '../src/utils/utils';
import styles from '../styles/overlay.module.css';
import Utils from "../src/utils/utils";
import styles from "../styles/overlay.module.css";
export default class Overlay extends Component {
#_beatSaverURL = "";
constructor(props) {
@ -36,16 +35,16 @@ export default class Overlay extends Component {
percentage: "100.00%",
failed: false,
leftHand: {
averageCut: [15.00],
averagePreSwing: [70.00],
averagePostSwing: [30.00],
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
},
rightHand: {
averageCut: [15.00],
averagePreSwing: [70.00],
averagePostSwing: [30.00],
}
}
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
},
};
this.setupTimer();
}
@ -60,10 +59,10 @@ export default class Overlay extends Component {
setupTimer() {
setInterval(() => {
if (this.isCurrentSongTimeProvided) {
return
return;
}
if (!this.state.paused && this.state.beatSaverData !== undefined) {
this.setState({ currentSongTime: this.state.currentSongTime + 1 })
this.setState({ currentSongTime: this.state.currentSongTime + 1 });
}
}, 1000);
}
@ -75,10 +74,10 @@ export default class Overlay extends Component {
*/
handleCurrentSongTime(data) {
try {
const time = data.status.performance.currentSongTime
const time = data.status.performance.currentSongTime;
if (time !== undefined && time != null) {
this.isCurrentSongTimeProvided = true
this.setState({ currentSongTime: time })
this.isCurrentSongTimeProvided = true;
this.setState({ currentSongTime: time });
}
} catch (e) {
// do nothing
@ -87,23 +86,25 @@ export default class Overlay extends Component {
async componentDidMount() {
console.log("Initializing...");
this.#_beatSaverURL = document.location.origin + "/api/beatsaver/map?hash=%s";
this.#_beatSaverURL =
document.location.origin + "/api/beatsaver/map?hash=%s";
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
// Check what website the player wants to use
if (params.beatleader === 'true') {
if (params.beatleader === "true") {
this.setState({ websiteType: "BeatLeader" });
}
const id = params.id;
if (!id) { // Check if the id param is valid
if (!id) {
// Check if the id param is valid
this.setState({ loading: false, isValidSteamId: false });
return;
}
// Check if the player wants to disable their stats (pp, global pos, etc)
if (params.showPlayerStats === 'false' || params.playerstats === 'false') {
if (params.showPlayerStats === "false" || params.playerstats === "false") {
this.setState({ showPlayerStats: false });
}
@ -114,13 +115,13 @@ export default class Overlay extends Component {
let shouldConnectSocket = false;
// Check if the player wants to show their current score information
if (params.showScoreInfo === 'true' || params.scoreinfo === 'true') {
if (params.showScoreInfo === "true" || params.scoreinfo === "true") {
this.setState({ showScore: true });
shouldConnectSocket = true;
}
// Check if the player wants to show the current song
if (params.showSongInfo === 'true' || params.songinfo === 'true') {
if (params.showSongInfo === "true" || params.songinfo === "true") {
this.setState({ showSongInfo: true });
shouldConnectSocket = true;
}
@ -143,11 +144,17 @@ export default class Overlay extends Component {
* @returns
*/
async updateData(id) {
const data = await fetch(new Utils().getWebsiteApi(id == "test" ? "Test" : this.state.websiteType).ApiUrl.replace("%s", id), {
mode: 'cors'
});
const data = await fetch(
new Utils()
.getWebsiteApi(id == "test" ? "Test" : this.state.websiteType)
.ApiUrl.replace("%s", id),
{
mode: "cors",
}
);
const json = await data.json();
if (json.errorMessage) { // Invalid account
if (json.errorMessage) {
// Invalid account
this.setState({ loading: false, isValidSteamId: false });
return;
}
@ -158,7 +165,10 @@ export default class Overlay extends Component {
* Setup the HTTP Status connection
*/
connectSocket(socketAddress) {
socketAddress = (socketAddress === undefined ? 'ws://localhost' : `ws://${socketAddress}`) + ":6557/socket";
socketAddress =
(socketAddress === undefined
? "ws://localhost"
: `ws://${socketAddress}`) + ":6557/socket";
if (this.state.isConnectedToSocket) return;
if (this.state.isVisible) {
@ -167,24 +177,26 @@ export default class Overlay extends Component {
console.log(`Connecting to ${socketAddress}`);
const socket = new WebSocket(socketAddress);
socket.addEventListener('open', () => {
socket.addEventListener("open", () => {
console.log(`Connected to ${socketAddress}`);
this.setState({ isConnectedToSocket: true });
});
socket.addEventListener('close', () => {
console.log("Attempting to re-connect to the HTTP Status socket in 10 seconds.");
socket.addEventListener("close", () => {
console.log(
"Attempting to re-connect to the HTTP Status socket in 10 seconds."
);
this.setState({ isConnectedToSocket: false });
setTimeout(() => this.connectSocket(), 10_000);
});
socket.addEventListener('message', (message) => {
socket.addEventListener("message", (message) => {
const json = JSON.parse(message.data);
this.handleCurrentSongTime(json)
this.handleCurrentSongTime(json);
if (!this.handlers[json.event]) {
console.log("Unhandled message from HTTP Status. (" + json.event + ")");
return;
}
this.handlers[json.event](json || []);
})
});
this.setState({ socket: socket });
}
@ -194,10 +206,12 @@ export default class Overlay extends Component {
* @param {[]} songData
*/
async setBeatSaver(songData) {
console.log("Updating BeatSaver info")
const data = await fetch(this.#_beatSaverURL.replace("%s", songData.levelId));
console.log("Updating BeatSaver info");
const data = await fetch(
this.#_beatSaverURL.replace("%s", songData.levelId)
);
const json = await data.json();
this.setState({ beatSaverData: json })
this.setState({ beatSaverData: json });
}
/**
@ -211,59 +225,68 @@ export default class Overlay extends Component {
}, 250);
this.setState({
leftHand: {
averageCut: [15.00],
averagePreSwing: [70.00],
averagePostSwing: [30.00],
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
},
rightHand: {
averageCut: [15.00],
averagePreSwing: [70.00],
averagePostSwing: [30.00],
averageCut: [15.0],
averagePreSwing: [70.0],
averagePostSwing: [30.0],
},
songInfo: undefined,
beatSaverData: undefined,
currentSongTime: 0,
currentScore: 0,
percentage: "100.00%",
isVisible: visible
isVisible: visible,
});
}
// The HTTP Status handlers
handlers = {
"hello": (data) => {
hello: (data) => {
console.log("Hello from HTTP Status!");
if (data.status) {
this.setState({songData: data});
this.setState({ songData: data });
if (data.status.beatmap) {
this.setBeatSaver(data.status.beatmap);
}
}
},
"scoreChanged": (data) => {
scoreChanged: (data) => {
const { status } = data;
const { score, currentMaxScore } = status.performance;
const percent = currentMaxScore > 0 ? ((score / currentMaxScore) * 1000 / 10).toFixed(2) : 0.00;
const percent =
currentMaxScore > 0
? (((score / currentMaxScore) * 1000) / 10).toFixed(2)
: 0.0;
this.setState({
currentScore: score,
percentage: this.state.failed ? percent * 2 : percent + "%"
})
percentage: this.state.failed ? percent * 2 : percent + "%",
});
},
"noteFullyCut": (data) => {
noteFullyCut: (data) => {
const { noteCut } = data;
console.log(noteCut)
console.log(noteCut);
// Left Saber
if (noteCut.saberType === 'SaberA') {
if (noteCut.saberType === "SaberA") {
const data = this.state.leftHand;
if (data.averageCut.includes(15) && data.averageCut.length === 1) {
data.averageCut = [];
}
if (data.averagePreSwing.includes(70) && data.averagePreSwing.length === 1) {
if (
data.averagePreSwing.includes(70) &&
data.averagePreSwing.length === 1
) {
data.averagePreSwing = [];
}
if (data.averagePostSwing.includes(30) && data.averagePostSwing.length === 1) {
if (
data.averagePostSwing.includes(30) &&
data.averagePostSwing.length === 1
) {
data.averagePostSwing = [];
}
data.averagePreSwing.push(noteCut.beforeSwingRating * 70);
@ -273,15 +296,21 @@ export default class Overlay extends Component {
}
// Left Saber
if (noteCut.saberType === 'SaberB') {
if (noteCut.saberType === "SaberB") {
const data = this.state.rightHand;
if (data.averageCut.includes(15) && data.averageCut.length === 1) {
data.averageCut = [];
}
if (data.averagePreSwing.includes(70) && data.averagePreSwing.length === 1) {
if (
data.averagePreSwing.includes(70) &&
data.averagePreSwing.length === 1
) {
data.averagePreSwing = [];
}
if (data.averagePostSwing.includes(30) && data.averagePostSwing.length === 1) {
if (
data.averagePostSwing.includes(30) &&
data.averagePostSwing.length === 1
) {
data.averagePostSwing = [];
}
data.averagePreSwing.push(noteCut.beforeSwingRating * 70);
@ -290,58 +319,60 @@ export default class Overlay extends Component {
this.setState({ rightHand: data });
}
},
"songStart": (data) => {
console.log("Going into level, resetting data.")
songStart: (data) => {
console.log("Going into level, resetting data.");
this.resetData(true);
this.setState({ songData: data, paused: false })
this.setState({ songData: data, paused: false });
this.setBeatSaver(data.status.beatmap);
},
"finished": () => {
finished: () => {
this.resetData(false);
},
"softFail": () => {
softFail: () => {
this.setState({ failed: true });
},
"pause": () => {
pause: () => {
this.setState({ paused: true });
},
"resume": () => {
resume: () => {
this.setState({ paused: false });
},
"menu": () => {
menu: () => {
this.resetData(false);
},
"noteCut": () => {},
"noteMissed": () => {},
"noteSpawned": () => {},
"bombMissed": () => {},
"beatmapEvent": () => {},
"energyChanged": () => {},
}
noteCut: () => {},
noteMissed: () => {},
noteSpawned: () => {},
bombMissed: () => {},
beatmapEvent: () => {},
energyChanged: () => {},
};
render() {
const { loading, isValidSteamId, data, websiteType } = this.state;
if (this.state.textColor !== undefined) {
const element = document.querySelector("." + styles.main);
element.style.color = this.state.textColor
element.style.color = this.state.textColor;
}
return <div className={styles.main}>
{ loading ?
return (
<div className={styles.main}>
{loading ? (
<div className={styles.loading}>
<h2>Loading...</h2>
</div>
: !isValidSteamId ?
) : !isValidSteamId ? (
<div className={styles.invalidPlayer}>
<h1>Invalid player, please visit the main page.</h1>
<Link href="/">
<a>Go Home</a>
</Link>
</div> :
</div>
) : (
<div className={styles.overlay}>
{
this.state.showPlayerStats ? <PlayerStats
{this.state.showPlayerStats ? (
<PlayerStats
pp={data.pp.toLocaleString()}
globalPos={data.rank.toLocaleString()}
country={data.country}
@ -349,18 +380,24 @@ export default class Overlay extends Component {
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}/> : <></>
}
) : (
<></>
)}
{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>
}
)}
</div>
);
}
}

@ -1,21 +1,23 @@
import Image from "next/image";
import styles from '../../styles/avatar.module.css';
import styles from "../../styles/avatar.module.css";
const Avatar = (props) => {
return <>
return (
<>
<Image
className={styles.playerAvatar}
src={props.url}
width={180}
height={180}
alt={'Avatar image'}
loading='lazy'
alt={"Avatar image"}
loading="lazy"
placeholder="blur"
blurDataURL="https://cdn.fascinated.cc/MhCUeHZLsh.webp?raw=true"
unoptimized={true}
/>
</>
}
);
};
export default Avatar;

@ -1,13 +1,15 @@
import { Navbar, Text } from "@nextui-org/react";
const NavBar = () => {
return <Navbar isBordered variant={"sticky"}>
return (
<Navbar isBordered variant={"sticky"}>
<Navbar.Brand>
<Text b color="inherit">
BeatSaber Overlay
</Text>
</Navbar.Brand>
</Navbar>
}
);
};
export default NavBar;

@ -1,24 +1,37 @@
import ReactCountryFlag from "react-country-flag";
import styles from '../../styles/playerStats.module.css';
import styles from "../../styles/playerStats.module.css";
import Avatar from "./Avatar";
const PlayerStats = (props) => {
return <div className={styles.playerStatsContainer}>
return (
<div className={styles.playerStatsContainer}>
<div>
<Avatar url={props.avatar} />
</div>
<div className={styles.playerStats}>
<p>{props.pp}pp <span style={{
fontSize: '20px',
}}>({props.websiteType})</span></p>
<p>
{props.pp}pp{" "}
<span
style={{
fontSize: "20px",
}}
>
({props.websiteType})
</span>
</p>
<p>#{props.globalPos}</p>
<div className={styles.playerCountry}>
<p>#{props.countryRank}</p>
<ReactCountryFlag className={styles.playerCountryIcon} svg countryCode={props.country} />
<ReactCountryFlag
className={styles.playerCountryIcon}
svg
countryCode={props.country}
/>
</div>
</div>
</div>
}
);
};
export default PlayerStats;

@ -1,9 +1,8 @@
import {Component} from "react";
import { Component } from "react";
import styles from '../../styles/scoreStats.module.css';
import styles from "../../styles/scoreStats.module.css";
export default class ScoreStats extends Component {
constructor(params) {
super(params);
}
@ -21,7 +20,8 @@ export default class ScoreStats extends Component {
render() {
const data = this.props.data;
return <div className={styles.scoreStats}>
return (
<div className={styles.scoreStats}>
<div className={styles.scoreStatsInfo}>
<p>{data.percentage}</p>
<p>{data.currentScore.toLocaleString()}</p>
@ -40,5 +40,6 @@ export default class ScoreStats extends Component {
</div>
</div>
</div>
);
}
}

@ -1,14 +1,13 @@
import {Component} from "react";
import { Component } from "react";
import styles from '../../styles/songInfo.module.css';
import styles from "../../styles/songInfo.module.css";
export default class SongInfo extends Component {
constructor(params) {
super(params);
this.state = {
diffColor: undefined
}
diffColor: undefined,
};
}
componentDidMount() {
@ -48,7 +47,9 @@ export default class SongInfo extends Component {
msToMinSeconds(millis) {
const minutes = Math.floor(millis / 60000);
const seconds = Number(((millis % 60000) / 1000).toFixed(0));
return seconds === 60 ? minutes + 1 + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
return seconds === 60
? minutes + 1 + ":00"
: minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
render() {
@ -56,29 +57,43 @@ export default class SongInfo extends Component {
const beatSaverData = this.props.data.beatSaverData.data;
const songArt = beatSaverData.songArt;
const bsr = beatSaverData.bsr;
const {
songName,
songAuthorName,
difficulty
} = data
const { songName, songAuthorName, difficulty } = data;
// what in the fuck is this?? LMFAO
const songTimerPercentage = ((this.props.data.currentSongTime / 1000) / (data.length / 1000)) * 100000;
const songTimerPercentage =
(this.props.data.currentSongTime / 1000 / (data.length / 1000)) * 100000;
return <div className={styles.songInfoContainer}>
<img src={songArt}/>
return (
<div className={styles.songInfoContainer}>
<img src={songArt} />
<div className={styles.songInfo}>
<p className={styles.songInfoSongName}>{songName.length > 35 ? songName.substring(0, 35) + "..." : songName}</p>
<p className={styles.songInfoSongName}>
{songName.length > 35
? songName.substring(0, 35) + "..."
: songName}
</p>
<p className={styles.songInfoSongAuthor}>{songAuthorName}</p>
<div className={styles.songInfoSongOtherContainer}>
<p className={styles.songInfoDiff} style={{ backgroundColor: this.state.diffColor }}>{difficulty}</p>
<p
className={styles.songInfoDiff}
style={{ backgroundColor: this.state.diffColor }}
>
{difficulty}
</p>
<p className={styles.songInfoBsr}>!bsr {bsr}</p>
</div>
<p className={styles.songTimeText}>{this.msToMinSeconds(this.props.data.currentSongTime * 1000)}/{this.msToMinSeconds(data.length)}</p>
<p className={styles.songTimeText}>
{this.msToMinSeconds(this.props.data.currentSongTime * 1000)}/
{this.msToMinSeconds(data.length)}
</p>
<div className={styles.songTimeContainer}>
<div className={styles.songTimeBackground}/>
<div className={styles.songTime} style={{ width: songTimerPercentage + '%' }}/>
<div className={styles.songTimeBackground} />
<div
className={styles.songTime}
style={{ width: songTimerPercentage + "%" }}
/>
</div>
</div>
</div>
);
}
}

@ -1,15 +1,15 @@
import Config from '../../config.json';
import Config from "../../config.json";
const WebsiteTypes = {
ScoreSaber: {
ApiUrl: Config.proxy_url + "/https://scoresaber.com/api/player/%s/full"
ApiUrl: Config.proxy_url + "/https://scoresaber.com/api/player/%s/full",
},
BeatLeader: {
ApiUrl: Config.proxy_url + "/https://api.beatleader.xyz/player/%s"
ApiUrl: Config.proxy_url + "/https://api.beatleader.xyz/player/%s",
},
Test: {
ApiUrl: "/api/mockdata"
}
}
ApiUrl: "/api/mockdata",
},
};
export default WebsiteTypes
export default WebsiteTypes;

@ -1,7 +1,7 @@
import WebsiteTypes from "../consts/WebsiteType";
export default class Utils {
constructor() {};
constructor() {}
/**
* Returns the information for the given website type.
@ -10,6 +10,6 @@ export default class Utils {
* @returns The website type's information.
*/
getWebsiteApi(website) {
return WebsiteTypes[website]
return WebsiteTypes[website];
}
}

@ -1,3 +1,5 @@
*, html, body {
*,
html,
body {
background-color: transparent;
}

@ -1,5 +1,5 @@
.main {
font-family: 'Roboto', sans-serif !important;
font-family: "Roboto", sans-serif !important;
color: white;
font-size: xx-large;
line-height: 1.4em !important;

@ -1,12 +1,12 @@
.main {
font-family: 'Teko', sans-serif !important;
font-family: "Teko", sans-serif !important;
color: white;
font-size: xx-large;
line-height: 1.4em !important;
}
.main p {
font-family: 'Teko', sans-serif !important;
font-family: "Teko", sans-serif !important;
color: white;
letter-spacing: normal;
}

@ -1,8 +1,8 @@
.scoreStats {
text-align: center;
position:absolute;
top:0;
right:0;
position: absolute;
top: 0;
right: 0;
margin-right: 5px;
min-width: 135px;
}

@ -1,8 +1,8 @@
.songInfoContainer {
display: flex;
position: fixed;
bottom:0;
left:0;
bottom: 0;
left: 0;
margin-left: 5px;
margin-bottom: 5px;
}

@ -1,9 +1,10 @@
import Config from '../config.json';
import Config from "../config.json";
const mapCache = new Map();
module.exports = {
BEATSAVER_MAP_API: Config.proxy_url + "/https://api.beatsaver.com/maps/hash/%s",
BEATSAVER_MAP_API:
Config.proxy_url + "/https://api.beatsaver.com/maps/hash/%s",
/**
* Gets a specified maps data from BeatSaver
@ -13,14 +14,15 @@ module.exports = {
*/
async getMapData(hash) {
hash = this.BEATSAVER_MAP_API.replace("%s", hash);
if (mapCache.has(hash)) { // Return from cache
if (mapCache.has(hash)) {
// Return from cache
return mapCache.get(hash);
}
const data = await fetch(hash, {
headers: {
"origin": "Fascinated Overlay"
}
origin: "Fascinated Overlay",
},
});
if (data.status === 404) {
return undefined;
@ -31,5 +33,5 @@ module.exports = {
mapCache.delete(hash);
}, 60 * 60 * 1000); // 1h
return json;
}
}
},
};