Initial commit.

This commit is contained in:
yenon 2023-11-29 22:20:58 +01:00
commit 78b102dfbf
26 changed files with 1349 additions and 0 deletions

183
.gitignore vendored Normal file
View File

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

3
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

6
.idea/compiler.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
</component>
</project>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="ReplaceUntilWithRangeUntil" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>

20
.idea/jarRepositories.xml generated Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
</component>
</project>

6
.idea/kotlinc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.20" />
</component>
</project>

7
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

29
build.gradle.kts Normal file
View File

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

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

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

234
gradlew vendored Executable file
View File

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

89
gradlew.bat vendored Normal file
View File

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

81
rconCommands.txt Normal file
View File

@ -0,0 +1,81 @@
ListCommands <ShowDetails [0|1]>
ShowCommandInfo <CommandName>
ListPermittedCommands <ShowDetails [0|1]>
AdminKillServer <Force [0|1]>
AdminSetMaxNumPlayers <NumPlayers>
AdminSetNumReservedSlots <NumReserved>
AdminSetServerPassword <Password>
AdminSlomo <TimeDilation>
AdminSetPublicQueueLimit <PublicQueueLimit>
ListPlayers
ListSquads
AdminListDisconnectedPlayers
AdminTeleportToPlayer <NameOrSteamId>
AdminTeleportToPlayerById <PlayerId>
AdminKick "<NameOrSteamId>" <KickReason>
AdminKickById <PlayerId> <KickReason>
AdminBan "<NameOrSteamId>" "<BanLength>" <BanReason>
AdminBanById <PlayerId> "<BanLength>" <BanReason>
AdminWarn "<NameOrSteamId>" <WarnReason>
AdminWarnById <PlayerId> <WarnReason>
AdminForceTeamChange <NameOrSteamId>
AdminForceTeamChangeById <PlayerId>
AdminRemovePlayerFromSquadById <PlayerId>
AdminRemovePlayerFromSquad <PlayerName>
AdminDemoteCommander <PlayerName>
AdminDemoteCommanderById <PlayerId>
AdminDisbandSquad <TeamNumber = [1|2]> <SquadIndex>
SLInviteMember <Name>
ListLevels
ListLayers
AdminChangeLevel <LevelName>
AdminChangeLayer <LayerName>
AdminSetNextLevel <LevelName>
AdminSetNextLayer <LayerName>
ShowCurrentMap
ShowNextMap
AdminVoteLevel
AdminVoteLayer
AdminVoteNextLevel
AdminVoteNextLayer
AdminBroadcast <Message>
ChatToAdmin <Message>
AdminVote "<Question>" "<Possibles answers, concatenated by +>" <Duration, in seconds>
AdminRestartMatch
AdminEndMatch
AdminPauseMatch
AdminUnpauseMatch
AdminSetFogOfWar <Layer based setting [0|1]>
AdminForceAllVehicleAvailability <Layer based setting, usually Disabled [0|1]>
AdminForceAllDeployableAvailability <Layer based setting, usually Disabled [0|1]>
AdminForceAllRoleAvailability <Layer based setting, usually Disabled [0|1]>
AdminForceAllActionAvailability <Layer based setting, usually Disabled [0|1]>
AdminNoTeamChangeTimer <Layer based setting, usually Timers active [0|1]>
AdminNoRespawnTimer <Layer based setting, usually Timers active [0|1]>
AdminDisableVehicleClaiming <Layer based setting, usually Claiming Enabled [0|1]>
AdminDisableVehicleTeamRequirement <Layer based setting, usually Requirement active [0|1]>
AdminDisableVehicleKitRequirement <Layer based setting, usually Requirement active [0|1]>
AdminAlwaysValidPlacement <AlwaysValid [0|1]>
AdminForceNetUpdateOnClientSaturation <Enabled [0|1]>
AdminAddCameraman <NameOrId>
AdminCreateVehicle <ClassName>
AdminCreateDeployable <ClassName>
AdminGiveEquipment <ClassName>
AdminSpawnActor <Index>
AdminDemoPlay <FileName>
AdminDemoRec <FileName>
AdminDemoStop
AdminProfileServer <SecondsToProfileFor> <bUseRaw [0|1]>
AdminProfileServerCSV <Start/Stop>
DebugVehicleList <Mode 0 = just vehicle index + info. Mode 1 = same as mode 0, but also crew names and what seat they're in. Mode 2 = same as Mode 1 but also shows empty seats.>
DebugVehicleSetComponentHealthByName "<Vehicle Name/Index. If it is "Current", it will use the vehicle you are currently in.>" <Component Index. If it is negative, it will set the health of the vehicle itself.> <New Component Health>
DebugPrintCustomOptions
AdminSetCustomOption "<Key>" <Value>
AdminRemoveCustomOption <Key>
DebugAddBuildSupply <Amount>
DebugAddAmmoSupply <Amount>
DebugRearmPlayer <NameOrSteamId>
RecordingStart
RecordingStart_Named <The name of the replay to create>
RecordingStop
RepGraphSetDSFTargetKBytesSec <New Target.>

12
settings.gradle.kts Normal file
View File

@ -0,0 +1,12 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "SquadCompanion"

21
src/main/kotlin/Css.kt Normal file
View File

@ -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()
}

View File

View File

@ -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<String>()
val rotationList = arrayListOf<String>()
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
}
}
}
}

View File

@ -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..<lines.size) {
lineCallback(stringBuilder.toString())
stringBuilder.clear()
stringBuilder.append(lines[i])
}
}
override fun close() {
coroutineScope.cancel()
}
}

85
src/main/kotlin/Main.kt Normal file
View File

@ -0,0 +1,85 @@
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.html.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.file.Paths
import java.text.SimpleDateFormat
val squadTimeFormat = SimpleDateFormat("yyyy.MM.dd-HH.mm.ss:SSS")
val logRegex = Regex("""^\[(\d{4}.\d{2}.\d{2}-\d{2}.\d{2}.\d{2}:\d{3})]\[([\d ]{3})](.*)$""")
val modules = arrayListOf<Module>(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<Throwable> { 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)
}

27
src/main/kotlin/Module.kt Normal file
View File

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

View File

@ -0,0 +1,77 @@
import io.ktor.server.html.*
import kotlinx.html.*
class OverviewTemplate(private val players: ListPlayersOutput) : Template<HTML> {
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<Int, List<Player>>) {
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<Int, List<Player>>) {
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)
}
}
}
}
}

View File

@ -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<Player>, val disconnected: ArrayList<DisconnectedPlayer>)
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<Player>()
val disconnected = arrayListOf<DisconnectedPlayer>()
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\"")
}
}

View File

@ -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<Boolean> = withContext(Dispatchers.IO) {
socketChannel.close()
socketChannel = SocketChannel.open().apply {
connect(InetSocketAddress(host, port))
finishConnect()
println("Socket is open.")
}
authenticate()
}
private fun authenticate(): Result<Boolean> {
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<String> = 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<currentId){
// responsePacket = readPacket()
//}
if (responsePacket.id != currentId || responsePacket.type != SERVERDATA_RESPONSE_VALUE) {
return@withContext Result.failure(
Exception(
"Out of order packet. Expected:$currentId, Got:${responsePacket.id}, Data:${
String(
responsePacket.data,
rconCharset
)
}"
)
)
}
if (responsePacket.data.size < 4084) {
//Short packet, no additional handling needed.
return@withContext Result.success(String(responsePacket.data, rconCharset))
}
//Long packet, we need to make sure we read all of it and receive an additional empty packet from Squad.
val packetByteList = LinkedList<ByteArray>()
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()
}
}

View File

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