Add app source for F-Droid release (v1.0.43)

Adds the full Android source tree with unit tests, fastlane store
metadata and the Gradle wrapper. The archive shipped without
gradle-wrapper.jar, so the official Gradle 9.7.1 wrapper jar is
included to make ./gradlew work from a fresh clone. .gitignore now
also excludes build output and keystores. README gains build
instructions and an updated structure tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015g6ECVSKcBG8CJPrqC3G5o
This commit is contained in:
Claude
2026-10-06 18:23:20 +00:00
parent 6851ba52ef
commit 6ac5a582db
242 changed files with 54260 additions and 1 deletions
@@ -0,0 +1,24 @@
package cc.skysparkle.matewave.network
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
object AppPermissions {
/** Runtime permissions for Bluetooth play: scan, advertise and connect (location before Android 12). */
val nearby: List<String> =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
listOf(
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_ADVERTISE
)
} else {
listOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
fun allGranted(context: Context, permissions: List<String>): Boolean =
permissions.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED }
}
@@ -0,0 +1,30 @@
package cc.skysparkle.matewave.network
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
object BatteryOptimization {
fun isIgnoring(context: Context): Boolean {
val power = context.getSystemService(Context.POWER_SERVICE) as? PowerManager ?: return true
return runCatching { power.isIgnoringBatteryOptimizations(context.packageName) }
.getOrDefault(true)
}
fun openSettings(context: Context) {
val intents = listOf(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:${context.packageName}")),
Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
)
for (intent in intents) {
val ok = runCatching {
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}.isSuccess
if (ok) return
}
NetworkLog.log("SYS", "Could not open battery settings")
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,191 @@
package cc.skysparkle.matewave.network
import org.json.JSONObject
enum class TransportType { BLUETOOTH, LAN }
enum class ConnectionState { DISCONNECTED, CONNECTING, CONNECTED, FAILED }
/**
* Wire protocol shared by all transports: one JSON object per message.
* Game messages travel inside [SignedMsg] once the handshake is done; only
* [ProfileMsg] and [PingMsg] are sent in the clear. Bump [PROTOCOL_VERSION] on any
* incompatible change: peers with an older version are rejected during the handshake.
*/
sealed class GameMessage {
data class MoveMsg(
val uci: String,
val remainingMillisSelf: Long,
val gameId: String = "",
val ply: Int = 0
) : GameMessage()
data class ResignMsg(val byWhite: Boolean, val gameId: String = "") : GameMessage()
data class DrawOfferMsg(val accept: Boolean? = null, val gameId: String = "") : GameMessage()
data class ChatMsg(val text: String? = null, val imageBase64: String? = null, val gameId: String = "") : GameMessage()
data class ProfileMsg(
val userId: String,
val name: String,
val avatarBase64: String?,
val backgroundBase64: String?,
val elo: Int,
val publicKey: String = "",
val signature: String = "",
val protocolVersion: Int = PROTOCOL_VERSION,
val ephemeralKey: String = "",
val initialSeconds: Int = 0,
val incrementSeconds: Int = 0,
val gameId: String = ""
) : GameMessage()
data class TimeoutMsg(val flaggedWhite: Boolean, val gameId: String = "") : GameMessage()
data class LeaveMsg(val byWhite: Boolean, val gameId: String = "") : GameMessage()
data class ProfileImagesMsg(
val avatarBase64: String? = null,
val backgroundBase64: String? = null,
val gameId: String = ""
) : GameMessage()
data class PingMsg(val reply: Boolean = false, val sessionId: Int = 0) : GameMessage()
data class SignedMsg(val inner: String, val tag: String, val seq: Int = 0) : GameMessage()
data class RematchMsg(
val action: String,
val gameId: String = "",
val newGameId: String = ""
) : GameMessage()
fun toJson(): String {
val o = JSONObject()
when (this) {
is MoveMsg -> {
o.put("type", "move"); o.put("uci", uci); o.put("t", remainingMillisSelf)
o.put("gameId", gameId); o.put("ply", ply)
}
is ResignMsg -> { o.put("type", "resign"); o.put("white", byWhite); o.put("gameId", gameId) }
is DrawOfferMsg -> {
o.put("type", "draw"); o.put("gameId", gameId)
if (accept != null) o.put("accept", accept)
}
is ChatMsg -> {
o.put("type", "chat"); o.put("gameId", gameId)
if (text != null) o.put("text", text)
if (imageBase64 != null) o.put("image", imageBase64)
}
is LeaveMsg -> { o.put("type", "leave"); o.put("byWhite", byWhite); o.put("gameId", gameId) }
is ProfileImagesMsg -> {
o.put("type", "profile_images"); o.put("gameId", gameId)
avatarBase64?.let { o.put("avatar", it) }
backgroundBase64?.let { o.put("background", it) }
}
is PingMsg -> { o.put("type", "ping"); o.put("reply", reply); o.put("sid", sessionId) }
is TimeoutMsg -> { o.put("type", "timeout"); o.put("white", flaggedWhite); o.put("gameId", gameId) }
is SignedMsg -> {
o.put("type", "signed"); o.put("inner", inner); o.put("tag", tag); o.put("seq", seq)
}
is RematchMsg -> {
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
}
is ProfileMsg -> {
o.put("type", "profile")
o.put("userId", userId)
o.put("name", name)
o.put("pv", protocolVersion)
if (initialSeconds > 0) {
o.put("ti", initialSeconds)
o.put("tx", incrementSeconds)
}
if (ephemeralKey.isNotEmpty()) o.put("ek", ephemeralKey)
if (gameId.isNotEmpty()) o.put("gid", gameId)
if (publicKey.isNotEmpty()) o.put("pk", publicKey)
if (signature.isNotEmpty()) o.put("sig", signature)
if (avatarBase64 != null) o.put("avatar", avatarBase64)
if (backgroundBase64 != null) o.put("background", backgroundBase64)
o.put("elo", elo)
}
}
return o.toString()
}
companion object {
const val PROTOCOL_VERSION = 5
fun fromJson(raw: String): GameMessage {
val o = JSONObject(raw)
return when (o.getString("type")) {
"move" -> MoveMsg(
o.getString("uci"), o.optLong("t", 0),
o.optString("gameId", ""), o.optInt("ply", 0)
)
"resign" -> ResignMsg(o.getBoolean("white"), o.optString("gameId", ""))
"draw" -> DrawOfferMsg(
if (o.has("accept")) o.getBoolean("accept") else null,
o.optString("gameId", "")
)
"chat" -> ChatMsg(
text = if (o.has("text")) o.getString("text") else null,
imageBase64 = if (o.has("image")) o.getString("image") else null,
gameId = o.optString("gameId", "")
)
"leave" -> LeaveMsg(o.getBoolean("byWhite"), o.optString("gameId", ""))
"profile_images" -> ProfileImagesMsg(
if (o.has("avatar")) o.getString("avatar") else null,
if (o.has("background")) o.getString("background") else null,
gameId = o.optString("gameId", "")
)
"ping" -> PingMsg(o.optBoolean("reply", false), o.optInt("sid", 0))
"timeout" -> TimeoutMsg(o.getBoolean("white"), o.optString("gameId", ""))
"signed" -> SignedMsg(o.getString("inner"), o.getString("tag"), o.optInt("seq", 0))
"rematch" -> RematchMsg(
o.getString("action"),
o.optString("gameId", ""),
o.optString("newGameId", "")
)
"profile" -> ProfileMsg(
userId = o.optString("userId", "").ifBlank { o.getString("name") },
protocolVersion = o.optInt("pv", 0),
initialSeconds = o.optInt("ti", 0),
incrementSeconds = o.optInt("tx", 0),
ephemeralKey = o.optString("ek", ""),
gameId = o.optString("gid", ""),
publicKey = o.optString("pk", ""),
signature = o.optString("sig", ""),
name = o.getString("name"),
avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null,
backgroundBase64 = if (o.has("background")) o.getString("background") else null,
elo = o.optInt("elo", 1200)
)
else -> throw IllegalArgumentException("Unknown message type")
}
}
}
}
/** A single peer-to-peer game connection (Bluetooth LE or LAN). */
interface ConnectionTransport {
val type: TransportType
val connectionState: kotlinx.coroutines.flow.StateFlow<ConnectionState>
fun startHosting()
fun startDiscoveryAndConnect(targetId: String? = null)
fun send(message: GameMessage)
fun addMessageListener(listener: (GameMessage) -> Unit): () -> Unit
fun disconnect()
}
@@ -0,0 +1,102 @@
package cc.skysparkle.matewave.network
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import java.util.concurrent.CopyOnWriteArrayList
/**
* Hosts a game on every available transport at once (LAN and, with permission, Bluetooth), so
* a guest can join over whichever channel found the host. The first transport to connect wins;
* hosting on the others is stopped and from then on this behaves exactly like the winner.
*/
class DualHostTransport(transports: List<ConnectionTransport>) : ConnectionTransport {
private val all = transports
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val lock = Any()
@Volatile private var active: ConnectionTransport? = null
private val listeners = CopyOnWriteArrayList<(GameMessage) -> Unit>()
private val unsubscribes = mutableListOf<() -> Unit>()
private var watchJob: Job? = null
private val _state = MutableStateFlow(ConnectionState.DISCONNECTED)
override val connectionState: StateFlow<ConnectionState> = _state
override val type: TransportType get() = active?.type ?: all.first().type
override fun startHosting() {
synchronized(lock) {
active = null
unsubscribes.forEach { it() }
unsubscribes.clear()
all.forEach { t ->
unsubscribes += t.addMessageListener { message ->
// The first message can arrive before the state change is observed: claim here too.
if (active == null && t.connectionState.value == ConnectionState.CONNECTED) claim(t)
if (active === t) listeners.forEach { it(message) }
}
}
}
_state.value = ConnectionState.CONNECTING
all.forEach { runCatching { it.startHosting() } }
watchJob?.cancel()
watchJob = scope.launch {
combine(all.map { it.connectionState }) { it.toList() }.collect { states ->
val current = active
if (current == null) {
val index = states.indexOfFirst { it == ConnectionState.CONNECTED }
when {
index >= 0 -> claim(all[index])
states.all { it == ConnectionState.FAILED } -> _state.value = ConnectionState.FAILED
else -> _state.value = ConnectionState.CONNECTING
}
} else {
_state.value = states[all.indexOf(current)]
}
}
}
}
private fun claim(winner: ConnectionTransport) {
val losers = synchronized(lock) {
if (active != null) return
active = winner
all.filter { it !== winner }
}
losers.forEach { runCatching { it.disconnect() } }
_state.value = ConnectionState.CONNECTED
}
override fun startDiscoveryAndConnect(targetId: String?) {
all.first().startDiscoveryAndConnect(targetId)
}
override fun send(message: GameMessage) {
active?.send(message)
}
override fun addMessageListener(listener: (GameMessage) -> Unit): () -> Unit {
listeners.add(listener)
return { listeners.remove(listener) }
}
override fun disconnect() {
watchJob?.cancel()
watchJob = null
synchronized(lock) {
unsubscribes.forEach { it() }
unsubscribes.clear()
active = null
}
all.forEach { runCatching { it.disconnect() } }
_state.value = ConnectionState.DISCONNECTED
}
}
@@ -0,0 +1,86 @@
package cc.skysparkle.matewave.network
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/** Periodic ping that detects a silently dropped connection. */
class Heartbeat(
private val scope: CoroutineScope,
private val transport: ConnectionTransport
) {
private var job: Job? = null
private val sessionId = java.util.concurrent.ThreadLocalRandom.current().nextInt(1, Int.MAX_VALUE)
private var unsubscribe: (() -> Unit)? = null
@Volatile private var lastReplyAt = 0L
@Volatile private var lastTrafficAt = 0L
fun start() {
if (job != null) return
lastReplyAt = System.currentTimeMillis()
lastTrafficAt = lastReplyAt
unsubscribe = transport.addMessageListener { msg ->
if (msg is GameMessage.PingMsg) {
if (msg.reply) {
if (msg.sessionId == sessionId) lastReplyAt = System.currentTimeMillis()
} else {
transport.send(GameMessage.PingMsg(reply = true, sessionId = msg.sessionId))
}
} else {
lastTrafficAt = System.currentTimeMillis()
}
}
job = scope.launch {
var wasConnected = false
while (true) {
delay(INTERVAL_MS)
val connected = transport.connectionState.value == ConnectionState.CONNECTED
if (!connected) {
wasConnected = false
continue
}
if (!wasConnected) {
val now = System.currentTimeMillis()
lastReplyAt = now
lastTrafficAt = now
wasConnected = true
}
val now = System.currentTimeMillis()
val silence = now - lastReplyAt
if (silence > TIMEOUT_MS && now - lastTrafficAt > TIMEOUT_MS) {
NetworkLog.reason(
transport.type.name,
DisconnectReason.REMOTE_DISCONNECTED,
"no reply for ${silence / 1000} s"
)
transport.disconnect()
continue
}
if (silence > TIMEOUT_MS) {
NetworkLog.log(transport.type.name, "No heartbeat reply for ${silence / 1000} s, but data is flowing")
}
transport.send(GameMessage.PingMsg(reply = false, sessionId = sessionId))
}
}
}
fun stop() {
job?.cancel()
job = null
unsubscribe?.invoke()
unsubscribe = null
}
private companion object {
const val INTERVAL_MS = 5_000L
const val TIMEOUT_MS = 16_000L
}
}
@@ -0,0 +1,663 @@
package cc.skysparkle.matewave.network
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.net.wifi.WifiManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.ServerSocket
import java.net.Socket
data class LanPeer(
val name: String,
val host: String,
val port: Int,
val playerId: String = "",
val displayName: String = "",
val elo: Int = 0,
val fingerprint: String = "",
val signature: String = "",
/** Raw NSD service name, used to remove the peer when the service is lost. */
val serviceName: String = ""
) {
val id: String get() = "$host:$port"
}
/**
* LAN transport: plain TCP sockets carrying newline-delimited JSON, with the game
* announced over NSD (mDNS). The listening socket stays open for discovery, but
* incoming connections are accepted only while the user is hosting a game.
*/
class LanTransport(
private val context: Context,
private val scope: CoroutineScope
) : ConnectionTransport {
companion object {
// Wire identifiers from before the rename; changing them would split old and new installs.
const val SERVICE_TYPE = "_chessapp._tcp."
const val SERVICE_NAME = "ChessApp"
const val CONNECT_TIMEOUT_MS = 8_000
const val MAX_MESSAGE_CHARS = 1_400_000
const val ACCEPT_POLL_MS = 1_000
const val RESOLVE_RETRY_MS = 400L
fun presencePayload(playerId: String, name: String, elo: Int): String =
"presence|$playerId|$name|$elo"
}
override val type = TransportType.LAN
private val _connectionState = MutableStateFlow(ConnectionState.DISCONNECTED)
override val connectionState: StateFlow<ConnectionState> = _connectionState
private val nsdManager: NsdManager? =
context.getSystemService(Context.NSD_SERVICE) as? NsdManager
private var serverSocket: ServerSocket? = null
private var socket: Socket? = null
private val socketLock = Any()
private fun claimSocket(candidate: Socket): Boolean = synchronized(socketLock) {
val existing = socket
if (existing != null && !existing.isClosed) return false
socket = candidate
true
}
private var output: OutputStream? = null
private val dispatcher = MessageDispatcher()
@Volatile private var hosting = false
private var registrationListener: NsdManager.RegistrationListener? = null
private var registeredServiceName: String? = null
private val ownServiceName: String by lazy {
val fingerprint = cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context)
?: cc.skysparkle.matewave.data.DeviceIdentity.deviceId(context).take(12)
"$SERVICE_NAME-$fingerprint"
}
fun fingerprintFromServiceName(serviceName: String): String? =
serviceName.substringAfter("$SERVICE_NAME-", "").ifEmpty { null }
private var discoveryListener: NsdManager.DiscoveryListener? = null
@Volatile private var discoveryGeneration = 0
private val resolveQueue = java.util.ArrayDeque<Pair<Int, NsdServiceInfo>>()
private var resolving = false
var lastError: String? = null
private set
private val outbox = Channel<String>(capacity = Channel.UNLIMITED)
private var writerStarted = false
override fun addMessageListener(listener: (GameMessage) -> Unit): () -> Unit =
dispatcher.add(listener)
private fun announceAllowed(): Boolean =
hosting || cc.skysparkle.matewave.presence.PresenceSettings(context).announceEnabled
fun applyAnnounceSetting() {
val port = serverSocket?.localPort
when {
!announceAllowed() -> unregisterService()
port != null -> registerService(port)
else -> startPresence()
}
}
fun republishProfile() {
val port = serverSocket?.localPort ?: return
unregisterService()
if (!announceAllowed()) return
scope.launch(Dispatchers.IO) {
kotlinx.coroutines.delay(400)
registerService(port)
}
}
private val presenceLock = Any()
private var presenceStarting = false
fun startPresence() {
synchronized(presenceLock) {
if (serverSocket != null || presenceStarting) return
presenceStarting = true
}
scope.launch(Dispatchers.IO) {
try {
val server = ServerSocket()
server.reuseAddress = true
server.bind(InetSocketAddress(0))
server.soTimeout = ACCEPT_POLL_MS
synchronized(presenceLock) { serverSocket = server; presenceStarting = false }
if (announceAllowed()) registerService(server.localPort)
acceptLoop(server)
} catch (e: IOException) {
synchronized(presenceLock) { presenceStarting = false }
lastError = "Could not open port: ${e.message}"
NetworkLog.reason("LAN", DisconnectReason.PORT_BUSY, e.message)
}
}
}
private suspend fun acceptLoop(server: ServerSocket) {
while (!server.isClosed) {
try {
val client = server.accept()
if (!hosting) {
try { client.close() } catch (_: IOException) {}
continue
}
if (socket != null && socket?.isClosed == false) {
try { client.close() } catch (_: IOException) {}
continue
}
client.tcpNoDelay = true
client.keepAlive = true
if (!claimSocket(client)) {
try { client.close() } catch (_: IOException) {}
continue
}
onConnected(client)
} catch (e: java.net.SocketTimeoutException) {
continue
} catch (e: IOException) {
if (server.isClosed) return
NetworkLog.log("LAN", "Accept failed: ${e.message}")
kotlinx.coroutines.delay(500)
}
}
}
override fun startHosting() {
hosting = true
_connectionState.value = ConnectionState.CONNECTING
lastError = null
val port = serverSocket?.localPort
if (port != null) registerService(port) else startPresence()
}
private fun onHostingEnded() {
if (!announceAllowed()) unregisterService()
}
private fun registerService(port: Int) {
val nsd = nsdManager ?: return
unregisterService()
val info = NsdServiceInfo().apply {
serviceName = ownServiceName
serviceType = SERVICE_TYPE
setPort(port)
val profile = cc.skysparkle.matewave.data.ProfileStore.get()
runCatching {
val shownName = profile.name.take(40)
setAttribute("id", profile.userId)
setAttribute("name", shownName)
setAttribute("elo", profile.elo.toString())
setAttribute("fp", cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context) ?: "")
cc.skysparkle.matewave.security.DeviceKeys.sign(
context, presencePayload(profile.userId, shownName, profile.elo)
)?.let { setAttribute("sig", it) }
}
}
val listener = object : NsdManager.RegistrationListener {
override fun onServiceRegistered(info: NsdServiceInfo?) {
registeredServiceName = info?.serviceName
}
override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
lastError = "Network service registration failed (code $errorCode). Connect by address manually."
}
override fun onServiceUnregistered(info: NsdServiceInfo?) {}
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) {}
}
registrationListener = listener
try {
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
} catch (e: Exception) {
lastError = "Service registration: ${e.message}"
}
}
private fun unregisterService() {
val nsd = nsdManager ?: return
registrationListener?.let {
try { nsd.unregisterService(it) } catch (_: Exception) {}
}
registrationListener = null
registeredServiceName = null
}
fun discoverPeers(onFound: (List<LanPeer>) -> Unit) {
val nsd = nsdManager ?: return
stopDiscovery()
discoveryGeneration += 1
val myGeneration = discoveryGeneration
val found = LinkedHashMap<String, LanPeer>()
synchronized(resolveQueue) { resolveQueue.clear(); resolving = false }
val listener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String?) {}
override fun onServiceFound(info: NsdServiceInfo) {
if (myGeneration != discoveryGeneration) return
if (info.serviceType?.contains("chessapp") != true) return
if (isSelf(info.serviceName)) return
synchronized(resolveQueue) { resolveQueue.addLast(myGeneration to info) }
drainResolveQueue(nsd, found, onFound)
}
override fun onServiceLost(info: NsdServiceInfo?) {
if (myGeneration != discoveryGeneration) return
val name = info?.serviceName ?: return
// Match the raw service name: LanPeer.name is a cleaned-up display form and never
// matched, so peers who left stayed "online".
val left = synchronized(found) { found.entries.removeAll { it.value.serviceName == name }; found.values.toList() }
scope.launch(Dispatchers.Main) { onFound(left) }
}
override fun onDiscoveryStopped(serviceType: String?) {}
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
lastError = "Network discovery failed (code $errorCode). Enter the address manually."
NetworkLog.log("LAN", "Network discovery failed to start, code $errorCode")
}
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {}
}
discoveryListener = listener
try {
nsd.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
} catch (e: Exception) {
lastError = "Network discovery: ${e.message}"
NetworkLog.log("LAN", "Network discovery: ${e.message}")
}
}
@androidx.annotation.RequiresApi(34)
private fun resolveModern(
nsd: NsdManager,
info: NsdServiceInfo,
myGeneration: Int,
found: LinkedHashMap<String, LanPeer>,
onFound: (List<LanPeer>) -> Unit,
finish: () -> Unit
) {
val executor = java.util.concurrent.Executors.newSingleThreadExecutor()
var done = false
val callback = object : NsdManager.ServiceInfoCallback {
override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) {
NetworkLog.log("LAN", "Could not get peer address, code $errorCode")
executor.shutdown(); finish()
}
override fun onServiceUpdated(updated: NsdServiceInfo) {
if (done) return
done = true
if (myGeneration == discoveryGeneration) {
val host = hostAddressOf(updated)
if (host != null && !isSelfEndpoint(host, updated.port)) {
val peer = peerFrom(updated, host)
val now = synchronized(found) { found[peer.id] = peer; found.values.toList() }
scope.launch(Dispatchers.Main) { onFound(now) }
}
}
try { nsd.unregisterServiceInfoCallback(this) } catch (_: Exception) {}
}
override fun onServiceLost() {
if (myGeneration != discoveryGeneration) return
val left = synchronized(found) { found.entries.removeAll { it.value.serviceName == info.serviceName }; found.values.toList() }
scope.launch(Dispatchers.Main) { onFound(left) }
}
override fun onServiceInfoCallbackUnregistered() {
executor.shutdown(); finish()
}
}
try {
nsd.registerServiceInfoCallback(info, executor, callback)
} catch (e: Exception) {
NetworkLog.log("LAN", "Address resolution: ${e.message}")
executor.shutdown(); finish()
}
}
private fun peerFrom(info: NsdServiceInfo, host: String): LanPeer {
fun attr(key: String): String = runCatching {
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
}.getOrDefault("")
return LanPeer(
name = displayNameOf(info.serviceName),
host = host,
port = info.port,
playerId = attr("id"),
displayName = attr("name"),
elo = attr("elo").toIntOrNull() ?: 0,
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
signature = attr("sig"),
serviceName = info.serviceName ?: ""
)
}
private fun displayNameOf(serviceName: String?): String {
val raw = serviceName ?: return SERVICE_NAME
return raw.substringBefore("-").ifBlank { SERVICE_NAME }
}
private fun isSelf(serviceName: String?): Boolean {
if (serviceName == null) return false
registeredServiceName?.let { if (serviceName == it) return true }
if (serviceName == ownServiceName) return true
return Regex("^${Regex.escape(ownServiceName)} \\(\\d+\\)$").matches(serviceName)
}
private fun isSelfEndpoint(host: String, port: Int): Boolean {
val ourPort = serverSocket?.localPort ?: return false
if (port != ourPort) return false
val ourAddress = localIpAddress()
return ourAddress == null || ourAddress == host
}
@Suppress("DEPRECATION")
private fun hostAddressOf(info: NsdServiceInfo): String? {
if (android.os.Build.VERSION.SDK_INT >= 34) {
val ipv4 = info.hostAddresses.firstOrNull { it is java.net.Inet4Address }
if (ipv4 != null) return ipv4.hostAddress
return info.hostAddresses.firstOrNull()?.hostAddress
}
return info.host?.hostAddress
}
private fun drainResolveQueue(
nsd: NsdManager,
found: LinkedHashMap<String, LanPeer>,
onFound: (List<LanPeer>) -> Unit
) {
val nextGeneration: Int
val next: NsdServiceInfo
synchronized(resolveQueue) {
if (resolving) return
val entry = resolveQueue.pollFirst() ?: return
nextGeneration = entry.first
next = entry.second
resolving = true
}
val finish = {
synchronized(resolveQueue) { resolving = false }
drainResolveQueue(nsd, found, onFound)
}
if (nextGeneration != discoveryGeneration) {
finish()
return
}
if (android.os.Build.VERSION.SDK_INT >= 34) {
resolveModern(nsd, next, nextGeneration, found, onFound, finish)
return
}
try {
@Suppress("DEPRECATION")
nsd.resolveService(next, object : NsdManager.ResolveListener {
override fun onResolveFailed(info: NsdServiceInfo?, errorCode: Int) {
if (errorCode == NsdManager.FAILURE_ALREADY_ACTIVE) {
synchronized(resolveQueue) { resolveQueue.addLast(nextGeneration to next) }
} else {
NetworkLog.log("LAN", "Could not resolve peer address, code $errorCode")
}
scope.launch { kotlinx.coroutines.delay(RESOLVE_RETRY_MS); finish() }
}
override fun onServiceResolved(resolved: NsdServiceInfo) {
if (nextGeneration == discoveryGeneration) {
val host = hostAddressOf(resolved)
if (host != null && !isSelfEndpoint(host, resolved.port)) {
val peer = peerFrom(resolved, host)
val now = synchronized(found) { found[peer.id] = peer; found.values.toList() }
scope.launch(Dispatchers.Main) { onFound(now) }
}
}
finish()
}
})
} catch (e: Exception) {
NetworkLog.log("LAN", "Address resolution: ${e.message}")
finish()
}
}
fun stopDiscovery() {
discoveryGeneration += 1
val nsd = nsdManager ?: return
discoveryListener?.let {
try { nsd.stopServiceDiscovery(it) } catch (_: Exception) {}
}
discoveryListener = null
}
override fun startDiscoveryAndConnect(targetId: String?) {
if (targetId.isNullOrBlank()) {
_connectionState.value = ConnectionState.FAILED
return
}
val host = targetId.substringBeforeLast(':', targetId).trim()
val port = targetId.substringAfterLast(':', "").toIntOrNull() ?: run {
lastError = "Address must look like 192.168.1.5:port"
NetworkLog.reason("LAN", DisconnectReason.PEER_NOT_FOUND)
_connectionState.value = ConnectionState.FAILED
return
}
_connectionState.value = ConnectionState.CONNECTING
lastError = null
scope.launch(Dispatchers.IO) {
try {
val s = Socket()
s.tcpNoDelay = true
s.keepAlive = true
s.connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS)
if (!claimSocket(s)) {
// Another connection won the race; report its state instead of hanging here.
try { s.close() } catch (_: IOException) {}
_connectionState.value =
if (socket?.isClosed == false) ConnectionState.CONNECTED else ConnectionState.FAILED
return@launch
}
onConnected(s)
} catch (e: IOException) {
lastError = "Could not connect to $host:$port: ${e.message}"
NetworkLog.reason("LAN", DisconnectReason.CONNECT_TIMEOUT, "$host:$port")
_connectionState.value = ConnectionState.FAILED
}
}
}
private fun onConnected(sock: Socket) {
output = sock.getOutputStream()
startWriterIfNeeded()
_connectionState.value = ConnectionState.CONNECTED
scope.launch(Dispatchers.IO) {
try {
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
while (true) {
val read = readBoundedLine(reader)
if (read is LineResult.EndOfStream) break
if (sock !== socket) break
if (read is LineResult.TooLong) {
NetworkLog.reason("LAN", DisconnectReason.MESSAGE_TOO_LARGE)
break
}
val line = (read as LineResult.Line).text
try {
dispatcher.dispatch(GameMessage.fromJson(line))
} catch (e: Exception) {
NetworkLog.log("LAN", "Malformed message skipped")
}
}
} catch (e: IOException) {
} finally {
releaseConnection(sock)
}
}
}
private fun releaseConnection(sock: Socket) {
try { sock.close() } catch (_: IOException) {}
val wasCurrent = synchronized(socketLock) {
if (sock === socket) {
socket = null
output = null
true
} else {
false
}
}
if (wasCurrent) {
hosting = false
onHostingEnded()
_connectionState.value = ConnectionState.DISCONNECTED
}
}
private fun startWriterIfNeeded() {
if (writerStarted) return
writerStarted = true
scope.launch(Dispatchers.IO) {
for (message in outbox) {
val currentSocket = socket
val currentOutput = output
if (currentSocket == null || currentOutput == null || currentSocket.isClosed) {
NetworkLog.log("LAN", "Message not sent: no connection")
continue
}
try {
currentOutput.write((message + "\n").toByteArray(Charsets.UTF_8))
currentOutput.flush()
} catch (e: IOException) {
releaseConnection(currentSocket)
}
}
}
}
private sealed class LineResult {
data class Line(val text: String) : LineResult()
object TooLong : LineResult()
object EndOfStream : LineResult()
}
private fun readBoundedLine(reader: BufferedReader): 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 >= MAX_MESSAGE_CHARS) return LineResult.TooLong
builder.append(ch.toChar())
}
}
override fun send(message: GameMessage) {
val json = message.toJson()
val size = json.length
if (size > MAX_MESSAGE_CHARS) {
NetworkLog.reason("LAN", DisconnectReason.MESSAGE_TOO_LARGE, "$size chars")
return
}
outbox.trySend(json)
}
override fun disconnect() {
val wasHosting = hosting
hosting = false
if (wasHosting) onHostingEnded()
synchronized(socketLock) {
try { socket?.close() } catch (_: IOException) {}
socket = null
output = null
}
var dropped = 0
while (outbox.tryReceive().isSuccess) dropped++
if (dropped > 0) {
repeat(dropped) { NetworkMetrics.messageDropped() }
NetworkLog.log("LAN", "Dropped unsent messages: $dropped")
}
_connectionState.value = ConnectionState.DISCONNECTED
}
fun shutdown() {
stopDiscovery()
unregisterService()
disconnect()
try { serverSocket?.close() } catch (_: IOException) {}
synchronized(presenceLock) { serverSocket = null; presenceStarting = false }
}
private fun localIpAddress(): String? {
try {
val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
@Suppress("DEPRECATION")
val ip = wifi?.connectionInfo?.ipAddress ?: 0
if (ip != 0) {
return "${ip and 0xff}.${ip shr 8 and 0xff}.${ip shr 16 and 0xff}.${ip shr 24 and 0xff}"
}
} catch (_: Exception) { }
try {
for (nif in NetworkInterface.getNetworkInterfaces()) {
if (!nif.isUp || nif.isLoopback) continue
val name = nif.name.lowercase()
if (name.startsWith("tun") || name.startsWith("ppp") || name.startsWith("rmnet")) continue
for (addr in nif.inetAddresses) {
if (!addr.isLoopbackAddress && addr.hostAddress?.contains(':') == false) {
return addr.hostAddress
}
}
}
} catch (_: Exception) { }
return null
}
}
@@ -0,0 +1,25 @@
package cc.skysparkle.matewave.network
import java.util.concurrent.CopyOnWriteArrayList
class MessageDispatcher {
private val listeners = CopyOnWriteArrayList<(GameMessage) -> Unit>()
fun add(listener: (GameMessage) -> Unit): () -> Unit {
listeners.add(listener)
return { listeners.remove(listener) }
}
fun dispatch(message: GameMessage) {
for (listener in listeners) {
try {
listener(message)
} catch (_: Exception) {
}
}
}
fun clear() {
listeners.clear()
}
}
@@ -0,0 +1,53 @@
package cc.skysparkle.matewave.network
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
enum class DisconnectReason(val userText: String, val textRes: Int) {
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
PERMISSION_DENIED("No nearby devices permission", cc.skysparkle.matewave.R.string.reason_permission_denied),
BLUETOOTH_OFF("Bluetooth is off", cc.skysparkle.matewave.R.string.reason_bluetooth_off),
WIFI_UNAVAILABLE("Phone is not connected to Wi-Fi", cc.skysparkle.matewave.R.string.reason_wifi_unavailable),
PEER_NOT_FOUND("Opponent not found", cc.skysparkle.matewave.R.string.reason_peer_not_found),
CONNECT_TIMEOUT("Opponent did not respond in time", cc.skysparkle.matewave.R.string.reason_connect_timeout),
SERVICE_NOT_FOUND("The other device does not have this app", cc.skysparkle.matewave.R.string.reason_service_not_found),
SUBSCRIBE_FAILED("Could not enable data reception", cc.skysparkle.matewave.R.string.reason_subscribe_failed),
WRITE_FAILED("Could not send data", cc.skysparkle.matewave.R.string.reason_write_failed),
MESSAGE_TOO_LARGE("Received message is too large", cc.skysparkle.matewave.R.string.reason_message_too_large),
REMOTE_DISCONNECTED("Opponent disconnected", cc.skysparkle.matewave.R.string.reason_remote_disconnected),
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy),
UNKNOWN("Unknown connection error", cc.skysparkle.matewave.R.string.reason_unknown)
}
data class NetworkEvent(
val at: Long,
val transport: String,
val text: String
)
/** In-memory connection log, copied into the diagnostics report from Settings. */
object NetworkLog {
private const val CAPACITY = 60
private val _events = MutableStateFlow<List<NetworkEvent>>(emptyList())
private val _lastReason = MutableStateFlow(DisconnectReason.NONE)
val lastReason: StateFlow<DisconnectReason> = _lastReason
fun log(transport: String, text: String) {
val event = NetworkEvent(System.currentTimeMillis(), transport, text)
_events.update { (it + event).takeLast(CAPACITY) }
}
fun reason(transport: String, reason: DisconnectReason, detail: String? = null) {
_lastReason.value = reason
log(transport, reason.userText + (detail?.let { ": $it" } ?: ""))
}
fun asText(): String = _events.value.joinToString("\n") { e ->
val time = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
.format(java.util.Date(e.at))
"$time [${e.transport}] ${e.text}"
}
}
@@ -0,0 +1,58 @@
package cc.skysparkle.matewave.network
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
object NetworkMetrics {
private val connectAttempts = AtomicInteger()
private val connectSuccesses = AtomicInteger()
private val chunksSent = AtomicLong()
private val chunkRetries = AtomicLong()
private val duplicateChunks = AtomicLong()
private val corruptedMessages = AtomicLong()
private val messagesDropped = AtomicLong()
private val lastConnectMillis = AtomicLong()
private val _updated = MutableStateFlow(0)
val updated: StateFlow<Int> = _updated
private fun touch() { _updated.update { it + 1 } }
fun connectStarted() { connectAttempts.incrementAndGet(); touch() }
fun connectSucceeded(millis: Long) {
connectSuccesses.incrementAndGet()
lastConnectMillis.set(millis)
touch()
}
fun chunkSent() { chunksSent.incrementAndGet() }
fun chunkRetried(count: Int) { chunkRetries.addAndGet(count.toLong()); touch() }
fun duplicateChunk() { duplicateChunks.incrementAndGet() }
fun messageCorrupted() { corruptedMessages.incrementAndGet(); touch() }
fun messageDropped() { messagesDropped.incrementAndGet(); touch() }
private fun retryPercent(): Int {
val sent = chunksSent.get()
if (sent == 0L) return 0
return ((chunkRetries.get() * 100) / sent).toInt()
}
fun asText(res: android.content.res.Resources): String = buildString {
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_connect_attempts,
connectAttempts.get(), connectSuccesses.get()))
val last = lastConnectMillis.get()
if (last > 0) appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_last_connect, last))
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_chunks,
chunksSent.get(), chunkRetries.get(), retryPercent()))
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_duplicates, duplicateChunks.get()))
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_corrupted, corruptedMessages.get()))
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_dropped, messagesDropped.get()))
}
}
@@ -0,0 +1,60 @@
package cc.skysparkle.matewave.network
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import androidx.core.content.ContextCompat
data class NetworkStatus(
val bluetoothSupported: Boolean,
val bluetoothOn: Boolean,
val wifiConnected: Boolean,
val permissionsGranted: Boolean,
val notificationsGranted: Boolean
) {
val bluetoothReady: Boolean
get() = bluetoothSupported && bluetoothOn && permissionsGranted
val lanReady: Boolean get() = wifiConnected
val anyChannelReady: Boolean get() = bluetoothReady || lanReady
val onlineBlocked: Boolean get() = !anyChannelReady
}
object NetworkRequirements {
fun check(context: Context): NetworkStatus {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
val adapter = manager?.adapter
val supported = adapter != null &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
val on = try { adapter?.isEnabled == true } catch (e: SecurityException) { false }
return NetworkStatus(
bluetoothSupported = supported,
bluetoothOn = on,
wifiConnected = isWifiConnected(context),
permissionsGranted = AppPermissions.nearby.all { granted(context, it) },
notificationsGranted = notificationsGranted(context)
)
}
private fun isWifiConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return false
val caps = cm.getNetworkCapabilities(cm.activeNetwork ?: return false) ?: return false
return caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
}
private fun notificationsGranted(context: Context): Boolean =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
granted(context, android.Manifest.permission.POST_NOTIFICATIONS)
} else true
private fun granted(context: Context, permission: String): Boolean =
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
}
@@ -0,0 +1,33 @@
package cc.skysparkle.matewave.network
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
/** Process-wide transport instances shared by presence and games. */
object Transports {
private val scope = CoroutineScope(SupervisorJob())
@Volatile private var ble: BleTransport? = null
@Volatile private var lan: LanTransport? = null
fun ble(context: Context): BleTransport =
ble ?: synchronized(this) {
ble ?: BleTransport(context.applicationContext, scope).also { ble = it }
}
fun lan(context: Context): LanTransport =
lan ?: synchronized(this) {
lan ?: LanTransport(context.applicationContext, scope).also { lan = it }
}
fun applyAnnounceSetting() {
lan?.applyAnnounceSetting()
ble?.applyAnnounceSetting()
}
fun releaseForGame() {
ble?.stopDiscovery()
lan?.stopDiscovery()
}
}