commit 78b102dfbf7754d4e93a0f7a8f9995f27e707e89 Author: yenon Date: Wed Nov 29 22:20:58 2023 +0100 Initial commit. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c88b43f --- /dev/null +++ b/.gitignore @@ -0,0 +1,183 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij,gradle,java,kotlin +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,gradle,java,kotlin + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### Kotlin ### +# Compiled class file + +# Log file + +# BlueJ files + +# Mobile Tools for Java (J2ME) + +# Package Files # + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/intellij,gradle,java,kotlin diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..61a9130 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..df543e3 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..fdc392f --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..e805548 --- /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..0363e93 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + + \ 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..49a982c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,29 @@ +plugins { + kotlin("jvm") version "1.9.20" +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(kotlin("test")) + + implementation("io.ktor:ktor-server-core-jvm:2.3.6") + implementation("io.ktor:ktor-server-netty-jvm:2.3.6") + implementation("io.ktor:ktor-server-status-pages-jvm:2.3.6") + implementation("io.ktor:ktor-server-default-headers-jvm:2.3.6") + implementation("io.ktor:ktor-server-html-builder:2.3.6") + implementation("org.jetbrains.kotlin-wrappers:kotlin-css:1.0.0-pre.650") +} + +tasks.test { + useJUnitPlatform() +} + +kotlin { + jvmToolchain(8) +} \ 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..06febab --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100755 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/rconCommands.txt b/rconCommands.txt new file mode 100644 index 0000000..4857699 --- /dev/null +++ b/rconCommands.txt @@ -0,0 +1,81 @@ +ListCommands +ShowCommandInfo +ListPermittedCommands +AdminKillServer +AdminSetMaxNumPlayers +AdminSetNumReservedSlots +AdminSetServerPassword +AdminSlomo +AdminSetPublicQueueLimit +ListPlayers +ListSquads +AdminListDisconnectedPlayers +AdminTeleportToPlayer +AdminTeleportToPlayerById +AdminKick "" +AdminKickById +AdminBan "" "" +AdminBanById "" +AdminWarn "" +AdminWarnById +AdminForceTeamChange +AdminForceTeamChangeById +AdminRemovePlayerFromSquadById +AdminRemovePlayerFromSquad +AdminDemoteCommander +AdminDemoteCommanderById +AdminDisbandSquad +SLInviteMember +ListLevels +ListLayers +AdminChangeLevel +AdminChangeLayer +AdminSetNextLevel +AdminSetNextLayer +ShowCurrentMap +ShowNextMap +AdminVoteLevel +AdminVoteLayer +AdminVoteNextLevel +AdminVoteNextLayer +AdminBroadcast +ChatToAdmin +AdminVote "" "" +AdminRestartMatch +AdminEndMatch +AdminPauseMatch +AdminUnpauseMatch +AdminSetFogOfWar +AdminForceAllVehicleAvailability +AdminForceAllDeployableAvailability +AdminForceAllRoleAvailability +AdminForceAllActionAvailability +AdminNoTeamChangeTimer +AdminNoRespawnTimer +AdminDisableVehicleClaiming +AdminDisableVehicleTeamRequirement +AdminDisableVehicleKitRequirement +AdminAlwaysValidPlacement +AdminForceNetUpdateOnClientSaturation +AdminAddCameraman +AdminCreateVehicle +AdminCreateDeployable +AdminGiveEquipment +AdminSpawnActor +AdminDemoPlay +AdminDemoRec +AdminDemoStop +AdminProfileServer +AdminProfileServerCSV +DebugVehicleList +DebugVehicleSetComponentHealthByName "" +DebugPrintCustomOptions +AdminSetCustomOption "" +AdminRemoveCustomOption +DebugAddBuildSupply +DebugAddAmmoSupply +DebugRearmPlayer +RecordingStart +RecordingStart_Named +RecordingStop +RepGraphSetDSFTargetKBytesSec \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..114ca77 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0" +} + +rootProject.name = "SquadCompanion" \ No newline at end of file diff --git a/src/main/kotlin/Css.kt b/src/main/kotlin/Css.kt new file mode 100644 index 0000000..ec3278c --- /dev/null +++ b/src/main/kotlin/Css.kt @@ -0,0 +1,21 @@ +object Css { + val cssString = """ + .teamView{ + height: 100%; + width: 100%; + display: flex; + } + .teamA{ + width: 50%; + } + .teamB{ + width: 50%; + } + .squadTable{ + width: 100%; + } + tr:nth-child(even) { + background-color: rgba(0, 0, 0, 0.5); + } + """.trimIndent() +} \ No newline at end of file diff --git a/src/main/kotlin/LayerInfo.kt b/src/main/kotlin/LayerInfo.kt new file mode 100644 index 0000000..e69de29 diff --git a/src/main/kotlin/LayerInfoModule.kt b/src/main/kotlin/LayerInfoModule.kt new file mode 100644 index 0000000..4e0e8e4 --- /dev/null +++ b/src/main/kotlin/LayerInfoModule.kt @@ -0,0 +1,39 @@ +import java.util.* + +object LayerInfoModule : Module() { + private val layerCountRegex = Regex("^" + Regex.escape("LogSquad: Found USQLayer Count : ") + """(\d+)$""") + private val layerAddedRegex = + Regex("^" + Regex.escape("LogSquad: Added Available Layer : ") + """([a-zA-Z0-9_-]+)$""") + private val rotationAddedRegex = + Regex("^" + Regex.escape("LogSquad: ") + """([a-zA-Z0-9_-]+)""" + Regex.escape(" was added to rotation list") + "$") + + val layerList = arrayListOf() + val rotationList = arrayListOf() + + override fun getName() = "Info Gatherer" + + override fun isOptional() = false + + override fun onEnable() { + + } + + override fun onDisable() { + + } + + override fun onLogMessage(time: Date, messageBurstGroup: Short, message: String) { + if (messageBurstGroup == 0.toShort()) { + layerAddedRegex.find(message)?.let { + layerList.add(it.groupValues[1]) + } + rotationAddedRegex.find(message)?.let { + rotationList.add(it.groupValues[1]) + } + layerCountRegex.find(message)?.let { + layerList.clear() + return + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/LogReader.kt b/src/main/kotlin/LogReader.kt new file mode 100644 index 0000000..6c16a57 --- /dev/null +++ b/src/main/kotlin/LogReader.kt @@ -0,0 +1,77 @@ +import kotlinx.coroutines.* +import java.io.BufferedInputStream +import java.io.ByteArrayInputStream +import java.nio.file.FileSystems +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardWatchEventKinds.ENTRY_CREATE +import kotlin.io.path.name + +class LogReader(path: Path, private val lineCallback: (String) -> Unit) : AutoCloseable { + private var reader: BufferedInputStream + private var watchJob: Job + private var readerJob: Job + private var stringBuilder = StringBuilder() + + private val coroutineScope = CoroutineScope(Dispatchers.IO) + + init { + val logWatcher = FileSystems.getDefault().newWatchService() + + val watchedDir = path.toAbsolutePath().parent + watchedDir.register(logWatcher, ENTRY_CREATE) + + reader = if (Files.isRegularFile(path)) { + Files.newInputStream(path).buffered() + } else { + ByteArrayInputStream(byteArrayOf()).buffered() + } + + watchJob = coroutineScope.launch(Dispatchers.IO) { + while (isActive) { + val watchKey = logWatcher.take() + watchKey.pollEvents().forEach { + if ((it.context() as Path).name == path.name) { + reader = Files.newInputStream(path).buffered() + } + } + watchKey.reset() + } + } + + readerJob = coroutineScope.launch(Dispatchers.IO) { + var currentReader = reader + while (isActive) { + var byteArray: ByteArray + do { + byteArray = currentReader.readBytes() + if (byteArray.isNotEmpty()) { + processByteArray(byteArray) + } + } while (byteArray.isNotEmpty()) + + if (currentReader != reader) { + currentReader = reader + } + + delay(10) + } + } + } + + fun processByteArray(byteArray: ByteArray) { + val lines = String(byteArray).split("\n") + + stringBuilder.append(lines[0]) + + for (i in 1..(LayerInfoModule) + +fun main() { + LogReader(Paths.get("SquadGame.log")) { logLine -> + logRegex.find(logLine)?.let { matchResult -> + val time = squadTimeFormat.parse(matchResult.groupValues[1]) + val id = matchResult.groupValues[2].trim().toShort() + val message = matchResult.groupValues[3] + + modules.forEach { + if (it.enabled) { + it.onLogMessage(time, id, message) + } + } + } + } + + val connection = RconConnection("195.201.62.238", 21114, "ThisIsJustATestServer") + val abstraction = RconAbstraction(connection) + GlobalScope.launch { + + //if(connection.reconnect().isFailure){ + // println("No connection :(") + //} + //println(connection.sendCommand("ListLayers")) + } + + embeddedServer(Netty, 8080) { + install(StatusPages) { + exception { call, cause -> + val writer = StringWriter() + cause.printStackTrace(PrintWriter(writer)) + call.respondText(text = "500: $writer", status = HttpStatusCode.InternalServerError) + } + } + routing { + get("/layers") { + call.respondText( + contentType = ContentType.Text.Plain, + text = "Count: " + LayerInfoModule.layerList.size + "\n\n" + + LayerInfoModule.layerList.joinToString("\n") + ) + } + get("/rotation") { + call.respondText( + contentType = ContentType.Text.Plain, + text = "Count: " + LayerInfoModule.rotationList.size + "\n\n" + + LayerInfoModule.rotationList.joinToString("\n") + ) + } + get("/currentPlayers") { + call.respondText( + contentType = ContentType.Text.Plain, + text = abstraction.getCurrentPlayers().toString() + ) + } + get("/overview") { + val players = abstraction.getCurrentPlayers() + + call.respondHtmlTemplate(OverviewTemplate(players)) {} + } + get("/css") { + call.respondText(contentType = ContentType.Text.CSS, text = Css.cssString) + } + } + }.start(true) +} \ No newline at end of file diff --git a/src/main/kotlin/Module.kt b/src/main/kotlin/Module.kt new file mode 100644 index 0000000..c3b99a9 --- /dev/null +++ b/src/main/kotlin/Module.kt @@ -0,0 +1,27 @@ +import java.util.* + +abstract class Module { + var enabled = false + + abstract fun getName(): String + + abstract fun isOptional(): Boolean + + abstract fun onEnable() + + abstract fun onDisable() + + abstract fun onLogMessage(time: Date, messageBurstGroup: Short, message: String) + + fun enable() { + enabled = true + onEnable() + } + + fun disable() { + enabled = false + onDisable() + } + + fun isEnabled() = enabled +} \ No newline at end of file diff --git a/src/main/kotlin/OverviewTemplate.kt b/src/main/kotlin/OverviewTemplate.kt new file mode 100644 index 0000000..8b0eb90 --- /dev/null +++ b/src/main/kotlin/OverviewTemplate.kt @@ -0,0 +1,77 @@ +import io.ktor.server.html.* +import kotlinx.html.* + +class OverviewTemplate(private val players: ListPlayersOutput) : Template { + private fun TR.makePlayer(player: Player) { + td { +player.role } + td { +player.name } + td { +player.steamId.toString() } + td { + button {//Message + +"✉" + } + button {//Kick + +"\uD83E\uDDB6" + } + button {//Ban + +"⛔" + } + } + } + + private fun FlowContent.makeSquad(squad: Map.Entry>) { + val leader = squad.value.find { it.leader } + +if (squad.key != 0) { + "Squad ${squad.key}" + } else { + "Unassigned" + } + table("squadTable") { + leader?.let { + thead { + tr { + makePlayer(leader) + } + } + } + squad.value.forEach { + if (!it.leader) { + tr { + makePlayer(it) + } + } + } + } + } + + private fun FlowContent.makeSide(team: Map>) { + if (team.keys.isEmpty()) { + +"empty" + return + } + team.forEach { + makeSquad(it) + } + } + + override fun HTML.apply() { + val teamA = players.players.filter { it.teamId == 1 }.groupBy { it.squadId } + val teamB = players.players.filter { it.teamId == 2 }.groupBy { it.squadId } + + head { + styleLink("/css") + } + + body { + div("teamView") { + div("teamA") { + makeSide(teamA) + } + div("teamB") { + makeSide(teamB) + } + } + } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/RconAbstraction.kt b/src/main/kotlin/RconAbstraction.kt new file mode 100644 index 0000000..fb42239 --- /dev/null +++ b/src/main/kotlin/RconAbstraction.kt @@ -0,0 +1,71 @@ +/* +Format for "ListPlayers" +----- Active Players ----- +ID: 0 | SteamID: 76561198037144702 | Name: [PACK] yenon | Team ID: 1 | Squad ID: N/A | Is Leader: False | Role: USA_Rifleman_01 +----- Recently Disconnected Players [Max of 15] ----- +ID: 1 | SteamID: 76561199074475884 | Since Disconnect: 03m.56s | Name: RoeveNn +ID: 2 | SteamID: 76561199262966526 | Since Disconnect: 03m.51s | Name: Aliko + */ + +data class ListPlayersOutput(val players: ArrayList, val disconnected: ArrayList) +data class Player( + val playerId: Int, + val steamId: Long, + val name: String, + val teamId: Int, + val squadId: Int, + val leader: Boolean, + val role: String +) + +data class DisconnectedPlayer(val playerId: Int, val steamId: Long, val time: String, val name: String) + +val activePlayerInListRegex = Regex( + """ID: (\d+) \| SteamID: (\d{17}) \| Name: (.*) \| Team ID: ([12]) \| Squad ID: (N/A|\d+) \| Is Leader: (False|True) \| Role: ([a-zA-Z0-9_]+)${'$'}""", + RegexOption.MULTILINE +) +val inactivePlayerInListRegex = Regex( + """ID: (\d+) \| SteamID: (\d{17}) \| Since Disconnect: (\d{2}m\.\d{2})s \| Name: (.*)${'$'}""", + RegexOption.MULTILINE +) + +class RconAbstraction(private val connection: RconConnection) { + suspend fun getCurrentPlayers(): ListPlayersOutput { + val active = arrayListOf() + val disconnected = arrayListOf() + connection.sendCommand("ListPlayers").getOrNull()?.let { + + println(it) + activePlayerInListRegex.findAll(it).forEach { match -> + val playerId = match.groupValues[1].toInt() + val steamId = match.groupValues[2].toLong() + val name = match.groupValues[3] + val teamId = match.groupValues[4].toInt() + val squadId = match.groupValues[5].toIntOrNull() ?: 0 + val leader = match.groupValues[6] == "True" + val role = match.groupValues[7] + active.add(Player(playerId, steamId, name, teamId, squadId, leader, role)) + } + inactivePlayerInListRegex.findAll(it).forEach { match -> + val playerId = match.groupValues[1].toInt() + val steamId = match.groupValues[2].toLong() + val disconnectedTime = match.groupValues[3] + val name = match.groupValues[4] + disconnected.add(DisconnectedPlayer(playerId, steamId, disconnectedTime, name)) + } + } + return ListPlayersOutput(active, disconnected) + } + + suspend fun kickPlayer(steamId: Long, reason: String) { + connection.sendCommand("AdminKickById $steamId \"$reason\"") + } + + suspend fun banPlayer(steamId: Long, time: String, reason: String) { + connection.sendCommand("AdminBanById $steamId $time \"$reason\"") + } + + suspend fun messagePlayer(steamId: Long, message: String) { + connection.sendCommand("AdminKickById $steamId \"$message\"") + } +} \ No newline at end of file diff --git a/src/main/kotlin/RconConnection.kt b/src/main/kotlin/RconConnection.kt new file mode 100644 index 0000000..cd6e3ec --- /dev/null +++ b/src/main/kotlin/RconConnection.kt @@ -0,0 +1,182 @@ +import io.ktor.utils.io.core.* +import io.ktor.utils.io.nio.* +import kotlinx.coroutines.* +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.net.InetSocketAddress +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.channels.SocketChannel +import java.util.* +import kotlin.text.toByteArray + +const val SERVERDATA_AUTH = 3 +const val SERVERDATA_AUTH_RESPONSE = 2 +const val SERVERDATA_EXECCOMMAND = 2 +const val SERVERDATA_RESPONSE_VALUE = 0 + +const val FAILED_AUTH_ID = -1 +const val ACCEPTED_AUTH_ID = 1 +const val SQUAD_CONSOLE_ID = 0 + +val rconCharset = Charsets.UTF_8 + +data class RconPacket(val id: Int, val type: Int, val data: ByteArray) + +class RconConnection(private val host: String, private val port: Int, password: String) : AutoCloseable { + + private val coroutineScope = CoroutineScope(Dispatchers.IO) + private val authPacket = + createPacketByteBuffer(RconPacket(ACCEPTED_AUTH_ID, SERVERDATA_AUTH, password.toByteArray(rconCharset))) + private var currentId = ACCEPTED_AUTH_ID + 1 + private var socketChannel: SocketChannel = SocketChannel.open() + private val mutex = Mutex() + + init { + coroutineScope.launch { + while (isActive) { + delay(5000) + sendCommand("ListPlayers") + //println("Keepalive: "+sendCommand("ListPlayers")) + } + } + } + + private suspend fun reconnect(): Result = withContext(Dispatchers.IO) { + socketChannel.close() + socketChannel = SocketChannel.open().apply { + connect(InetSocketAddress(host, port)) + finishConnect() + println("Socket is open.") + } + + authenticate() + } + + private fun authenticate(): Result { + println("Sending auth packet") + socketChannel.write(authPacket) + println("Auth sent") + readPacket() + val packet = readPacket() + println("Response: $packet") + return if (packet.type == SERVERDATA_AUTH_RESPONSE) { + println(packet.id == ACCEPTED_AUTH_ID) + Result.success(packet.id == ACCEPTED_AUTH_ID) + } else { + Result.success(false) + } + } + + suspend fun sendCommand(command: String): Result = withContext(Dispatchers.IO) { + mutex.withLock { + if (!socketChannel.isConnected) { + println("reconnect needed.") + val reconnectResult = reconnect() + if (reconnectResult.isFailure) { + return@withContext Result.failure(reconnectResult.exceptionOrNull()!!) + } + reconnectResult.getOrNull()?.let { + if (!it) { + return@withContext Result.failure(Exception("Wrong password.")) + } + } + } + + currentId++ + val commandPacket = + createPacketByteBuffer(RconPacket(currentId, SERVERDATA_EXECCOMMAND, command.toByteArray(rconCharset))) + socketChannel.write(commandPacket) + + var responsePacket = readPacket() + //while (responsePacket.id() + do { + packetByteList.add(responsePacket.data) + responsePacket = readPacket() + } while (responsePacket.data.isEmpty()) + + if (responsePacket.id != currentId) { + return@withContext Result.failure(Exception("Out of order packet.")) + } + + val totalBytes = packetByteList.sumOf { it.size } + val combinedBytes = ByteArray(totalBytes) + var start = 0 + + packetByteList.forEach { + it.copyInto(combinedBytes, start) + start += it.size + } + + return@withContext Result.success(String(combinedBytes, rconCharset)) + } + } + + private fun readPacket(): RconPacket { + var packet = readRawPacket() + while (packet.id == 0 && packet.type == 1) { + println("Console ${packet.data.size}: " + String(packet.data)) + packet = readRawPacket() + } + return packet + } + + private fun readRawPacket(): RconPacket { + print("Reading new packet") + val size = socketChannel.readPacketExact(4L).readIntLittleEndian() + println(", size: $size") + val packet = socketChannel.readPacketExact(size.toLong()) + + val id = packet.readIntLittleEndian() + val type = packet.readIntLittleEndian() + val data = packet.readBytes(size - 10) + println("Read packet with id: $id, type: $type") + + return RconPacket(id, type, data) + } + + private fun createPacketByteBuffer(packet: RconPacket): ByteBuffer { + val length = 4 + 4 + 4 + packet.data.size + 2 + val buffer = ByteBuffer.allocate(length) + buffer.order(ByteOrder.LITTLE_ENDIAN) + + buffer.putInt(length - 4) + buffer.putInt(packet.id) + buffer.putInt(packet.type) + + buffer.put(packet.data) + + //rcon needs 0 terminated string with additional 0 as end of packet + buffer.put(0) + buffer.put(0) + + return buffer.flip() as ByteBuffer + } + + override fun close() { + socketChannel.close() + } +} \ No newline at end of file diff --git a/src/test/kotlin/WatchTest.kt b/src/test/kotlin/WatchTest.kt new file mode 100644 index 0000000..f9f1a1b --- /dev/null +++ b/src/test/kotlin/WatchTest.kt @@ -0,0 +1,82 @@ +import org.junit.jupiter.api.Test +import java.nio.file.Files +import java.nio.file.Paths +import kotlin.test.assertEquals + +class WatchTest { + @Test + fun testWatch() { + val target = Paths.get("testWatch") + val writer = Files.newBufferedWriter(target) + val reader = Files.newBufferedReader(target) + + writer.write("This is some text.\n") + writer.flush() + assertEquals("This is some text.", reader.readLine()) + assertEquals(null, reader.readLine()) + + writer.write("Test\n") + writer.flush() + assertEquals("Test", reader.readLine()) + assertEquals(null, reader.readLine()) + writer.close() + reader.close() + Files.delete(target) + } + + @Test + fun testReplaceRead() { + val target = Paths.get("testReplace") + val targetBackup = Paths.get("testReplace.bak") + + var index = 0 + val reader = LogReader(target) { + println(it) + when (index) { + 0 -> { + if (it == "Testing") { + index++ + } + } + + 1 -> { + if (it == "123") { + index++ + } + } + + 2 -> { + if (it == "456") { + index++ + } + } + } + } + Thread.sleep(100) + + var writer = Files.newBufferedWriter(target) + writer.write("Testing\n") + writer.flush() + writer.close() + + Thread.sleep(100) + + Files.move(target, targetBackup) + + writer = Files.newBufferedWriter(target) + writer.write("123\n") + writer.flush() + writer.write("456\n") + writer.flush() + writer.close() + + Thread.sleep(100) + + reader.close() + + Files.delete(target) + Files.delete(targetBackup) + + assertEquals(index, 3) + } +} \ No newline at end of file