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 # Ignore Gradle build output directory
build 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 duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest { attributes["Main-Class"] = "xyz.etztech.stonks.AppKt" } manifest { attributes["Main-Class"] = "xyz.etztech.stonks.AppKt" }
configurations["compileClasspath"].forEach { file: File -> from(zipTree(file.absoluteFile)) } 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 { application {

View File

@ -8,7 +8,6 @@ import kotlinx.serialization.*
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.* import org.jetbrains.exposed.sql.transactions.*
import xyz.etztech.stonks.dsl.AggregateStatistics
import xyz.etztech.stonks.dsl.LiveStatistics import xyz.etztech.stonks.dsl.LiveStatistics
import xyz.etztech.stonks.dsl.Players import xyz.etztech.stonks.dsl.Players
import xyz.etztech.stonks.dsl.Statistics import xyz.etztech.stonks.dsl.Statistics
@ -26,7 +25,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
Javalin.create { config -> Javalin.create { config ->
config.enableCorsForAllOrigins() config.enableCorsForAllOrigins()
config.addStaticFiles("spa") config.addStaticFiles("spa")
config.addSinglePageRoot("", "spa/index.html") config.addSinglePageRoot("/", "spa")
config.enforceSsl = false config.enforceSsl = false
config.ignoreTrailingSlashes = true config.ignoreTrailingSlashes = true
} }
@ -36,7 +35,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
run { run {
if (statisticsCache.isEmpty() or if (statisticsCache.isEmpty() or
(Duration.between(Instant.now(), statisticsCacheTimestamp) > (Duration.between(Instant.now(), statisticsCacheTimestamp) >
Duration.ofMinutes(5)) Duration.ofHours(1))
) { ) {
transaction(database) { transaction(database) {
addLogger(StdOutSqlLogger) addLogger(StdOutSqlLogger)
@ -93,7 +92,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
run { run {
if (playersCache.isEmpty() or if (playersCache.isEmpty() or
(Duration.between(Instant.now(), playersCacheTimestamp) > (Duration.between(Instant.now(), playersCacheTimestamp) >
Duration.ofMinutes(5)) Duration.ofHours(1))
) { ) {
transaction(database) { transaction(database) {
addLogger(StdOutSqlLogger) 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) } app.get("api/*") { ctx -> ctx.status(404) }
println("Javalin web server started") println("Javalin web server started")
@ -228,13 +199,3 @@ data class HistoricalStatisticValue(
val timestamp: String, val timestamp: String,
val value: Long 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.io.FileInputStream
import java.util.* import java.util.*
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.serialization.*
import org.h2.tools.Server import org.h2.tools.Server
import org.jetbrains.exposed.exceptions.ExposedSQLException import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.transactions.transaction
import xyz.etztech.stonks.api.initApiServer 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.LiveStatistics
import xyz.etztech.stonks.dsl.Players import xyz.etztech.stonks.dsl.Players
import xyz.etztech.stonks.dsl.Statistics import xyz.etztech.stonks.dsl.Statistics
import xyz.etztech.stonks.statisticsimporter.StatisticsImporter import xyz.etztech.stonks.statisticsimporter.StatisticsImporter
fun main() = runBlocking { fun main() =
println("Starting Stonks...") runBlocking {
println("Starting Stonks...")
val fis = FileInputStream("./stonks.config") val fis = FileInputStream("./stonks.config")
val config = Properties() val config = Properties()
config.load(fis) config.load(fis)
val databaseBaseDir = config.getProperty("databaseBaseDir") val databaseBaseDir = config.getProperty("databaseBaseDir")
val databaseName = config.getProperty("databaseName") val databaseName = config.getProperty("databaseName")
val h2StartWebServer = config.getProperty("h2StartWebServer").toBoolean() val h2StartWebServer = config.getProperty("h2StartWebServer").toBoolean()
val h2tWebServerPort = config.getProperty("h2tWebServerPort").toInt() val h2tWebServerPort = config.getProperty("h2tWebServerPort").toInt()
val h2TcpServerPort = config.getProperty("h2TcpServerPort").toInt() val h2TcpServerPort = config.getProperty("h2TcpServerPort").toInt()
val apiServerPort = config.getProperty("apiServerPort").toInt() val apiServerPort = config.getProperty("apiServerPort").toInt()
val statisticsUpdateInterval = config.getProperty("statisticsUpdateInterval").toLong() val statisticsUpdateInterval = config.getProperty("statisticsUpdateInterval").toLong()
val minecraftStatsFolder = config.getProperty("minecraftStatsFolder") val minecraftStatsFolder = config.getProperty("minecraftStatsFolder")
val database = val database =
initH2Server( initH2Server(
databaseBaseDir, databaseBaseDir,
databaseName, databaseName,
h2TcpServerPort, h2TcpServerPort,
h2StartWebServer, h2StartWebServer,
h2tWebServerPort 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( fun initH2Server(
databaseBaseDir: String, databaseBaseDir: String,
@ -62,20 +59,11 @@ fun initH2Server(
): Database { ): Database {
val webServer = val webServer =
Server.createWebServer( Server.createWebServer(
"-baseDir", "-trace", "-baseDir", databaseBaseDir, "-webPort", h2WebServerPort.toString())
databaseBaseDir,
"-webPort",
h2WebServerPort.toString()
)
val tcpServer = val tcpServer =
Server.createTcpServer( Server.createTcpServer(
"-trace", "-trace", "-baseDir", databaseBaseDir, "-webPort", h2TcpServerPort.toString())
"-baseDir",
databaseBaseDir,
"-webPort",
h2TcpServerPort.toString()
)
if (h2StartWebServer) { if (h2StartWebServer) {
webServer.start() webServer.start()
@ -91,9 +79,7 @@ fun initH2Server(
addLogger(StdOutSqlLogger) addLogger(StdOutSqlLogger)
SchemaUtils.create(Statistics) SchemaUtils.create(Statistics)
SchemaUtils.create(LiveStatistics) SchemaUtils.create(LiveStatistics)
SchemaUtils.create(AggregateStatistics)
SchemaUtils.create(Players) SchemaUtils.create(Players)
SchemaUtils.create(KeyValue)
// Create indexes with explicit SQL because I can't figure out how to do it with exposed // 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 // Wrap it in a try block because it throws an exception if index already exists
@ -116,42 +102,17 @@ fun initH2Server(
TransactionManager.current() TransactionManager.current()
.exec("CREATE INDEX idx_type_name ON LiveStatistics (\"Type\", \"Name\")") .exec("CREATE INDEX idx_type_name ON LiveStatistics (\"Type\", \"Name\")")
} catch (e: ExposedSQLException) {} } 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 return database
} }
suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) = coroutineScope { suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) =
launch { coroutineScope {
while (true) { launch {
StatisticsImporter.importStatistics(folder, db) while (true) {
delay(interval) 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.*
import org.jetbrains.exposed.sql.`java-time`.timestamp 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() { object Statistics : Table() {
val playerId: Column<String> = varchar("PlayerId", 150) val playerId: Column<String> = varchar("PlayerId", 150)
val type: Column<String> = varchar("Type", 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") 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() { object Players : Table() {
val id: Column<String> = varchar("Id", 150) val id: Column<String> = varchar("Id", 150)
val name: Column<String> = varchar("Name", 150) val name: Column<String> = varchar("Name", 150)
@ -41,10 +32,3 @@ object Players : Table() {
override val primaryKey = PrimaryKey(id, name = "PK_id") 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() private val klaxon = Klaxon()
fun importStatistics(folder: String, database: Database) { fun importStatistics(folder: String, database: Database) {
println("Starting new statistics import.") println("Importing new statistics...")
File(folder).listFiles().forEach { readFile(it, database) } File(folder).listFiles().forEach { readFile(it, database) }
println("Updating live statistics table...") println("Updating live statistics table...")
updateLiveStatistics(database) updateLiveStatistics(database)
println("Updating aggregate statistics table...")
updateAggregateStatistics(database)
println("Refreshing player names...") println("Refreshing player names...")
refreshPlayerNames(database) refreshPlayerNames(database)
println("Finished new statistics import.")
} }
fun readFile(file: File, database: Database) { fun readFile(file: File, database: Database) {
val statsFile = StatsFile.fromJson(file.readText()) val statsFile = StatsFile.fromJson(file.readText())
val playerId = file.nameWithoutExtension val playerId = file.nameWithoutExtension
val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()
transaction(database) { transaction(database) {
addLogger(StdOutSqlLogger)
val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()
LiveStatistics.slice(LiveStatistics.type, LiveStatistics.name, LiveStatistics.value) LiveStatistics.slice(LiveStatistics.type, LiveStatistics.name, LiveStatistics.value)
.select { LiveStatistics.playerId eq playerId } .select { LiveStatistics.playerId eq playerId }
.forEach { .forEach {
if (playerStats.containsKey(it[LiveStatistics.type])) { if (playerStats.containsKey(it[LiveStatistics.type])) {
playerStats[it[LiveStatistics.type]]?.put( playerStats[it[LiveStatistics.type]]?.put(
it[LiveStatistics.name], it[LiveStatistics.name], it[LiveStatistics.value])
it[LiveStatistics.value]
)
} else { } else {
playerStats.put( playerStats.put(
it[LiveStatistics.type], it[LiveStatistics.type],
mapOf<String, Long>( mapOf<String, Long>(
it[LiveStatistics.name] to it[LiveStatistics.name] to
it[LiveStatistics.value] it[LiveStatistics.value])
) .toMutableMap())
.toMutableMap()
)
} }
} }
}
transaction(database) {
statsFile?.stats?.forEach { type, stats -> statsFile?.stats?.forEach { type, stats ->
stats.forEach { name, value -> stats.forEach { name, value ->
if (playerStats.get(type)?.get(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" UPDATE SET T."Value" = S."Value", T."Rank" = S."Rank"
WHEN NOT MATCHED THEN WHEN NOT MATCHED THEN
INSERT VALUES (S."PlayerId", S."Type", S."Name", S."Value", S."Rank") INSERT VALUES (S."PlayerId", S."Type", S."Name", S."Value", S."Rank")
""".trimIndent() """.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()
)
} }
} }
@ -202,7 +135,7 @@ object StatisticsImporter {
.map { it[LiveStatistics.playerId] } .map { it[LiveStatistics.playerId] }
savedPlayers savedPlayers
.filter { Duration.between(it.timestamp, Instant.now()) > Duration.ofDays(1) } .filter { Duration.between(Instant.now(), it.timestamp) > Duration.ofDays(1) }
.forEach { player -> .forEach { player ->
runBlocking { runBlocking {
val name = getName(player.id) val name = getName(player.id)
@ -243,8 +176,9 @@ object StatisticsImporter {
suspend fun getName(id: String): String? { suspend fun getName(id: String): String? {
val response: HttpResponse = val response: HttpResponse =
httpClient.request( httpClient.request(
"https://sessionserver.mojang.com/session/minecraft/profile/${id.replace("-", "")}" "https://sessionserver.mojang.com/session/minecraft/profile/${id.replace("-", "")}") {
) { method = HttpMethod.Get } method = HttpMethod.Get
}
if (response.status.isSuccess()) { if (response.status.isSuccess()) {
try { try {
return MojangProfileResponse.fromJson(response.readText())?.name return MojangProfileResponse.fromJson(response.readText())?.name

32
spa/package-lock.json generated
View File

@ -4777,11 +4777,6 @@
"wrap-ansi": "^6.2.0" "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": { "co": {
"version": "4.6.0", "version": "4.6.0",
"resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz",
@ -5794,15 +5789,6 @@
"utila": "~0.4" "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": { "dom-serializer": {
"version": "0.2.2", "version": "0.2.2",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.2.tgz", "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", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" "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": { "react-query": {
"version": "3.18.1", "version": "3.18.1",
"resolved": "https://registry.npmjs.org/react-query/-/react-query-3.18.1.tgz", "resolved": "https://registry.npmjs.org/react-query/-/react-query-3.18.1.tgz",
@ -13185,19 +13166,6 @@
"tslib": "^1.0.0" "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": { "read-pkg": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", "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-icons": "^4.2.0",
"react-query": "^3.18.1", "react-query": "^3.18.1",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "4.0.3", "react-scripts": "4.0.3"
"react-virtualized": "^9.22.3"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "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" /> <meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#FFFFFF" /> <meta name="theme-color" content="#000000" />
<!--
<meta <meta
name="description" name="description"
content="Web site created using create-react-app" content="Web site created using create-react-app"
/> />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
-->
<!-- <!--
Notice the use of %PUBLIC_URL% in the tags above. Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build. 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. 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`. Learn how to configure a non-root public URL by running `npm run build`.
--> -->
<title>Stonks!</title> <title>React App</title>
</head> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <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 React from "react";
import { useQuery } from "react-query"; import { useQuery } from "react-query";
import axios from "axios"; 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 { Container } from "@chakra-ui/react";
import Search from "./Search"; import Search from "./Search";
@ -41,17 +41,14 @@ const App = () => {
<Statistic <Statistic
type={routeProps.match.params.type} type={routeProps.match.params.type}
name={routeProps.match.params.name} name={routeProps.match.params.name}
players={players.data} players={players}
/> />
)} )}
/> />
<Route <Route
path="/player/:id" path="/player/:id"
render={(routeProps) => ( render={(routeProps) => (
<Player <Player playerId={routeProps.match.params.id} players={players} />
playerId={routeProps.match.params.id}
players={players.data}
/>
)} )}
/> />
<Route> <Route>

View File

@ -1,28 +1,41 @@
import React from "react"; import React, { useMemo, useState } from "react";
import { useQuery } from "react-query"; import { useQuery } from "react-query";
import axios from "axios"; import axios from "axios";
import { import {
Button,
Center, Center,
Flex,
Heading, Heading,
Icon,
Image, Image,
Table, Table,
Thead, Thead,
Tbody, Tbody,
Tfoot,
Tr, Tr,
Th, Th,
Td, Td,
TableCaption,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName";
const Player = ({ playerId, players }) => { const Player = ({ playerId, players }) => {
const playerStats = useQuery(`player ${playerId}`, async () => { const playerStats = useQuery(
const { data } = await axios.get(`/api/players/${playerId}`); `player ${playerId}`,
data.sort((a, b) => a.rank - b.rank || b.value - a.value); async () => {
return data.filter((x) => x.value > 0); 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 ( return (
<> <>
@ -41,11 +54,10 @@ const Player = ({ playerId, players }) => {
height="48px" height="48px"
src={`https://minotar.net/avatar/${playerId.replaceAll("-", "")}/48`} src={`https://minotar.net/avatar/${playerId.replaceAll("-", "")}/48`}
mr="4" mr="4"
rounded="md"
/> />
{playerName} {playerDict[playerId]}
</Heading> </Heading>
<Table size="sm" variant="striped"> <Table variant="simple" size="sm" variant="striped">
<Thead> <Thead>
<Tr> <Tr>
<Th>Statistic</Th> <Th>Statistic</Th>
@ -54,23 +66,19 @@ const Player = ({ playerId, players }) => {
</Tr> </Tr>
</Thead> </Thead>
<Tbody> <Tbody>
{playerStats.isSuccess ? ( {playerStats.data.map((x, i) => {
playerStats.data.map((x, i) => { return (
return ( <Tr key={i}>
<Tr key={i}> <Td>
<Td> <Link to={`/statistic/${x.type}/${x.name}`}>
<Link to={`/statistic/${x.type}/${x.name}`}> {x.type} {x.name}
{prettifyStatisticName(x.type, x.name)} </Link>
</Link> </Td>
</Td> <Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.rank}</Td> <Td isNumeric>{x.value}</Td>
<Td isNumeric>{x.value}</Td> </Tr>
</Tr> );
); })}
})
) : (
<></>
)}
</Tbody> </Tbody>
</Table> </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 React, { useMemo, useState } from "react";
import Fuse from "fuse.js"; 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 { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom"; 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 Search = ({ statistics, players }) => {
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
@ -17,7 +14,7 @@ const Search = ({ statistics, players }) => {
return { return {
type: "statistic", type: "statistic",
value: s, value: s,
searchTerm: prettifyStatisticName(s.type, s.name), searchTerm: `${s.type} ${s.name}`,
}; };
}) })
.concat( .concat(
@ -42,92 +39,54 @@ const Search = ({ statistics, players }) => {
return searchEngine.search(`'"${searchTerm}"'`); return searchEngine.search(`'"${searchTerm}"'`);
}, [searchEngine, 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 ( return (
<WindowScroller> <>
{({ height, isScrolling, onChildScroll, scrollTop, registerChild }) => ( <Heading as="h1" size="4xl" my="8">
<> <Center>📈</Center>
<Heading as="h1" size="4xl" my="8"> </Heading>
<Center>📈</Center> <Input
</Heading> placeholder="Find statistics or players"
<Input size="lg"
placeholder="Find statistics or players" variant="filled"
size="lg" value={searchTerm}
variant="filled" onChange={(event) => setSearchTerm(event.target.value)}
value={searchTerm} />
onChange={(event) => setSearchTerm(event.target.value)} <Flex direction="column" align="stretch" my="4">
mb="8" {searchResults.map((x, i) => {
/> return (
{searchResults.length === 0 ? <AggregatesShowcase /> : <></>} <Link
<div ref={registerChild}> to={
{searchResults.length > 0 ? ( x.item.type === "player"
<AutoSizer disableHeight> ? `/${x.item.type}/${x.item.value.id}`
{({ width }) => ( : `/${x.item.type}/${x.item.value.type}/${x.item.value.name}`
<List }
autoHeight >
height={height} <Button
isScrolling={isScrolling} key={i}
onScroll={onChildScroll} size="sm"
scrollTop={scrollTop} leftIcon={
rowCount={searchResults.length} x.item.type === "player" ? (
rowHeight={36} <Icon as={FaUserCircle} />
rowRenderer={renderRow} ) : (
width={width} <Icon
/> as={FaArrowAltCircleRight}
)} transform="rotate(-45deg)"
</AutoSizer> />
) : ( )
<></> }
)} variant="ghost"
</div> my="0.5"
</> display="block"
)} textAlign="left"
</WindowScroller> 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 { useQuery } from "react-query";
import axios from "axios"; import axios from "axios";
import { import {
Button,
Center, Center,
Flex,
Heading, Heading,
Icon,
Input,
Table, Table,
Thead, Thead,
Tbody, Tbody,
Tfoot,
Tr, Tr,
Th, Th,
Td, Td,
TableCaption,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { FaUserCircle, FaArrowAltCircleRight } from "react-icons/fa";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName";
const Statistic = ({ type, name, players }) => { const Statistic = ({ type, name, players }) => {
const ranking = useQuery(`statistic ${type} ${name}`, async () => { const ranking = useQuery(
const { data } = await axios.get(`/api/statistics/${type}/${name}`); `statistic ${type} ${name}`,
return data.filter((x) => x.value > 0); async () => {
}); const { data } = await axios.get(`/api/statistics/${type}/${name}`);
return data;
},
{
placeholderData: [],
}
);
const playerDict = useMemo(() => { const playerDict = useMemo(() => {
return Object.assign({}, ...players.map((x) => ({ [x.id]: x.name }))); return Object.assign({}, ...players.data.map((x) => ({ [x.id]: x.name })));
}, [players]); }, players);
return ( return (
<> <>
@ -35,9 +47,9 @@ const Statistic = ({ type, name, players }) => {
Stonks for Stonks for
</Heading> </Heading>
<Heading as="h1" size="xl" mb="8"> <Heading as="h1" size="xl" mb="8">
{prettifyStatisticName(type, name)} {type} {name}
</Heading> </Heading>
<Table size="sm" variant="striped"> <Table variant="simple" size="sm" variant="striped">
<Thead> <Thead>
<Tr> <Tr>
<Th>Player</Th> <Th>Player</Th>
@ -46,23 +58,19 @@ const Statistic = ({ type, name, players }) => {
</Tr> </Tr>
</Thead> </Thead>
<Tbody> <Tbody>
{ranking.isSuccess ? ( {ranking.data.map((x, i) => {
ranking.data.map((x, i) => { return (
return ( <Tr key={i}>
<Tr key={i}> <Td>
<Td> <Link to={`/player/${x.playerId}`}>
<Link to={`/player/${x.playerId}`}> {playerDict[x.playerId]}
{playerDict[x.playerId]} </Link>
</Link> </Td>
</Td> <Td isNumeric>{x.rank}</Td>
<Td isNumeric>{x.rank}</Td> <Td isNumeric>{x.value}</Td>
<Td isNumeric>{x.value}</Td> </Tr>
</Tr> );
); })}
})
) : (
<></>
)}
</Tbody> </Tbody>
</Table> </Table>
</> </>

View File

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