mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Add opt-in GOG achievements through Comet (#651)
This commit is contained in:
1 parent
3ed756b067
commit
8f36eb7f54
35 files changed
+1364
-45
No files matched your search
@@ -562,7 +562,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
||||
if (drawerOpen) {
|
||||
syncLossless()
|
||||
refreshAchievementsInFront()
|
||||
padBridge?.releaseAll()
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val requested = sessionOverlay.requestFocus()
|
||||
@@ -571,6 +570,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
|
||||
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
|
||||
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
runCatching { resolveAchievementsInFront() }
|
||||
.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
}
|
||||
achievementsInFront = found
|
||||
if (found == null) achievementsOpen = false
|
||||
}
|
||||
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
|
||||
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
|
||||
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
|
||||
@@ -758,6 +766,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
achievementsInFront?.takeIf { achievementsOpen }?.let { inFront ->
|
||||
SessionAchievements(inFront.game, inFront.title, onClose = ::closeAchievements)
|
||||
}
|
||||
com.droiddeck.launcher.ui.AchievementNotificationOverlay()
|
||||
if (SessionState.suspended) SessionPausedOverlay(
|
||||
title = pausedTitle(),
|
||||
onResume = { SessionService.resume(this@SessionActivity) },
|
||||
@@ -798,35 +807,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
padBridge?.triggerQam()
|
||||
}
|
||||
|
||||
/** Re-reads so the drawer's count picks up the panel's fresh list. */
|
||||
private fun closeAchievements() {
|
||||
achievementsOpen = false
|
||||
refreshAchievementsInFront()
|
||||
}
|
||||
private fun closeAchievements() { achievementsOpen = false }
|
||||
|
||||
private fun refreshAchievementsInFront() {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM) { achievementsInFront = null; return }
|
||||
Thread({
|
||||
val found = runCatching { resolveAchievementsInFront() }.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
uiHandler.post { achievementsInFront = found }
|
||||
}, "achievements-in-front").start()
|
||||
}
|
||||
|
||||
/** Steam's focused game (a Steam title means none), else the last store launch, else the session's own game. */
|
||||
/** A live game window only; Steam's overlay may be in front of that window. */
|
||||
private fun resolveAchievementsInFront(): AchievementsInFront? {
|
||||
if (!SessionState.running || SessionState.mode != SessionService.MODE_STEAM) return null
|
||||
val snapshot = AgentGuest.focus(this) ?: return null
|
||||
val games = LibraryCache.load(this)
|
||||
fun storeOf(g: Library.SteamGame) = Store.byId(g.source)?.let { st -> g.storeId?.let { st to it } }
|
||||
val byKey = games.mapNotNull { g -> g.profileKey.toLongOrNull()?.let { it to g } }.toMap()
|
||||
val focused = runCatching { AgentGuest.activeSteamAppId(this, byKey.keys) }.getOrNull()?.let(byKey::get)
|
||||
val url = SessionState.steamUrl?.substringAfter("rungameid/", "")?.takeIf { it.isNotEmpty() }
|
||||
val (store, id) = (if (focused != null) storeOf(focused)
|
||||
else StoreLaunchRequests.lastLaunched ?: games.firstOrNull { it.gameIdString == url }?.let(::storeOf))
|
||||
?: return null
|
||||
val windows = snapshot.optJSONArray("focusableApps")?.let { list -> List(list.length()) { list.optLong(it) } }.orEmpty()
|
||||
val focusedId = snapshot.optLong("focusedApp").takeUnless { snapshot.isNull("focusedApp") }
|
||||
val appId = com.droiddeck.launcher.session.SessionAchievementGame.activeAppId(focusedId, windows, byKey.keys) ?: return null
|
||||
val focused = byKey[appId] ?: return null
|
||||
val store = Store.byId(focused.source) ?: return null
|
||||
val id = focused.storeId ?: return null
|
||||
val source = StoreAchievements.forSource(store.id) ?: return null
|
||||
val sidecar = StoreGameSidecar.find(this, store, id) ?: return null
|
||||
val game = StoreAchievements.Game.of(sidecar)
|
||||
val saved = source.cached(this, game)?.takeIf { it.isNotEmpty() }
|
||||
return AchievementsInFront(game, sidecar.title, saved?.let { l -> l.count { it.unlocked } to l.size })
|
||||
val list = source.cached(this, game) ?: (source.fetch(this, game) as? StoreAchievements.Result.Found)?.list ?: return null
|
||||
if (list.isEmpty()) return null
|
||||
return AchievementsInFront(game, sidecar.title, list.count { it.unlocked } to list.size)
|
||||
}
|
||||
|
||||
private fun togglePcKeyboard() {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import android.os.FileObserver
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -16,6 +21,9 @@ import java.util.UUID
|
||||
* whatever runs does so inside the live session with its own environment.
|
||||
*/
|
||||
object AgentGuest {
|
||||
private val main by lazy { Handler(Looper.getMainLooper()) }
|
||||
var focusRevision by mutableIntStateOf(0)
|
||||
private set
|
||||
private const val TAG = "AgentGuest"
|
||||
private const val POLL_MS = 50L
|
||||
private val lock = Any()
|
||||
@@ -70,6 +78,7 @@ object AgentGuest {
|
||||
if (key == lastFocusKey) return
|
||||
lastFocusKey = key
|
||||
}
|
||||
main.post { focusRevision++ }
|
||||
SessionEvents.record("focus.changed", fields + ("seq" to snapshot.optInt("seq")))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** An active game needs a live window; a launch URL or stale Steam base layer is insufficient. */
|
||||
internal object SessionAchievementGame {
|
||||
fun activeAppId(focused: Long?, windows: List<Long>, installed: Set<Long>): Long? {
|
||||
if (focused != null && focused > 0 && focused != 769L) {
|
||||
return focused.takeIf { it in windows && it in installed }
|
||||
}
|
||||
return windows.filter { it != 769L && it in installed }.distinct().singleOrNull()
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -334,6 +334,7 @@ class SessionService : Service() {
|
||||
SessionFiles.stage(this, root)
|
||||
com.droiddeck.launcher.agent.AgentGuest.reset(this)
|
||||
// The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included.
|
||||
com.droiddeck.launcher.stores.gog.GogComet.begin()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
@@ -1540,6 +1541,7 @@ class SessionService : Service() {
|
||||
}
|
||||
updateDownloadMonitoring()
|
||||
val stoppedGen = sessionGen
|
||||
val stoppedSession = SessionState.sessionId
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
GpuClockPin.stop(this)
|
||||
@@ -1586,13 +1588,14 @@ class SessionService : Service() {
|
||||
if (prootPid > 1 || auxiliary.isNotEmpty()) {
|
||||
Thread({
|
||||
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
finishSessionStop(status, stoppedGen)
|
||||
Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession); finishSessionStop(status, stoppedGen) }, "gog-session-stop").start()
|
||||
}
|
||||
}
|
||||
if (prootPid > 1) acquireLocks()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Session-owned unlocks; history reads and upload acknowledgements never create notifications. */
|
||||
object AchievementNotifications {
|
||||
data class Unlock(val client: String, val id: String, val name: String, val description: String, val icon: String?, val game: String)
|
||||
|
||||
private var session: String? = null
|
||||
private val seen = HashSet<String>()
|
||||
var pending by mutableStateOf<List<Unlock>>(emptyList())
|
||||
private set
|
||||
|
||||
fun begin(owner: String?) = StoresState.post {
|
||||
session = owner
|
||||
seen.clear()
|
||||
pending = emptyList()
|
||||
}
|
||||
|
||||
fun end(owner: String?) = StoresState.post {
|
||||
if (session == owner) {
|
||||
session = null
|
||||
seen.clear()
|
||||
pending = emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
fun unlock(owner: String, unlock: Unlock) = StoresState.post {
|
||||
if (session == owner && seen.add("${unlock.client}:${unlock.id}")) {
|
||||
pending = (pending + unlock).take(16)
|
||||
}
|
||||
}
|
||||
|
||||
fun dismiss(unlock: Unlock) {
|
||||
if (pending.firstOrNull() === unlock) pending = pending.drop(1)
|
||||
}
|
||||
|
||||
/** Only presentation fields from the owned daemon, bounded before entering Compose. */
|
||||
fun parse(event: JSONObject, game: String): Unlock? {
|
||||
val client = event.optString("client_id")
|
||||
val id = event.optString("id")
|
||||
val name = event.optString("name").trim()
|
||||
if (!client.matches(Regex("[0-9]{1,32}")) || id.isBlank() || id.length > 256 || name.isEmpty()) return null
|
||||
val icon = event.optString("icon").takeIf { it.length <= 2048 && it.startsWith("https://") }
|
||||
return Unlock(client, id, name.take(256), event.optString("description").take(1024), icon, game.take(256))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.epic.EpicAchievements
|
||||
import com.droiddeck.launcher.stores.gog.GogAchievements
|
||||
import org.json.JSONArray
|
||||
@@ -94,6 +96,9 @@ abstract class StoreAchievements(val source: String, val label: String) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "StoreAchievements"
|
||||
var revision by androidx.compose.runtime.mutableIntStateOf(0)
|
||||
private set
|
||||
fun invalidate() { revision++ }
|
||||
|
||||
private val all: List<StoreAchievements> by lazy { listOf(GogAchievements, EpicAchievements) }
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ class StoreGameSidecar(
|
||||
val epic: EpicOptions = EpicOptions(),
|
||||
/** GOG / Epic cloud saves for this game: down before a launch, up after it (the game card's switch). */
|
||||
val cloud: Boolean = true,
|
||||
val achievements: Boolean = true,
|
||||
) {
|
||||
val isInstalled: Boolean get() = state == STATE_INSTALLED
|
||||
|
||||
@@ -53,8 +54,8 @@ class StoreGameSidecar(
|
||||
exe: String = this.exe, launcher: String? = this.launcher, args: List<String> = this.args,
|
||||
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
|
||||
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
|
||||
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud,
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud)
|
||||
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud, achievements: Boolean = this.achievements,
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements)
|
||||
|
||||
fun toJson(): JSONObject = JSONObject().apply {
|
||||
put("version", VERSION)
|
||||
@@ -65,6 +66,7 @@ class StoreGameSidecar(
|
||||
if (state != STATE_INSTALLED) put("state", state)
|
||||
if (store == Store.EPIC) put("epic", JSONObject().put("eos", epic.eos).put("offline", epic.offline))
|
||||
if (store != Store.AMAZON) put("cloud", cloud)
|
||||
if (store == Store.GOG) put("achievements", achievements)
|
||||
if (!launcher.isNullOrEmpty()) put("launcher", launcher)
|
||||
if (args.isNotEmpty()) put("args", JSONArray(args))
|
||||
if (env.isNotEmpty()) put("env", JSONObject(env as Map<*, *>))
|
||||
@@ -116,6 +118,12 @@ class StoreGameSidecar(
|
||||
return read(folder)?.takeIf { it.cloud == on }
|
||||
}
|
||||
|
||||
fun updateAchievements(folder: File, on: Boolean): StoreGameSidecar? {
|
||||
val current = read(folder) ?: return null
|
||||
current.copy(achievements = on).write(folder)
|
||||
return read(folder)?.takeIf { it.achievements == on }
|
||||
}
|
||||
|
||||
/** The sidecar in [folder], or null when there is none or it cannot be read. */
|
||||
fun read(folder: File): StoreGameSidecar? {
|
||||
val f = file(folder)
|
||||
@@ -153,6 +161,7 @@ class StoreGameSidecar(
|
||||
// An "overlay" (or "v") field from an earlier build is read past: there is no overlay.
|
||||
epic = o.optJSONObject("epic")?.let { e -> EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false)) } ?: EpicOptions(),
|
||||
cloud = o.optBoolean("cloud", true),
|
||||
achievements = o.optBoolean("achievements", true),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ object StoreInstalls {
|
||||
onStep?.invoke(0, STEPS)
|
||||
// The user's launch choices survive an update or a repair.
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud))
|
||||
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud, achievements = before?.achievements ?: sidecar.achievements))
|
||||
finished.write(folder)
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled != true) throw java.io.IOException("the install record could not be written in ${folder.name}")
|
||||
onStep?.invoke(1, STEPS)
|
||||
|
||||
@@ -59,6 +59,8 @@ object StoreLaunchRequests {
|
||||
return // withdrawn already, or not complete yet (the rename brings it again)
|
||||
}
|
||||
val reply = when (request.optString("op")) {
|
||||
"gog-achievements" -> runCatching { com.droiddeck.launcher.stores.gog.GogComet.prepare(app, request.optString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("ready", false).put("reason", "service-unavailable") }
|
||||
"epic-code" -> {
|
||||
val id = request.optString("id")
|
||||
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
|
||||
|
||||
@@ -174,7 +174,8 @@ object StoresState {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
backends[store]?.signOut(app)
|
||||
StoreAccounts.clear(app, store)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else StoreAccounts.clear(app, store)
|
||||
main.post {
|
||||
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store)
|
||||
logLine("${store.label}: signed out")
|
||||
|
||||
@@ -33,7 +33,12 @@ object GogAuth {
|
||||
fun isSignedIn(context: Context): Boolean = StoreAccounts.read(context, Store.GOG)?.optString("access_token", "")?.isNotEmpty() == true
|
||||
|
||||
/** Saves a fresh sign-in and looks the account's name up for the chip. Blocking. */
|
||||
fun saveLogin(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
|
||||
fun saveLogin(context: Context, accessToken: String, refreshToken: String?, userId: String?) = GogComet.replaceAccount {
|
||||
saveAccount(context, accessToken, refreshToken, userId)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun saveAccount(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
|
||||
var username = ""
|
||||
runCatching {
|
||||
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = accessToken, userAgent = GALAXY_UA)
|
||||
@@ -52,6 +57,7 @@ object GogAuth {
|
||||
|
||||
/** A usable access token, refreshed when the recorded login time says it has expired; null when signed out or the refresh failed. */
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun validToken(context: Context): String? {
|
||||
val json = StoreAccounts.read(context, Store.GOG) ?: return null
|
||||
val token = json.optString("access_token", "").ifEmpty { return null }
|
||||
@@ -63,6 +69,7 @@ object GogAuth {
|
||||
|
||||
/** Refreshes the access token; the new one, or null on any failure. Blocking. */
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun refresh(context: Context): String? {
|
||||
val json = StoreAccounts.read(context, Store.GOG) ?: return null
|
||||
val refreshToken = json.optString("refresh_token", "").ifEmpty { return null }
|
||||
@@ -87,6 +94,27 @@ object GogAuth {
|
||||
}
|
||||
}
|
||||
|
||||
/** A complete companion snapshot. Never exported through the guest request channel. */
|
||||
@Synchronized
|
||||
fun cometCredentials(context: Context): JSONObject? {
|
||||
val access = validToken(context) ?: return null
|
||||
val saved = StoreAccounts.read(context, Store.GOG) ?: return null
|
||||
val refresh = saved.optString("refresh_token").ifEmpty { return null }
|
||||
var user = saved.optString("user_id")
|
||||
var username = saved.optString("username")
|
||||
if (!user.matches(Regex("[0-9]+")) || username.isEmpty()) {
|
||||
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = access, userAgent = GALAXY_UA, timeoutMs = 5_000) ?: return null
|
||||
val info = runCatching { JSONObject(body) }.getOrNull() ?: return null
|
||||
user = info.optString("galaxyUserId", info.optString("userId", user))
|
||||
username = info.optString("username", username)
|
||||
if (!user.matches(Regex("[0-9]+")) || username.isEmpty()) return null
|
||||
saved.put("user_id", user).put("username", username)
|
||||
StoreAccounts.write(context, Store.GOG, saved)
|
||||
}
|
||||
return JSONObject().put("access_token", access).put("refresh_token", refresh)
|
||||
.put("user_id", user).put("username", username)
|
||||
}
|
||||
|
||||
class GameToken(val accessToken: String, val userId: String)
|
||||
|
||||
/** The Galaxy refresh token exchanged for one scoped to a game's own client. Blocking. */
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.AchievementNotifications
|
||||
import com.droiddeck.launcher.stores.StoreAchievements
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Owns one Galaxy companion; only its structured, secret-free events reach Android logs. */
|
||||
object GogComet {
|
||||
private const val TAG = "GogComet"
|
||||
private const val BIN = "/usr/local/lib/droiddeck-comet/comet"
|
||||
private val lock = Any()
|
||||
@Volatile private var process: Process? = null
|
||||
private var pid = -1
|
||||
private var started: String? = null
|
||||
private var account = ""
|
||||
private var session: String? = null
|
||||
private var accepting = false
|
||||
private var generation: String? = null
|
||||
@Volatile private var gamesByClient: Map<String, StoreGameSidecar> = emptyMap()
|
||||
var status by mutableStateOf("off")
|
||||
private set
|
||||
|
||||
fun enabled(context: Context) = GogPrefs.get(context).getBoolean("achievements", false)
|
||||
|
||||
fun setEnabled(context: Context, on: Boolean) {
|
||||
GogPrefs.get(context).edit().putBoolean("achievements", on).apply()
|
||||
|
||||
}
|
||||
|
||||
fun begin() = synchronized(lock) {
|
||||
stopLocked()
|
||||
accepting = true
|
||||
generation = SessionState.sessionId
|
||||
AchievementNotifications.begin(generation)
|
||||
}
|
||||
|
||||
/** Account replacement and launch preparation use the same lock, preventing stale restarts. */
|
||||
fun replaceAccount(change: () -> Unit) = synchronized(lock) {
|
||||
stopLocked()
|
||||
AchievementNotifications.begin(generation)
|
||||
change()
|
||||
}
|
||||
|
||||
fun stop() = synchronized(lock) {
|
||||
stopLocked()
|
||||
}
|
||||
|
||||
fun end(expected: String?) = synchronized(lock) {
|
||||
if (generation == expected) {
|
||||
accepting = false
|
||||
stopLocked()
|
||||
AchievementNotifications.end(expected)
|
||||
generation = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun report(value: String) {
|
||||
StoresState.post { status = value }
|
||||
Log.i(TAG, value)
|
||||
SessionEvents.record("gog.achievements", mapOf("status" to value))
|
||||
}
|
||||
|
||||
private fun publishPolicy(context: Context): File {
|
||||
val dir = File(context.filesDir, "gog-achievements").apply { mkdirs() }
|
||||
val games = if (!enabled(context)) emptyMap() else StoreInstallRoot.gameFolders(context).mapNotNull { folder ->
|
||||
val game = StoreGameSidecar.read(folder) ?: return@mapNotNull null
|
||||
if (game.store != Store.GOG || !game.achievements) return@mapNotNull null
|
||||
val client = GogPrefs.get(context).getString("client_id_${game.id}", null)
|
||||
?: runCatching { JSONObject(File(folder, "goggame-${game.id}.info").readText()).optString("clientId") }.getOrNull()
|
||||
client?.takeIf { it.matches(Regex("[0-9]+")) }?.let { it to game }
|
||||
}.toMap()
|
||||
gamesByClient = games
|
||||
val file = File(dir, "clients.json")
|
||||
val tmp = File(dir, "clients.json.tmp")
|
||||
tmp.writeText(org.json.JSONArray(games.keys.toList()).toString())
|
||||
check(tmp.renameTo(file))
|
||||
return file
|
||||
}
|
||||
|
||||
/** No arbitrary paths or credentials from the guest are accepted. */
|
||||
fun prepare(context: Context, id: String): JSONObject = synchronized(lock) {
|
||||
fun reply(ready: Boolean, reason: String): JSONObject {
|
||||
report(reason)
|
||||
return JSONObject().put("ok", ready).put("ready", ready).put("reason", reason)
|
||||
}
|
||||
if (!accepting || !SessionState.running || generation != SessionState.sessionId) return reply(false, "no-session")
|
||||
val folder = StoreInstallRoot.gameFolders(context).firstOrNull { f -> StoreGameSidecar.read(f)?.let { it.store == Store.GOG && it.id == id } == true }
|
||||
val sidecar = folder?.let { StoreGameSidecar.read(it) }
|
||||
if (sidecar?.store != Store.GOG || sidecar.id != id) return reply(false, "no-game")
|
||||
val policy = publishPolicy(context)
|
||||
if (!enabled(context) || !sidecar.achievements) return reply(false, "off")
|
||||
val credentials = GogAuth.cometCredentials(context) ?: return reply(false,
|
||||
if (StoreAccounts.isUnavailable(Store.GOG)) "credentials-unavailable"
|
||||
else if (StoreAccounts.read(context, Store.GOG)?.optString("refresh_token").isNullOrEmpty()) "sign-in-needed" else "credentials-unavailable")
|
||||
if (!SessionState.running || generation != SessionState.sessionId) return reply(false, "no-session")
|
||||
val user = credentials.getString("user_id")
|
||||
if (process?.isAlive == true && account == user && session == SessionState.sessionId && identity(pid) == started) {
|
||||
return JSONObject().put("ok", true).put("ready", true).put("reason", "ready")
|
||||
}
|
||||
stopLocked()
|
||||
if (!File(LinuxRuntime.rootDir(context), BIN.removePrefix("/")).isFile) return reply(false, "not-installed")
|
||||
val data = File(context.filesDir, "gog-achievements").apply { mkdirs() }
|
||||
val ready = CountDownLatch(1)
|
||||
val command = LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(),
|
||||
listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin"))
|
||||
val pb = ProcessBuilder(command).redirectErrorStream(true)
|
||||
pb.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", context.cacheDir.path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
try {
|
||||
val child = pb.start()
|
||||
process = child; account = user; session = SessionState.sessionId
|
||||
Thread({
|
||||
runCatching { child.inputStream.bufferedReader().useLines { lines -> lines.forEach { line ->
|
||||
// Raw upstream errors/payloads can contain tokens. Never forward them.
|
||||
when {
|
||||
line.startsWith("DROIDDECK_COMET_READY:") -> {
|
||||
val childPid = line.substringAfter(':').toIntOrNull() ?: -1
|
||||
if (childPid > 1 && process === child) {
|
||||
pid = childPid; started = identity(childPid); ready.countDown()
|
||||
}
|
||||
}
|
||||
line.startsWith("DROIDDECK_COMET_UNLOCKED:") -> if (process === child) {
|
||||
val event = runCatching { JSONObject(line.substringAfter(':')) }.getOrNull()
|
||||
val game = event?.optString("client_id")?.let { gamesByClient[it] }
|
||||
val unlock = event?.let { AchievementNotifications.parse(it, game?.title.orEmpty()) }
|
||||
val owner = session
|
||||
if (game != null && unlock != null && owner != null && owner == SessionState.sessionId && SessionState.running) {
|
||||
report("unlocked-locally")
|
||||
AchievementNotifications.unlock(owner, unlock)
|
||||
SessionEvents.record("achievement.unlocked", mapOf("store" to "gog", "gameId" to game.id, "achievementId" to unlock.id))
|
||||
}
|
||||
}
|
||||
line == "DROIDDECK_COMET_PENDING" -> if (process === child) report("pending-upload")
|
||||
line.startsWith("DROIDDECK_COMET_UPLOADED:") -> if (process === child && line.substringAfter(':').toIntOrNull()?.let { it > 0 } == true) { report("uploaded"); StoresState.post { StoreAchievements.invalidate() } }
|
||||
}
|
||||
} } }
|
||||
if (process === child) report("service-unavailable")
|
||||
ready.countDown()
|
||||
}, "gog-comet-output").start()
|
||||
child.outputStream.bufferedWriter().use { it.write(credentials.toString()) }
|
||||
if (!ready.await(5, TimeUnit.SECONDS) || pid <= 1 || started == null || !child.isAlive) {
|
||||
stopLocked(); return reply(false, "service-unavailable")
|
||||
}
|
||||
reply(true, "ready")
|
||||
} catch (e: Exception) {
|
||||
stopLocked()
|
||||
reply(false, "service-unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
private fun identity(pid: Int): String? = if (pid <= 1) null else runCatching {
|
||||
File("/proc/$pid/stat").readText().substringAfterLast(") ").split(' ')[19]
|
||||
}.getOrNull()
|
||||
|
||||
private fun stopLocked() {
|
||||
val child = process ?: return
|
||||
// Signal the announced daemon, not proot; start time prevents signalling a reused PID.
|
||||
if (started != null && identity(pid) == started) android.os.Process.sendSignal(pid, 2)
|
||||
if (!child.waitFor(5, TimeUnit.SECONDS)) {
|
||||
if (started != null && identity(pid) == started) android.os.Process.sendSignal(pid, 15)
|
||||
child.destroy()
|
||||
}
|
||||
process = null; pid = -1; started = null; account = ""; session = null
|
||||
report("stopped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.stores.AchievementNotifications
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
internal fun AchievementNotificationOverlay() {
|
||||
val unlock = AchievementNotifications.pending.firstOrNull()
|
||||
var visible by remember(unlock) { mutableStateOf(false) }
|
||||
LaunchedEffect(unlock) {
|
||||
if (unlock == null) return@LaunchedEffect
|
||||
visible = true
|
||||
SessionEvents.record("achievement.notification-shown", mapOf("achievementId" to unlock.id))
|
||||
delay(5_000)
|
||||
visible = false
|
||||
delay(Motion.ms(220).toLong())
|
||||
AchievementNotifications.dismiss(unlock)
|
||||
}
|
||||
Box(Modifier.fillMaxSize().padding(20.dp), contentAlignment = Alignment.BottomEnd) {
|
||||
AnimatedVisibility(
|
||||
visible, enter = fadeIn(Motion.tw(220)) + slideInVertically(Motion.tw(300)) { it / 2 },
|
||||
exit = fadeOut(Motion.tw(180)) + slideOutVertically(Motion.tw(220)) { it / 3 },
|
||||
) { if (unlock != null) AchievementNotificationCard(unlock) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AchievementNotificationCard(unlock: AchievementNotifications.Unlock) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Row(
|
||||
Modifier.widthIn(max = 360.dp).clip(shape).background(pal.surface.copy(alpha = 0.97f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.65f), shape).padding(14.dp)
|
||||
.testTag("achievement-notification"),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Box(Modifier.size(48.dp).clip(RoundedCornerShape(10.dp)).background(pal.surfaceVariant), contentAlignment = Alignment.Center) {
|
||||
Trophy(26.dp, description = null)
|
||||
if (unlock.icon != null) AsyncImage(unlock.icon, null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Trophy(13.dp, description = null)
|
||||
Text(stringResource(R.string.achievement_unlocked).uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.8.sp, color = pal.signal)
|
||||
}
|
||||
Text(unlock.name, color = pal.onBackground, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (unlock.game.isNotBlank()) Text(unlock.game, color = pal.onSurfaceVariant, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Preview(widthDp = 420, heightDp = 150)
|
||||
@Composable
|
||||
private fun AchievementNotificationPreview() = DroidDeckTheme {
|
||||
Box(Modifier.padding(20.dp)) {
|
||||
AchievementNotificationCard(AchievementNotifications.Unlock("1", "first", "First Steps", "", null, "Hollow Valley"))
|
||||
}
|
||||
}
|
||||
@@ -495,8 +495,8 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
// An Epic game's own launch choices, kept in its sidecar so a launch from the Steam client
|
||||
// honours them too (droiddeck-store-launch reads the same file).
|
||||
// Epic's launch choices; cloud saves live in the game's Cloud saves view, so a GOG game has no card.
|
||||
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC }
|
||||
// Store launch choices; cloud saves have their own view.
|
||||
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
|
||||
if (cardStore != null && game?.gameFiles != null) add { m ->
|
||||
Box(m) {
|
||||
StoreLaunchCard(host, game.gameFiles!!, cardStore)
|
||||
@@ -537,7 +537,14 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
||||
val options = sidecar?.epic ?: com.droiddeck.launcher.stores.EpicOptions()
|
||||
val epic = store == com.droiddeck.launcher.stores.Store.EPIC
|
||||
val key = "store-" + store.id
|
||||
val value = buildList {
|
||||
val value = if (!epic) stringResource(when {
|
||||
!com.droiddeck.launcher.stores.gog.GogComet.enabled(appContext) || sidecar?.achievements == false -> R.string.gog_achievements_off
|
||||
com.droiddeck.launcher.stores.gog.GogComet.status == "sign-in-needed" -> R.string.gog_achievements_signin
|
||||
com.droiddeck.launcher.stores.gog.GogComet.status in listOf("service-unavailable", "credentials-unavailable", "not-installed") -> R.string.gog_achievements_unavailable
|
||||
com.droiddeck.launcher.stores.gog.GogComet.status == "uploaded" -> R.string.gog_achievements_uploaded
|
||||
com.droiddeck.launcher.stores.gog.GogComet.status == "pending-upload" || com.droiddeck.launcher.stores.gog.GogComet.status == "unlocked-locally" -> R.string.gog_achievements_pending
|
||||
else -> R.string.gog_achievements_on
|
||||
}) else buildList {
|
||||
if (epic && options.offline) add(stringResource(R.string.epic_card_offline))
|
||||
else if (epic && options.eos) add(stringResource(R.string.epic_card_eos))
|
||||
}.ifEmpty { listOf(stringResource(R.string.epic_card_none)) }.joinToString(" · ")
|
||||
@@ -556,6 +563,16 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
||||
host.open = if (host.open == key) null else key
|
||||
}
|
||||
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = store.shortLabel) { first ->
|
||||
if (!epic) {
|
||||
MenuItem(stringResource(R.string.gog_achievements), checked = sidecar?.achievements != false, focusRequester = first,
|
||||
detail = if (!com.droiddeck.launcher.stores.gog.GogComet.enabled(appContext)) stringResource(R.string.gog_achievements_enable_store) else null) {
|
||||
val on = sidecar?.achievements == false
|
||||
Thread({
|
||||
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateAchievements(folder, on) }.getOrNull()
|
||||
com.droiddeck.launcher.stores.StoresState.post { sidecar = written ?: sidecar }
|
||||
}, "gog-game-achievements").start()
|
||||
}
|
||||
}
|
||||
if (epic) {
|
||||
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
|
||||
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
|
||||
|
||||
@@ -78,7 +78,7 @@ internal class AchievementsState(val list: List<Achievement>?, val reason: Reaso
|
||||
internal fun rememberAchievements(game: StoreAchievements.Game?): AchievementsState? {
|
||||
val ctx = LocalContext.current.applicationContext
|
||||
var state by remember(game) { mutableStateOf(if (game == null) null else AchievementsState.READING) }
|
||||
LaunchedEffect(game) {
|
||||
LaunchedEffect(game, StoreAchievements.revision) {
|
||||
if (game == null) return@LaunchedEffect
|
||||
val source = StoreAchievements.forSource(game.source) ?: return@LaunchedEffect
|
||||
val cached = withContext(Dispatchers.IO) { source.cached(ctx, game) }
|
||||
@@ -101,8 +101,8 @@ internal fun achievementsNote(state: AchievementsState, label: String): String?
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Trophy(size: Dp = 18.dp, modifier: Modifier = Modifier) {
|
||||
Icon(Icons.Filled.EmojiEvents, stringResource(R.string.achievements_all), modifier.size(size), tint = TrophyGold)
|
||||
internal fun Trophy(size: Dp = 18.dp, modifier: Modifier = Modifier, description: String? = stringResource(R.string.achievements_all)) {
|
||||
Icon(Icons.Filled.EmojiEvents, description, modifier.size(size), tint = TrophyGold)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -553,6 +553,14 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
|
||||
}
|
||||
// The queue's two knobs as one compact row, the same control the Downloads page has.
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DownloadControls(st, a) }
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
var gogAchievements by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(com.droiddeck.launcher.stores.gog.GogComet.enabled(context)) }
|
||||
SettingsRow(stringResource(R.string.gog_achievements), stringResource(R.string.gog_achievements_hint)) {
|
||||
ToggleSwitch(gogAchievements, label = stringResource(R.string.gog_achievements)) {
|
||||
gogAchievements = it
|
||||
com.droiddeck.launcher.stores.gog.GogComet.setEnabled(context, it)
|
||||
}
|
||||
}
|
||||
StoresEngineRow()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user