commit 28f69217886ebd77df61269b5ecd52035a3b07a4 Author: Chaoscaot Date: Sat Oct 25 12:50:47 2025 +0200 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b1dff0d --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..9bb5ac9 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +sw \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..2a65317 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..3efb2d8 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..7070480 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,21 @@ + + + + 10.12.3 + JavaOnly + true + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..81a8aa4 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,40 @@ +plugins { + kotlin("jvm") version "2.2.20" + kotlin("plugin.serialization") version "2.2.0" + application +} + +group = "de.steamwar" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(kotlin("test")) + + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + + implementation("com.github.ajalt.clikt:clikt:5.0.3") + implementation("com.github.ajalt.mordant:mordant:3.0.2") + implementation("com.github.ajalt.mordant:mordant-coroutines:3.0.2") + + implementation("org.mariadb.jdbc:mariadb-java-client:3.3.1") + implementation("org.jetbrains.exposed:exposed-core:1.0.0-rc-2") + implementation("org.jetbrains.exposed:exposed-jdbc:1.0.0-rc-2") + implementation("org.jetbrains.exposed:exposed-dao:1.0.0-rc-2") + implementation("org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0-rc-2") +} + +tasks.test { + useJUnitPlatform() +} +kotlin { + jvmToolchain(21) +} + +application { + mainClass.set("de.steamwar.MainKt") +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..754383c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Oct 23 18:47:16 CEST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..b0f1cd5 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +rootProject.name = "sw" \ No newline at end of file diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt new file mode 100644 index 0000000..9afa8e5 --- /dev/null +++ b/src/main/kotlin/Main.kt @@ -0,0 +1,17 @@ +package de.steamwar + +import com.github.ajalt.clikt.core.main +import com.github.ajalt.clikt.core.subcommands +import de.steamwar.commands.SteamWar +import de.steamwar.commands.database.DatabaseCommand +import de.steamwar.commands.database.InfoCommand +import de.steamwar.commands.database.ResetCommand +import de.steamwar.commands.user.UserCommand +import de.steamwar.commands.user.UsesrInfoCommand + +fun main(args: Array) = SteamWar() + .subcommands( + DatabaseCommand().subcommands(InfoCommand(), ResetCommand()), + UserCommand().subcommands(UsesrInfoCommand()) + ) + .main(args) \ No newline at end of file diff --git a/src/main/kotlin/commands/SteamWar.kt b/src/main/kotlin/commands/SteamWar.kt new file mode 100644 index 0000000..d87e975 --- /dev/null +++ b/src/main/kotlin/commands/SteamWar.kt @@ -0,0 +1,14 @@ +package de.steamwar.commands + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.findOrSetObject +import com.github.ajalt.mordant.rendering.TextStyles +import de.steamwar.db.Database + +class SteamWar: CliktCommand(name = "sw") { + val db by findOrSetObject { Database() } + + override fun run() { + echo("${TextStyles.bold("SteamWar-CLI")} (${db.database})") + } +} \ No newline at end of file diff --git a/src/main/kotlin/commands/database/DatabaseCommand.kt b/src/main/kotlin/commands/database/DatabaseCommand.kt new file mode 100644 index 0000000..9c2e5ec --- /dev/null +++ b/src/main/kotlin/commands/database/DatabaseCommand.kt @@ -0,0 +1,22 @@ +package de.steamwar.commands.database + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.CliktError +import com.github.ajalt.clikt.core.Context +import com.github.ajalt.clikt.core.requireObject +import com.github.ajalt.clikt.parameters.options.flag +import com.github.ajalt.clikt.parameters.options.option +import de.steamwar.db.Database + +class DatabaseCommand: CliktCommand(name = "db") { + val useProduction by option().flag() + val db by requireObject() + + override fun help(context: Context): String = "Run database commands" + + override fun run() { + if (!useProduction && db.database == "production") { + throw CliktError("You should not use the production database!") + } + } +} diff --git a/src/main/kotlin/commands/database/InfoCommand.kt b/src/main/kotlin/commands/database/InfoCommand.kt new file mode 100644 index 0000000..9942e0e --- /dev/null +++ b/src/main/kotlin/commands/database/InfoCommand.kt @@ -0,0 +1,23 @@ +package de.steamwar.commands.database + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.requireObject +import com.github.ajalt.mordant.table.table +import de.steamwar.db.Database + +class InfoCommand: CliktCommand() { + val db by requireObject() + + override fun run() { + val tables = db.execute("SHOW TABLES") { it.getString(1) } + + echo( + table { + header { row("Name") } + body { + tables.map { row(it) } + } + } + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/commands/database/ResetCommand.kt b/src/main/kotlin/commands/database/ResetCommand.kt new file mode 100644 index 0000000..26fcac5 --- /dev/null +++ b/src/main/kotlin/commands/database/ResetCommand.kt @@ -0,0 +1,31 @@ +package de.steamwar.commands.database + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.CliktError +import com.github.ajalt.clikt.core.requireObject +import com.github.ajalt.mordant.rendering.TextColors +import com.github.ajalt.mordant.rendering.TextStyles +import de.steamwar.db.Database +import java.io.File + +class ResetCommand: CliktCommand() { + val db by requireObject() + + override fun run() { + val schemaFile = File("/var/Schema.sql") + if (!schemaFile.exists()) { + throw CliktError("Schema file not found!") + } + + val schema = schemaFile.readText() + + val tables = db.execute("SHOW TABLES;") { it.getString(1) } + for (table in tables) { + db.execute("DROP TABLE IF EXISTS $table;") { } + } + + db.execute(schema) { } + + echo(TextColors.brightGreen(TextStyles.bold("Database reset!"))) + } +} \ No newline at end of file diff --git a/src/main/kotlin/commands/user/UserCommand.kt b/src/main/kotlin/commands/user/UserCommand.kt new file mode 100644 index 0000000..12533fc --- /dev/null +++ b/src/main/kotlin/commands/user/UserCommand.kt @@ -0,0 +1,26 @@ +package de.steamwar.commands.user + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.CliktError +import com.github.ajalt.clikt.core.findOrSetObject +import com.github.ajalt.clikt.parameters.arguments.argument +import de.steamwar.db.schema.SteamwarUser +import de.steamwar.db.schema.SteamwarUserTable +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.core.or +import org.jetbrains.exposed.v1.jdbc.transactions.transaction + +class UserCommand: CliktCommand("user") { + val userId by argument() + val user by findOrSetObject("user") { + transaction { + SteamwarUser.find { (SteamwarUserTable.id eq userId.toIntOrNull()) or (SteamwarUserTable.username eq userId) } + .firstOrNull() + ?.let { return@transaction it } ?: throw CliktError("User not found!") + } + } + + override fun run() { + user.id + } +} \ No newline at end of file diff --git a/src/main/kotlin/commands/user/UsesrInfoCommand.kt b/src/main/kotlin/commands/user/UsesrInfoCommand.kt new file mode 100644 index 0000000..313ff5e --- /dev/null +++ b/src/main/kotlin/commands/user/UsesrInfoCommand.kt @@ -0,0 +1,50 @@ +package de.steamwar.commands.user + +import com.github.ajalt.clikt.core.CliktCommand +import com.github.ajalt.clikt.core.requireObject +import com.github.ajalt.mordant.table.table +import de.steamwar.db.schema.Session +import de.steamwar.db.schema.SteamwarUser +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import kotlin.time.DurationUnit +import kotlin.time.ExperimentalTime + +class UsesrInfoCommand: CliktCommand("info") { + val user by requireObject("user") + + @OptIn(ExperimentalTime::class) + override fun run() { + transaction { + val sessions = Session.selectAll().where { Session.user eq user.id.value }.map { it[Session.start] to it[Session.end] } + + val totalPlayed = sessions.map { it.second - it.first }.sumOf { it.toDouble(DurationUnit.HOURS) } + val firstJoin = sessions.minByOrNull { it.first }?.first + val lastJoin = sessions.maxByOrNull { it.second }?.second + + echo( + table { + body { + row("Name", user.username) + row("UUID", user.uuid) + row("Team", user.team.name) + row("Leader", user.leader) + row("Locale", user.locale) + row("Beigetreten am", firstJoin) + row("Zuletzt gesehen am", lastJoin) + row("Spielzeit", totalPlayed.toString() + "h") + row("Punishments", table { + header { row("Typ", "Ersteller", "Von", "Bis", "Grund") } + body { + user.punishments.map { + row(it.type, it.punisher.username, it.starttime.toString(), if (it.perma) "Perma" else it.endtime.toString(), it.reason) + } + } + }) + } + } + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/db/Database.kt b/src/main/kotlin/db/Database.kt new file mode 100644 index 0000000..dc8c0e5 --- /dev/null +++ b/src/main/kotlin/db/Database.kt @@ -0,0 +1,83 @@ +package de.steamwar.db + +import com.github.ajalt.clikt.core.CliktError +import org.jetbrains.exposed.v1.core.Expression +import org.jetbrains.exposed.v1.core.ExpressionWithColumnType +import org.jetbrains.exposed.v1.core.Function +import org.jetbrains.exposed.v1.core.IColumnType +import org.jetbrains.exposed.v1.core.LongColumnType +import org.jetbrains.exposed.v1.core.QueryBuilder +import org.jetbrains.exposed.v1.core.WindowFunction +import org.jetbrains.exposed.v1.core.WindowFunctionDefinition +import org.jetbrains.exposed.v1.core.append +import org.jetbrains.exposed.v1.jdbc.Database +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import java.io.File +import java.sql.ResultSet +import java.util.Properties +import kotlin.time.ExperimentalTime +import kotlin.time.Instant + +class Database { + val host: String + val port: String + val database: String + + init { + val config = File(System.getProperty("user.home"), "mysql.properties") + + if (!config.exists()) { + throw CliktError("Config file not found!") + } + + val props = Properties(); + + props.load(config.inputStream()) + + host = props.getProperty("host") + port = props.getProperty("port") + database = props.getProperty("database") + + val username = props.getProperty("user") + val password = props.getProperty("password") + + val url = "jdbc:mariadb://$host:$port/$database" + + Database.Companion.connect(url, driver = "org.mariadb.jdbc.Driver", user = username, password = password) + } + + fun execute(sql: String, transform: (ResultSet) -> T): List = transaction { + val result = mutableListOf() + exec(sql) { rs -> + while (rs.next()) { + result += transform(rs) + } + } + return@transaction result + } + + fun executeSingle(sql: String, transform: (ResultSet) -> T): T? { + return execute(sql) { rs -> + if (!rs.next()) { + return@execute null + } + transform(rs) + }.single() + } +} + +class UnixTimestamp( + val expr: Expression, + columnType: IColumnType +) : Function(columnType), WindowFunction { + override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { + append("UNIX_TIMESTAMP(", expr, ")") + } + + override fun over(): WindowFunctionDefinition { + return WindowFunctionDefinition(columnType, this) + } +} + +@OptIn(ExperimentalTime::class) +fun ExpressionWithColumnType.unixTimestamp(): UnixTimestamp = UnixTimestamp(this, LongColumnType()) \ No newline at end of file diff --git a/src/main/kotlin/db/schema/Punishments.kt b/src/main/kotlin/db/schema/Punishments.kt new file mode 100644 index 0000000..64d8677 --- /dev/null +++ b/src/main/kotlin/db/schema/Punishments.kt @@ -0,0 +1,32 @@ +package de.steamwar.db.schema + +import org.jetbrains.exposed.v1.core.dao.id.EntityID +import org.jetbrains.exposed.v1.core.dao.id.IntIdTable +import org.jetbrains.exposed.v1.dao.IntEntity +import org.jetbrains.exposed.v1.dao.IntEntityClass +import org.jetbrains.exposed.v1.datetime.timestamp +import kotlin.time.ExperimentalTime + +@OptIn(ExperimentalTime::class) +object Punishments: IntIdTable("Punishments", "PunishmentId") { + val user = integer("userid").references(SteamwarUserTable.id) + val punisher = integer("punisher").references(SteamwarUserTable.id) + val type = varchar("type", 16) + val reason = text("reason") + val starttime = timestamp("starttime") + val endtime = timestamp("endtime") + val perma = bool("perma") +} + +@OptIn(ExperimentalTime::class) +class Punishment(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(Punishments) + + var user by SteamwarUser referencedOn Punishments.user + var punisher by SteamwarUser referencedOn Punishments.punisher + var type by Punishments.type + var reason by Punishments.reason + var starttime by Punishments.starttime + var endtime by Punishments.endtime + var perma by Punishments.perma +} \ No newline at end of file diff --git a/src/main/kotlin/db/schema/Session.kt b/src/main/kotlin/db/schema/Session.kt new file mode 100644 index 0000000..0580bd6 --- /dev/null +++ b/src/main/kotlin/db/schema/Session.kt @@ -0,0 +1,12 @@ +package de.steamwar.db.schema + +import org.jetbrains.exposed.v1.core.Table +import org.jetbrains.exposed.v1.datetime.timestamp +import kotlin.time.ExperimentalTime + +@OptIn(ExperimentalTime::class) +object Session: Table("Session") { + val user = integer("userid").references(SteamwarUserTable.id) + val start = timestamp("starttime") + val end = timestamp("endtime") +} diff --git a/src/main/kotlin/db/schema/SteamwarUser.kt b/src/main/kotlin/db/schema/SteamwarUser.kt new file mode 100644 index 0000000..c14be1a --- /dev/null +++ b/src/main/kotlin/db/schema/SteamwarUser.kt @@ -0,0 +1,34 @@ +package de.steamwar.db.schema + +import org.jetbrains.exposed.v1.core.dao.id.EntityID +import org.jetbrains.exposed.v1.core.dao.id.IntIdTable +import org.jetbrains.exposed.v1.dao.IntEntity +import org.jetbrains.exposed.v1.dao.IntEntityClass + +object SteamwarUserTable: IntIdTable("UserData") { + val uuid = uuid("uuid") + val username = varchar("username", 255) + val team = integer("team").references(TeamTable.id) + val leader = bool("leader") + val locale = varchar("locale", 16) + val manualLocale = bool("manuallocale") + val bedrock = bool("bedrock") + val password = varchar("password", 1024) + val discordId = long("DiscordId") +} + +class SteamwarUser(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(SteamwarUserTable) + + var uuid by SteamwarUserTable.uuid + var username by SteamwarUserTable.username + var team by Team referencedOn SteamwarUserTable.team + var leader by SteamwarUserTable.leader + var locale by SteamwarUserTable.locale + var manualLocale by SteamwarUserTable.manualLocale + var bedrock by SteamwarUserTable.bedrock + var password by SteamwarUserTable.password + var discordId by SteamwarUserTable.discordId + + val punishments by Punishment referrersOn Punishments.user +} \ No newline at end of file diff --git a/src/main/kotlin/db/schema/Team.kt b/src/main/kotlin/db/schema/Team.kt new file mode 100644 index 0000000..ae57d6a --- /dev/null +++ b/src/main/kotlin/db/schema/Team.kt @@ -0,0 +1,26 @@ +package de.steamwar.db.schema + +import org.jetbrains.exposed.v1.core.dao.id.EntityID +import org.jetbrains.exposed.v1.core.dao.id.IntIdTable +import org.jetbrains.exposed.v1.dao.IntEntity +import org.jetbrains.exposed.v1.dao.IntEntityClass + +object TeamTable: IntIdTable("Team", "TeamId") { + val kuerzel = varchar("TeamKuerzel", 16) + val color = varchar("TeamColor", 16) + val name = varchar("TeamName", 255) + val deleted = bool("TeamDeleted") + val address = varchar("Address", 16) + val port = integer("Port") +} + +class Team(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(TeamTable) + + var kuerzel by TeamTable.kuerzel + var color by TeamTable.color + var name by TeamTable.name + var deleted by TeamTable.deleted + var address by TeamTable.address + var port by TeamTable.port +} \ No newline at end of file