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:
@@ -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")
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
@@ -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>
|
||||
Reference in New Issue
Block a user