Compare commits

..

No commits in common. "a9ea232e138c7f598ae1d9951a13d5cec2eeeacf" and "5a53fd5f6871ffe653102a49cc0843e0f9870b92" have entirely different histories.

10 changed files with 56 additions and 262 deletions

3
.gitignore vendored
View File

@ -182,5 +182,4 @@ gradle-app.setting
# End of https://www.toptal.com/developers/gitignore/api/intellij,java,gradle,kotlin
data.json
token
data.json

View File

@ -1,22 +0,0 @@
import dev.kord.core.Kord
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
object Discord {
private lateinit var kord: Kord
suspend fun init(token: String) {
kord = Kord(token)
CoroutineScope(Dispatchers.IO).launch {
kord.login()
}
}
suspend fun sendMessage(message: String) {
kord.rest.channel.createMessage(Settings.instance.discordChannelId) {
this.content = "<@&${Settings.instance.discordGroupId}>$message"
}
}
}

View File

@ -1,18 +1,15 @@
import dev.kord.common.entity.Snowflake
import dev.kord.core.Kord
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.nio.file.Files
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.io.path.Path
suspend fun main() {
Settings.load()
val path = Path("data.json")
if (Files.isRegularFile(path)) {
@ -22,32 +19,25 @@ suspend fun main() {
RaceHolder.save(path)
})
Discord.init(withContext(Dispatchers.IO) {
Files.readString(Path("token"))
})
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
runBlocking {
RaceHolder.races.forEach {
it.rescanAll()
}
}
}, 0, 5, TimeUnit.MINUTES)
val kord = Kord("MTE3MTIwODc1MDE5MTg5MDQ4Mw.GOUedL.i3zD6IG5B6fFRvaSOotWwJ5KBRK2whC9xr0vL8")
val server = embeddedServer(CIO, port = 8080){
routing {
get("/"){
call.respondRedirect("/search")
}
settingsPage()
searchPage()
trackPage()
racePage()
get("/hi") {
Discord.sendMessage("Herro!")
kord.rest.channel.createMessage(Snowflake("1040400994355392522")) {
this.content = "<@&978289601506586624> Herro!"
}
}
}
}
println("connection to localhost:8080 now possible.")
server.start(true)
server.start(false)
kord.login()
}

View File

