Lay the groundwork for some new features

This commit is contained in:
Maxwell Jeffress 2024-10-28 18:07:37 +11:00
parent 5b813c2335
commit 18be6c6fd4

View File

@ -7,41 +7,62 @@ import java.util.UUID
import java.io.File import java.io.File
import java.io.BufferedReader import java.io.BufferedReader
/*
import java.math.BigInteger
import java.security.MessageDigest
fun md5(input:String): String {
val md = MessageDigest.getInstance("MD5")
return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
}
object WsSessionManager { object WsSessionManager {
val sessions = ConcurrentHashMap<String, WsContext>() private val sessions = ConcurrentHashMap<WsContext, String>()
fun addSession(sessionID: String, ctx: WsContext) { private val sessionIds = ConcurrentHashMap<String, WsContext>()
sessions[sessionID] = ctx
}
fun removeSession(sessionID: String) {
sessions.remove(sessionID)
}
fun broadcast(message: String) {
sessions.values.forEach { ctx ->
ctx.send(message)
}
}
}
*/
object WsSessionManager {
private val sessions = ConcurrentHashMap<String, WsContext>()
fun addSession(ctx: WsContext) { fun addSession(ctx: WsContext) {
// Generate our own UUID for the session since we can't access Javalin's private sessionId try {
val sessionId = UUID.randomUUID().toString() val sessionId = UUID.randomUUID().toString()
sessions[sessionId] = ctx sessions[ctx] = sessionId
sessionIds[sessionId] = ctx
} catch (e: Exception) {
println("Error adding session: ${e.message}")
}
} }
fun removeSession(ctx: WsContext) { fun removeSession(ctx: WsContext) {
// Find and remove the session by context try {
sessions.entries.removeIf { it.value === ctx } val sessionId = sessions[ctx]
if (sessionId != null) {
sessions.remove(ctx)
sessionIds.remove(sessionId)
}
} catch (e: Exception) {
println("Error removing session: ${e.message}")
}
} }
fun broadcast(message: String) { fun broadcast(message: String) {
sessions.values.forEach { ctx -> val deadSessions = mutableListOf<WsContext>()
sessions.keys.forEach { ctx ->
try {
if (ctx.session.isOpen) {
ctx.send(message) ctx.send(message)
} else {
deadSessions.add(ctx)
}
} catch (e: Exception) {
println("Error broadcasting to session: ${e.message}")
deadSessions.add(ctx)
} }
} }
// Clean up any dead sessions
deadSessions.forEach { removeSession(it) }
}
fun getSessionCount(): Int = sessions.size
} }
fun extractMessageContent(inputData: String): String { fun extractMessageContent(inputData: String): String {
@ -79,6 +100,7 @@ fun handleSentMessage(inputData: String): String {
var token = "" var token = ""
var message = "" var message = ""
var dataType = "" var dataType = ""
var command = ""
var isParsingData = 0 var isParsingData = 0
for (char in inputData) { for (char in inputData) {
val character = char val character = char
@ -95,6 +117,8 @@ fun handleSentMessage(inputData: String): String {
token += character token += character
} else if (dataType == "message") { } else if (dataType == "message") {
message += character message += character
} else if (dataType == "command") {
command += character
} }
} }
} else { } else {
@ -120,6 +144,7 @@ fun handleSentMessage(inputData: String): String {
var usernameInDatabase = "" var usernameInDatabase = ""
var tokenInDatabase = "" var tokenInDatabase = ""
var saltInDatabase = ""
var currentStage = 0 var currentStage = 0
for (char in userLine) { for (char in userLine) {
if (char == ':') { if (char == ':') {
@ -129,9 +154,16 @@ fun handleSentMessage(inputData: String): String {
usernameInDatabase += char usernameInDatabase += char
} else if (currentStage == 1) { } else if (currentStage == 1) {
tokenInDatabase += char tokenInDatabase += char
} else if (currentStage == 2) {
saltInDatabase += char
} }
} }
tokenInDatabase = tokenInDatabase.replace(":", "") tokenInDatabase = tokenInDatabase.replace(":", "")
saltInDatabase = saltInDatabase.replace(":", "")
val tokenWithSalt = (md5(token + saltInDatabase))
/*println(saltInDatabase)
println(tokenWithSalt)
if (tokenWithSalt != tokenInDatabase) {*/
if (token != tokenInDatabase) { if (token != tokenInDatabase) {
return("Invalid token! Please try putting in your password right") return("Invalid token! Please try putting in your password right")
} }
@ -359,6 +391,7 @@ fun authKey(inputData: String): String {
} }
fun main(args: Array<String>) { fun main(args: Array<String>) {
var users = listOf("")
val app = Javalin.create() val app = Javalin.create()
.get("/") { ctx -> ctx.result("dingus") } .get("/") { ctx -> ctx.result("dingus") }
.get("/api/send/{content}") { ctx -> .get("/api/send/{content}") { ctx ->
@ -372,10 +405,10 @@ fun main(args: Array<String>) {
.get("/api/createaccount/{content}") { ctx -> ctx.result(createAccount(ctx.pathParam("content")))} .get("/api/createaccount/{content}") { ctx -> ctx.result(createAccount(ctx.pathParam("content")))}
.get("/api/syncmessages/{content}") { ctx -> ctx.result(syncMessages(ctx.pathParam("content")))} .get("/api/syncmessages/{content}") { ctx -> ctx.result(syncMessages(ctx.pathParam("content")))}
.get("/api/authkey/{content}") { ctx -> ctx.result(authKey(ctx.pathParam("content")))} .get("/api/authkey/{content}") { ctx -> ctx.result(authKey(ctx.pathParam("content")))}
.ws("/api/websocket") { ws -> .ws("/api/websocket") { ws ->
ws.onConnect { ctx -> ws.onConnect { ctx ->
WsSessionManager.addSession(ctx) WsSessionManager.addSession(ctx)
ctx.send("Websocket success")
} }
ws.onClose { ctx -> ws.onClose { ctx ->
WsSessionManager.removeSession(ctx) WsSessionManager.removeSession(ctx)
@ -384,52 +417,18 @@ fun main(args: Array<String>) {
println(ctx.message()) println(ctx.message())
val successState = handleSentMessage(ctx.message()) val successState = handleSentMessage(ctx.message())
if (successState != "Success") { if (successState != "Success") {
try {
ctx.send(successState) ctx.send(successState)
} catch (e: Exception) {
println("Error sending error message: ${e.message}")
}
} else { } else {
// Broadcast the message to all clients if successful
val messageContent = extractMessageContent(ctx.message()) val messageContent = extractMessageContent(ctx.message())
WsSessionManager.broadcast(messageContent) WsSessionManager.broadcast(messageContent)
ctx.send("Message sent successfully")
} }
} }
} }
.start(7070) .start(7070)
} }
/*
fun main(args: Array<String>) {
val app = Javalin.create()
.get("/") { ctx -> ctx.result("dingus") }
.get("/api/send/{content}") { ctx ->
val result = handleSentMessage(ctx.pathParam("content"))
if (result == "Success") {
val messageContent = extractMessageContent(ctx.pathParam("content")
WsSessionManager.broadcast(messageContent)
ctx.result(result)
}
}
.get("/api/createaccount/{content}") { ctx -> ctx.result(createAccount(ctx.pathParam("content")))}
.get("/api/syncmessages/{content}") { ctx -> ctx.result(syncMessages(ctx.pathParam("content")))}
.get("/api/authkey/{content}") { ctx -> ctx.result(authKey(ctx.pathParam("content")))}
.ws("/api/websocket") { ws ->
ws.onConnect { ctx ->
WsSessionManager.addSession(ctx.sessionId, ctx)
ctx.send("Websocket success")
}
ws.onClose { ctx ->
WsSessionManager.removeSession(ctx.sessionId)
}
ws.onMessage { ctx ->
println(ctx.message())
val successState = handleSentMessage(ctx.message())
if (successState != "Success") {
ctx.send(successState)
} else {
ctx.send("Message sent successfully")
}
}
}
.start(7070)
}*/