Initial SyncGames tree: agent, Android, deploy, docs.

Session-gated MinIO save sync with AppImage GUI, CLI edit/session flow, and Gitea release helper.

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
2026-07-14 22:06:36 -05:00
co-authored by Cursor
commit 0d6b0b2f80
76 changed files with 5697 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
# SyncGames Android (Kotlin + Compose)
Light UI for Path 3 session ops against MinIO over Cloudflare HTTPS.
## Features
- Settings (endpoint, keys in EncryptedSharedPreferences, device id, games JSON)
- Game list → Start / End / Status / History / Restore
- Doctor probe (PUT/GET/DELETE) to validate NGINX/Cloudflare
- Implements the same protocol as the Python agent (`docs/protocol.md`)
## Build
Open `android/` in Android Studio, sync Gradle, run on a device/emulator.
```bash
cd android
./gradlew :app:assembleDebug # after generating the Gradle wrapper in Android Studio once
```
Sideload `app/build/outputs/apk/debug/app-debug.apk`.
## First-run config
1. Settings → set `https://syncgames-s3.<your-domain>`
2. MinIO access/secret keys
3. `device_id` e.g. `phone-android`
4. Edit games JSON `nativePath` to the absolute Eden/Yuzu save folder on the device
## Note on Storage Access Framework
v1 accepts absolute paths in games JSON for devices where the save tree is readable. A SAF folder picker can be added without changing the protocol layer.
+55
View File
@@ -0,0 +1,55 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
}
android {
namespace = "com.syncgames.app"
compileSdk = 35
defaultConfig {
applicationId = "com.syncgames.app"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
}
dependencies {
val composeBom = platform("androidx.compose:compose-bom:2024.10.01")
implementation(composeBom)
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("androidx.activity:activity-compose:1.9.3")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
implementation("androidx.navigation:navigation-compose:2.8.3")
implementation("androidx.security:security-crypto:1.1.0-alpha06")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
implementation("com.amazonaws:aws-android-sdk-s3:2.77.1")
implementation("org.json:json:20240303")
debugImplementation("androidx.compose.ui:ui-tooling")
}
+1
View File
@@ -0,0 +1 @@
# Add project specific ProGuard rules here.
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.SyncGames"
android:usesCleartextTraffic="false">
<activity
android:name=".MainActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,20 @@
package com.syncgames.app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.MaterialTheme
import com.syncgames.app.ui.SyncGamesApp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MaterialTheme {
SyncGamesApp()
}
}
}
}
@@ -0,0 +1,15 @@
package com.syncgames.app
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.syncgames.app.ui.SyncGamesApp
@Preview
@Composable
fun PreviewApp() {
MaterialTheme {
// Preview placeholder — full app needs Application context for ViewModel
androidx.compose.material3.Text("SyncGames")
}
}
@@ -0,0 +1,70 @@
package com.syncgames.app.data
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
data class AppSettings(
val endpointUrl: String = "",
val bucket: String = "syncgames",
val region: String = "us-east-1",
val accessKey: String = "",
val secretKey: String = "",
val deviceId: String = "phone-android",
val gamesJson: String = DEFAULT_GAMES,
)
val DEFAULT_GAMES = """
[
{"id":"eden-saves","name":"Eden Emulator Saves","nativePath":""},
{"id":"yuzu-saves","name":"Yuzu Emulator Saves","nativePath":""}
]
""".trimIndent()
class SettingsRepository(context: Context) {
private val masterKey = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
private val prefs = EncryptedSharedPreferences.create(
context,
"syncgames_secure",
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
)
fun load(): AppSettings = AppSettings(
endpointUrl = prefs.getString("endpoint_url", "") ?: "",
bucket = prefs.getString("bucket", "syncgames") ?: "syncgames",
region = prefs.getString("region", "us-east-1") ?: "us-east-1",
accessKey = prefs.getString("access_key", "") ?: "",
secretKey = prefs.getString("secret_key", "") ?: "",
deviceId = prefs.getString("device_id", "phone-android") ?: "phone-android",
gamesJson = prefs.getString("games_json", DEFAULT_GAMES) ?: DEFAULT_GAMES,
)
fun save(settings: AppSettings) {
prefs.edit()
.putString("endpoint_url", settings.endpointUrl)
.putString("bucket", settings.bucket)
.putString("region", settings.region)
.putString("access_key", settings.accessKey)
.putString("secret_key", settings.secretKey)
.putString("device_id", settings.deviceId)
.putString("games_json", settings.gamesJson)
.apply()
}
fun setGamePath(gameId: String, path: String) {
val cur = load()
val arr = org.json.JSONArray(cur.gamesJson)
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i)
if (o.getString("id") == gameId) {
o.put("nativePath", path)
}
}
save(cur.copy(gamesJson = arr.toString(2)))
}
}
@@ -0,0 +1,34 @@
package com.syncgames.app.protocol
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
object HashUtil {
fun sha256File(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val buf = ByteArray(1024 * 1024)
while (true) {
val n = input.read(buf)
if (n <= 0) break
digest.update(buf, 0, n)
}
}
return "sha256:" + digest.digest().joinToString("") { "%02x".format(it) }
}
fun sha256Bytes(data: ByteArray): String {
val digest = MessageDigest.getInstance("SHA-256")
digest.update(data)
return "sha256:" + digest.digest().joinToString("") { "%02x".format(it) }
}
fun treeHash(fileChecksums: Map<String, String>): String {
val lines = fileChecksums.keys.sorted().joinToString("") { rel ->
val digest = fileChecksums.getValue(rel).removePrefix("sha256:")
"$rel\u0000$digest\n"
}
return sha256Bytes(lines.toByteArray(Charsets.UTF_8))
}
}
@@ -0,0 +1,96 @@
package com.syncgames.app.protocol
import org.json.JSONObject
import java.time.Instant
import java.util.UUID
data class Lease(
val holder: String,
val expiresAt: String,
val sessionId: String,
)
data class Meta(
val schema: Int = 1,
val gameId: String,
val liveHash: String?,
val fileChecksums: Map<String, String>,
val lease: Lease?,
val versionsToKeep: Int,
val updatedAt: String?,
val updatedBy: String?,
) {
fun toJson(): String {
val o = JSONObject()
o.put("schema", schema)
o.put("game_id", gameId)
o.put("live_hash", liveHash)
val files = JSONObject()
fileChecksums.forEach { (k, v) -> files.put(k, v) }
o.put("file_checksums", files)
if (lease == null) {
o.put("lease", JSONObject.NULL)
} else {
o.put(
"lease",
JSONObject()
.put("holder", lease.holder)
.put("expires_at", lease.expiresAt)
.put("session_id", lease.sessionId),
)
}
o.put("versions_to_keep", versionsToKeep)
o.put("updated_at", updatedAt)
o.put("updated_by", updatedBy)
return o.toString(2) + "\n"
}
companion object {
fun empty(gameId: String, versions: Int = 5) = Meta(
gameId = gameId,
liveHash = null,
fileChecksums = emptyMap(),
lease = null,
versionsToKeep = versions,
updatedAt = Instant.now().toString(),
updatedBy = null,
)
fun fromJson(text: String): Meta {
val o = JSONObject(text)
val filesObj = o.optJSONObject("file_checksums") ?: JSONObject()
val files = mutableMapOf<String, String>()
filesObj.keys().forEach { key -> files[key] = filesObj.getString(key) }
val leaseObj = o.optJSONObject("lease")
val lease = if (leaseObj == null || o.isNull("lease")) null else Lease(
holder = leaseObj.getString("holder"),
expiresAt = leaseObj.getString("expires_at"),
sessionId = leaseObj.getString("session_id"),
)
return Meta(
schema = o.optInt("schema", 1),
gameId = o.getString("game_id"),
liveHash = if (o.isNull("live_hash")) null else o.optString("live_hash", null),
fileChecksums = files,
lease = lease,
versionsToKeep = o.optInt("versions_to_keep", 5),
updatedAt = if (o.isNull("updated_at")) null else o.optString("updated_at"),
updatedBy = if (o.isNull("updated_by")) null else o.optString("updated_by"),
)
}
fun newLease(holder: String, ttlHours: Long = 6): Lease {
val expires = Instant.now().plusSeconds(ttlHours * 3600)
return Lease(holder, expires.toString(), UUID.randomUUID().toString())
}
}
}
fun Lease?.isActive(): Boolean {
if (this == null) return false
return try {
Instant.parse(expiresAt).isAfter(Instant.now())
} catch (_: Exception) {
false
}
}
@@ -0,0 +1,165 @@
package com.syncgames.app.protocol
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.S3ClientOptions
import com.amazonaws.services.s3.model.CopyObjectRequest
import com.amazonaws.services.s3.model.DeleteObjectRequest
import com.amazonaws.services.s3.model.ListObjectsV2Request
import com.amazonaws.services.s3.model.ObjectMetadata
import com.amazonaws.services.s3.model.PutObjectRequest
import java.io.ByteArrayInputStream
import java.io.File
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
class MinioStore(
endpointUrl: String,
private val bucket: String,
accessKey: String,
secretKey: String,
region: String = "us-east-1",
) {
private val s3: AmazonS3 = AmazonS3Client(BasicAWSCredentials(accessKey, secretKey)).apply {
setEndpoint(endpointUrl)
setS3ClientOptions(
S3ClientOptions.builder()
.setPathStyleAccess(true)
.build(),
)
// Region is mainly for signing; path-style custom endpoints ignore AWS regional hosts.
setRegion(com.amazonaws.regions.Region.getRegion(com.amazonaws.regions.Regions.fromName(region)))
}
fun getMeta(gameId: String): Meta? {
val key = "games/$gameId/meta.json"
if (!s3.doesObjectExist(bucket, key)) return null
return s3.getObjectAsString(bucket, key).let { Meta.fromJson(it) }
}
fun putMeta(gameId: String, meta: Meta) {
val bytes = meta.toJson().toByteArray(Charsets.UTF_8)
val md = ObjectMetadata().apply {
contentLength = bytes.size.toLong()
contentType = "application/json"
}
s3.putObject(PutObjectRequest(bucket, "games/$gameId/meta.json", ByteArrayInputStream(bytes), md))
}
fun listLive(gameId: String): List<String> {
val prefix = "games/$gameId/live/"
return listRels(prefix)
}
private fun listRels(prefix: String): List<String> {
val out = mutableListOf<String>()
var token: String? = null
do {
val req = ListObjectsV2Request()
.withBucketName(bucket)
.withPrefix(prefix)
.withContinuationToken(token)
val res = s3.listObjectsV2(req)
res.objectSummaries.forEach { sum ->
if (!sum.key.endsWith("/")) {
out += sum.key.removePrefix(prefix)
}
}
token = if (res.isTruncated) res.nextContinuationToken else null
} while (token != null)
return out
}
fun downloadLive(gameId: String, destDir: File): Map<String, String> {
destDir.mkdirs()
val checksums = mutableMapOf<String, String>()
val prefix = "games/$gameId/live/"
for (rel in listLive(gameId)) {
val target = File(destDir, rel)
target.parentFile?.mkdirs()
s3.getObject(bucket, prefix + rel).objectContent.use { input ->
target.outputStream().use { output -> input.copyTo(output) }
}
checksums[rel] = HashUtil.sha256File(target)
}
return checksums
}
fun uploadTree(gameId: String, kind: String, extra: String, localDir: File): Map<String, String> {
val base = when (kind) {
"live" -> "games/$gameId/live"
"history" -> "games/$gameId/history/$extra"
else -> error("bad kind")
}
val checksums = mutableMapOf<String, String>()
localDir.walkTopDown().filter { it.isFile }.forEach { file ->
val rel = file.relativeTo(localDir).invariantSeparatorsPath
s3.putObject(bucket, "$base/$rel", file)
checksums[rel] = HashUtil.sha256File(file)
}
return checksums
}
fun deleteLiveNotIn(gameId: String, keep: Set<String>) {
for (rel in listLive(gameId)) {
if (rel !in keep) {
s3.deleteObject(DeleteObjectRequest(bucket, "games/$gameId/live/$rel"))
}
}
}
fun listHistory(gameId: String): List<String> {
val prefix = "games/$gameId/history/"
val set = linkedSetOf<String>()
for (rel in listRels(prefix)) {
val parts = rel.split("/")
if (parts.size >= 2) set += "${parts[0]}/${parts[1]}"
}
return set.sortedDescending()
}
fun copyHistoryToLive(gameId: String, deviceTs: String) {
for (rel in listLive(gameId)) {
s3.deleteObject(bucket, "games/$gameId/live/$rel")
}
val srcPrefix = "games/$gameId/history/$deviceTs/"
for (rel in listRels(srcPrefix)) {
val src = srcPrefix + rel
val dst = "games/$gameId/live/$rel"
s3.copyObject(CopyObjectRequest(bucket, src, bucket, dst))
}
}
fun pruneDeviceHistory(gameId: String, deviceId: String, keep: Int) {
val prefix = "games/$gameId/history/$deviceId/"
val stamps = listRels(prefix).map { it.substringBefore("/") }.toSet().sortedDescending()
for (stamp in stamps.drop(keep)) {
for (rel in listRels("$prefix$stamp/")) {
s3.deleteObject(bucket, "$prefix$stamp/$rel")
}
}
}
fun probe(): String {
val ts = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")
.withZone(ZoneOffset.UTC)
.format(Instant.now())
val key = "games/_probe/ping-$ts.txt"
val body = "syncgames-probe\n".toByteArray()
val md = ObjectMetadata().apply { contentLength = body.size.toLong() }
s3.putObject(PutObjectRequest(bucket, key, ByteArrayInputStream(body), md))
val got = s3.getObjectAsString(bucket, key).toByteArray()
s3.deleteObject(bucket, key)
require(got.contentEquals(body)) { "probe mismatch — check NGINX buffering" }
return HashUtil.sha256Bytes(body)
}
companion object {
fun isoTs(): String =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")
.withZone(ZoneOffset.UTC)
.format(Instant.now())
}
}
@@ -0,0 +1,158 @@
package com.syncgames.app.protocol
import android.content.Context
import org.json.JSONObject
import java.io.File
import java.time.Instant
class SessionService(
private val context: Context,
private val store: MinioStore,
private val deviceId: String,
private val leaseTtlHours: Long = 6,
) {
private val sessionsDir: File
get() = File(context.filesDir, "sessions").also { it.mkdirs() }
private val wipRoot: File
get() = File(context.filesDir, "wip").also { it.mkdirs() }
fun acquireLease(gameId: String, versions: Int = 5): Meta {
var meta = store.getMeta(gameId) ?: Meta.empty(gameId, versions)
val lease = meta.lease
if (lease.isActive() && lease?.holder != deviceId) {
error("lease_held: held by ${lease?.holder} until ${lease?.expiresAt}")
}
val newLease = Meta.newLease(deviceId, leaseTtlHours)
meta = meta.copy(lease = newLease, versionsToKeep = versions)
store.putMeta(gameId, meta)
val again = store.getMeta(gameId)
if (again?.lease?.holder != deviceId) error("lease_held: lost race")
return again
}
fun start(gameId: String, nativeRoot: File, versions: Int = 5): Meta {
val meta = acquireLease(gameId, versions)
val staging = File(wipRoot, gameId).also {
if (it.exists()) it.deleteRecursively()
it.mkdirs()
}
val checksums = store.downloadLive(gameId, staging)
copyTree(staging, nativeRoot)
val parent = meta.liveHash ?: if (checksums.isNotEmpty()) HashUtil.treeHash(checksums) else null
writeSession(
gameId,
JSONObject()
.put("game_id", gameId)
.put("parent_live_hash", parent)
.put("session_id", meta.lease?.sessionId)
.put("started_at", Instant.now().toString())
.put("device_id", deviceId)
.put("native_root", nativeRoot.absolutePath),
)
return meta
}
fun end(gameId: String, nativeRoot: File, forceHash: Boolean = false): Meta {
val sess = readSession(gameId) ?: error("config_error: no local session")
val parent = if (sess.isNull("parent_live_hash")) null else sess.optString("parent_live_hash")
val staging = File(wipRoot, gameId).also {
if (it.exists()) it.deleteRecursively()
it.mkdirs()
}
copyTree(nativeRoot, staging)
val checksums = checksumTree(staging)
val wipHash = if (checksums.isEmpty()) null else HashUtil.treeHash(checksums)
var meta = store.getMeta(gameId) ?: Meta.empty(gameId)
if (!forceHash && meta.liveHash != null && parent != null && meta.liveHash != parent) {
error("stale_wip: parent $parent != live ${meta.liveHash}")
}
val ts = MinioStore.isoTs()
store.uploadTree(gameId, "history", "$deviceId/$ts", staging)
store.uploadTree(gameId, "live", "", staging)
store.deleteLiveNotIn(gameId, checksums.keys)
meta = meta.copy(
liveHash = wipHash,
fileChecksums = checksums,
lease = null,
updatedAt = Instant.now().toString(),
updatedBy = deviceId,
)
store.putMeta(gameId, meta)
store.pruneDeviceHistory(gameId, deviceId, meta.versionsToKeep)
File(sessionsDir, "$gameId.json").delete()
staging.deleteRecursively()
return meta
}
fun history(gameId: String): List<String> = store.listHistory(gameId)
fun restore(gameId: String, deviceTs: String, nativeRoot: File, versions: Int = 5): Meta {
acquireLease(gameId, versions)
store.copyHistoryToLive(gameId, deviceTs)
val staging = File(wipRoot, gameId).also {
if (it.exists()) it.deleteRecursively()
it.mkdirs()
}
val checksums = store.downloadLive(gameId, staging)
val liveHash = if (checksums.isEmpty()) null else HashUtil.treeHash(checksums)
var meta = store.getMeta(gameId) ?: Meta.empty(gameId, versions)
meta = meta.copy(
liveHash = liveHash,
fileChecksums = checksums,
updatedAt = Instant.now().toString(),
updatedBy = deviceId,
)
store.putMeta(gameId, meta)
copyTree(staging, nativeRoot)
writeSession(
gameId,
JSONObject()
.put("game_id", gameId)
.put("parent_live_hash", liveHash)
.put("session_id", meta.lease?.sessionId)
.put("started_at", Instant.now().toString())
.put("device_id", deviceId)
.put("restored_from", deviceTs)
.put("native_root", nativeRoot.absolutePath),
)
return meta
}
fun status(gameId: String): String {
val meta = store.getMeta(gameId)
val sess = readSession(gameId)
return "live=${meta?.liveHash}\nlease=${meta?.lease}\nsession=$sess"
}
private fun writeSession(gameId: String, obj: JSONObject) {
File(sessionsDir, "$gameId.json").writeText(obj.toString(2))
}
private fun readSession(gameId: String): JSONObject? {
val f = File(sessionsDir, "$gameId.json")
if (!f.exists()) return null
return JSONObject(f.readText())
}
private fun copyTree(from: File, to: File) {
if (!from.exists()) return
to.mkdirs()
from.walkTopDown().forEach { src ->
val rel = src.relativeTo(from)
val dst = File(to, rel.path)
if (src.isDirectory) dst.mkdirs()
else {
dst.parentFile?.mkdirs()
src.copyTo(dst, overwrite = true)
}
}
}
private fun checksumTree(root: File): Map<String, String> {
val out = linkedMapOf<String, String>()
root.walkTopDown().filter { it.isFile }.forEach { f ->
out[f.relativeTo(root).invariantSeparatorsPath] = HashUtil.sha256File(f)
}
return out
}
}
@@ -0,0 +1,275 @@
package com.syncgames.app.ui
import android.app.Application
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.syncgames.app.data.AppSettings
import com.syncgames.app.data.SettingsRepository
import com.syncgames.app.protocol.MinioStore
import com.syncgames.app.protocol.SessionService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import java.io.File
data class GameUi(val id: String, val name: String, val nativePath: String)
class SyncGamesViewModel(app: Application) : AndroidViewModel(app) {
private val repo = SettingsRepository(app)
private val _settings = MutableStateFlow(repo.load())
val settings: StateFlow<AppSettings> = _settings
private val _status = MutableStateFlow("")
val status: StateFlow<String> = _status
private val _history = MutableStateFlow<List<String>>(emptyList())
val history: StateFlow<List<String>> = _history
fun games(): List<GameUi> {
val arr = JSONArray(_settings.value.gamesJson)
return buildList {
for (i in 0 until arr.length()) {
val o = arr.getJSONObject(i)
add(
GameUi(
id = o.getString("id"),
name = o.optString("name", o.getString("id")),
nativePath = o.optString("nativePath", ""),
),
)
}
}
}
fun saveSettings(s: AppSettings) {
repo.save(s)
_settings.value = s
}
private fun service(): SessionService {
val s = _settings.value
require(s.endpointUrl.isNotBlank()) { "Configure endpoint URL in Settings" }
val store = MinioStore(s.endpointUrl, s.bucket, s.accessKey, s.secretKey, s.region)
return SessionService(getApplication(), store, s.deviceId)
}
fun doctor() = runOp("doctor") {
val s = _settings.value
val store = MinioStore(s.endpointUrl, s.bucket, s.accessKey, s.secretKey, s.region)
"probe_ok ${store.probe()}"
}
fun start(game: GameUi) = runOp("start") {
require(game.nativePath.isNotBlank()) { "Set native save path for ${game.id}" }
val meta = service().start(game.id, File(game.nativePath))
"Started ${game.id}; lease=${meta.lease}"
}
fun end(game: GameUi) = runOp("end") {
require(game.nativePath.isNotBlank()) { "Set native save path for ${game.id}" }
val meta = service().end(game.id, File(game.nativePath))
"Ended ${game.id}; live=${meta.liveHash}"
}
fun loadHistory(gameId: String) = runOp("history") {
val items = service().history(gameId)
_history.value = items
"history ${items.size} entries"
}
fun restore(game: GameUi, from: String) = runOp("restore") {
require(game.nativePath.isNotBlank()) { "Set native save path for ${game.id}" }
val meta = service().restore(game.id, from, File(game.nativePath))
"Restored $from; live=${meta.liveHash}"
}
fun refreshStatus(gameId: String) = runOp("status") {
service().status(gameId)
}
private fun runOp(label: String, block: () -> String) {
viewModelScope.launch {
_status.value = "$label"
_status.value = try {
withContext(Dispatchers.IO) { block() }
} catch (e: Exception) {
"error: ${e.message}"
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SyncGamesApp(vm: SyncGamesViewModel = viewModel()) {
val nav = rememberNavController()
val status by vm.status.collectAsState()
NavHost(navController = nav, startDestination = "games") {
composable("games") {
Scaffold(topBar = {
TopAppBar(
title = { Text("SyncGames") },
actions = {
TextButton(onClick = { nav.navigate("settings") }) { Text("Settings") }
},
)
}) { pad ->
GamesScreen(pad, vm, status, onOpen = { nav.navigate("game/$it") })
}
}
composable("settings") {
Scaffold(topBar = {
TopAppBar(
title = { Text("Settings") },
navigationIcon = {
TextButton(onClick = { nav.popBackStack() }) { Text("Back") }
},
)
}) { pad ->
SettingsScreen(pad, vm)
}
}
composable("game/{id}") { entry ->
val id = entry.arguments?.getString("id") ?: return@composable
Scaffold(topBar = {
TopAppBar(
title = { Text(id) },
navigationIcon = {
TextButton(onClick = { nav.popBackStack() }) { Text("Back") }
},
)
}) { pad ->
GameDetailScreen(pad, vm, id, status)
}
}
}
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
private fun GamesScreen(
pad: PaddingValues,
vm: SyncGamesViewModel,
status: String,
onOpen: (String) -> Unit,
) {
Column(Modifier.padding(pad).padding(16.dp).fillMaxSize(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(status)
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(vm.games()) { g ->
Card(onClick = { onOpen(g.id) }, modifier = Modifier.fillMaxWidth()) {
Column(Modifier.padding(16.dp)) {
Text(g.name)
Text(g.id)
Text(if (g.nativePath.isBlank()) "path: not set" else "path: ${g.nativePath}")
}
}
}
}
OutlinedButton(onClick = { vm.doctor() }) { Text("Doctor (probe MinIO)") }
}
}
@Composable
private fun SettingsScreen(pad: PaddingValues, vm: SyncGamesViewModel) {
val cur by vm.settings.collectAsState()
var endpoint by remember(cur) { mutableStateOf(cur.endpointUrl) }
var bucket by remember(cur) { mutableStateOf(cur.bucket) }
var access by remember(cur) { mutableStateOf(cur.accessKey) }
var secret by remember(cur) { mutableStateOf(cur.secretKey) }
var device by remember(cur) { mutableStateOf(cur.deviceId) }
var gamesJson by remember(cur) { mutableStateOf(cur.gamesJson) }
Column(
Modifier.padding(pad).padding(16.dp).fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(endpoint, { endpoint = it }, label = { Text("Endpoint URL") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(bucket, { bucket = it }, label = { Text("Bucket") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(access, { access = it }, label = { Text("Access key") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(secret, { secret = it }, label = { Text("Secret key") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(device, { device = it }, label = { Text("Device id") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(gamesJson, { gamesJson = it }, label = { Text("Games JSON") }, modifier = Modifier.fillMaxWidth(), minLines = 4)
Button(onClick = {
vm.saveSettings(
AppSettings(
endpointUrl = endpoint.trim(),
bucket = bucket.trim(),
accessKey = access.trim(),
secretKey = secret.trim(),
deviceId = device.trim(),
gamesJson = gamesJson,
),
)
}) { Text("Save") }
Text("Paste absolute native save folder paths into games JSON nativePath fields (SAF path picker can be added later).")
}
}
@Composable
private fun GameDetailScreen(pad: PaddingValues, vm: SyncGamesViewModel, gameId: String, status: String) {
val game = vm.games().firstOrNull { it.id == gameId } ?: return
val history by vm.history.collectAsState()
var confirmRestore by remember { mutableStateOf<String?>(null) }
Column(
Modifier.padding(pad).padding(16.dp).fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(game.name)
Text("path: ${game.nativePath.ifBlank { "(set in Settings games JSON)" }}")
Text(status)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { vm.start(game) }) { Text("Start session") }
Button(onClick = { vm.end(game) }) { Text("End session") }
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { vm.refreshStatus(game.id) }) { Text("Status") }
OutlinedButton(onClick = { vm.loadHistory(game.id) }) { Text("History") }
}
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
items(history) { item ->
OutlinedButton(onClick = { confirmRestore = item }) { Text("Restore $item") }
}
}
confirmRestore?.let { from ->
Text("Type YES conceptually: confirm restore of $from")
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = {
vm.restore(game, from)
confirmRestore = null
}) { Text("Confirm restore") }
OutlinedButton(onClick = { confirmRestore = null }) { Text("Cancel") }
}
}
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SyncGames</string>
</resources>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.SyncGames" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
+5
View File
@@ -0,0 +1,5 @@
plugins {
id("com.android.application") version "8.7.2" apply false
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
android.nonTransitiveRClass=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+16
View File
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "SyncGames"
include(":app")