Compare commits

..

No commits in common. "main" and "release-0.1" have entirely different histories.

20 changed files with 189 additions and 615 deletions

2
.gitignore vendored
View File

@ -3,5 +3,3 @@
# Ignore Gradle build output directory
build
/app/databases

View File

@ -1,9 +0,0 @@
MIT License
Copyright (c) 2021 ImaKlutz
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -76,16 +76,6 @@ tasks.withType<Jar> {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest { attributes["Main-Class"] = "xyz.etztech.stonks.AppKt" }
configurations["compileClasspath"].forEach { file: File -> from(zipTree(file.absoluteFile)) }
doFirst {
val proc = Runtime.getRuntime().exec("npm.cmd run --prefix ./spa build")
// Read the output from the command
println("NPM RUN BUILD - STD INPUT")
proc.getInputStream().bufferedReader().forEachLine { println(it) }
println("NPM RUN BUILD - STD ERROR")
proc.getErrorStream().bufferedReader().forEachLine { println(it) }
}
}
application {

View File

@ -8,7 +8,6 @@ import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.*
import xyz.etztech.stonks.dsl.AggregateStatistics
import xyz.etztech.stonks.dsl.LiveStatistics
import xyz.etztech.stonks.dsl.Players
import xyz.etztech.stonks.dsl.Statistics
@ -26,7 +25,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
Javalin.create { config ->
config.enableCorsForAllOrigins()
config.addStaticFiles("spa")
config.addSinglePageRoot("", "spa/index.html")
config.addSinglePageRoot("/", "spa")
config.enforceSsl = false
config.ignoreTrailingSlashes = true
}
@ -36,7 +35,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
run {
if (statisticsCache.isEmpty() or
(Duration.between(Instant.now(), statisticsCacheTimestamp) >
Duration.ofMinutes(5))
Duration.ofHours(1))
) {
transaction(database) {
addLogger(StdOutSqlLogger)
@ -93,7 +92,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
run {
if (playersCache.isEmpty() or
(Duration.between(Instant.now(), playersCacheTimestamp) >
Duration.ofMinutes(5))
Duration.ofHours(1))
) {
transaction(database) {
addLogger(StdOutSqlLogger)
@ -174,34 +173,6 @@ fun initApiServer(apiServerPort: Int, database: Database) {
}
}
app.get("api/aggregates") { ctx ->
run {
transaction(database) {
addLogger(StdOutSqlLogger)
val maxValueExpr = AggregateStatistics.value.max()
val aggregates =
AggregateStatistics.slice(
AggregateStatistics.type,
AggregateStatistics.name,
maxValueExpr
)
.selectAll()
.groupBy(AggregateStatistics.type, AggregateStatistics.name)
.map {
AggregateValue(
it[AggregateStatistics.type],
it[AggregateStatistics.name],
it[maxValueExpr]!!
)
}
ctx.result(Json { prettyPrint = true }.encodeToString(aggregates))
}
}
}
app.get("api/*") { ctx -> ctx.status(404) }
println("Javalin web server started")
@ -228,13 +199,3 @@ data class HistoricalStatisticValue(
val timestamp: String,
val value: Long
)
@Serializable data class AggregateValue(val type: String, val name: String, val value: Long)
@Serializable
data class HistoricalAggregateValue(
val type: String,
val name: String,
val timestamp: String,
val value: Long
)

View File

@ -4,54 +4,51 @@ import com.natpryce.konfig.*
import java.io.FileInputStream
import java.util.*
import kotlinx.coroutines.*
import kotlinx.serialization.*
import org.h2.tools.Server
import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.etztech.stonks.api.initApiServer
import xyz.etztech.stonks.dsl.AggregateStatistics
import xyz.etztech.stonks.dsl.KeyValue
import xyz.etztech.stonks.dsl.LiveStatistics
import xyz.etztech.stonks.dsl.Players
import xyz.etztech.stonks.dsl.Statistics
import xyz.etztech.stonks.statisticsimporter.StatisticsImporter
fun main() = runBlocking {
println("Starting Stonks...")
fun main() =
runBlocking {
println("Starting Stonks...")
val fis = FileInputStream("./stonks.config")
val config = Properties()
val fis = FileInputStream("./stonks.config")
val config = Properties()
config.load(fis)
config.load(fis)
val databaseBaseDir = config.getProperty("databaseBaseDir")
val databaseName = config.getProperty("databaseName")
val h2StartWebServer = config.getProperty("h2StartWebServer").toBoolean()
val h2tWebServerPort = config.getProperty("h2tWebServerPort").toInt()
val h2TcpServerPort = config.getProperty("h2TcpServerPort").toInt()
val apiServerPort = config.getProperty("apiServerPort").toInt()
val statisticsUpdateInterval = config.getProperty("statisticsUpdateInterval").toLong()
val minecraftStatsFolder = config.getProperty("minecraftStatsFolder")
val databaseBaseDir = config.getProperty("databaseBaseDir")
val databaseName = config.getProperty("databaseName")
val h2StartWebServer = config.getProperty("h2StartWebServer").toBoolean()
val h2tWebServerPort = config.getProperty("h2tWebServerPort").toInt()
val h2TcpServerPort = config.getProperty("h2TcpServerPort").toInt()
val apiServerPort = config.getProperty("apiServerPort").toInt()
val statisticsUpdateInterval = config.getProperty("statisticsUpdateInterval").toLong()
val minecraftStatsFolder = config.getProperty("minecraftStatsFolder")
val database =
initH2Server(
databaseBaseDir,
databaseName,
h2TcpServerPort,
h2StartWebServer,
h2tWebServerPort
)
val database =
initH2Server(
databaseBaseDir,
databaseName,
h2TcpServerPort,
h2StartWebServer,
h2tWebServerPort)
initApiServer(apiServerPort, database)
initApiServer(apiServerPort, database)
initPeriodicFetching(statisticsUpdateInterval, minecraftStatsFolder, database)
initPeriodicFetching(statisticsUpdateInterval, minecraftStatsFolder, database)
delay(60 * 1000L)
delay(60 * 1000L)
println("END")
}
println("END")
}
fun initH2Server(
databaseBaseDir: String,
@ -62,20 +59,11 @@ fun initH2Server(
): Database {
val webServer =
Server.createWebServer(
"-baseDir",
databaseBaseDir,
"-webPort",
h2WebServerPort.toString()
)
"-trace", "-baseDir", databaseBaseDir, "-webPort", h2WebServerPort.toString())
val tcpServer =
Server.createTcpServer(
"-trace",
"-baseDir",
databaseBaseDir,
"-webPort",
h2TcpServerPort.toString()
)
"-trace", "-baseDir", databaseBaseDir, "-webPort", h2TcpServerPort.toString())
if (h2StartWebServer) {
webServer.start()
@ -91,9 +79,7 @@ fun initH2Server(
addLogger(StdOutSqlLogger)
SchemaUtils.create(Statistics)
SchemaUtils.create(LiveStatistics)
SchemaUtils.create(AggregateStatistics)
SchemaUtils.create(Players)
SchemaUtils.create(KeyValue)
// Create indexes with explicit SQL because I can't figure out how to do it with exposed
// Wrap it in a try block because it throws an exception if index already exists
@ -116,42 +102,17 @@ fun initH2Server(
TransactionManager.current()
.exec("CREATE INDEX idx_type_name ON LiveStatistics (\"Type\", \"Name\")")
} catch (e: ExposedSQLException) {}
val schemaVersions =
KeyValue.slice(KeyValue.value).select { KeyValue.key.eq("SchemaVersion") }.map {
it[KeyValue.value]
}
val schemaVersion = if (schemaVersions.count() > 0) schemaVersions.single() else 0
println("Database schemaVersion = ${schemaVersion}")
if (schemaVersion < 1) {
println("Migrating database to schemaVersion 1.")
TransactionManager.current().exec("TRUNCATE TABLE AGGREGATESTATISTICS")
KeyValue.insert {
it[KeyValue.key] = "SchemaVersion"
it[KeyValue.value] = 1
}
}
if (schemaVersion < 2) {
println("Migrating database to schemaVersion 2.")
TransactionManager.current().exec("TRUNCATE TABLE AGGREGATESTATISTICS")
KeyValue.update({ KeyValue.key eq "SchemaVersion" }) { it[KeyValue.value] = 2 }
}
}
return database
}
suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) = coroutineScope {
launch {
while (true) {
StatisticsImporter.importStatistics(folder, db)
delay(interval)
suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) =
coroutineScope {
launch {
while (true) {
StatisticsImporter.importStatistics(folder, db)
delay(interval)
}
}
}
}
}

View File

@ -4,6 +4,16 @@ import java.time.Instant
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.`java-time`.timestamp
object LiveStatistics : Table() {
val playerId: Column<String> = varchar("PlayerId", 150)
val type: Column<String> = varchar("Type", 150)
val name: Column<String> = varchar("Name", 150)
val value: Column<Long> = long("Value")
val rank: Column<Int> = integer("Rank")
override val primaryKey = PrimaryKey(playerId, type, name, name = "PK_playerId_type_name")
}
object Statistics : Table() {
val playerId: Column<String> = varchar("PlayerId", 150)
val type: Column<String> = varchar("Type", 150)
@ -15,25 +25,6 @@ object Statistics : Table() {
PrimaryKey(playerId, type, name, timestamp, name = "PK_playerId_type_name_timestamp")
}
object LiveStatistics : Table() {
val playerId: Column<String> = varchar("PlayerId", 150)
val type: Column<String> = varchar("Type", 150)
val name: Column<String> = varchar("Name", 150)
val value: Column<Long> = long("Value")
val rank: Column<Int> = integer("Rank")
override val primaryKey = PrimaryKey(playerId, type, name, name = "PK_playerId_type_name")
}
object AggregateStatistics : Table() {
val type: Column<String> = varchar("Type", 150)
val name: Column<String> = varchar("Name", 150)
val timestamp: Column<Instant> = timestamp("Timestamp")
val value: Column<Long> = long("Value")
override val primaryKey = PrimaryKey(type, name, timestamp, name = "PK_type_name_timestamp")
}
object Players : Table() {
val id: Column<String> = varchar("Id", 150)
val name: Column<String> = varchar("Name", 150)
@ -41,10 +32,3 @@ object Players : Table() {
override val primaryKey = PrimaryKey(id, name = "PK_id")
}
object KeyValue : Table() {
val key: Column<String> = varchar("Key", 150)
val value: Column<Int> = integer("Value")
override val primaryKey = PrimaryKey(key, name = "PK_key")
}

View File

@ -26,45 +26,39 @@ object StatisticsImporter {
private val klaxon = Klaxon()
fun importStatistics(folder: String, database: Database) {
println("Starting new statistics import.")
println("Importing new statistics...")
File(folder).listFiles().forEach { readFile(it, database) }
println("Updating live statistics table...")
updateLiveStatistics(database)
println("Updating aggregate statistics table...")
updateAggregateStatistics(database)
println("Refreshing player names...")
refreshPlayerNames(database)
println("Finished new statistics import.")
}
fun readFile(file: File, database: Database) {
val statsFile = StatsFile.fromJson(file.readText())
val playerId = file.nameWithoutExtension
val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()
transaction(database) {
addLogger(StdOutSqlLogger)
val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()
LiveStatistics.slice(LiveStatistics.type, LiveStatistics.name, LiveStatistics.value)
.select { LiveStatistics.playerId eq playerId }
.forEach {
if (playerStats.containsKey(it[LiveStatistics.type])) {
playerStats[it[LiveStatistics.type]]?.put(
it[LiveStatistics.name],
it[LiveStatistics.value]
)
it[LiveStatistics.name], it[LiveStatistics.value])
} else {
playerStats.put(
it[LiveStatistics.type],
mapOf<String, Long>(
it[LiveStatistics.name] to
it[LiveStatistics.value]
)
.toMutableMap()
)
it[LiveStatistics.value])
.toMutableMap())
}
}
}
transaction(database) {
statsFile?.stats?.forEach { type, stats ->
stats.forEach { name, value ->
if (playerStats.get(type)?.get(name) != value) {
@ -119,68 +113,7 @@ object StatisticsImporter {
UPDATE SET T."Value" = S."Value", T."Rank" = S."Rank"
WHEN NOT MATCHED THEN
INSERT VALUES (S."PlayerId", S."Type", S."Name", S."Value", S."Rank")
""".trimIndent()
)
}
}
fun updateAggregateStatistics(database: Database) {
transaction(database) {
TransactionManager.current()
.exec(
"""
SET @Timestamp = CURRENT_TIMESTAMP;
INSERT INTO AGGREGATESTATISTICS ("Type", "Name", "Timestamp", "Value")
SELECT LiveMax."Type",
'',
@Timestamp AS "Timestamp",
SUM(LiveMax."Value")
FROM (
SELECT Live."Type",
Live."Name",
MAX(Live."Value") AS "Value"
FROM livestatistics as Live
WHERE array_contains(array['minecraft:mined'], Live."Type")
GROUP BY Live."Type", Live."Name", Live."PlayerId"
) as LiveMax
LEFT JOIN (
SELECT AGGREGATESTATISTICS."Type",
AGGREGATESTATISTICS."Name",
MAX(AGGREGATESTATISTICS."Value") as "Value"
FROM AGGREGATESTATISTICS
GROUP BY AGGREGATESTATISTICS."Type", AGGREGATESTATISTICS."Name"
) as Agg
ON LiveMax."Type" = Agg."Type"
GROUP BY LiveMax."Type"
HAVING sum(LiveMax."Value") <> max(Agg."Value") OR max(Agg."Value") IS NULL;
INSERT INTO AGGREGATESTATISTICS ("Type", "Name", "Timestamp", "Value")
SELECT LiveMax."Type",
LiveMax."Name",
@Timestamp AS "Timestamp",
SUM(LiveMax."Value")
FROM (
SELECT Live."Type",
Live."Name",
MAX(Live."Value") AS "Value"
FROM livestatistics as Live
WHERE array_contains(array['minecraft:animals_bred', 'minecraft:play_one_minute', 'minecraft:deaths', 'minecraft:player_kills', 'minecraft:aviate_one_cm', 'minecraft:boat_one_cm', 'minecraft:crouch_one_cm', 'minecraft:horse_one_cm', 'minecraft:minecart_one_cm', 'minecraft:sprint_one_cm', 'minecraft:strider_one_cm', 'minecraft:swim_one_cm', 'minecraft:walk_on_water_one_cm', 'minecraft:walk_one_cm', 'minecraft:walk_under_water_one_cm' ], Live."Name")
OR array_contains(array['minecraft:killed', 'minecraft:killed_by'], Live."Type")
GROUP BY Live."Type", Live."Name", Live."PlayerId"
) as LiveMax
LEFT JOIN (
SELECT AGGREGATESTATISTICS."Type",
AGGREGATESTATISTICS."Name",
MAX(AGGREGATESTATISTICS."Value") as "Value"
FROM AGGREGATESTATISTICS
GROUP BY AGGREGATESTATISTICS."Type", AGGREGATESTATISTICS."Name"
) as Agg
ON LiveMax."Type" = Agg."Type" AND LiveMax."Name" = Agg."Name"
GROUP BY LiveMax."Type", LiveMax."Name"
HAVING SUM(LiveMax."Value") <> MAX(Agg."Value") OR MAX(Agg."Value") IS NULL;
""".trimIndent()
)
""".trimIndent())
}
}
@ -202,7 +135,7 @@ object StatisticsImporter {
.map { it[LiveStatistics.playerId] }
savedPlayers
.filter { Duration.between(it.timestamp, Instant.now()) > Duration.ofDays(1) }
.filter { Duration.between(Instant.now(), it.timestamp) > Duration.ofDays(1) }
.forEach { player ->
runBlocking {
val name = getName(player.id)
@ -243,8 +176,9 @@ object StatisticsImporter {
suspend fun getName(id: String): String? {
val response: HttpResponse =
httpClient.request(
"https://sessionserver.mojang.com/session/minecraft/profile/${id.replace("-", "")}"
) { method = HttpMethod.Get }
"https://sessionserver.mojang.com/session/minecraft/profile/${id.replace("-", "")}") {
method = HttpMethod.Get
}
if (response.status.isSuccess()) {
try {
return MojangProfileResponse.fromJson(response.readText())?.name

32
spa/package-lock.json generated
View File

@ -4777,11 +4777,6 @@
"wrap-ansi": "^6.2.0"
}
},
"clsx": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-1.1.1.tgz",
"integrity": "sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA=="
},
"co": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz",
@ -5794,15 +5789,6 @@
"utila": "~0.4"
}
},
"dom-helpers": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
"integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
"requires": {
"@babel/runtime": "^7.8.7",
"csstype": "^3.0.2"
}
},
"dom-serializer": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.2.tgz",
@ -13022,11 +13008,6 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"react-lifecycles-compat": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz",
"integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA=="
},
"react-query": {
"version": "3.18.1",
"resolved": "https://registry.npmjs.org/react-query/-/react-query-3.18.1.tgz",
@ -13185,19 +13166,6 @@
"tslib": "^1.0.0"
}
},
"react-virtualized": {
"version": "9.22.3",
"resolved": "https://registry.npmjs.org/react-virtualized/-/react-virtualized-9.22.3.tgz",
"integrity": "sha512-MKovKMxWTcwPSxE1kK1HcheQTWfuCxAuBoSTf2gwyMM21NdX/PXUhnoP8Uc5dRKd+nKm8v41R36OellhdCpkrw==",
"requires": {
"@babel/runtime": "^7.7.2",
"clsx": "^1.0.4",
"dom-helpers": "^5.1.3",
"loose-envify": "^1.4.0",
"prop-types": "^15.7.2",
"react-lifecycles-compat": "^3.0.4"
}
},
"read-pkg": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz",

View File

@ -18,8 +18,7 @@
"react-icons": "^4.2.0",
"react-query": "^3.18.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-virtualized": "^9.22.3"
"react-scripts": "4.0.3"
},
"scripts": {
"start": "react-scripts start",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -4,14 +4,12 @@
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#FFFFFF" />
<!--
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
-->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
@ -21,7 +19,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Stonks!</title>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

View File

@ -1,79 +0,0 @@
import React from "react";
import { useQuery } from "react-query";
import axios from "axios";
import { SimpleGrid, Stat, StatLabel, StatNumber } from "@chakra-ui/react";
import prettifyStatisticName from "./PrettifyStatisticName";
import StackedBar from "./StackedBar";
const AggregatesShowcase = () => {
const aggregates = useQuery(`aggregates`, async () => {
const { data } = await axios.get(`/api/aggregates`);
return data;
});
const killedAggregates = aggregates.isSuccess
? aggregates.data
.filter((x) => x.type === "minecraft:killed")
.sort((a, b) => b.value - a.value)
: [];
// const killedTotal = killedAggregates.reduce((acc, val) => acc + val.value, 0);
const killedByAggregates = aggregates.isSuccess
? aggregates.data
.filter((x) => x.type === "minecraft:killed_by")
.sort((a, b) => b.value - a.value)
: [];
// const killedByTotal = killedByAggregates.reduce(
// (acc, val) => acc + val.value,
// 0
// );
const travelAggregates = aggregates.isSuccess
? aggregates.data
.filter(
(x) => x.type === "minecraft:custom" && x.name.endsWith("one_cm")
)
.sort((a, b) => b.value - a.value)
: [];
// const travelTotal = travelAggregates.reduce((acc, val) => acc + val.value, 0);
return aggregates.isSuccess ? (
<>
<StackedBar heading="Mobs Killed" aggregates={killedAggregates} />
<StackedBar heading="Causes of Death" aggregates={killedByAggregates} />
<StackedBar heading="Preferred Travel" aggregates={travelAggregates} />
<SimpleGrid columns={2} mt={4} spacingY={4} spacingX={8}>
{aggregates.data
.filter(
(x) =>
x.type !== "minecraft:killed" &&
x.type !== "minecraft:killed_by" &&
!x.name.endsWith("one_cm")
)
.map((x, i) => {
var value = x.value;
if (x.name === "minecraft:play_one_minute") {
value = Math.floor(x.value / 20 / 60);
}
return (
<Stat key={i}>
<StatLabel>{prettifyStatisticName(x.type, x.name)}</StatLabel>
<StatNumber>{`${value
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`}</StatNumber>
</Stat>
);
})}
</SimpleGrid>
</>
) : (
<></>
);
};
export default AggregatesShowcase;

View File

@ -1,7 +1,7 @@
import React from "react";
import { useQuery } from "react-query";
import axios from "axios";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import { BrowserRouter, Switch, Redirect, Route } from "react-router-dom";
import { Container } from "@chakra-ui/react";
import Search from "./Search";
@ -41,17 +41,14 @@ const App = () => {
<Statistic
type={routeProps.match.params.type}
name={routeProps.match.params.name}
players={players.data}
players={players}
/>
)}
/>
<Route
path="/player/:id"
render={(routeProps) => (
<Player
playerId={routeProps.match.params.id}
players={players.data}
/>
<Player playerId={routeProps.match.params.id} players={players} />
)}
/>
<Route>

View File

@ -1,28 +1,41 @@
import React from "react";
import React, { useMemo, useState } from "react";
import { useQuery } from "react-query";
import axios from "axios";
import {
Button,
Center,
Flex,
Heading,
Icon,
Image,
Table,
Thead,
Tbody,
Tfoot,
Tr,
Th,
Td,
TableCaption,
} from "@chakra-ui/react";
import { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName";
const Player = ({ playerId, players }) => {
const playerStats = useQuery(`player ${playerId}`, async () => {
const { data } = await axios.get(`/api/players/${playerId}`);
data.sort((a, b) => a.rank - b.rank || b.value - a.value);
return data.filter((x) => x.value > 0);
});
const playerStats = useQuery(
`player ${playerId}`,
async () => {
const { data } = await axios.get(`/api/players/${playerId}`);
data.sort((a, b) => a.rank - b.rank);
return data;
},
{
placeholderData: [],
}
);
const playerName = players?.find((x) => x.id === playerId)?.name;
const playerDict = useMemo(() => {
return Object.assign({}, ...players.data.map((x) => ({ [x.id]: x.name })));
}, players);
return (
<>
@ -41,11 +54,10 @@ const Player = ({ playerId, players }) => {
height="48px"
src={`https://minotar.net/avatar/${playerId.replaceAll("-", "")}/48`}
mr="4"
rounded="md"
/>
{playerName}
{playerDict[playerId]}
</Heading>
<Table size="sm" variant="striped">
<Table variant="simple" size="sm" variant="striped">
<Thead>
<Tr>
<Th>Statistic</Th>
@ -54,23 +66,19 @@ const Player = ({ playerId, players }) => {
</Tr>
</Thead>
<Tbody>
{playerStats.isSuccess ? (
playerStats.data.map((x, i) => {
return (
<Tr key={i}>
<Td>
<Link to={`/statistic/${x.type}/${x.name}`}>
{prettifyStatisticName(x.type, x.name)}
</Link>
</Td>
<Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.value}</Td>
</Tr>
);
})
) : (
<></>
)}
{playerStats.data.map((x, i) => {
return (
<Tr key={i}>
<Td>
<Link to={`/statistic/${x.type}/${x.name}`}>
{x.type} {x.name}
</Link>
</Td>
<Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.value}</Td>
</Tr>
);
})}
</Tbody>
</Table>
</>

View File

@ -1,16 +0,0 @@
const prettifyStatisticName = (type, name) => {
return toTitleCase(
`${type.replace("custom", "")} ${name}`
.replaceAll("minecraft:", "")
.replaceAll("_", " ")
.trim()
);
};
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
export default prettifyStatisticName;

View File

@ -1,12 +1,9 @@
import React, { useMemo, useState } from "react";
import Fuse from "fuse.js";
import { Button, Center, Heading, Icon, Input } from "@chakra-ui/react";
import { Button, Center, Flex, Heading, Icon, Input } from "@chakra-ui/react";
import { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom";
import { AutoSizer, WindowScroller, List } from "react-virtualized";
import prettifyStatisticName from "./PrettifyStatisticName";
import AggregatesShowcase from "./AggregatesShowcase";
const Search = ({ statistics, players }) => {
const [searchTerm, setSearchTerm] = useState("");
@ -17,7 +14,7 @@ const Search = ({ statistics, players }) => {
return {
type: "statistic",
value: s,
searchTerm: prettifyStatisticName(s.type, s.name),
searchTerm: `${s.type} ${s.name}`,
};
})
.concat(
@ -42,92 +39,54 @@ const Search = ({ statistics, players }) => {
return searchEngine.search(`'"${searchTerm}"'`);
}, [searchEngine, searchTerm]);
const renderRow = ({
index, // Index of row
isScrolling, // The List is currently being scrolled
isVisible, // This row is visible within the List (eg it is not an overscanned row)
key, // Unique key within array of rendered rows
parent, // Reference to the parent List (instance)
style, // Style object to be applied to row (to position it);
// This must be passed through to the rendered row element.
}) => {
const x = searchResults[index];
return (
<Link
key={
x.item.type === "player"
? `/${x.item.type}/${x.item.value.id}`
: `/${x.item.type}/${x.item.value.type}/${x.item.value.name}`
}
to={
x.item.type === "player"
? `/${x.item.type}/${x.item.value.id}`
: `/${x.item.type}/${x.item.value.type}/${x.item.value.name}`
}
style={style}
>
<Button
size="sm"
leftIcon={
x.item.type === "player" ? (
<Icon as={FaUserCircle} />
) : (
<Icon as={FaArrowAltCircleRight} transform="rotate(-45deg)" />
)
}
variant="ghost"
my="0.5"
display="block"
textAlign="left"
width="100%"
>
{x.item.searchTerm}
</Button>
</Link>
);
};
return (
<WindowScroller>
{({ height, isScrolling, onChildScroll, scrollTop, registerChild }) => (
<>
<Heading as="h1" size="4xl" my="8">
<Center>📈</Center>
</Heading>
<Input
placeholder="Find statistics or players"
size="lg"
variant="filled"
value={searchTerm}
onChange={(event) => setSearchTerm(event.target.value)}
mb="8"
/>
{searchResults.length === 0 ? <AggregatesShowcase /> : <></>}
<div ref={registerChild}>
{searchResults.length > 0 ? (
<AutoSizer disableHeight>
{({ width }) => (
<List
autoHeight
height={height}
isScrolling={isScrolling}
onScroll={onChildScroll}
scrollTop={scrollTop}
rowCount={searchResults.length}
rowHeight={36}
rowRenderer={renderRow}
width={width}
/>
)}
</AutoSizer>
) : (
<></>
)}
</div>
</>
)}
</WindowScroller>
<>
<Heading as="h1" size="4xl" my="8">
<Center>📈</Center>
</Heading>
<Input
placeholder="Find statistics or players"
size="lg"
variant="filled"
value={searchTerm}
onChange={(event) => setSearchTerm(event.target.value)}
/>
<Flex direction="column" align="stretch" my="4">
{searchResults.map((x, i) => {
return (
<Link
to={
x.item.type === "player"
? `/${x.item.type}/${x.item.value.id}`
: `/${x.item.type}/${x.item.value.type}/${x.item.value.name}`
}
>
<Button
key={i}
size="sm"
leftIcon={
x.item.type === "player" ? (
<Icon as={FaUserCircle} />
) : (
<Icon
as={FaArrowAltCircleRight}
transform="rotate(-45deg)"
/>
)
}
variant="ghost"
my="0.5"
display="block"
textAlign="left"
width="100%"
>
{x.item.searchTerm}
</Button>
</Link>
);
})}
</Flex>
</>
);
};

View File

@ -1,61 +0,0 @@
import React, { useMemo } from "react";
import useHover from "./useHover";
import { Box, Heading, HStack, Tooltip } from "@chakra-ui/react";
import prettifyStatisticName from "./PrettifyStatisticName";
const randomColor = () =>
`hsl(${Math.floor(Math.random() * 359)}, ${
50 + Math.floor(Math.random() * 50)
}%, ${25 + Math.floor(Math.random() * 50)}%)`;
const StackedBarSegment = ({ aggregate, total }) => {
const color = useMemo(randomColor, []);
const [hoverRef, isHovered] = useHover();
return (
<Tooltip
hasArrow
label={`${aggregate.value
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")} ${prettifyStatisticName(
aggregate.type,
aggregate.name
)}`}
>
<Box
width={aggregate.value / total}
height="100%"
filter={isHovered ? "clear" : "saturate(0.5)"}
backgroundColor={color}
ref={hoverRef}
></Box>
</Tooltip>
);
};
const StackedBar = ({ heading, aggregates }) => {
const total = aggregates.reduce((acc, val) => acc + val.value, 0);
return (
<>
<Heading size="xs" mt="4" fontWeight="medium">
{heading}
</Heading>
<HStack
width="100%"
height="8"
spacing="0"
rounded="md"
overflow="hidden"
mt="2"
>
{aggregates.map((x, i) => (
<StackedBarSegment key={i} aggregate={x} total={total} />
))}
</HStack>
</>
);
};
export default StackedBar;

View File

@ -1,28 +1,40 @@
import React, { useMemo } from "react";
import React, { useMemo, useState } from "react";
import { useQuery } from "react-query";
import axios from "axios";
import {
Button,
Center,
Flex,
Heading,
Icon,
Input,
Table,
Thead,
Tbody,
Tfoot,
Tr,
Th,
Td,
TableCaption,
} from "@chakra-ui/react";
import { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName";
const Statistic = ({ type, name, players }) => {
const ranking = useQuery(`statistic ${type} ${name}`, async () => {
const { data } = await axios.get(`/api/statistics/${type}/${name}`);
return data.filter((x) => x.value > 0);
});
const ranking = useQuery(
`statistic ${type} ${name}`,
async () => {
const { data } = await axios.get(`/api/statistics/${type}/${name}`);
return data;
},
{
placeholderData: [],
}
);
const playerDict = useMemo(() => {
return Object.assign({}, ...players.map((x) => ({ [x.id]: x.name })));
}, [players]);
return Object.assign({}, ...players.data.map((x) => ({ [x.id]: x.name })));
}, players);
return (
<>
@ -35,9 +47,9 @@ const Statistic = ({ type, name, players }) => {
Stonks for
</Heading>
<Heading as="h1" size="xl" mb="8">
{prettifyStatisticName(type, name)}
{type} {name}
</Heading>
<Table size="sm" variant="striped">
<Table variant="simple" size="sm" variant="striped">
<Thead>
<Tr>
<Th>Player</Th>
@ -46,23 +58,19 @@ const Statistic = ({ type, name, players }) => {
</Tr>
</Thead>
<Tbody>
{ranking.isSuccess ? (
ranking.data.map((x, i) => {
return (
<Tr key={i}>
<Td>
<Link to={`/player/${x.playerId}`}>
{playerDict[x.playerId]}
</Link>
</Td>
<Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.value}</Td>
</Tr>
);
})
) : (
<></>
)}
{ranking.data.map((x, i) => {
return (
<Tr key={i}>
<Td>
<Link to={`/player/${x.playerId}`}>
{playerDict[x.playerId]}
</Link>
</Td>
<Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.value}</Td>
</Tr>
);
})}
</Tbody>
</Table>
</>

View File

@ -6,7 +6,6 @@ import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App.js";
import "./index.css";
import "react-virtualized/styles.css";
const queryClient = new QueryClient();

View File

@ -1,25 +0,0 @@
import { useEffect, useRef, useState } from "react";
function useHover() {
const [value, setValue] = useState(false);
const ref = useRef(null);
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
useEffect(
() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseover", handleMouseOver);
node.addEventListener("mouseout", handleMouseOut);
return () => {
node.removeEventListener("mouseover", handleMouseOver);
node.removeEventListener("mouseout", handleMouseOut);
};
}
} //,
//[ref.current] // Recall only if ref changes
);
return [ref, value];
}
export default useHover;