Skip to content

Commit

Permalink
Provide server name, device, and commit hash in handshake
Browse files Browse the repository at this point in the history
  • Loading branch information
toasterofbread committed Dec 18, 2023
1 parent dc6e88c commit 32e06a4
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 25 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
local.properties
build/
.idea/
.fleet/
.gradle/
*.gen.kt
src/nativeInterop/cinterop
src/nativeInterop/cinterop
48 changes: 45 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import org.jetbrains.kotlin.gradle.internal.ensureParentDirsCreated
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithHostTests
import java.io.PrintWriter
import java.io.ByteArrayOutputStream

val GENERATED_FILE_PREFIX = "// Generated on build in build.gradle.kts\n"

plugins {
kotlin("multiplatform") version "1.9.10"
Expand Down Expand Up @@ -81,17 +84,17 @@ tasks.withType<Wrapper> {
}

tasks.register("bundleIcon") {
val in_file = project.file("icon.png")
val in_file: File = project.file("icon.png")
inputs.file(in_file)

val out_file = project.file("src/nativeMain/kotlin/icon.gen.kt")
val out_file: File = project.file("src/nativeMain/kotlin/Icon.gen.kt")
outputs.file(out_file)

doLast {
check(in_file.isFile)

out_file.writer().use { writer ->
writer.write("// https://youtrack.jetbrains.com/issue/KT-39194\n")
writer.write("${GENERATED_FILE_PREFIX}\n// https://youtrack.jetbrains.com/issue/KT-39194\n")
writer.write("val ICON_BYTES: ByteArray = byteArrayOf(")

val bytes: ByteArray = in_file.readBytes()
Expand All @@ -113,8 +116,19 @@ tasks.register("bundleIcon") {
}
}

tasks.register("bundleGitCommitHash") {
val out_file: File = project.file("src/nativeMain/kotlin/GitCommitHash.gen.kt")
outputs.file(out_file)

doLast {
val git_commit_hash: String = getCurrentGitCommitHash()!!
out_file.writeText("${GENERATED_FILE_PREFIX}val GIT_COMMIT_HASH: String = \"$git_commit_hash\"\n")
}
}

tasks.getByName("compileKotlinNative") {
dependsOn("bundleIcon")
dependsOn("bundleGitCommitHash")
}

tasks.register("generateCInteropDefinitions") {
Expand Down Expand Up @@ -219,3 +233,31 @@ fun pkgConfig(
}
}

fun cmd(vararg args: String): String {
val out = ByteArrayOutputStream()
exec {
commandLine(args.toList())
standardOutput = out
}
return out.toString().trim()
}

fun getCurrentGitTag(): String? {
try {
return cmd("git", "tag", "--points-at", "HEAD").ifBlank { null }
}
catch (e: Throwable) {
RuntimeException("Getting Git tag failed", e).printStackTrace()
return null
}
}

fun getCurrentGitCommitHash(): String? {
try {
return cmd("git", "rev-parse", "HEAD").ifBlank { null }
}
catch (e: Throwable) {
RuntimeException("Getting Git commit hash failed", e).printStackTrace()
return null
}
}
2 changes: 1 addition & 1 deletion src/nativeMain/kotlin/cinterop/mpv/MpvCommandInterface.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ data class ServerStatusData(
val volume: Double
)

fun Player.getCurrentStatusJson(): JsonElement =
fun Player.getCurrentStateJson(): JsonElement =
Json.encodeToJsonElement(
ServerStatusData(
(0 until item_count).map { getItem(it) ?: "" },
Expand Down
2 changes: 0 additions & 2 deletions src/nativeMain/kotlin/main.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import com.github.ajalt.clikt.core.subcommands
import kotlinx.cinterop.ExperimentalForeignApi
import spms.Command
import spms.client.cli.CommandLineClient
import spms.client.player.PlayerClient
Expand All @@ -9,7 +8,6 @@ import kotlin.system.exitProcess
fun String.toRed() =
"\u001b[31m$this\u001b[0m"

@OptIn(ExperimentalForeignApi::class)
fun main(args: Array<String>) {
try {
val command: Command = SpMsCommand().subcommands(CommandLineClient.get(), PlayerClient.get())
Expand Down
65 changes: 55 additions & 10 deletions src/nativeMain/kotlin/spms/server/SpMs.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package spms.server

import GIT_COMMIT_HASH
import cinterop.mpv.MpvClientImpl
import cinterop.mpv.getCurrentStatusJson
import cinterop.mpv.getCurrentStateJson
import cinterop.zmq.ZmqRouter
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.MemScope
import kotlinx.cinterop.*
import kotlinx.coroutines.channels.Channel
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
Expand All @@ -13,12 +13,13 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import libzmq.ZMQ_NOBLOCK
import platform.posix.gethostname
import spms.player.HeadlessPlayer
import spms.player.Player
import spms.player.PlayerEvent
import spms.player.StreamProviderServer
import spms.serveraction.ServerAction
import kotlin.experimental.ExperimentalNativeApi
import kotlin.system.getTimeMillis

const val SERVER_EXPECT_REPLY_CHAR: Char = '!'
Expand Down Expand Up @@ -295,9 +296,9 @@ class SpMs(mem_scope: MemScope, val secondary_port: Int, headless: Boolean = fal
return
}

val handshake: SpMsClientHandshake
val client_handshake: SpMsClientHandshake
try {
handshake = handshake_message.parts.firstOrNull()?.let { Json.decodeFromString(it) } ?: return
client_handshake = handshake_message.parts.firstOrNull()?.let { Json.decodeFromString(it) } ?: return
}
catch (e: SerializationException) {
println("Ignoring SerializationException in onClientMessage")
Expand All @@ -307,19 +308,27 @@ class SpMs(mem_scope: MemScope, val secondary_port: Int, headless: Boolean = fal
val client: SpMsClient = SpMsClient(
handshake_message.client_id,
SpMsClientInfo(
getNewClientName(handshake.name),
handshake.type,
handshake.getLanguage()
getNewClientName(client_handshake.name),
client_handshake.type,
client_handshake.getLanguage()
),
player_event_inc
)

clients.add(client)

val server_handshake: SpMsServerHandshake =
SpMsServerHandshake(
SpMs.application_name,
getDeviceName(),
GIT_COMMIT_HASH,
player.getCurrentStateJson()
)

sendMultipart(
Message(
client.id_bytes,
listOf(Json.encodeToString(player.getCurrentStatusJson()))
listOf(Json.encodeToString(server_handshake))
)
)

Expand Down Expand Up @@ -360,4 +369,40 @@ class SpMs(mem_scope: MemScope, val secondary_port: Int, headless: Boolean = fal

override fun toString(): String =
"SpMs(player=$player)"

companion object {
const val application_name: String = "spmp-server"
}
}

@OptIn(ExperimentalForeignApi::class, ExperimentalNativeApi::class)
fun getDeviceName(): String {
val hostname: String = memScoped {
val str: CPointer<ByteVarOf<Byte>> = allocArray(1024)
gethostname(str, 1023U)
return@memScoped str.toKString()
}

val os: String =
when (Platform.osFamily) {
OsFamily.MACOSX -> "OSX"
OsFamily.IOS -> "iOS"
OsFamily.LINUX -> "Linux"
OsFamily.WINDOWS -> "Windows"
OsFamily.ANDROID -> "Android"
OsFamily.WASM -> "Wasm"
OsFamily.TVOS -> "TV"
OsFamily.WATCHOS -> "WatchOS"
OsFamily.UNKNOWN -> "Unknown"
}

val architecture: String =
when (Platform.cpuArchitecture) {
CpuArchitecture.X86 -> "x86"
CpuArchitecture.X64 -> "x86-64"
CpuArchitecture.UNKNOWN -> "Unknown"
else -> Platform.cpuArchitecture.name
}

return "$hostname ($os $architecture)"
}
9 changes: 9 additions & 0 deletions src/nativeMain/kotlin/spms/server/SpMsClient.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package spms.server

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import spms.localisation.Language

typealias SpMsClientID = Int
Expand All @@ -19,6 +20,14 @@ data class SpMsClientHandshake(
Language.fromCode(language) ?: Language.default
}

@Serializable
data class SpMsServerHandshake(
val name: String,
val device_name: String,
val spms_commit_hash: String,
val server_state: JsonElement
)

@Serializable
data class SpMsClientInfo(
val name: String,
Expand Down
4 changes: 0 additions & 4 deletions src/nativeMain/kotlin/spms/server/SpMsCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,4 @@ class SpMsCommand: Command(
}
}
}

companion object {
const val application_name: String = "spmp-server"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package spms.serveraction

import cinterop.mpv.getCurrentStatusJson
import cinterop.mpv.getCurrentStateJson
import com.github.ajalt.clikt.core.Context
import io.ktor.client.HttpClient
import kotlinx.cinterop.ExperimentalForeignApi
Expand All @@ -23,15 +23,14 @@ import platform.posix.getenv
import spms.localisation.loc
import spms.player.Player
import spms.server.SpMs
import spms.server.SpMsCommand

@Suppress("OPT_IN_USAGE")
@OptIn(ExperimentalForeignApi::class)
fun getCacheDir(): Path =
when (Platform.osFamily) {
OsFamily.LINUX -> "/home/${getenv("USER")!!.toKString()}/.cache/".toPath()
else -> throw NotImplementedError(Platform.osFamily.name)
}.resolve(SpMsCommand.application_name)
}.resolve(SpMs.application_name)

class ServerActionGetStatus: ServerAction(
identifier = "status",
Expand All @@ -40,7 +39,7 @@ class ServerActionGetStatus: ServerAction(
parameters = emptyList()
) {
override fun execute(server: SpMs, context: ActionContext): JsonElement {
return server.player.getCurrentStatusJson()
return server.player.getCurrentStateJson()
}

private val cache_files: MutableMap<String, JsonElement> = mutableMapOf()
Expand Down

0 comments on commit 32e06a4

Please sign in to comment.