Compare commits

..

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

11 changed files with 150 additions and 183 deletions

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

@ -36,7 +36,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 +93,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)

View File

@ -4,7 +4,6 @@ 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.*
@ -12,7 +11,6 @@ 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.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
@ -93,7 +91,6 @@ fun initH2Server(
SchemaUtils.create(LiveStatistics) SchemaUtils.create(LiveStatistics)
SchemaUtils.create(AggregateStatistics) 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,32 +113,6 @@ 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

View File

@ -41,10 +41,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,7 +26,7 @@ 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)
@ -34,7 +34,6 @@ object StatisticsImporter {
updateAggregateStatistics(database) 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) {
@ -65,6 +64,8 @@ object StatisticsImporter {
} }
} }
transaction(database) { transaction(database) {
addLogger(StdOutSqlLogger)
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) {
@ -132,53 +133,29 @@ object StatisticsImporter {
SET @Timestamp = CURRENT_TIMESTAMP; SET @Timestamp = CURRENT_TIMESTAMP;
INSERT INTO AGGREGATESTATISTICS ("Type", "Name", "Timestamp", "Value") INSERT INTO AGGREGATESTATISTICS ("Type", "Name", "Timestamp", "Value")
SELECT LiveMax."Type", SELECT Live."Type",
'', '',
@Timestamp AS "Timestamp", @Timestamp AS "Timestamp",
SUM(LiveMax."Value") sum(Live."Value")
FROM ( FROM LIVESTATISTICS as Live
SELECT Live."Type", LEFT JOIN AGGREGATESTATISTICS as Agg
Live."Name", ON Live."Type" = Agg."Type"
MAX(Live."Value") AS "Value"
FROM livestatistics as Live
WHERE array_contains(array['minecraft:mined'], Live."Type") WHERE array_contains(array['minecraft:mined'], Live."Type")
GROUP BY Live."Type", Live."Name", Live."PlayerId" GROUP BY Live."Type"
) as LiveMax HAVING sum(Live."Value") <> max(Agg."Value");
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") INSERT INTO AGGREGATESTATISTICS ("Type", "Name", "Timestamp", "Value")
SELECT LiveMax."Type",
LiveMax."Name",
@Timestamp AS "Timestamp",
SUM(LiveMax."Value")
FROM (
SELECT Live."Type", SELECT Live."Type",
Live."Name", Live."Name",
MAX(Live."Value") AS "Value" @Timestamp AS "Timestamp",
Sum(Live."Value")
FROM livestatistics as Live FROM livestatistics as Live
LEFT JOIN AGGREGATESTATISTICS as Agg
ON Live."Type" = Agg."Type" AND Live."Name" = Agg."Name"
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") 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") OR array_contains(array['minecraft:killed', 'minecraft:killed_by'], Live."Type")
GROUP BY Live."Type", Live."Name", Live."PlayerId" GROUP BY Live."Type", Live."Name"
) as LiveMax HAVING sum(Live."Value") <> max(Agg."Value");
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 +179,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)

View File

@ -2,43 +2,59 @@ import React from "react";
import { useQuery } from "react-query"; import { useQuery } from "react-query";
import axios from "axios"; import axios from "axios";
import { SimpleGrid, Stat, StatLabel, StatNumber } from "@chakra-ui/react"; import {
AspectRatio,
Box,
Flex,
Heading,
HStack,
Icon,
SimpleGrid,
Stat,
StatLabel,
StatNumber,
StatHelpText,
StatArrow,
StatGroup,
Tooltip,
} 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 prettifyStatisticName from "./PrettifyStatisticName";
import StackedBar from "./StackedBar"; import StackedBar from "./StackedBar";
const AggregatesShowcase = () => { const AggregatesShowcase = () => {
const aggregates = useQuery(`aggregates`, async () => { const aggregates = useQuery(
const { data } = await axios.get(`/api/aggregates`); `aggregates`,
async () => {
const { data } = await axios.get(`http://localhost:7000/api/aggregates`);
return data; return data;
}); },
{
placeholderData: [],
}
);
const killedAggregates = aggregates.isSuccess const killedAggregates = aggregates.data
? aggregates.data
.filter((x) => x.type === "minecraft:killed") .filter((x) => x.type === "minecraft:killed")
.sort((a, b) => b.value - a.value) .sort((a, b) => b.value - a.value);
: []; const killedTotal = killedAggregates.reduce((acc, val) => acc + val.value, 0);
// const killedTotal = killedAggregates.reduce((acc, val) => acc + val.value, 0);
const killedByAggregates = aggregates.isSuccess const killedByAggregates = aggregates.data
? aggregates.data
.filter((x) => x.type === "minecraft:killed_by") .filter((x) => x.type === "minecraft:killed_by")
.sort((a, b) => b.value - a.value) .sort((a, b) => b.value - a.value);
: []; const killedByTotal = killedByAggregates.reduce(
// const killedByTotal = killedByAggregates.reduce( (acc, val) => acc + val.value,
// (acc, val) => acc + val.value, 0
// 0 );
// );
const travelAggregates = aggregates.isSuccess const travelAggregates = aggregates.data
? aggregates.data .filter((x) => x.type === "minecraft:custom" && x.name.endsWith("one_cm"))
.filter( .sort((a, b) => b.value - a.value);
(x) => x.type === "minecraft:custom" && x.name.endsWith("one_cm") const travelTotal = travelAggregates.reduce((acc, val) => acc + val.value, 0);
)
.sort((a, b) => b.value - a.value)
: [];
// const travelTotal = travelAggregates.reduce((acc, val) => acc + val.value, 0);
return aggregates.isSuccess ? ( return aggregates.isFetched ? (
<> <>
<StackedBar heading="Mobs Killed" aggregates={killedAggregates} /> <StackedBar heading="Mobs Killed" aggregates={killedAggregates} />
@ -57,15 +73,18 @@ const AggregatesShowcase = () => {
.map((x, i) => { .map((x, i) => {
var value = x.value; var value = x.value;
if (x.name === "minecraft:play_one_minute") { if (x.name === "minecraft:play_one_minute") {
value = Math.floor(x.value / 20 / 60); value = x.value / 20 / 60;
} }
return ( return (
<Stat key={i}> <Stat key={i}>
<StatLabel>{prettifyStatisticName(x.type, x.name)}</StatLabel> <StatLabel>{prettifyStatisticName(x.type, x.name)}</StatLabel>
<StatNumber>{`${value <StatNumber>{`${x.value
.toString() .toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`}</StatNumber> .replace(
/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,
","
)}`}</StatNumber>
</Stat> </Stat>
); );
})} })}

View File

@ -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

@ -16,13 +16,19 @@ import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName"; import prettifyStatisticName from "./PrettifyStatisticName";
const Player = ({ playerId, players }) => { const Player = ({ playerId, players }) => {
const playerStats = useQuery(`player ${playerId}`, async () => { const playerStats = useQuery(
`player ${playerId}`,
async () => {
const { data } = await axios.get(`/api/players/${playerId}`); const { data } = await axios.get(`/api/players/${playerId}`);
data.sort((a, b) => a.rank - b.rank || b.value - a.value); data.sort((a, b) => a.rank - b.rank);
return data.filter((x) => x.value > 0); return data;
}); },
{
placeholderData: [],
}
);
const playerName = players?.find((x) => x.id === playerId)?.name; const playerName = players.data.find((x) => x.id === playerId)?.name;
return ( return (
<> <>
@ -54,8 +60,7 @@ 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>
@ -67,10 +72,7 @@ const Player = ({ playerId, players }) => {
<Td isNumeric>{x.value}</Td> <Td isNumeric>{x.value}</Td>
</Tr> </Tr>
); );
}) })}
) : (
<></>
)}
</Tbody> </Tbody>
</Table> </Table>
</> </>

View File

@ -1,6 +1,21 @@
import React, { useMemo } from "react"; import React, { useMemo } from "react";
import useHover from "./useHover"; import useHover from "./useHover";
import { Box, Heading, HStack, Tooltip } from "@chakra-ui/react"; import {
AspectRatio,
Box,
Button,
Heading,
HStack,
Icon,
Input,
Stat,
StatLabel,
StatNumber,
StatHelpText,
StatArrow,
StatGroup,
Tooltip,
} from "@chakra-ui/react";
import prettifyStatisticName from "./PrettifyStatisticName"; import prettifyStatisticName from "./PrettifyStatisticName";
const randomColor = () => const randomColor = () =>
@ -18,15 +33,15 @@ const StackedBarSegment = ({ aggregate, total }) => {
hasArrow hasArrow
label={`${aggregate.value label={`${aggregate.value
.toString() .toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")} ${prettifyStatisticName( .replace(
aggregate.type, /\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,
aggregate.name ","
)}`} )} ${prettifyStatisticName(aggregate.type, aggregate.name)}`}
> >
<Box <Box
width={aggregate.value / total} width={aggregate.value / total}
height="100%" height="100%"
filter={isHovered ? "clear" : "saturate(0.5)"} filter={isHovered ? "clear" : "saturate(0.15)"}
backgroundColor={color} backgroundColor={color}
ref={hoverRef} ref={hoverRef}
></Box> ></Box>

View File

@ -15,13 +15,19 @@ import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName"; import prettifyStatisticName from "./PrettifyStatisticName";
const Statistic = ({ type, name, players }) => { 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}`); const { data } = await axios.get(`/api/statistics/${type}/${name}`);
return data.filter((x) => x.value > 0); 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 (
@ -46,8 +52,7 @@ 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>
@ -59,10 +64,7 @@ const Statistic = ({ type, name, players }) => {
<Td isNumeric>{x.value}</Td> <Td isNumeric>{x.value}</Td>
</Tr> </Tr>
); );
}) })}
) : (
<></>
)}
</Tbody> </Tbody>
</Table> </Table>
</> </>

View File

@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
function useHover() { function useHover() {
const [value, setValue] = useState(false); const [value, setValue] = useState(false);
@ -16,8 +16,8 @@ function useHover() {
node.removeEventListener("mouseout", handleMouseOut); node.removeEventListener("mouseout", handleMouseOut);
}; };
} }
} //, },
//[ref.current] // Recall only if ref changes [ref.current] // Recall only if ref changes
); );
return [ref, value]; return [ref, value];
} }