@ -1,7 +1,3 @@
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@ -9,34 +5,28 @@ import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
@Serializable
data class Track(
val trackId: Long,
val endTime: LocalDateTime? = null,
var leaderboard: Velocidrone.Leaderboard = Velocidrone.Leaderboard(
true, "", "",
arrayOf()
)
)
@Serializable
data class RaceData(var name: String, var description: String) {
private val trackList = arrayListOf<Track>()
private val trackList = arrayListOf<Long>()
private val leaderboardMap = hashMapOf<Long, Velocidrone.Leaderboard>()
private var totalScores = arrayListOf<Pair<String, Long>>()
fun addTrack(track: Track) {
trackList.add(track)
fun addTrack(trackId: Long) {
trackList.add(trackId)
}
fun removeTrack(track: Track) {
trackList.remove(track)
fun removeTrack(trackId: Long) {
trackList.remove(trackId)
leaderboardMap.remove(trackId)
}
private suspend fun rescanLeaderboard(track: Track, newLeaderboardCallback: (Velocidrone.Leaderboard) -> Unit) {
Velocidrone.getLeaderboardForId(track.trackId).getOrNull()?.let { newLeaderboard ->
if (track.leaderboard != newLeaderboard) {
track.leaderboard = newLeaderboard
newLeaderboardCallback(newLeaderboard)
private suspend fun rescanLeaderboard(trackId: Long, newLeaderboardCallback: (Velocidrone.Leaderboard) -> Unit) {
if (trackList.contains(trackId)) {
Velocidrone.getLeaderboardForId(trackId).getOrNull()?.let { newLeaderboard ->
if (leaderboardMap[trackId]?.equals(newLeaderboard) == false) {
leaderboardMap[trackId] = newLeaderboard
newLeaderboardCallback(newLeaderboard)
}
}
}
}
@ -44,10 +34,8 @@ data class RaceData(var name: String, var description: String) {
suspend fun rescanAll() {
var changes = false
trackList.forEach {
if ((it.endTime?.toInstant(TimeZone.UTC)?.compareTo(Clock.System.now()) ?: -1) < 0) {
rescanLeaderboard(it) {
changes = true
}
rescanLeaderboard(it) {
changes = true
}
}
if (changes) {
@ -55,11 +43,11 @@ data class RaceData(var name: String, var description: String) {
}
}
private fun calculateTotalScores() {
fun calculateTotalScores() {
val scoreMap = hashMapOf<String, Long>()
trackList.forEach { track ->
track.leaderboard.trackTimes.sortedBy { it.lapTime }.forEachIndexed { index, it ->
scoreMap[it.playerName] = scoreMap.getOrDefault(it.playerName, 0L) + 1 + index
leaderboardMap.forEach { leaderboardEntry ->
leaderboardEntry.value.tracktimes.sortedBy { it.lap_time }.forEach {
scoreMap[it.playername] = scoreMap.getOrDefault(it.playername, 0L) + 1
}
}
synchronized(totalScores) {
@ -67,10 +55,6 @@ data class RaceData(var name: String, var description: String) {
scoreMap.asIterable().sortedByDescending { it.value }.map { it.toPair() }.toCollection(totalScores)
}
}
fun getTracks(): ArrayList<Track> {
return trackList
}
}
object RaceHolder {

View File

@ -9,33 +9,13 @@ fun Routing.racePage() {
get("/race/list") {
raceOverviewPage(RaceHolder.races)
}
get("/races/{id}/show") {
}
get("/races/{raceId}/remove/{trackId}") {
val raceId = call.parameters["raceId"]
val trackId = call.parameters["trackId"]?.toLong()
RaceHolder.races.find { it.name == raceId }?.let { raceData ->
val toBeRemovedTrack = raceData.getTracks().find { it.trackId == trackId }
toBeRemovedTrack?.let {
raceData.removeTrack(it)
}
}
call.respondRedirect("/races/$raceId/show")
}
get("/race/new") {
newRacePage()
}
post("/race/new") {
val parameters = call.receiveParameters()
val name = parameters["name"]
val description = parameters["description"]
if (name == null || description == null) {
newRacePage("Not all parameters given.", name ?: "", description ?: "")
return@post
@ -44,7 +24,6 @@ fun Routing.racePage() {
newRacePage("Race with the same name already exists.", name, description)
return@post
}
RaceHolder.races.add(RaceData(name, description))
call.respondRedirect("/race/list")
}

View File

@ -68,7 +68,7 @@ private suspend fun PipelineContext<Unit,ApplicationCall>.searchResultPage(track
}
}
}
trackResults.userTracks.forEach {
trackResults.user_tracks.forEach {
tr {
td {
form("/track/" + it.id + "/add") {
@ -81,10 +81,10 @@ private suspend fun PipelineContext<Unit,ApplicationCall>.searchResultPage(track
}
}
td {
+it.trackName
+it.track_name
}
td {
+it.playerName
+it.playername
}
}
}

View File

@ -1,32 +0,0 @@
import dev.kord.common.entity.Snowflake
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.nio.file.Files
import kotlin.io.path.Path
const val SETTINGS = "settings.json"
@Serializable
class Settings {
companion object {
var instance = Settings()
fun load() {
if (Files.isRegularFile(Path(SETTINGS))) {
val reader = Files.newBufferedReader(Path(SETTINGS))
instance = Json.decodeFromString<Settings>(reader.readText())
reader.close()
}
}
fun save() {
val writer = Files.newBufferedWriter(Path(SETTINGS))
writer.write(Json.encodeToString(instance))
writer.close()
}
}
var discordChannelId = Snowflake(0)
var discordGroupId = Snowflake(0)
}

View File

@ -1,41 +0,0 @@
import dev.kord.common.entity.Snowflake
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.html.*
fun Routing.settingsPage() {
get("/settings") {
respondThemedHtml("Settings") {
form("/settings", encType = FormEncType.applicationXWwwFormUrlEncoded, method = FormMethod.post) {
p {
+"GroupID:"
textInput(name = "groupId") {
value = Settings.instance.discordGroupId.toString()
}
}
p {
+"ChannelID:"
textInput(name = "channelId") {
value = Settings.instance.discordChannelId.toString()
}
}
submitInput { }
}
}
}
post("/settings") {
val params = call.receiveParameters()
params["groupId"]?.let { Settings.instance.discordGroupId = Snowflake(it) }
params["channelId"]?.let { Settings.instance.discordChannelId = Snowflake(it) }
CoroutineScope(Dispatchers.IO).launch {
Settings.save()
}
call.respondRedirect("/settings")
}
}

View File

@ -3,7 +3,6 @@ import io.ktor.server.html.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.util.pipeline.*
import kotlinx.datetime.toLocalDateTime
import kotlinx.html.*
import java.net.URLDecoder
import java.net.URLEncoder
@ -23,12 +22,11 @@ fun Routing.trackPage() {
}
}
post("/track/{id}/add") {
val endTime = call.receiveParameters()["endTime"]?.toLocalDateTime()
call.parameters["id"]?.toLong()?.let { trackId ->
val param = call.receiveParameters()
param["race"]?.let { raceString ->
val decoded = URLDecoder.decode(raceString, Charsets.UTF_8)
RaceHolder.races.find { it.name == decoded }?.addTrack(Track(trackId, endTime))
RaceHolder.races.find { it.name == decoded }?.addTrack(trackId)
}
}
}
@ -49,10 +47,10 @@ private suspend fun PipelineContext<Unit, ApplicationCall>.trackPage(leaderboard
td { +"Name" }
}
}
leaderboard.trackTimes.sortedBy { it.lapTime }.forEach {
leaderboard.tracktimes.sortedBy { it.lap_time }.forEach {
tr {
td { +it.lapTime.toString() }
td { +it.playerName }
td { +it.lap_time.toString() }
td { +it.playername }
}
}
}
@ -72,10 +70,6 @@ private suspend fun PipelineContext<Unit, ApplicationCall>.addTrackPage(trackId:
}
}
}
p {
+"Optional end time:"
dateTimeLocalInput(name = "endTime")
}
submitInput()
}
}

View File

@ -2,7 +2,6 @@ import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.net.URLEncoder
@ -14,67 +13,38 @@ import javax.crypto.spec.SecretKeySpec
object Velocidrone{
private val key = "BatCaveGGevaCtaB".toByteArray(Charset.defaultCharset())
private fun decodeVeloBase64(input: ByteArray): Result<String> {
fun decodeVeloBase64(input: ByteArray): Result<String> {
val decoded = Base64.getDecoder().decode(input)
val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"))
return Result.success(String(cipher.doFinal(decoded)))
}
private fun encodeVeloBase64(input: String): ByteArray {
fun encodeVeloBase64(input: String): ByteArray {
val encoded: ByteArray = input.toByteArray()
val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"))
return Base64.getEncoder().encode(cipher.doFinal(encoded))
}
private val client = HttpClient(CIO)
val client = HttpClient(CIO)
@Serializable
data class Leaderboard(
val success:Boolean,
@SerialName("message_title")
val messageTitle: String,
val message_title:String,
val message:String,
@SerialName("tracktimes")
val trackTimes: Array<TrackTime>
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Leaderboard
if (success != other.success) return false
if (messageTitle != other.messageTitle) return false
if (message != other.message) return false
if (!trackTimes.contentEquals(other.trackTimes)) return false
return true
}
override fun hashCode(): Int {
var result = success.hashCode()
result = 31 * result + messageTitle.hashCode()
result = 31 * result + message.hashCode()
result = 31 * result + trackTimes.contentHashCode()
return result
}
}
val tracktimes:Array<TrackTime>
)
@Serializable
data class TrackTime(
@SerialName("lap_time")
val lapTime: Float,
@SerialName("playername")
val playerName: String,
@SerialName("model_id")
val modelId: Long,
val lap_time:Float,
val playername: String,
val model_id: Long,
val country: String,
@SerialName("sim_version")
val simVersion: String,
@SerialName("device_type")
val deviceType: Long
val sim_version: String,
val device_type: Long
)
suspend fun getLeaderboardForId(id:Long): Result<Leaderboard> {
@ -96,44 +66,17 @@ object Velocidrone{
data class TrackResults(
val success:Boolean,
val detail:String,
@SerialName("user_tracks")
val userTracks: Array<Track>
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TrackResults
if (success != other.success) return false
if (detail != other.detail) return false
if (!userTracks.contentEquals(other.userTracks)) return false
return true
}
override fun hashCode(): Int {
var result = success.hashCode()
result = 31 * result + detail.hashCode()
result = 31 * result + userTracks.contentHashCode()
return result
}
}
val user_tracks:Array<Track>
)
@Serializable
data class Track(
val id:Long,
@SerialName("scenery_id")
val sceneryId: Long,
@SerialName("track_name")
val trackName: String,
@SerialName("track_type")
val trackType: String,
@SerialName("playername")
val playerName: String,
val scenery_id:Long,
val track_name:String,
val track_type:String,
val playername:String,
val rating:Float,
@SerialName("total_ratings")
val totalRatings: Long,
val total_ratings:Long,
val date:String
)