mirror of
https://github.com/kalarina-bit/Matewave.git
synced 2026-11-22 16:16:10 +00:00
Add spectator protocol and server for LAN games
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package cc.skysparkle.matewave.network
|
||||
|
||||
import java.io.Reader
|
||||
|
||||
/** Result of reading one newline-delimited message from a socket. */
|
||||
sealed class LineResult {
|
||||
data class Line(val text: String) : LineResult()
|
||||
object TooLong : LineResult()
|
||||
object EndOfStream : LineResult()
|
||||
}
|
||||
|
||||
/** Reads one line of at most [maxChars] characters; longer lines are reported, not buffered. */
|
||||
fun readBoundedLine(reader: Reader, maxChars: Int): LineResult {
|
||||
val builder = StringBuilder()
|
||||
while (true) {
|
||||
val ch = reader.read()
|
||||
if (ch == -1) {
|
||||
return if (builder.isEmpty()) LineResult.EndOfStream
|
||||
else LineResult.Line(builder.toString())
|
||||
}
|
||||
if (ch == '\n'.code) return LineResult.Line(builder.toString())
|
||||
if (ch == '\r'.code) continue
|
||||
if (builder.length >= maxChars) return LineResult.TooLong
|
||||
builder.append(ch.toChar())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
enum class PresenceStatus { ONLINE, IN_GAME, OFFLINE }
|
||||
|
||||
/** Where to watch a game: the host's address and spectator port. */
|
||||
data class SpectateTarget(val host: String, val port: Int, val gameTag: String)
|
||||
|
||||
/** A player seen on the network, reduced to what spectating needs. */
|
||||
data class NearbyPlayerGame(
|
||||
val playerId: String,
|
||||
val host: String,
|
||||
val gameTag: String,
|
||||
val spectatePort: Int
|
||||
)
|
||||
|
||||
data class FriendGameStatus(
|
||||
val status: PresenceStatus,
|
||||
val target: SpectateTarget? = null,
|
||||
/** Live count from the host, null until it has answered. */
|
||||
val spectators: Int? = null,
|
||||
val max: Int = MAX_SPECTATORS
|
||||
) {
|
||||
val full: Boolean get() = spectators != null && spectators >= max
|
||||
}
|
||||
|
||||
/**
|
||||
* Online, In game or Offline for one player, and where to watch. Both players of a game announce
|
||||
* the same tag, but only the host serves spectators, so the guest's game is watched through the
|
||||
* host. A host that says its game has ended overrides an announcement that is not updated yet.
|
||||
*/
|
||||
object FriendStatusResolver {
|
||||
fun resolve(
|
||||
playerId: String,
|
||||
nearby: Map<String, NearbyPlayerGame>,
|
||||
probes: Map<SpectateTarget, SpectatorMessage.Status>
|
||||
): FriendGameStatus {
|
||||
val player = nearby[playerId] ?: return FriendGameStatus(PresenceStatus.OFFLINE)
|
||||
if (player.gameTag.isEmpty()) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||
val host = hostOf(player, nearby) ?: return FriendGameStatus(PresenceStatus.IN_GAME)
|
||||
val target = SpectateTarget(host.host, host.spectatePort, host.gameTag)
|
||||
val probe = probes[target]
|
||||
if (probe != null && !probe.inGame) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||
return FriendGameStatus(PresenceStatus.IN_GAME, target, probe?.count, probe?.max ?: MAX_SPECTATORS)
|
||||
}
|
||||
|
||||
/** Every host worth asking for a live spectator count. */
|
||||
fun targets(nearby: Collection<NearbyPlayerGame>): Set<SpectateTarget> =
|
||||
nearby.filter { it.gameTag.isNotEmpty() && it.spectatePort > 0 && it.host.isNotEmpty() }
|
||||
.map { SpectateTarget(it.host, it.spectatePort, it.gameTag) }
|
||||
.toSet()
|
||||
|
||||
private fun hostOf(player: NearbyPlayerGame, nearby: Map<String, NearbyPlayerGame>): NearbyPlayerGame? {
|
||||
if (player.spectatePort > 0 && player.host.isNotEmpty()) return player
|
||||
return nearby.values.firstOrNull {
|
||||
it.playerId != player.playerId && it.gameTag == player.gameTag && it.spectatePort > 0 && it.host.isNotEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
/**
|
||||
* What this device adds to its network announcement while it plays a watchable LAN game: a short
|
||||
* tag shared by both players of the game, and, on the host, the spectator port. Older app versions
|
||||
* ignore these attributes.
|
||||
*/
|
||||
object SpectatorAdvert {
|
||||
const val KEY_GAME = "g"
|
||||
const val KEY_PORT = "sp"
|
||||
|
||||
data class State(val gameTag: String = "", val spectatePort: Int = 0)
|
||||
|
||||
@Volatile var current = State()
|
||||
private set
|
||||
|
||||
/** Returns true when the announcement has to be published again. */
|
||||
@Synchronized
|
||||
fun update(state: State): Boolean {
|
||||
if (state == current) return false
|
||||
current = state
|
||||
return true
|
||||
}
|
||||
|
||||
fun clear(): Boolean = update(State())
|
||||
|
||||
fun attributes(state: State = current): Map<String, String> = buildMap {
|
||||
if (state.gameTag.isNotEmpty()) put(KEY_GAME, state.gameTag)
|
||||
if (state.gameTag.isNotEmpty() && state.spectatePort > 0) put(KEY_PORT, state.spectatePort.toString())
|
||||
}
|
||||
|
||||
/** Reads the attributes of a discovered player; anything malformed counts as absent. */
|
||||
fun parse(attribute: (String) -> String): State {
|
||||
val tag = attribute(KEY_GAME).takeIf { TAG_PATTERN.matches(it) } ?: return State()
|
||||
val port = attribute(KEY_PORT).toIntOrNull()?.takeIf { it in 1..65_535 } ?: 0
|
||||
return State(tag, port)
|
||||
}
|
||||
|
||||
/** Short tag of a game id, so the game id itself is not announced. */
|
||||
fun tagOf(gameId: String): String {
|
||||
if (gameId.isEmpty()) return ""
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
||||
return digest.take(4).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.network.LineResult
|
||||
import cc.skysparkle.matewave.network.readBoundedLine
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Socket
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
|
||||
/**
|
||||
* One spectator's connection to a hosted game. Events arrive on a background thread, in order.
|
||||
* Silence longer than [Timing.silenceTimeoutMs] (the host pings every few seconds) means the host
|
||||
* is gone, which also covers Wi-Fi switching off on either side.
|
||||
*/
|
||||
class SpectatorClient(
|
||||
private val host: String,
|
||||
private val port: Int,
|
||||
private val onEvent: (Event) -> Unit,
|
||||
private val timing: Timing = Timing(),
|
||||
private val version: Int = SpectatorProtocol.VERSION,
|
||||
private val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||
) {
|
||||
data class Timing(val connectTimeoutMs: Int = 5_000, val silenceTimeoutMs: Int = 15_000)
|
||||
|
||||
enum class Failure { UNREACHABLE, FULL, NO_GAME, UPDATE_THIS_APP, UPDATE_HOST_APP }
|
||||
|
||||
sealed class Event {
|
||||
data class Joined(val welcome: SpectatorMessage.Welcome) : Event()
|
||||
data class Received(val message: SpectatorMessage) : Event()
|
||||
data class JoinFailed(val failure: Failure) : Event()
|
||||
|
||||
/** The connection ended after joining; [hostClosed] is true when the host said goodbye. */
|
||||
data class Disconnected(val hostClosed: Boolean) : Event()
|
||||
}
|
||||
|
||||
@Volatile private var socket: Socket? = null
|
||||
@Volatile private var output: BufferedWriter? = null
|
||||
@Volatile private var stopped = false
|
||||
private val writer = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "spectator-send").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
Thread({ run() }, "spectator-receive").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
fun requestResync() = send(SpectatorMessage.Resync)
|
||||
|
||||
fun stop() {
|
||||
if (stopped) return
|
||||
stopped = true
|
||||
try {
|
||||
writer.execute {
|
||||
writeLine(SpectatorMessage.Leave)
|
||||
closeSocket()
|
||||
}
|
||||
} catch (e: RejectedExecutionException) {
|
||||
closeSocket()
|
||||
}
|
||||
writer.shutdown()
|
||||
// A send stuck on a dead connection must not keep the socket open.
|
||||
Thread({
|
||||
try { Thread.sleep(STOP_GRACE_MS) } catch (_: InterruptedException) {}
|
||||
closeSocket()
|
||||
}, "spectator-stop").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
val s = Socket()
|
||||
socket = s
|
||||
val reader: BufferedReader
|
||||
try {
|
||||
if (stopped) throw IOException("Stopped")
|
||||
s.tcpNoDelay = true
|
||||
s.connect(InetSocketAddress(host, port), timing.connectTimeoutMs)
|
||||
s.soTimeout = timing.silenceTimeoutMs
|
||||
output = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||
reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||
} catch (e: IOException) {
|
||||
closeSocket()
|
||||
emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||
return
|
||||
}
|
||||
send(SpectatorMessage.Hello(minVersion))
|
||||
|
||||
var joined = false
|
||||
var hostClosed = false
|
||||
try {
|
||||
while (!stopped) {
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||
if (read !is LineResult.Line) break
|
||||
val envelope = SpectatorProtocol.decode(read.text) ?: continue
|
||||
val message = envelope.message
|
||||
if (!joined) {
|
||||
// reject keeps its shape across versions, so read it before the version gate.
|
||||
if (message is SpectatorMessage.Reject) {
|
||||
emit(Event.JoinFailed(failureOf(message)))
|
||||
return
|
||||
}
|
||||
if (envelope.version < minVersion) {
|
||||
emit(Event.JoinFailed(Failure.UPDATE_HOST_APP))
|
||||
return
|
||||
}
|
||||
if (message is SpectatorMessage.Welcome) {
|
||||
joined = true
|
||||
emit(Event.Joined(message))
|
||||
}
|
||||
continue
|
||||
}
|
||||
when (message) {
|
||||
null -> Unit
|
||||
SpectatorMessage.Closing -> hostClosed = true
|
||||
is SpectatorMessage.Ping -> {
|
||||
send(SpectatorMessage.Pong)
|
||||
emit(Event.Received(message))
|
||||
}
|
||||
else -> emit(Event.Received(message))
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// Silence timeout or connection reset.
|
||||
} finally {
|
||||
closeSocket()
|
||||
}
|
||||
if (joined) emit(Event.Disconnected(hostClosed)) else emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||
}
|
||||
|
||||
private fun failureOf(reject: SpectatorMessage.Reject): Failure = when (reject.reason) {
|
||||
RejectReason.FULL -> Failure.FULL
|
||||
RejectReason.NO_GAME -> Failure.NO_GAME
|
||||
RejectReason.UPDATE_REQUIRED ->
|
||||
if (version < reject.minVersion) Failure.UPDATE_THIS_APP else Failure.UPDATE_HOST_APP
|
||||
RejectReason.OTHER -> Failure.UNREACHABLE
|
||||
}
|
||||
|
||||
private fun emit(event: Event) {
|
||||
if (!stopped) onEvent(event)
|
||||
}
|
||||
|
||||
private fun send(message: SpectatorMessage) {
|
||||
try {
|
||||
writer.execute { writeLine(message) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
// Stopped.
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeLine(message: SpectatorMessage) {
|
||||
val out = output ?: return
|
||||
try {
|
||||
out.write(SpectatorProtocol.encode(message, version))
|
||||
out.write("\n")
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
closeSocket()
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeSocket() {
|
||||
try { socket?.close() } catch (_: IOException) {}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STOP_GRACE_MS = 500L
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot status query, used to show live spectator counts in the Friends list. */
|
||||
object SpectatorProbe {
|
||||
fun query(host: String, port: Int, timeoutMs: Int = 2_000): SpectatorMessage.Status? = try {
|
||||
Socket().use { s ->
|
||||
s.connect(InetSocketAddress(host, port), timeoutMs)
|
||||
s.soTimeout = timeoutMs
|
||||
val out = s.getOutputStream()
|
||||
out.write((SpectatorProtocol.encode(SpectatorMessage.StatusQuery) + "\n").toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||
(read as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text)?.message as? SpectatorMessage.Status }
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.engine.Board
|
||||
import cc.skysparkle.matewave.engine.ChessEngine
|
||||
import cc.skysparkle.matewave.engine.GameStatus
|
||||
import cc.skysparkle.matewave.engine.Move
|
||||
import cc.skysparkle.matewave.engine.Notation
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.opposite
|
||||
|
||||
/** What a spectator sees of a game. */
|
||||
data class SpectatorView(
|
||||
val gameId: String,
|
||||
val white: SpectatorPlayer,
|
||||
val black: SpectatorPlayer,
|
||||
val startBoard: Board,
|
||||
val board: Board,
|
||||
val movesUci: List<String>,
|
||||
val moveSans: List<String>,
|
||||
val lastMove: Move?,
|
||||
val initialSeconds: Int,
|
||||
val incrementSeconds: Int,
|
||||
val clock: SpectatorClock?,
|
||||
val result: SpectatorResult?
|
||||
) {
|
||||
val ply: Int get() = movesUci.size
|
||||
}
|
||||
|
||||
/**
|
||||
* The spectator's copy of the game, rebuilt from a snapshot and moved forward by live moves. Moves
|
||||
* are checked against the rules; anything that does not follow on asks for a fresh snapshot.
|
||||
*/
|
||||
class SpectatorGame {
|
||||
enum class Applied { APPLIED, IGNORED, NEEDS_RESYNC }
|
||||
|
||||
var view: SpectatorView? = null
|
||||
private set
|
||||
|
||||
fun load(snapshot: SpectatorSnapshot): Boolean {
|
||||
val start = Board.startPosition()
|
||||
var board = start
|
||||
val sans = ArrayList<String>(snapshot.movesUci.size)
|
||||
var last: Move? = null
|
||||
for (uci in snapshot.movesUci) {
|
||||
val move = resolve(board, uci) ?: return false
|
||||
sans.add(Notation.toSan(board, move))
|
||||
board = ChessEngine.applyMove(board, move)
|
||||
last = move
|
||||
}
|
||||
view = SpectatorView(
|
||||
gameId = snapshot.gameId,
|
||||
white = snapshot.white,
|
||||
black = snapshot.black,
|
||||
startBoard = start,
|
||||
board = board,
|
||||
movesUci = snapshot.movesUci,
|
||||
moveSans = sans,
|
||||
lastMove = last,
|
||||
initialSeconds = snapshot.initialSeconds,
|
||||
incrementSeconds = snapshot.incrementSeconds,
|
||||
clock = snapshot.clock,
|
||||
result = snapshot.result
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
fun onMove(message: SpectatorMessage.MovePlayed): Applied {
|
||||
val current = view ?: return Applied.NEEDS_RESYNC
|
||||
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||
if (current.result != null || message.ply <= current.ply) return Applied.IGNORED
|
||||
if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
||||
val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
||||
view = current.copy(
|
||||
board = ChessEngine.applyMove(current.board, move),
|
||||
movesUci = current.movesUci + move.toUci(),
|
||||
moveSans = current.moveSans + Notation.toSan(current.board, move),
|
||||
lastMove = move,
|
||||
clock = message.clock ?: current.clock
|
||||
)
|
||||
return Applied.APPLIED
|
||||
}
|
||||
|
||||
fun onGameOver(message: SpectatorMessage.GameOver): Applied {
|
||||
val current = view ?: return Applied.NEEDS_RESYNC
|
||||
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||
view = current.copy(
|
||||
result = message.result,
|
||||
clock = (message.clock ?: current.clock)?.copy(running = null)
|
||||
)
|
||||
return Applied.APPLIED
|
||||
}
|
||||
|
||||
fun onClock(clock: SpectatorClock?) {
|
||||
val current = view ?: return
|
||||
if (clock == null || current.result != null) return
|
||||
view = current.copy(clock = clock)
|
||||
}
|
||||
|
||||
private fun resolve(board: Board, uci: String): Move? {
|
||||
if (uci.length !in 4..5) return null
|
||||
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
||||
if (candidate.from !in 0..63 || candidate.to !in 0..63) return null
|
||||
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
||||
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** Turns successive host snapshots into the messages spectators need to follow along. */
|
||||
object SpectatorDiff {
|
||||
fun between(old: SpectatorSnapshot?, new: SpectatorSnapshot): List<SpectatorMessage> {
|
||||
if (old == null) return emptyList()
|
||||
if (old.gameId != new.gameId || old.white != new.white || old.black != new.black) {
|
||||
return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
val events = ArrayList<SpectatorMessage>()
|
||||
val before = old.movesUci
|
||||
val after = new.movesUci
|
||||
if (after != before) {
|
||||
if (after.size <= before.size || after.subList(0, before.size) != before) {
|
||||
return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
for (i in before.size until after.size) {
|
||||
val isLast = i == after.lastIndex
|
||||
events += SpectatorMessage.MovePlayed(new.gameId, i + 1, after[i], if (isLast) new.clock else null)
|
||||
}
|
||||
}
|
||||
when {
|
||||
old.result == null && new.result != null -> events += SpectatorMessage.GameOver(new.gameId, new.result, new.clock)
|
||||
old.result != null && new.result != old.result -> return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
return events
|
||||
}
|
||||
}
|
||||
|
||||
/** Result of a finished game as spectators are told it. */
|
||||
object SpectatorResults {
|
||||
fun of(
|
||||
status: GameStatus,
|
||||
sideToMove: PieceColor,
|
||||
timedOutSide: PieceColor?,
|
||||
resignedSide: PieceColor?,
|
||||
leftMidGame: Boolean
|
||||
): SpectatorResult? = when (status) {
|
||||
GameStatus.ONGOING -> null
|
||||
GameStatus.CHECKMATE -> SpectatorResult(SpectatorOutcome.CHECKMATE, sideToMove.opposite())
|
||||
GameStatus.STALEMATE -> SpectatorResult(SpectatorOutcome.STALEMATE, null)
|
||||
GameStatus.DRAW_50_MOVES -> SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null)
|
||||
GameStatus.DRAW_REPETITION -> SpectatorResult(SpectatorOutcome.REPETITION, null)
|
||||
GameStatus.DRAW_MATERIAL -> SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null)
|
||||
GameStatus.TIMEOUT -> SpectatorResult(SpectatorOutcome.TIMEOUT, timedOutSide?.opposite())
|
||||
GameStatus.TIMEOUT_DRAW -> SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null)
|
||||
GameStatus.RESIGNATION -> SpectatorResult(
|
||||
if (leftMidGame) SpectatorOutcome.LEFT else SpectatorOutcome.RESIGNATION,
|
||||
resignedSide?.opposite()
|
||||
)
|
||||
GameStatus.DRAW_AGREEMENT -> SpectatorResult(SpectatorOutcome.AGREEMENT, null)
|
||||
}
|
||||
|
||||
fun leftBy(side: PieceColor) = SpectatorResult(SpectatorOutcome.LEFT, side.opposite())
|
||||
|
||||
val interrupted = SpectatorResult(SpectatorOutcome.INTERRUPTED, null)
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.network.LineResult
|
||||
import cc.skysparkle.matewave.network.readBoundedLine
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.net.SocketTimeoutException
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
import java.util.concurrent.ThreadFactory
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Runs on the host player's device and streams the game to up to [maxSpectators] spectators on
|
||||
* its own listening socket; the players' connection is never touched. Each spectator gets its own
|
||||
* bounded queue and writer thread, so a slow or vanished spectator is dropped without delaying
|
||||
* the game or anyone else. Spectators can only listen: anything they send besides keepalives and
|
||||
* resync requests is ignored.
|
||||
*/
|
||||
class SpectatorHub(
|
||||
private val maxSpectators: Int = MAX_SPECTATORS,
|
||||
private val timing: Timing = Timing(),
|
||||
private val log: (String) -> Unit = {}
|
||||
) {
|
||||
data class Timing(
|
||||
val helloTimeoutMs: Int = 5_000,
|
||||
val pingIntervalMs: Long = 5_000,
|
||||
/** A spectator that answers no ping for this long is gone (e.g. its Wi-Fi went off). */
|
||||
val silenceTimeoutMs: Int = 20_000,
|
||||
val queueCapacity: Int = 512
|
||||
)
|
||||
|
||||
private val lock = Any()
|
||||
private val spectators = LinkedHashSet<Spectator>()
|
||||
private var latest: SpectatorSnapshot? = null
|
||||
private var latestAtNanos = 0L
|
||||
private var closed = false
|
||||
private var server: ServerSocket? = null
|
||||
private val handshaking = AtomicInteger()
|
||||
|
||||
private val threads = Executors.newCachedThreadPool(daemonThreads("spectator"))
|
||||
private val ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("spectator-ping"))
|
||||
|
||||
private val _count = MutableStateFlow(0)
|
||||
val count: StateFlow<Int> = _count
|
||||
|
||||
val port: Int get() = server?.localPort ?: 0
|
||||
|
||||
/** Opens the spectator socket on [bindAddress] (all interfaces by default) and returns its port. */
|
||||
fun start(bindAddress: InetAddress? = null): Int {
|
||||
val socket = synchronized(lock) {
|
||||
check(!closed) { "Hub is closed" }
|
||||
server?.let { return it.localPort }
|
||||
ServerSocket().also {
|
||||
it.reuseAddress = true
|
||||
it.bind(InetSocketAddress(bindAddress, 0))
|
||||
server = it
|
||||
}
|
||||
}
|
||||
threads.execute { acceptLoop(socket) }
|
||||
ticker.scheduleAtFixedRate(
|
||||
{ runCatching { sendPings() } },
|
||||
timing.pingIntervalMs, timing.pingIntervalMs, TimeUnit.MILLISECONDS
|
||||
)
|
||||
return socket.localPort
|
||||
}
|
||||
|
||||
/** Replaces the current game state and sends [events] to every spectator, atomically. */
|
||||
fun publish(snapshot: SpectatorSnapshot, events: List<SpectatorMessage> = emptyList()) {
|
||||
synchronized(lock) {
|
||||
if (closed) return
|
||||
latest = snapshot
|
||||
latestAtNanos = System.nanoTime()
|
||||
if (events.isEmpty() || spectators.isEmpty()) return
|
||||
val targets = spectators.toList()
|
||||
events.forEach { deliver(targets, SpectatorProtocol.encode(it)) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends [finalEvents] and a goodbye to everyone, then stops accepting and closes. */
|
||||
fun close(finalEvents: List<SpectatorMessage> = emptyList()) {
|
||||
val targets = synchronized(lock) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
spectators.toList().also { spectators.clear() }
|
||||
}
|
||||
_count.value = 0
|
||||
val lines = finalEvents.map { SpectatorProtocol.encode(it) } + SpectatorProtocol.encode(SpectatorMessage.Closing)
|
||||
targets.forEach { spectator ->
|
||||
lines.forEach { spectator.offer(it) }
|
||||
spectator.finish()
|
||||
}
|
||||
closeQuietly(server)
|
||||
ticker.shutdownNow()
|
||||
threads.shutdown()
|
||||
}
|
||||
|
||||
private fun acceptLoop(socket: ServerSocket) {
|
||||
while (!socket.isClosed) {
|
||||
val client = try {
|
||||
socket.accept()
|
||||
} catch (e: IOException) {
|
||||
if (socket.isClosed) return
|
||||
log("Spectator accept failed: ${e.message}")
|
||||
continue
|
||||
}
|
||||
if (handshaking.incrementAndGet() > MAX_HANDSHAKING) {
|
||||
handshaking.decrementAndGet()
|
||||
closeQuietly(client)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
threads.execute { serve(client) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
handshaking.decrementAndGet()
|
||||
closeQuietly(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun serve(client: Socket) {
|
||||
var spectator: Spectator? = null
|
||||
var reader: BufferedReader? = null
|
||||
try {
|
||||
client.tcpNoDelay = true
|
||||
client.soTimeout = timing.helloTimeoutMs
|
||||
reader = BufferedReader(InputStreamReader(client.getInputStream(), Charsets.UTF_8))
|
||||
val first = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||
val envelope = (first as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text) }
|
||||
when (envelope?.message) {
|
||||
SpectatorMessage.StatusQuery -> reply(client, status())
|
||||
is SpectatorMessage.Hello -> {
|
||||
if (envelope.version < SpectatorProtocol.MIN_COMPATIBLE_VERSION) {
|
||||
log("Spectator with protocol ${envelope.version} told to update")
|
||||
reply(client, SpectatorMessage.Reject(RejectReason.UPDATE_REQUIRED, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||
} else {
|
||||
spectator = admit(client)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// Timed out or closed before saying hello.
|
||||
} finally {
|
||||
handshaking.decrementAndGet()
|
||||
if (spectator == null) closeQuietly(client)
|
||||
}
|
||||
val admitted = spectator ?: return
|
||||
listen(admitted, reader ?: return)
|
||||
}
|
||||
|
||||
private fun admit(client: Socket): Spectator? {
|
||||
var reject: RejectReason? = null
|
||||
var spectator: Spectator? = null
|
||||
synchronized(lock) {
|
||||
val game = latest
|
||||
when {
|
||||
closed || game == null -> reject = RejectReason.NO_GAME
|
||||
spectators.size >= maxSpectators -> reject = RejectReason.FULL
|
||||
else -> {
|
||||
val joined = Spectator(client, timing.queueCapacity)
|
||||
val others = spectators.toList()
|
||||
spectators.add(joined)
|
||||
val n = spectators.size
|
||||
_count.value = n
|
||||
joined.offer(SpectatorProtocol.encode(SpectatorMessage.Welcome(n, maxSpectators, liveSnapshot(game))))
|
||||
deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(n, maxSpectators)))
|
||||
spectator = joined
|
||||
}
|
||||
}
|
||||
}
|
||||
reject?.let {
|
||||
reply(client, SpectatorMessage.Reject(it, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||
return null
|
||||
}
|
||||
val joined = spectator ?: return null
|
||||
try {
|
||||
threads.execute { write(joined) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
drop(joined)
|
||||
return null
|
||||
}
|
||||
return joined
|
||||
}
|
||||
|
||||
private fun listen(spectator: Spectator, reader: BufferedReader) {
|
||||
try {
|
||||
spectator.socket.soTimeout = timing.silenceTimeoutMs
|
||||
while (true) {
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||
if (read !is LineResult.Line) break
|
||||
when (SpectatorProtocol.decode(read.text)?.message) {
|
||||
SpectatorMessage.Resync -> synchronized(lock) {
|
||||
val game = latest
|
||||
if (game != null && !closed) {
|
||||
deliver(listOf(spectator), SpectatorProtocol.encode(SpectatorMessage.NewGame(liveSnapshot(game))))
|
||||
}
|
||||
}
|
||||
SpectatorMessage.Leave -> break
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
} catch (e: SocketTimeoutException) {
|
||||
log("Spectator silent for ${timing.silenceTimeoutMs / 1000} s, dropped")
|
||||
} catch (e: IOException) {
|
||||
// Connection reset.
|
||||
} finally {
|
||||
drop(spectator)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(spectator: Spectator) {
|
||||
try {
|
||||
val out = BufferedWriter(OutputStreamWriter(spectator.socket.getOutputStream(), Charsets.UTF_8))
|
||||
while (true) {
|
||||
val item = spectator.queue.take()
|
||||
if (item === POISON) break
|
||||
out.write(item as String)
|
||||
out.write("\n")
|
||||
if (spectator.queue.isEmpty()) out.flush()
|
||||
}
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
// Spectator went away.
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
} finally {
|
||||
drop(spectator)
|
||||
closeQuietly(spectator.socket)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendPings() {
|
||||
val line: String
|
||||
val targets: List<Spectator>
|
||||
synchronized(lock) {
|
||||
if (closed || spectators.isEmpty()) return
|
||||
line = SpectatorProtocol.encode(SpectatorMessage.Ping(liveClock()))
|
||||
targets = spectators.toList()
|
||||
}
|
||||
deliver(targets, line)
|
||||
}
|
||||
|
||||
private fun deliver(targets: List<Spectator>, line: String) {
|
||||
for (spectator in targets) {
|
||||
if (!spectator.offer(line)) {
|
||||
log("Spectator too slow, dropped")
|
||||
drop(spectator)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drop(spectator: Spectator) {
|
||||
val others: List<Spectator>
|
||||
val remaining: Int
|
||||
synchronized(lock) {
|
||||
// Already dropped, or the hub is closing and its writer is flushing the goodbye.
|
||||
if (!spectators.remove(spectator)) return
|
||||
remaining = spectators.size
|
||||
_count.value = remaining
|
||||
others = spectators.toList()
|
||||
}
|
||||
spectator.shutdown()
|
||||
if (!closed) deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(remaining, maxSpectators)))
|
||||
}
|
||||
|
||||
private fun status(): SpectatorMessage.Status = synchronized(lock) {
|
||||
val game = latest
|
||||
SpectatorMessage.Status(
|
||||
inGame = !closed && game != null && game.result == null,
|
||||
count = spectators.size,
|
||||
max = maxSpectators,
|
||||
minVersion = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||
)
|
||||
}
|
||||
|
||||
private fun elapsedMs(): Long = (System.nanoTime() - latestAtNanos) / 1_000_000L
|
||||
|
||||
private fun liveClock(): SpectatorClock? = latest?.clock?.advancedBy(elapsedMs())
|
||||
|
||||
private fun liveSnapshot(game: SpectatorSnapshot): SpectatorSnapshot =
|
||||
if (game.clock == null) game else game.copy(clock = game.clock.advancedBy(elapsedMs()))
|
||||
|
||||
private fun reply(client: Socket, message: SpectatorMessage) {
|
||||
try {
|
||||
val out = client.getOutputStream()
|
||||
out.write((SpectatorProtocol.encode(message) + "\n").toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
// Nothing more to tell a peer that is gone.
|
||||
}
|
||||
}
|
||||
|
||||
/** One spectator's outgoing queue; one slot is kept free for the end marker. */
|
||||
private class Spectator(val socket: Socket, private val capacity: Int) {
|
||||
val queue = ArrayBlockingQueue<Any>(capacity + 1)
|
||||
private var open = true
|
||||
|
||||
@Synchronized
|
||||
fun offer(line: String): Boolean = open && queue.size < capacity && queue.offer(line)
|
||||
|
||||
/** Lets the writer send what is queued, then close. */
|
||||
@Synchronized
|
||||
fun finish() {
|
||||
if (!open) return
|
||||
open = false
|
||||
queue.offer(POISON)
|
||||
}
|
||||
|
||||
/** Stops at once, discarding anything unsent. */
|
||||
@Synchronized
|
||||
fun shutdown() {
|
||||
open = false
|
||||
queue.clear()
|
||||
queue.offer(POISON)
|
||||
closeQuietly(socket)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val POISON = Any()
|
||||
|
||||
/** Connections allowed to sit in the hello phase at once. */
|
||||
const val MAX_HANDSHAKING = 32
|
||||
|
||||
fun closeQuietly(c: Closeable?) {
|
||||
try { c?.close() } catch (_: IOException) {}
|
||||
}
|
||||
|
||||
fun daemonThreads(name: String): ThreadFactory {
|
||||
val n = AtomicInteger()
|
||||
return ThreadFactory { r -> Thread(r, "$name-${n.incrementAndGet()}").apply { isDaemon = true } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Feeds a hub from the host's game: each new snapshot becomes the messages spectators need. */
|
||||
class SpectatorBroadcaster(val hub: SpectatorHub) {
|
||||
private var last: SpectatorSnapshot? = null
|
||||
|
||||
fun update(snapshot: SpectatorSnapshot) {
|
||||
val events = SpectatorDiff.between(last, snapshot)
|
||||
last = snapshot
|
||||
hub.publish(snapshot, events)
|
||||
}
|
||||
|
||||
/** Stops spectating; [final] is the last state, e.g. the result of a game left midway. */
|
||||
fun close(final: SpectatorSnapshot? = null) {
|
||||
val events = if (final != null) SpectatorDiff.between(last, final) else emptyList()
|
||||
hub.close(events)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Most spectators one hosted game accepts at the same time. */
|
||||
const val MAX_SPECTATORS = 20
|
||||
|
||||
data class SpectatorPlayer(val id: String, val name: String, val elo: Int)
|
||||
|
||||
data class SpectatorClock(val whiteMs: Long, val blackMs: Long, val running: PieceColor?) {
|
||||
/** The same clock [elapsedMs] later. */
|
||||
fun advancedBy(elapsedMs: Long): SpectatorClock {
|
||||
if (elapsedMs <= 0) return this
|
||||
return when (running) {
|
||||
PieceColor.WHITE -> copy(whiteMs = (whiteMs - elapsedMs).coerceAtLeast(0))
|
||||
PieceColor.BLACK -> copy(blackMs = (blackMs - elapsedMs).coerceAtLeast(0))
|
||||
null -> this
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class SpectatorOutcome(val wire: String) {
|
||||
CHECKMATE("checkmate"),
|
||||
STALEMATE("stalemate"),
|
||||
FIFTY_MOVES("fifty"),
|
||||
REPETITION("repetition"),
|
||||
INSUFFICIENT_MATERIAL("material"),
|
||||
TIMEOUT("timeout"),
|
||||
TIMEOUT_DRAW("timeout_draw"),
|
||||
RESIGNATION("resign"),
|
||||
AGREEMENT("agreement"),
|
||||
LEFT("left"),
|
||||
INTERRUPTED("interrupted"),
|
||||
UNKNOWN("unknown");
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): SpectatorOutcome = entries.firstOrNull { it.wire == value } ?: UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
/** How a game ended; [winner] is null for draws and interrupted games. */
|
||||
data class SpectatorResult(val outcome: SpectatorOutcome, val winner: PieceColor?)
|
||||
|
||||
/** Everything a spectator needs to show a game from any point: players, moves, clocks, result. */
|
||||
data class SpectatorSnapshot(
|
||||
val gameId: String,
|
||||
val white: SpectatorPlayer,
|
||||
val black: SpectatorPlayer,
|
||||
val movesUci: List<String>,
|
||||
val initialSeconds: Int,
|
||||
val incrementSeconds: Int,
|
||||
val clock: SpectatorClock?,
|
||||
val result: SpectatorResult? = null
|
||||
)
|
||||
|
||||
enum class RejectReason(val wire: String) {
|
||||
FULL("full"),
|
||||
UPDATE_REQUIRED("update"),
|
||||
NO_GAME("no_game"),
|
||||
OTHER("other");
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): RejectReason = entries.firstOrNull { it.wire == value } ?: OTHER
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SpectatorMessage {
|
||||
// Spectator to host.
|
||||
data class Hello(val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION) : SpectatorMessage()
|
||||
data object StatusQuery : SpectatorMessage()
|
||||
data object Pong : SpectatorMessage()
|
||||
data object Resync : SpectatorMessage()
|
||||
data object Leave : SpectatorMessage()
|
||||
|
||||
// Host to spectator.
|
||||
data class Welcome(val count: Int, val max: Int, val game: SpectatorSnapshot) : SpectatorMessage()
|
||||
data class Status(val inGame: Boolean, val count: Int, val max: Int, val minVersion: Int) : SpectatorMessage()
|
||||
data class Reject(val reason: RejectReason, val minVersion: Int) : SpectatorMessage()
|
||||
data class MovePlayed(val gameId: String, val ply: Int, val uci: String, val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data class GameOver(val gameId: String, val result: SpectatorResult, val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data class NewGame(val game: SpectatorSnapshot) : SpectatorMessage()
|
||||
data class Count(val count: Int, val max: Int) : SpectatorMessage()
|
||||
data class Ping(val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data object Closing : SpectatorMessage()
|
||||
}
|
||||
|
||||
/** One decoded line: the sender's protocol version and the message, or null for an unknown type. */
|
||||
data class SpectatorEnvelope(val version: Int, val message: SpectatorMessage?)
|
||||
|
||||
/**
|
||||
* Wire format between a hosted game and its spectators: one JSON object per line, each carrying
|
||||
* the sender's protocol version in "sv". Unknown types are skipped, never fatal.
|
||||
*/
|
||||
object SpectatorProtocol {
|
||||
/**
|
||||
* Bump on incompatible changes and raise [MIN_COMPATIBLE_VERSION] to the oldest version still
|
||||
* understood. hello, status and reject keep their shape so any two versions can still tell
|
||||
* each other that an update is required.
|
||||
*/
|
||||
const val VERSION = 1
|
||||
const val MIN_COMPATIBLE_VERSION = 1
|
||||
|
||||
const val MAX_HOST_LINE_CHARS = 64_000
|
||||
const val MAX_CLIENT_LINE_CHARS = 1_024
|
||||
|
||||
private const val MAX_NAME_CHARS = 40
|
||||
private const val MAX_PLIES = 2_000
|
||||
|
||||
fun encode(message: SpectatorMessage, version: Int = VERSION): String {
|
||||
val o = JSONObject()
|
||||
o.put("sv", version)
|
||||
when (message) {
|
||||
is SpectatorMessage.Hello -> { o.put("type", "hello"); o.put("min", message.minVersion) }
|
||||
SpectatorMessage.StatusQuery -> o.put("type", "query")
|
||||
SpectatorMessage.Pong -> o.put("type", "pong")
|
||||
SpectatorMessage.Resync -> o.put("type", "resync")
|
||||
SpectatorMessage.Leave -> o.put("type", "leave")
|
||||
is SpectatorMessage.Welcome -> {
|
||||
o.put("type", "welcome"); o.put("n", message.count); o.put("max", message.max)
|
||||
o.put("game", snapshotJson(message.game))
|
||||
}
|
||||
is SpectatorMessage.Status -> {
|
||||
o.put("type", "status"); o.put("live", message.inGame)
|
||||
o.put("n", message.count); o.put("max", message.max); o.put("min", message.minVersion)
|
||||
}
|
||||
is SpectatorMessage.Reject -> {
|
||||
o.put("type", "reject"); o.put("reason", message.reason.wire); o.put("min", message.minVersion)
|
||||
}
|
||||
is SpectatorMessage.MovePlayed -> {
|
||||
o.put("type", "move"); o.put("gid", message.gameId); o.put("ply", message.ply); o.put("uci", message.uci)
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
is SpectatorMessage.GameOver -> {
|
||||
o.put("type", "end"); o.put("gid", message.gameId); o.put("result", resultJson(message.result))
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
is SpectatorMessage.NewGame -> { o.put("type", "game"); o.put("game", snapshotJson(message.game)) }
|
||||
is SpectatorMessage.Count -> { o.put("type", "count"); o.put("n", message.count); o.put("max", message.max) }
|
||||
is SpectatorMessage.Ping -> {
|
||||
o.put("type", "ping")
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
SpectatorMessage.Closing -> o.put("type", "closing")
|
||||
}
|
||||
return o.toString()
|
||||
}
|
||||
|
||||
/** Null when the line is not a protocol message at all. */
|
||||
fun decode(line: String): SpectatorEnvelope? {
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||
val type = o.optString("type", "")
|
||||
if (type.isEmpty()) return null
|
||||
val version = o.optInt("sv", 0)
|
||||
val message = runCatching { decodeMessage(type, o) }.getOrNull()
|
||||
return SpectatorEnvelope(version, message)
|
||||
}
|
||||
|
||||
private fun decodeMessage(type: String, o: JSONObject): SpectatorMessage? = when (type) {
|
||||
"hello" -> SpectatorMessage.Hello(o.optInt("min", o.optInt("sv", 0)))
|
||||
"query" -> SpectatorMessage.StatusQuery
|
||||
"pong" -> SpectatorMessage.Pong
|
||||
"resync" -> SpectatorMessage.Resync
|
||||
"leave" -> SpectatorMessage.Leave
|
||||
"welcome" -> SpectatorMessage.Welcome(o.getInt("n"), o.getInt("max"), parseSnapshot(o.getJSONObject("game")))
|
||||
"status" -> SpectatorMessage.Status(o.getBoolean("live"), o.getInt("n"), o.getInt("max"), o.optInt("min", 0))
|
||||
"reject" -> SpectatorMessage.Reject(RejectReason.fromWire(o.getString("reason")), o.optInt("min", 0))
|
||||
"move" -> SpectatorMessage.MovePlayed(
|
||||
o.getString("gid"), o.getInt("ply"), o.getString("uci"), o.optJSONObject("clock")?.let(::parseClock)
|
||||
)
|
||||
"end" -> SpectatorMessage.GameOver(
|
||||
o.getString("gid"), parseResult(o.getJSONObject("result")), o.optJSONObject("clock")?.let(::parseClock)
|
||||
)
|
||||
"game" -> SpectatorMessage.NewGame(parseSnapshot(o.getJSONObject("game")))
|
||||
"count" -> SpectatorMessage.Count(o.getInt("n"), o.getInt("max"))
|
||||
"ping" -> SpectatorMessage.Ping(o.optJSONObject("clock")?.let(::parseClock))
|
||||
"closing" -> SpectatorMessage.Closing
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun sideWire(side: PieceColor?): String = when (side) {
|
||||
PieceColor.WHITE -> "w"
|
||||
PieceColor.BLACK -> "b"
|
||||
null -> ""
|
||||
}
|
||||
|
||||
private fun sideOf(wire: String): PieceColor? = when (wire) {
|
||||
"w" -> PieceColor.WHITE
|
||||
"b" -> PieceColor.BLACK
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun clockJson(c: SpectatorClock) = JSONObject().apply {
|
||||
put("w", c.whiteMs); put("b", c.blackMs)
|
||||
if (c.running != null) put("r", sideWire(c.running))
|
||||
}
|
||||
|
||||
private fun parseClock(o: JSONObject) = SpectatorClock(
|
||||
whiteMs = o.getLong("w").coerceAtLeast(0),
|
||||
blackMs = o.getLong("b").coerceAtLeast(0),
|
||||
running = sideOf(o.optString("r", ""))
|
||||
)
|
||||
|
||||
private fun resultJson(r: SpectatorResult) = JSONObject().apply {
|
||||
put("o", r.outcome.wire)
|
||||
if (r.winner != null) put("w", sideWire(r.winner))
|
||||
}
|
||||
|
||||
private fun parseResult(o: JSONObject) = SpectatorResult(
|
||||
outcome = SpectatorOutcome.fromWire(o.getString("o")),
|
||||
winner = sideOf(o.optString("w", ""))
|
||||
)
|
||||
|
||||
private fun playerJson(p: SpectatorPlayer) = JSONObject().apply {
|
||||
put("id", p.id); put("name", p.name); put("elo", p.elo)
|
||||
}
|
||||
|
||||
private fun parsePlayer(o: JSONObject) = SpectatorPlayer(
|
||||
id = o.optString("id", "").take(64),
|
||||
name = o.optString("name", "").take(MAX_NAME_CHARS),
|
||||
elo = o.optInt("elo", 0)
|
||||
)
|
||||
|
||||
private fun snapshotJson(s: SpectatorSnapshot) = JSONObject().apply {
|
||||
put("gid", s.gameId)
|
||||
put("wp", playerJson(s.white))
|
||||
put("bp", playerJson(s.black))
|
||||
put("moves", JSONArray().also { array -> s.movesUci.forEach { array.put(it) } })
|
||||
put("ti", s.initialSeconds)
|
||||
put("tx", s.incrementSeconds)
|
||||
s.clock?.let { put("clock", clockJson(it)) }
|
||||
s.result?.let { put("result", resultJson(it)) }
|
||||
}
|
||||
|
||||
private fun parseSnapshot(o: JSONObject): SpectatorSnapshot {
|
||||
val array = o.getJSONArray("moves")
|
||||
require(array.length() <= MAX_PLIES)
|
||||
return SpectatorSnapshot(
|
||||
gameId = o.getString("gid"),
|
||||
white = parsePlayer(o.getJSONObject("wp")),
|
||||
black = parsePlayer(o.getJSONObject("bp")),
|
||||
movesUci = List(array.length()) { array.getString(it) },
|
||||
initialSeconds = o.optInt("ti", 0),
|
||||
incrementSeconds = o.optInt("tx", 0),
|
||||
clock = o.optJSONObject("clock")?.let(::parseClock),
|
||||
result = o.optJSONObject("result")?.let(::parseResult)
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user