chookchat/client-cli/src/main/kotlin/Main.kt
2024-11-05 20:35:10 +11:00

115 lines
3.2 KiB
Kotlin

package xyz.maxwellj.chookpen.client
import okhttp3.*
import java.util.Scanner
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess
import java.io.File
import kotlin.system.exitProcess
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')
}
fun main() {
// Variables
var name = ""
var server = ""
var port = ""
var hasHTTPS = ""
var password = ""
var configFile = File("${System.getProperty("user.home")}/chookpen.profile")
var configStage = 0
for (char in configFile.readText()) {
if (char == ':') {configStage ++}
if (configStage == 0) {
name += char
} else if (configStage == 1) {
password += char
} else if (configStage == 2) {
server += char
} else if (configStage == 3) {
port += char
} else if (configStage == 4) {
hasHTTPS += char
}
}
server = server.replace(":", "")
port = port.replace(":", "")
hasHTTPS = hasHTTPS.replace(":", "")
password = password.replace(":", "")
if (password == "x") {
println("Enter your password:")
password = readln()
}
val client = OkHttpClient.Builder()
.pingInterval(30, TimeUnit.SECONDS)
.build()
val request = Request.Builder()
.url("ws://localhost:7070/api/websocket")
.build()
var webSocket: WebSocket? = null
val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
println(password)
println(md5(password))
println("Connection opened")
webSocket.send("username:{$name}token:{${md5(password)}}message:{Joined the room}")
}
override fun onMessage(webSocket: WebSocket, text: String) {
println("$text")
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
println("Connection closing: $reason")
webSocket.close(1000, null)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
println("Connection failed: ${t.message}")
}
}
// Set up shutdown hook for Ctrl+C handling
Runtime.getRuntime().addShutdownHook(Thread {
println("\nShutting down gracefully...")
webSocket?.close(1000, "Client shutting down")
client.dispatcher.executorService.shutdown()
})
// Initialize WebSocket connection
webSocket = client.newWebSocket(request, listener)
// Set up input handling
val scanner = Scanner(System.`in`)
println("Type your messages (press Enter to send, Ctrl+C to quit):")
while (true) {
try {
val input = scanner.nextLine()
if (input.isNotEmpty()) {
webSocket?.send("username:{$name}token:{${md5(password)}}message:{$input}")
}
} catch (e: Exception) {
// Handle any input-related exceptions
println("Error reading input: ${e.message}")
break
}
}
}