Compare commits
30 Commits
release-0.
...
main
Author | SHA1 | Date |
---|---|---|
Kevin Belisle | 5b7885368f | |
Kevin Belisle | d224ac81d8 | |
Kevin Belisle | c3286bfa7f | |
Kevin Belisle | 7c637f181e | |
Kevin Belisle | 34e5e207d9 | |
Kevin Belisle | 8e27e95fd9 | |
Kevin Belisle | 6b3f87c401 | |
Kevin Belisle | 24d33afd59 | |
Kevin Belisle | a86453f497 | |
Kevin Belisle | 959ac79fbd | |
Kevin Belisle | 7c359aa390 | |
Kevin Belisle | 7f9f9a01c4 | |
Kevin Belisle | e4ecd5d1b1 | |
Kevin Belisle | 2ba00ab2c6 | |
Kevin Belisle | f1afe82492 | |
Kevin Belisle | b8d642e393 | |
Kevin Belisle | ad466ca35b | |
Kevin Belisle | f452a84863 | |
Klutz | 7d92796b82 | |
Kevin Belisle | a03bd8ff8d | |
Kevin Belisle | 6512f3ca41 | |
Kevin Belisle | 4c9e819ef9 | |
Kevin Belisle | dbe58f135b | |
Kevin Belisle | b5a16e7b4b | |
Kevin Belisle | c12f3482d3 | |
Kevin Belisle | 443bde126f | |
Kevin Belisle | 33e6b23a6b | |
Kevin Belisle | c801bd1157 | |
Kevin Belisle | 4aff34926f | |
Kevin Belisle | f6e6b90d8d |
|
@ -3,3 +3,5 @@
|
|||
|
||||
# Ignore Gradle build output directory
|
||||
build
|
||||
|
||||
/app/databases
|
|
@ -0,0 +1,9 @@
|
|||
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.
|
|
@ -76,6 +76,16 @@ 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 {
|
||||
|
|
|
@ -8,6 +8,7 @@ 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
|
||||
|
@ -25,7 +26,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
|
|||
Javalin.create { config ->
|
||||
config.enableCorsForAllOrigins()
|
||||
config.addStaticFiles("spa")
|
||||
config.addSinglePageRoot("/", "spa")
|
||||
config.addSinglePageRoot("", "spa/index.html")
|
||||
config.enforceSsl = false
|
||||
config.ignoreTrailingSlashes = true
|
||||
}
|
||||
|
@ -35,7 +36,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
|
|||
run {
|
||||
if (statisticsCache.isEmpty() or
|
||||
(Duration.between(Instant.now(), statisticsCacheTimestamp) >
|
||||
Duration.ofHours(1))
|
||||
Duration.ofMinutes(5))
|
||||
) {
|
||||
transaction(database) {
|
||||
addLogger(StdOutSqlLogger)
|
||||
|
@ -92,7 +93,7 @@ fun initApiServer(apiServerPort: Int, database: Database) {
|
|||
run {
|
||||
if (playersCache.isEmpty() or
|
||||
(Duration.between(Instant.now(), playersCacheTimestamp) >
|
||||
Duration.ofHours(1))
|
||||
Duration.ofMinutes(5))
|
||||
) {
|
||||
transaction(database) {
|
||||
addLogger(StdOutSqlLogger)
|
||||
|
@ -173,6 +174,34 @@ 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")
|
||||
|
@ -199,3 +228,13 @@ 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
|
||||
)
|
||||
|
|
|
@ -4,19 +4,21 @@ 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 {
|
||||
fun main() = runBlocking {
|
||||
println("Starting Stonks...")
|
||||
|
||||
val fis = FileInputStream("./stonks.config")
|
||||
|
@ -39,7 +41,8 @@ fun main() =
|
|||
databaseName,
|
||||
h2TcpServerPort,
|
||||
h2StartWebServer,
|
||||
h2tWebServerPort)
|
||||
h2tWebServerPort
|
||||
)
|
||||
|
||||
initApiServer(apiServerPort, database)
|
||||
|
||||
|
@ -48,7 +51,7 @@ fun main() =
|
|||
delay(60 * 1000L)
|
||||
|
||||
println("END")
|
||||
}
|
||||
}
|
||||
|
||||
fun initH2Server(
|
||||
databaseBaseDir: String,
|
||||
|
@ -59,11 +62,20 @@ fun initH2Server(
|
|||
): Database {
|
||||
val webServer =
|
||||
Server.createWebServer(
|
||||
"-trace", "-baseDir", databaseBaseDir, "-webPort", h2WebServerPort.toString())
|
||||
"-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()
|
||||
|
@ -79,7 +91,9 @@ 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
|
||||
|
@ -102,17 +116,42 @@ 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 {
|
||||
suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) = coroutineScope {
|
||||
launch {
|
||||
while (true) {
|
||||
StatisticsImporter.importStatistics(folder, db)
|
||||
delay(interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,16 +4,6 @@ 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)
|
||||
|
@ -25,6 +15,25 @@ 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)
|
||||
|
@ -32,3 +41,10 @@ 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")
|
||||
}
|
||||
|
|
|
@ -26,39 +26,45 @@ object StatisticsImporter {
|
|||
private val klaxon = Klaxon()
|
||||
|
||||
fun importStatistics(folder: String, database: Database) {
|
||||
println("Importing new statistics...")
|
||||
println("Starting new statistics import.")
|
||||
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
|
||||
|
||||
transaction(database) {
|
||||
addLogger(StdOutSqlLogger)
|
||||
|
||||
val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()
|
||||
|
||||
transaction(database) {
|
||||
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) {
|
||||
|
@ -113,7 +119,68 @@ 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())
|
||||
""".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()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -135,7 +202,7 @@ object StatisticsImporter {
|
|||
.map { it[LiveStatistics.playerId] }
|
||||
|
||||
savedPlayers
|
||||
.filter { Duration.between(Instant.now(), it.timestamp) > Duration.ofDays(1) }
|
||||
.filter { Duration.between(it.timestamp, Instant.now()) > Duration.ofDays(1) }
|
||||
.forEach { player ->
|
||||
runBlocking {
|
||||
val name = getName(player.id)
|
||||
|
@ -176,9 +243,8 @@ 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
|
||||
|
|
|
@ -4777,6 +4777,11 @@
|
|||
"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",
|
||||
|
@ -5789,6 +5794,15 @@
|
|||
"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",
|
||||
|
@ -13008,6 +13022,11 @@
|
|||
"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",
|
||||
|
@ -13166,6 +13185,19 @@
|
|||
"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",
|
||||
|
|
|
@ -18,7 +18,8 @@
|
|||
"react-icons": "^4.2.0",
|
||||
"react-query": "^3.18.1",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-scripts": "4.0.3"
|
||||
"react-scripts": "4.0.3",
|
||||
"react-virtualized": "^9.22.3"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
|
|
Binary file not shown.
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 15 KiB |
|
@ -4,12 +4,14 @@
|
|||
<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="#000000" />
|
||||
<meta name="theme-color" content="#FFFFFF" />
|
||||
<!--
|
||||
<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.
|
||||
|
@ -19,7 +21,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>React App</title>
|
||||
<title>Stonks!</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
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;
|
|
@ -1,7 +1,7 @@
|
|||
import React from "react";
|
||||
import { useQuery } from "react-query";
|
||||
import axios from "axios";
|
||||
import { BrowserRouter, Switch, Redirect, Route } from "react-router-dom";
|
||||
import { BrowserRouter, Switch, Route } from "react-router-dom";
|
||||
import { Container } from "@chakra-ui/react";
|
||||
|
||||
import Search from "./Search";
|
||||
|
@ -41,14 +41,17 @@ const App = () => {
|
|||
<Statistic
|
||||
type={routeProps.match.params.type}
|
||||
name={routeProps.match.params.name}
|
||||
players={players}
|
||||
players={players.data}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Route
|
||||
path="/player/:id"
|
||||
render={(routeProps) => (
|
||||
<Player playerId={routeProps.match.params.id} players={players} />
|
||||
<Player
|
||||
playerId={routeProps.match.params.id}
|
||||
players={players.data}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Route>
|
||||
|
|
|
@ -1,41 +1,28 @@
|
|||
import React, { useMemo, useState } from "react";
|
||||
import React 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 playerStats = useQuery(`player ${playerId}`, async () => {
|
||||
const { data } = await axios.get(`/api/players/${playerId}`);
|
||||
data.sort((a, b) => a.rank - b.rank);
|
||||
return data;
|
||||
},
|
||||
{
|
||||
placeholderData: [],
|
||||
}
|
||||
);
|
||||
data.sort((a, b) => a.rank - b.rank || b.value - a.value);
|
||||
return data.filter((x) => x.value > 0);
|
||||
});
|
||||
|
||||
const playerDict = useMemo(() => {
|
||||
return Object.assign({}, ...players.data.map((x) => ({ [x.id]: x.name })));
|
||||
}, players);
|
||||
const playerName = players?.find((x) => x.id === playerId)?.name;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
@ -54,10 +41,11 @@ const Player = ({ playerId, players }) => {
|
|||
height="48px"
|
||||
src={`https://minotar.net/avatar/${playerId.replaceAll("-", "")}/48`}
|
||||
mr="4"
|
||||
rounded="md"
|
||||
/>
|
||||
{playerDict[playerId]}
|
||||
{playerName}
|
||||
</Heading>
|
||||
<Table variant="simple" size="sm" variant="striped">
|
||||
<Table size="sm" variant="striped">
|
||||
<Thead>
|
||||
<Tr>
|
||||
<Th>Statistic</Th>
|
||||
|
@ -66,19 +54,23 @@ const Player = ({ playerId, players }) => {
|
|||
</Tr>
|
||||
</Thead>
|
||||
<Tbody>
|
||||
{playerStats.data.map((x, i) => {
|
||||
{playerStats.isSuccess ? (
|
||||
playerStats.data.map((x, i) => {
|
||||
return (
|
||||
<Tr key={i}>
|
||||
<Td>
|
||||
<Link to={`/statistic/${x.type}/${x.name}`}>
|
||||
{x.type} {x.name}
|
||||
{prettifyStatisticName(x.type, x.name)}
|
||||
</Link>
|
||||
</Td>
|
||||
<Td isNumeric>{x.rank}</Td>
|
||||
<Td isNumeric>{x.value}</Td>
|
||||
</Tr>
|
||||
);
|
||||
})}
|
||||
})
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</Tbody>
|
||||
</Table>
|
||||
</>
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
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;
|
|
@ -1,9 +1,12 @@
|
|||
import React, { useMemo, useState } from "react";
|
||||
import Fuse from "fuse.js";
|
||||
|
||||
import { Button, Center, Flex, Heading, Icon, Input } from "@chakra-ui/react";
|
||||
import { Button, Center, 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("");
|
||||
|
@ -14,7 +17,7 @@ const Search = ({ statistics, players }) => {
|
|||
return {
|
||||
type: "statistic",
|
||||
value: s,
|
||||
searchTerm: `${s.type} ${s.name}`,
|
||||
searchTerm: prettifyStatisticName(s.type, s.name),
|
||||
};
|
||||
})
|
||||
.concat(
|
||||
|
@ -39,39 +42,38 @@ const Search = ({ statistics, players }) => {
|
|||
return searchEngine.search(`'"${searchTerm}"'`);
|
||||
}, [searchEngine, searchTerm]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<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) => {
|
||||
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
|
||||
key={i}
|
||||
size="sm"
|
||||
leftIcon={
|
||||
x.item.type === "player" ? (
|
||||
<Icon as={FaUserCircle} />
|
||||
) : (
|
||||
<Icon
|
||||
as={FaArrowAltCircleRight}
|
||||
transform="rotate(-45deg)"
|
||||
/>
|
||||
<Icon as={FaArrowAltCircleRight} transform="rotate(-45deg)" />
|
||||
)
|
||||
}
|
||||
variant="ghost"
|
||||
|
@ -84,9 +86,48 @@ const Search = ({ statistics, players }) => {
|
|||
</Button>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</Flex>
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
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;
|
|
@ -1,40 +1,28 @@
|
|||
import React, { useMemo, useState } from "react";
|
||||
import React, { useMemo } 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 ranking = useQuery(`statistic ${type} ${name}`, async () => {
|
||||
const { data } = await axios.get(`/api/statistics/${type}/${name}`);
|
||||
return data;
|
||||
},
|
||||
{
|
||||
placeholderData: [],
|
||||
}
|
||||
);
|
||||
return data.filter((x) => x.value > 0);
|
||||
});
|
||||
|
||||
const playerDict = useMemo(() => {
|
||||
return Object.assign({}, ...players.data.map((x) => ({ [x.id]: x.name })));
|
||||
}, players);
|
||||
return Object.assign({}, ...players.map((x) => ({ [x.id]: x.name })));
|
||||
}, [players]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
@ -47,9 +35,9 @@ const Statistic = ({ type, name, players }) => {
|
|||
Stonks for
|
||||
</Heading>
|
||||
<Heading as="h1" size="xl" mb="8">
|
||||
{type} {name}
|
||||
{prettifyStatisticName(type, name)}
|
||||
</Heading>
|
||||
<Table variant="simple" size="sm" variant="striped">
|
||||
<Table size="sm" variant="striped">
|
||||
<Thead>
|
||||
<Tr>
|
||||
<Th>Player</Th>
|
||||
|
@ -58,7 +46,8 @@ const Statistic = ({ type, name, players }) => {
|
|||
</Tr>
|
||||
</Thead>
|
||||
<Tbody>
|
||||
{ranking.data.map((x, i) => {
|
||||
{ranking.isSuccess ? (
|
||||
ranking.data.map((x, i) => {
|
||||
return (
|
||||
<Tr key={i}>
|
||||
<Td>
|
||||
|
@ -70,7 +59,10 @@ const Statistic = ({ type, name, players }) => {
|
|||
<Td isNumeric>{x.value}</Td>
|
||||
</Tr>
|
||||
);
|
||||
})}
|
||||
})
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</Tbody>
|
||||
</Table>
|
||||
</>
|
||||
|
|
|
@ -6,6 +6,7 @@ import { QueryClient, QueryClientProvider } from "react-query";
|
|||
import App from "./App.js";
|
||||
|
||||
import "./index.css";
|
||||
import "react-virtualized/styles.css";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
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;
|
Loading…
Reference in New Issue