mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat(stores): add Rockstar store and classic GTA launches
This commit is contained in:
1 parent
9cc37d0a12
commit
b841b232b4
42 files changed
+2708
-22
No files matched your search
@@ -72,6 +72,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ubisoft.UbisoftBackend)
|
||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
||||
}
|
||||
|
||||
private fun prefetchAddonPacks() {
|
||||
|
||||
@@ -418,6 +418,7 @@ object AddedGames {
|
||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
|
||||
run {
|
||||
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
|
||||
if (sidecar?.store == Store.ROCKSTAR && (!com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id) || sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) return
|
||||
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
|
||||
val ranking = rank(folder, reuse)
|
||||
val candidates = ranking.exes
|
||||
@@ -433,6 +434,7 @@ object AddedGames {
|
||||
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
||||
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
|
||||
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
|
||||
if (sidecar?.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarLaunch.applyDefaults(context, sidecar.id, appId)
|
||||
val config = accountConfig(SessionPrefs.activeSteamRoot(context))
|
||||
val record = config?.let { shortcutRecord(it, appId) }
|
||||
val rev = record?.optInt("rev", 0) ?: 0
|
||||
|
||||
@@ -70,6 +70,8 @@ object SessionFiles {
|
||||
GameEnvironmentStore.publish(context)
|
||||
WinComponents.publish(context)
|
||||
val files = arrayOf(
|
||||
"rockstar/helpers/Launcher32.exe" to "usr/local/lib/droiddeck-rockstar/Launcher32.exe",
|
||||
"rockstar/helpers/Launcher64.exe" to "usr/local/lib/droiddeck-rockstar/Launcher64.exe",
|
||||
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
|
||||
"usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu",
|
||||
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
|
||||
@@ -241,7 +243,7 @@ object SessionFiles {
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("linuxfs/$asset").use { input ->
|
||||
(if (asset.startsWith("rockstar/")) requireNotNull(javaClass.getResourceAsStream("/$asset")) else context.assets.open("linuxfs/$asset")).use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setExecutable(true, false) && staged.renameTo(target)
|
||||
|
||||
@@ -87,7 +87,7 @@ object CloudSaves {
|
||||
val item = sidecar.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> ""
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> ""
|
||||
} ?: return null
|
||||
p.edit()
|
||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||
@@ -148,7 +148,7 @@ object CloudSaves {
|
||||
val dir = when (store) {
|
||||
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
|
||||
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
@@ -173,7 +173,7 @@ object CloudSaves {
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
|
||||
}
|
||||
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
|
||||
|
||||
@@ -15,6 +15,7 @@ internal object LoginFlows {
|
||||
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
|
||||
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
|
||||
Store.EA -> eaFlow(browserUserAgent)
|
||||
Store.ROCKSTAR -> rockstarFlow(browserUserAgent)
|
||||
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
}
|
||||
|
||||
@@ -22,6 +23,7 @@ internal object LoginFlows {
|
||||
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var ubisoftFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var eaFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var rockstarFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
|
||||
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
|
||||
@@ -9,7 +9,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
|
||||
BATTLENET("battlenet", "Battle.net", "Battle.net"),
|
||||
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
|
||||
EA("ea", "EA", "EA");
|
||||
EA("ea", "EA", "EA"),
|
||||
ROCKSTAR("rockstar", "Rockstar Games", "Rockstar");
|
||||
|
||||
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
||||
|
||||
|
||||
@@ -67,8 +67,8 @@ object StoreAccounts {
|
||||
fun write(context: Context, store: Store, json: JSONObject) {
|
||||
unavailable.remove(store)
|
||||
val f = credentialsFile(context, store)
|
||||
if (seal(f, json, retry = store == Store.XBOX) == null) {
|
||||
check(store != Store.XBOX) { "Android Keystore is unavailable for Xbox credentials" }
|
||||
if (seal(f, json, retry = store == Store.XBOX || store == Store.ROCKSTAR) == null) {
|
||||
check(store != Store.XBOX && store != Store.ROCKSTAR) { "Android Keystore is unavailable for ${store.label} credentials" }
|
||||
put(f, json.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,8 +18,13 @@ object StoreLaunch {
|
||||
const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe"
|
||||
|
||||
fun writeLauncher(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
|
||||
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT
|
||||
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT || sidecar.store == Store.ROCKSTAR
|
||||
val file = File(folder, LAUNCHER)
|
||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null)
|
||||
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) {
|
||||
file.delete()
|
||||
return sidecar.copy(launcher = null)
|
||||
}
|
||||
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
|
||||
file.writeText(launcherText(sidecar))
|
||||
return sidecar.copy(launcher = LAUNCHER)
|
||||
@@ -32,7 +37,7 @@ object StoreLaunch {
|
||||
val lines = ArrayList<String>()
|
||||
lines += "@echo off"
|
||||
lines += "setlocal"
|
||||
lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
|
||||
if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
|
||||
lines += "cd /d \"%~dp0$dir\""
|
||||
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
||||
val args = sidecar.args.joinToString(" ") { quoteArg(it) }
|
||||
@@ -54,6 +59,9 @@ object StoreLaunch {
|
||||
lines += "del \"%~dp0$EPIC_ARGS\""
|
||||
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
|
||||
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
|
||||
} else if (sidecar.store == Store.ROCKSTAR) {
|
||||
lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\""
|
||||
lines += "exit /b %errorlevel%"
|
||||
} else if (sidecar.store == Store.UBISOFT) {
|
||||
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
|
||||
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
|
||||
@@ -93,11 +101,12 @@ object StoreLaunch {
|
||||
return Library.addedGame(context, game)
|
||||
}
|
||||
|
||||
/** Gives a Ubisoft game installed before it needed one the launcher that starts the launcher service. */
|
||||
fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
|
||||
if (sidecar.store != Store.UBISOFT || !sidecar.isInstalled) return sidecar
|
||||
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
||||
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) return sidecar
|
||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
||||
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
||||
if (sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
|
||||
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
|
||||
val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
||||
if (exe == sidecar.exe && sidecar.launcher == LAUNCHER &&
|
||||
runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar
|
||||
|
||||
@@ -76,6 +76,14 @@ object StoreLaunchRequests {
|
||||
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason)
|
||||
}
|
||||
}
|
||||
"rockstar-launch" -> runCatching {
|
||||
lastLaunched = Store.ROCKSTAR to request.optString("id")
|
||||
com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id"))
|
||||
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"rockstar-exited" -> {
|
||||
if (lastLaunched == (Store.ROCKSTAR to request.optString("id"))) lastLaunched = null
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"ubisoft-launch" -> {
|
||||
val id = request.optString("id")
|
||||
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
|
||||
|
||||
@@ -66,6 +66,7 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
|
||||
fun pageReady(result: String): Boolean = true
|
||||
fun forgetSignIn(done: () -> Unit) = done()
|
||||
fun pageFinished(view: WebView, url: String) {}
|
||||
}
|
||||
|
||||
private var store: Store? = null
|
||||
@@ -283,6 +284,7 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
if (!isPopup && url != null && view != null) flow?.pageFinished(view, url)
|
||||
if (url != null && view != null && flow?.readsPage == true && flow?.isRedirect(url) == true) complete(view, url)
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ object StoreSizes {
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.ITCH, Store.GAMEJOLT -> {}
|
||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> {}
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> {}
|
||||
}
|
||||
}
|
||||
}, pool).exceptionally { error ->
|
||||
@@ -132,7 +132,7 @@ object StoreSizes {
|
||||
AmazonManifest.parse(bytes).totalInstallSize
|
||||
}
|
||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaSizes.size(context, item)
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> 0L
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
||||
} }
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.webkit.CookieManager
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.security.SecureRandom
|
||||
|
||||
object RockstarAuth {
|
||||
private const val TAG = "RockstarAuth"
|
||||
const val SIGN_IN_HOST = "https://signin.rockstargames.com"
|
||||
private const val LAUNCHER_SITE = "https://rgl.rockstargames.com"
|
||||
private const val GATEWAY = "$LAUNCHER_SITE/api/connect/gateway"
|
||||
|
||||
const val START_URL = "$SIGN_IN_HOST/robots.txt"
|
||||
|
||||
const val CODE_URL = "$SIGN_IN_HOST/droiddeck/auth-code"
|
||||
val SIGN_IN_URLS = listOf(SIGN_IN_HOST, LAUNCHER_SITE, "https://www.rockstargames.com", "https://socialclub.rockstargames.com")
|
||||
const val COOKIE_DOMAIN = ".rockstargames.com"
|
||||
|
||||
const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
|
||||
private const val PREFS = "stores.rockstar"
|
||||
private const val TICKET_MARGIN_MS = 15 * 60 * 1000L
|
||||
private val lock = Any()
|
||||
|
||||
class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long)
|
||||
|
||||
internal fun fingerprint(context: Context): JSONObject {
|
||||
val p = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
fun stable(key: String, bytes: Int): String = p.getString(key, null) ?: ByteArray(bytes).also { SecureRandom().nextBytes(it) }
|
||||
.joinToString("") { "%02x".format(it) }.also { p.edit().putString(key, it).apply() }
|
||||
val device = "DROIDDECK-" + (Build.MODEL ?: "ANDROID").uppercase().replace(Regex("[^A-Z0-9]"), "").take(12)
|
||||
return fingerprintOf(device, stable("volume_serial", 4), stable("cpu_info", 8))
|
||||
}
|
||||
|
||||
internal fun fingerprintOf(device: String, volume: String, cpu: String): JSONObject = JSONObject()
|
||||
.put("device_name", device)
|
||||
.put("machine_name", device)
|
||||
.put("os_version", "10.0.19045")
|
||||
.put("volume_serial", volume)
|
||||
.put("cpu_info", cpu)
|
||||
|
||||
internal fun state(fingerprint: JSONObject) = "{\"fp\": $fingerprint}"
|
||||
|
||||
internal fun bridgeScript(fingerprint: JSONObject, title: String, codeUrl: String = CODE_URL): String = """
|
||||
(function(){
|
||||
if (window.__droiddeckRgsc) return 'again';
|
||||
window.__droiddeckRgsc = true;
|
||||
var fp = $fingerprint, title = ${JSONObject.quote(title)}, back = ${JSONObject.quote(codeUrl)}, seq = 0;
|
||||
function later(cb, v){ setTimeout(function(){ try { if (cb) cb(v); } catch (e) {} }, 0); }
|
||||
var answers = {
|
||||
GetWindowConfig: { serviceInfo: { rosPlatform: 'pc' }, platformInfo: {} },
|
||||
GetDeviceId: { fingerprintKvp: fp },
|
||||
GetVersionInfo: { isDebugSdk: false },
|
||||
GetProfileList: { profiles: [] },
|
||||
GetCommandLineArguments: { arguments: [] }
|
||||
};
|
||||
window.rgscQueryCancel = function(){};
|
||||
window.rgscQuery = function(q){
|
||||
q = q || {};
|
||||
var p = q.params || {};
|
||||
if (q.method === 'CallAuthResult' && p.authCode) {
|
||||
later(q.onSuccess, {});
|
||||
setTimeout(function(){ location.replace(back + '?code=' + encodeURIComponent(p.authCode)); }, 50);
|
||||
} else if ((q.method === 'CallAuthResult' && p.result === 3) || (q.method === 'CallSetWindowState' && p.state === 3)) {
|
||||
later(q.onSuccess, {});
|
||||
setTimeout(function(){ location.replace(back + '?cancel=1'); }, 50);
|
||||
} else if (q.method === 'CallLaunchExternalBrowser' && p.url) {
|
||||
window.open(p.url, '_blank');
|
||||
later(q.onSuccess, {});
|
||||
} else {
|
||||
later(q.onSuccess, Object.prototype.hasOwnProperty.call(answers, q.method) ? answers[q.method] : {});
|
||||
}
|
||||
return ++seq;
|
||||
};
|
||||
window.rgscAddSubscription = function(s){
|
||||
s = s || {};
|
||||
if (s.method === 'OnStartAuth') later(s.onSuccess, { launchPlatform: 0, titleLaunchInfo: { activeTitleName: title, externalPlatformInfo: {} }, profile: null, errorMessage: null });
|
||||
return ++seq;
|
||||
};
|
||||
var form = '/signin/user-form?cid=launcher&lang=en-US';
|
||||
fetch(form, { credentials: 'include' })
|
||||
.then(function(r){ return r.text(); })
|
||||
.then(function(h){
|
||||
history.replaceState(null, '', form); document.open(); document.write(h); document.close();
|
||||
var css = document.createElement('style');
|
||||
css.textContent = '[data-ui-name="launcherSettings"]{display:none!important}';
|
||||
(document.head || document.documentElement).appendChild(css);
|
||||
});
|
||||
return 'ok';
|
||||
})()
|
||||
""".trimIndent()
|
||||
|
||||
fun isCodeUrl(url: String) = url.startsWith(CODE_URL)
|
||||
|
||||
internal fun cancelled(url: String): Boolean = android.net.Uri.parse(url).getQueryParameter("cancel") == "1"
|
||||
|
||||
internal fun codeFrom(url: String): String? = android.net.Uri.parse(url).getQueryParameter("code")?.takeIf { it.isNotBlank() }
|
||||
|
||||
fun completeSignIn(context: Context, url: String): String? {
|
||||
val code = codeFrom(url) ?: return "no auth code"
|
||||
val fp = fingerprint(context)
|
||||
val gateway = "$GATEWAY?code=" + URLEncoder.encode(code, "UTF-8") + "&fingerprint=" + URLEncoder.encode(state(fp), "UTF-8")
|
||||
val c = URL(gateway).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 25_000
|
||||
c.instanceFollowRedirects = false
|
||||
c.setRequestProperty("User-Agent", USER_AGENT)
|
||||
c.setRequestProperty("Accept", "application/json")
|
||||
c.setRequestProperty("X-Requested-With", "XMLHttpRequest")
|
||||
c.setRequestProperty("Origin", LAUNCHER_SITE)
|
||||
c.setRequestProperty("Referer", "$LAUNCHER_SITE/")
|
||||
runCatching { CookieManager.getInstance().getCookie(LAUNCHER_SITE) }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { c.setRequestProperty("Cookie", it) }
|
||||
val (status, body) = try {
|
||||
val s = c.responseCode
|
||||
s to ((if (s in 200..299) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty())
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
val o = runCatching { JSONObject(body) }.getOrNull()
|
||||
val token = o?.optString("ScAuthToken")?.takeIf { it.isNotEmpty() && it != "null" }
|
||||
if (token == null) {
|
||||
Log.w(TAG, "gateway $status; fields ${o?.keys()?.asSequence()?.toList() ?: "not json"}")
|
||||
return "gateway $status"
|
||||
}
|
||||
val account = JSONObject()
|
||||
.put("access_token", token)
|
||||
.put("remembered_machine_token", o.optString("RememberedMachineToken").takeIf { it != "null" }.orEmpty())
|
||||
.put("login_guid", o.optString("LoginGuid").takeIf { it != "null" }.orEmpty())
|
||||
.put("display_name", "Rockstar Games")
|
||||
.put("signed_in_at", System.currentTimeMillis())
|
||||
StoreAccounts.write(context.applicationContext, Store.ROCKSTAR, account)
|
||||
val t = runCatching { mint(context) }.onFailure { Log.w(TAG, "first ticket: ${it.message}") }.getOrNull()
|
||||
if (t == null) {
|
||||
StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR)
|
||||
return "ticket"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun ticket(context: Context, fresh: Boolean = false): Ticket? = synchronized(lock) {
|
||||
val o = StoreAccounts.read(context.applicationContext, Store.ROCKSTAR) ?: return null
|
||||
if (!fresh) {
|
||||
val current = stored(o)
|
||||
if (com.droiddeck.launcher.session.SessionState.running &&
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.lastLaunched?.first == Store.ROCKSTAR) {
|
||||
return current?.takeIf { it.expiresAt > System.currentTimeMillis() }
|
||||
}
|
||||
current?.takeIf { it.expiresAt - System.currentTimeMillis() > TICKET_MARGIN_MS }?.let { return it }
|
||||
}
|
||||
runCatching { mint(context) }.onFailure { Log.w(TAG, "ticket: ${it.message}") }.getOrNull()
|
||||
}
|
||||
|
||||
private fun stored(o: JSONObject): Ticket? {
|
||||
val t = o.optString("ticket").takeIf { it.isNotEmpty() } ?: return null
|
||||
return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"))
|
||||
}
|
||||
|
||||
private fun mint(context: Context): Ticket {
|
||||
val app = context.applicationContext
|
||||
val o = StoreAccounts.read(app, Store.ROCKSTAR) ?: throw IllegalStateException("not signed in")
|
||||
val root = try {
|
||||
RockstarRos.result("auth.asmx/CreateTicketScAuthToken2", listOf(
|
||||
"ticket" to "", "platformName" to "pcros", "scAuthToken" to o.optString("access_token"),
|
||||
"rememberedMachineToken" to o.optString("remembered_machine_token"),
|
||||
), headers = mapOf("SCS-MFAMachineFingerPrint" to state(fingerprint(app))))
|
||||
} catch (e: RockstarRos.RosException) {
|
||||
if (e.code.startsWith("AuthenticationFailed")) com.droiddeck.launcher.stores.StoresState.markSignInExpired(Store.ROCKSTAR)
|
||||
throw e
|
||||
}
|
||||
val t = parseTicket(root) ?: throw IllegalStateException("no ticket in the answer")
|
||||
o.put("ticket", t.ticket).put("session_key", t.sessionKey).put("session_ticket", t.sessionTicket)
|
||||
.put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt)
|
||||
if (t.nickname.isNotEmpty()) o.put("display_name", t.nickname)
|
||||
StoreAccounts.write(app, Store.ROCKSTAR, o)
|
||||
return t
|
||||
}
|
||||
|
||||
internal fun parseTicket(root: org.w3c.dom.Element, now: Long = System.currentTimeMillis()): Ticket? {
|
||||
val ticket = RockstarRos.text(root, "Ticket")?.takeIf { it.isNotEmpty() } ?: return null
|
||||
val account = RockstarRos.first(root, "RockstarAccount")
|
||||
val secs = RockstarRos.text(root, "SecsUntilExpiration")?.toLongOrNull() ?: 3600L
|
||||
return Ticket(
|
||||
ticket, RockstarRos.text(root, "SessionKey").orEmpty(), RockstarRos.text(root, "SessionTicket").orEmpty(),
|
||||
(account?.let { RockstarRos.text(it, "RockstarId") } ?: RockstarRos.text(root, "RockstarId")).orEmpty(),
|
||||
account?.let { RockstarRos.text(it, "Nickname") }.orEmpty(),
|
||||
now + secs * 1000L,
|
||||
)
|
||||
}
|
||||
|
||||
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) }
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.LoginFlows
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreBackend
|
||||
import com.droiddeck.launcher.stores.StoreFront
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.StoreShelves
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.WebCookies
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import org.w3c.dom.Element
|
||||
|
||||
object RockstarBackend : StoreBackend {
|
||||
override val store: Store = Store.ROCKSTAR
|
||||
|
||||
init {
|
||||
LoginFlows.rockstarFlow = { ua -> RockstarLogin(ua) }
|
||||
}
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(
|
||||
Intent(context, StoreLoginActivity::class.java)
|
||||
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
RockstarAuth.signOut(context.applicationContext)
|
||||
RockstarLibrary.reset()
|
||||
runCatching { WebCookies.expire(RockstarAuth.SIGN_IN_URLS, RockstarAuth.COOKIE_DOMAIN, listOf("/")) {} }
|
||||
}
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
Thread({ RockstarLibrary.sync(app) }, "rockstar-sync").start()
|
||||
}
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {
|
||||
StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(RockstarCatalog.shelves(), StoresState.library[store], RockstarCatalog::sameGame) }
|
||||
}
|
||||
|
||||
override fun search(context: Context, query: String): List<CatalogItem> =
|
||||
StoreFront.markOwned(RockstarCatalog.search(query), StoresState.library[store], RockstarCatalog::sameGame)
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
|
||||
val app = context.applicationContext
|
||||
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
|
||||
bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { RockstarInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
}
|
||||
|
||||
internal class RockstarLogin(override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
override val startUrl: String get() = RockstarAuth.START_URL
|
||||
override fun isRedirect(url: String): Boolean = RockstarAuth.isCodeUrl(url)
|
||||
|
||||
override fun pageFinished(view: WebView, url: String) {
|
||||
if (!url.startsWith(RockstarAuth.START_URL)) return
|
||||
val title = "launcher"
|
||||
view.evaluateJavascript(RockstarAuth.bridgeScript(RockstarAuth.fingerprint(view.context), title)) { Log.d("RockstarLogin", "bridge: $it") }
|
||||
}
|
||||
|
||||
override fun forgetSignIn(done: () -> Unit) {
|
||||
runCatching { WebCookies.expire(RockstarAuth.SIGN_IN_URLS, RockstarAuth.COOKIE_DOMAIN, listOf("/")) { done() } }.onFailure { done() }
|
||||
}
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? = if (RockstarAuth.cancelled(url)) null else try {
|
||||
RockstarAuth.completeSignIn(activity, url)?.let {
|
||||
Log.w("RockstarLogin", "sign-in incomplete: $it")
|
||||
activity.getString(R.string.stores_login_error_verification)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("RockstarLogin", "sign-in failed: ${e.javaClass.simpleName}")
|
||||
activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
}
|
||||
|
||||
internal data class RockstarApp(val id: String, val name: String, val titleId: String, val branches: List<RockstarBranch>, val parent: String = "")
|
||||
|
||||
internal data class RockstarBranch(val id: String, val name: String, val buildId: String, val isDefault: Boolean, val accessToken: String) {
|
||||
val hasBuild: Boolean get() = (buildId.toLongOrNull() ?: 0L) > 0 && accessToken.isNotEmpty()
|
||||
}
|
||||
|
||||
internal data class RockstarPackage(val title: String, val featured: Boolean)
|
||||
|
||||
internal class RockstarAccountApps(val apps: List<RockstarApp>, val packages: List<RockstarPackage>)
|
||||
|
||||
internal object RockstarApps {
|
||||
fun parse(root: Element): List<RockstarApp> = RockstarRos.all(root, "App").map { a ->
|
||||
val branches = RockstarRos.first(a, "Branches")?.let { RockstarRos.children(it, "Branch") }.orEmpty().map { b ->
|
||||
RockstarBranch(b.getAttribute("Id"), b.getAttribute("Name"), b.getAttribute("BuildId"),
|
||||
b.getAttribute("IsDefault").equals("true", true), RockstarRos.text(b, "AccessToken").orEmpty())
|
||||
}
|
||||
val parent = (a.parentNode?.parentNode as? Element)?.takeIf { it.tagName == "App" }?.getAttribute("Name").orEmpty()
|
||||
RockstarApp(a.getAttribute("Id"), a.getAttribute("Name"), a.getAttribute("TitleId"), branches, parent)
|
||||
}
|
||||
|
||||
fun packages(root: Element): List<RockstarPackage> = RockstarRos.all(root, "PackageJson").mapNotNull { p ->
|
||||
val o = runCatching { org.json.JSONObject(p.textContent) }.getOrNull() ?: return@mapNotNull null
|
||||
o.optString("title").takeIf { it.isNotEmpty() }?.let { RockstarPackage(it, o.optBoolean("isFeatured")) }
|
||||
}
|
||||
|
||||
fun fetch(ticket: String, log: (String) -> Unit): RockstarAccountApps {
|
||||
val root = RockstarRos.result("app.asmx/GetAppsAndPackages", listOf("ticket" to ticket))
|
||||
val out = RockstarAccountApps(parse(root), packages(root))
|
||||
log("Rockstar: packages " + out.packages.joinToString(", ") { it.title + if (it.featured) " (featured)" else "" }.ifEmpty { "none" } +
|
||||
"; builds " + out.apps.filter { a -> a.branches.any { it.hasBuild } }.joinToString(", ") { it.name }.ifEmpty { "none" })
|
||||
return out
|
||||
}
|
||||
|
||||
fun branch(app: RockstarApp): RockstarBranch? = app.branches.firstOrNull { it.isDefault && it.hasBuild } ?: app.branches.firstOrNull { it.hasBuild }
|
||||
|
||||
fun deliverer(apps: List<RockstarApp>, title: RockstarTitle): RockstarApp? = apps
|
||||
.filter { RockstarTitles.byId(it.name) == title && !it.name.endsWith("_steam") && !it.name.endsWith("_epic") }
|
||||
.sortedBy { if (it.name == title.id) 0 else 1 }
|
||||
.firstOrNull { branch(it) != null }
|
||||
}
|
||||
|
||||
object RockstarLibrary {
|
||||
private val generation = java.util.concurrent.atomic.AtomicInteger()
|
||||
private val running = java.util.concurrent.atomic.AtomicReference<Int?>(null)
|
||||
|
||||
fun reset() {
|
||||
generation.incrementAndGet()
|
||||
StoresState.post {
|
||||
StoresState.library.remove(Store.ROCKSTAR)
|
||||
StoresState.shelves.remove(Store.ROCKSTAR)
|
||||
}
|
||||
}
|
||||
|
||||
private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() }
|
||||
|
||||
internal fun owned(account: RockstarAccountApps): List<RockstarTitle> =
|
||||
account.packages.filter { !it.featured }.flatMap { RockstarTitles.forName(it.title) }.distinct()
|
||||
|
||||
internal fun games(account: RockstarAccountApps): List<CatalogItem> = owned(account).mapNotNull { t ->
|
||||
RockstarApps.deliverer(account.apps, t)?.let { RockstarTitles.item(t, owned = true, extra = mapOf("app" to it.name, "appId" to it.id)) }
|
||||
}.sortedBy { it.title.lowercase() }
|
||||
|
||||
fun sync(app: Context) {
|
||||
val gen = generation.get()
|
||||
if (running.getAndSet(gen) == gen) return
|
||||
try {
|
||||
val t = RockstarAuth.ticket(app)
|
||||
if (t == null) {
|
||||
post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_sign_in) }
|
||||
return
|
||||
}
|
||||
if (StoresState.library[Store.ROCKSTAR].isNullOrEmpty()) post(gen) { StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list) }
|
||||
val account = RockstarApps.fetch(t.ticket) { StoresState.logLine(it) }
|
||||
val games = games(account)
|
||||
owned(account).filter { o -> games.none { it.id == o.id } }.takeIf { it.isNotEmpty() }?.let { elsewhere ->
|
||||
StoresState.logLine("Rockstar: owned through another store, installs from there: " + elsewhere.joinToString(", ") { it.name })
|
||||
}
|
||||
post(gen) {
|
||||
StoresState.status.remove(Store.ROCKSTAR)
|
||||
StoresState.problems.remove(Store.ROCKSTAR)
|
||||
StoresState.library[Store.ROCKSTAR] = games
|
||||
StoresState.shelves[Store.ROCKSTAR]?.let { StoresState.shelves[Store.ROCKSTAR] = StoreFront.markOwned(it, games, RockstarCatalog::sameGame) }
|
||||
}
|
||||
StoresState.logLine("Rockstar: ${games.size} owned games")
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("Rockstar: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(300)}")
|
||||
post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_failed) }
|
||||
} finally {
|
||||
running.compareAndSet(gen, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object RockstarCatalog {
|
||||
fun all(): List<CatalogItem> = RockstarTitles.all.map { RockstarTitles.item(it) }
|
||||
|
||||
fun shelves(): StoreShelves {
|
||||
val all = all()
|
||||
val newest = all.sortedByDescending { it.releaseDate }
|
||||
val headline = listOf("gta5_gen9", "rdr2", "rdr", "gta4", "gtasaunreal", "lanoire", "mp3")
|
||||
return StoreShelves(
|
||||
whatsNew = newest,
|
||||
trending = headline.mapNotNull { id -> all.firstOrNull { it.id == id } } + all.filter { it.id !in headline },
|
||||
art = all.mapNotNull { it.imageUrl },
|
||||
)
|
||||
}
|
||||
|
||||
fun search(query: String): List<CatalogItem> {
|
||||
val q = StoreFront.titleKey(query)
|
||||
if (q.length < 2) return emptyList()
|
||||
return all().filter { StoreFront.titleKey(it.title).contains(q) }
|
||||
}
|
||||
|
||||
fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean = shelf.id == owned.id
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreExe
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.w3c.dom.Element
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
internal data class RockstarChunk(val fileEntryId: String, val chunkId: String, val sha256: String, val offset: Long, val size: Long)
|
||||
|
||||
internal data class RockstarFile(val entryId: String, val versionId: String, val path: String, val size: Long, val sha256: String, val chunks: List<RockstarChunk>)
|
||||
|
||||
internal data class RockstarBuild(val buildId: String, val version: String, val preload: Boolean, val files: List<RockstarFile>) {
|
||||
val bytes: Long get() = files.sumOf { it.size }
|
||||
}
|
||||
|
||||
internal object RockstarManifest {
|
||||
fun inside(root: File, relative: String): File {
|
||||
require(safePath(relative) == relative) { "Unsafe Rockstar install path" }
|
||||
val base = root.canonicalFile
|
||||
var target = base
|
||||
for (part in relative.split('/')) {
|
||||
target = File(target, part)
|
||||
require(!Files.isSymbolicLink(target.toPath())) { "Rockstar install path is a symbolic link" }
|
||||
}
|
||||
require(target.canonicalFile.toPath().startsWith(base.toPath())) { "Rockstar install path leaves its folder" }
|
||||
return target
|
||||
}
|
||||
|
||||
fun verified(target: File, chunk: RockstarChunk, cancelled: () -> Boolean = { false }): Boolean {
|
||||
if (cancelled()) return false
|
||||
if (!target.isFile || chunk.offset < 0 || chunk.size < 0 || chunk.offset > target.length() || chunk.size > target.length() - chunk.offset) return false
|
||||
return RandomAccessFile(target, "r").use { input ->
|
||||
input.seek(chunk.offset)
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(256 * 1024)
|
||||
var remaining = chunk.size
|
||||
while (remaining > 0) {
|
||||
if (cancelled()) return false
|
||||
val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
|
||||
if (count <= 0) return false
|
||||
digest.update(buffer, 0, count)
|
||||
remaining -= count
|
||||
}
|
||||
digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.sha256, true)
|
||||
}
|
||||
}
|
||||
|
||||
fun safePath(raw: String): String? {
|
||||
val parts = raw.replace('\\', '/').split('/').filter { it.isNotEmpty() && it != "." }
|
||||
if (parts.isEmpty() || parts.any { it == ".." || it.contains(':') }) return null
|
||||
return parts.joinToString("/")
|
||||
}
|
||||
|
||||
fun parse(root: Element): RockstarBuild {
|
||||
val result = RockstarRos.first(root, "Result") ?: throw IllegalStateException("manifest without a result")
|
||||
val files = RockstarRos.all(result, "FileDetails").map { f ->
|
||||
val entry = f.getAttribute("FileEntryId")
|
||||
val path = safePath(RockstarRos.text(f, "RelativePath").orEmpty()) ?: throw IllegalStateException("unsafe path in the manifest")
|
||||
val chunks = RockstarRos.first(f, "FileChunks")?.let { RockstarRos.children(it, "Chunk") }.orEmpty().map { c ->
|
||||
RockstarChunk(entry, c.getAttribute("FileChunkId"), c.getAttribute("SHA256Hash").lowercase(),
|
||||
c.getAttribute("StartByteOffset").toLong(), c.getAttribute("Size").toLong())
|
||||
}
|
||||
val whole = RockstarRos.children(f, "SHA256Hash").firstOrNull()?.textContent?.trim()?.lowercase().orEmpty()
|
||||
RockstarFile(entry, f.getAttribute("FileEntryVersionId"), path, f.getAttribute("FileSize").toLong(), whole, chunks)
|
||||
}
|
||||
return RockstarBuild(result.getAttribute("BuildId"), result.getAttribute("VersionNumber"),
|
||||
RockstarRos.text(result, "IsPreload").equals("true", true), files)
|
||||
}
|
||||
|
||||
fun batches(chunks: List<RockstarChunk>, maxBytes: Long = 48L * 1024 * 1024, maxCount: Int = 16): List<List<RockstarChunk>> {
|
||||
val out = ArrayList<List<RockstarChunk>>()
|
||||
var cur = ArrayList<RockstarChunk>()
|
||||
var bytes = 0L
|
||||
for (c in chunks) {
|
||||
if (cur.isNotEmpty() && (bytes + c.size > maxBytes || cur.size >= maxCount)) { out += cur; cur = ArrayList(); bytes = 0 }
|
||||
cur += c
|
||||
bytes += c.size
|
||||
}
|
||||
if (cur.isNotEmpty()) out += cur
|
||||
return out
|
||||
}
|
||||
|
||||
fun key(file: RockstarFile, chunk: RockstarChunk) = "${file.versionId}:${chunk.chunkId}"
|
||||
}
|
||||
|
||||
internal class RockstarInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
|
||||
val ticket = RockstarAuth.ticket(app)?.ticket ?: throw IllegalStateException("Not signed in to Rockstar Games")
|
||||
val title = RockstarTitles.byId(item.id) ?: throw IllegalStateException("Rockstar has no PC build of ${item.title}")
|
||||
val account = RockstarApps.fetch(ticket) { handle.log(it) }
|
||||
if (title !in RockstarLibrary.owned(account)) throw IllegalStateException("${item.title} is not in this Rockstar account's library")
|
||||
val owned = RockstarApps.deliverer(account.apps, title)
|
||||
?: throw IllegalStateException("${item.title} is owned through another store and installs from there")
|
||||
val branch = RockstarApps.branch(owned)!!
|
||||
handle.log("rockstar: ${owned.name} branch ${branch.name} build ${branch.buildId}")
|
||||
val build = RockstarManifest.parse(RockstarRos.result("app.asmx/GetBuildManifestFull", listOf("ticket" to ticket, "branchAccessToken" to branch.accessToken)))
|
||||
if (build.preload) throw IllegalStateException("${item.title} is a preload Rockstar has not unlocked yet")
|
||||
handle.log("rockstar: build ${build.buildId} ${build.version}, ${build.files.size} files, ${build.bytes} bytes")
|
||||
handle.diskSize(build.bytes)
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.ROCKSTAR, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val ledger = RockstarManifest.inside(folder, LEDGER)
|
||||
val done = HashSet<String>().apply { if (ledger.isFile) ledger.readLines().filterTo(this) { it.isNotBlank() } }
|
||||
val pending = ArrayList<Pair<RockstarFile, RockstarChunk>>()
|
||||
var have = 0L
|
||||
for (f in build.files) {
|
||||
if (cancelled.get()) return null
|
||||
val target = RockstarManifest.inside(folder, f.path)
|
||||
target.parentFile?.mkdirs()
|
||||
for (c in f.chunks) {
|
||||
if (cancelled.get()) return null
|
||||
if (RockstarManifest.key(f, c) in done && RockstarManifest.verified(target, c, cancelled::get)) have += c.size else pending += f to c
|
||||
}
|
||||
if (cancelled.get()) return null
|
||||
RandomAccessFile(target, "rw").use { if (it.length() != f.size) it.setLength(f.size) }
|
||||
}
|
||||
val fileOf = pending.associate { (f, c) -> "${c.fileEntryId}:${c.chunkId}" to f }
|
||||
val total = build.bytes
|
||||
val progress = AtomicLong(have)
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
handle.progress(have, total, "Downloading (${build.files.size} files)")
|
||||
|
||||
val queue = ConcurrentLinkedQueue(RockstarManifest.batches(pending.map { it.second }))
|
||||
val failure = AtomicReference<Throwable?>(null)
|
||||
val pool = Executors.newFixedThreadPool(WORKERS, DownloadQueue.workerFactory("rockstar-dl"))
|
||||
val ledgerLock = Any()
|
||||
repeat(WORKERS) {
|
||||
pool.execute {
|
||||
while (!cancelled.get() && failure.get() == null) {
|
||||
val batch = queue.poll() ?: break
|
||||
try {
|
||||
val urls = chunkUrls(ticket, branch.accessToken, batch)
|
||||
for (c in batch) {
|
||||
if (cancelled.get()) break
|
||||
val f = fileOf.getValue("${c.fileEntryId}:${c.chunkId}")
|
||||
fetch({ retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) {
|
||||
handle.progress(progress.get(), total, "Downloading (${build.files.size} files)")
|
||||
}
|
||||
synchronized(ledgerLock) { ledger.appendText(RockstarManifest.key(f, c) + "\n") }
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
failure.compareAndSet(null, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pool.shutdown()
|
||||
while (!pool.awaitTermination(250, TimeUnit.MILLISECONDS)) Unit
|
||||
if (cancelled.get()) return null
|
||||
failure.get()?.let { throw it }
|
||||
|
||||
handle.interruptible(false)
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val exe = resolve(folder, title.exe) ?: StoreExe.pick(folder, null, item.title).ifEmpty { title.exe.replace('\\', '/') }
|
||||
handle.log("rockstar: exe=$exe")
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.ROCKSTAR, item.id, item.title, exe = exe,
|
||||
installVersion = build.version.ifEmpty { build.buildId }, installedAt = System.currentTimeMillis(),
|
||||
cover = cover, hero = item.imageUrl, cloud = false,
|
||||
extra = mapOf("rosTitleId" to title.rosTitleId.toString(), "app" to owned.name, "buildId" to build.buildId, "platform" to title.platform),
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar, onStep = { d, steps -> handle.stageProgress(d.toLong(), steps.toLong()) })
|
||||
ledger.delete()
|
||||
return folder.path
|
||||
}
|
||||
|
||||
private fun chunkUrls(ticket: String, branchToken: String, batch: List<RockstarChunk>): Map<String, String> {
|
||||
val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" }
|
||||
val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv))
|
||||
return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap()
|
||||
}
|
||||
|
||||
private fun fetch(url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) {
|
||||
var lastError: Exception? = null
|
||||
for (attempt in 0 until 3) {
|
||||
if (cancelled.get()) return
|
||||
val written = AtomicLong(0)
|
||||
try {
|
||||
val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
try {
|
||||
if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}")
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
RandomAccessFile(target, "rw").use { out ->
|
||||
out.seek(chunk.offset)
|
||||
c.inputStream.use { input ->
|
||||
val buf = ByteArray(256 * 1024)
|
||||
var last = 0L
|
||||
while (true) {
|
||||
if (cancelled.get()) { progress.addAndGet(-written.get()); return }
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says")
|
||||
out.write(buf, 0, n)
|
||||
digest.update(buf, 0, n)
|
||||
written.addAndGet(n.toLong())
|
||||
progress.addAndGet(n.toLong())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - last > 400) { last = now; report() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val hex = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check")
|
||||
report()
|
||||
return
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
progress.addAndGet(-written.get())
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed")
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
}
|
||||
|
||||
internal companion object {
|
||||
const val LEDGER = ".droiddeck-rockstar-chunks"
|
||||
private const val WORKERS = 4
|
||||
|
||||
fun resolve(folder: File, configured: String): String? {
|
||||
var at = folder
|
||||
for (part in configured.replace('\\', '/').split('/').filter { it.isNotEmpty() }) {
|
||||
at = at.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null
|
||||
}
|
||||
return if (at.isFile) at.relativeTo(folder).invariantSeparatorsPath else null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import org.json.JSONObject
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
object RockstarLaunch {
|
||||
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe")
|
||||
|
||||
fun supports(id: String?) = id != null && id in pipes
|
||||
|
||||
fun applyDefaults(app: Context, id: String, appId: Long) {
|
||||
val scope = (appId and 0xffffffffL).toString()
|
||||
when (id) {
|
||||
"gta3" -> GameEnvironmentStore.setDefault(app, scope, "FEX_X87REDUCEDPRECISION", "0")
|
||||
"gtasa" -> GameEnvironmentStore.setDefault(app, scope, "PROTON_USE_WINED3D", "1")
|
||||
}
|
||||
}
|
||||
|
||||
fun prepare(app: Context, id: String): JSONObject {
|
||||
val pipe = pipes[id] ?: return failure("unsupported-title")
|
||||
val title = RockstarTitles.byId(id) ?: return failure("unknown-title")
|
||||
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
} ?: return failure("not-installed")
|
||||
val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed")
|
||||
val exe = installed.exeFile(folder).canonicalFile
|
||||
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile ||
|
||||
!java.io.File(folder, "MTLX.dll").isFile) return failure("missing-game-files")
|
||||
var ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
val account = try {
|
||||
RockstarApps.fetch(ticket.ticket) {}
|
||||
} catch (e: RockstarRos.RosException) {
|
||||
if (!(e.code.contains("Ticket", true) || e.code.contains("Sign", true) || e.code.contains("Auth", true))) throw e
|
||||
ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
RockstarApps.fetch(ticket.ticket) {}
|
||||
}
|
||||
if (RockstarLibrary.owned(account).none { it.id == id } || RockstarApps.deliverer(account.apps, title) == null) return failure("not-owned")
|
||||
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to title.rosTitleId.toString(), "platformId" to "8"))
|
||||
val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token")
|
||||
val hash = MessageDigest.getInstance("SHA-256").digest(RockstarAuth.fingerprint(app).toString().toByteArray()).copyOf(16)
|
||||
val launch = RockstarRos.result("app.asmx/GetTitleLaunchData", listOf("ticket" to ticket.ticket, "titleAccessToken" to token,
|
||||
"machineHash" to Base64.getEncoder().encodeToString(hash)))
|
||||
val encoded = RockstarRos.text(launch, "Data") ?: return failure("no-launch-data")
|
||||
val iv = RockstarRos.text(launch, "EndpointIV") ?: return failure("no-launch-iv")
|
||||
val material = RockstarLaunchCipher.decode(encoded, iv)
|
||||
return JSONObject().put("ok", true).put("pipe", pipe).put("material", material).put("expiresAt", System.currentTimeMillis() + 90_000)
|
||||
}
|
||||
|
||||
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.Base64
|
||||
|
||||
internal object RockstarLaunchCipher {
|
||||
private val data by lazy {
|
||||
val bytes = requireNotNull(javaClass.getResourceAsStream("/rockstar/legacy-cipher.bin")).use { it.readBytes() }
|
||||
require(bytes.size == 86852 && bytes.copyOfRange(0, 8).contentEquals("DDRGLC01".toByteArray()))
|
||||
bytes
|
||||
}
|
||||
private val tables by lazy {
|
||||
ByteBuffer.wrap(data, 8, 86016).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().let { buffer -> IntArray(buffer.remaining()).also { buffer.get(it) } }
|
||||
}
|
||||
private val order = intArrayOf(0, 7, 10, 13, 1, 4, 11, 14, 2, 5, 8, 15, 3, 6, 9, 12)
|
||||
|
||||
internal fun decrypt(cipher: ByteArray, iv: ByteArray, inner: Boolean): ByteArray {
|
||||
require(cipher.isNotEmpty() && cipher.size <= 65536 && cipher.size % 16 == 0 && iv.size == 16)
|
||||
val map = 86024
|
||||
val key = map + 272 + if (inner) 272 else 0
|
||||
val keys = ByteBuffer.wrap(data, key, 272).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().let { buffer -> IntArray(68).also { buffer.get(it) } }
|
||||
val output = ByteArray(cipher.size)
|
||||
var previous = iv
|
||||
for (offset in cipher.indices step 16) {
|
||||
var state = cipher.copyOfRange(offset, offset + 16)
|
||||
for (round in 0..16) {
|
||||
val next = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
|
||||
for (column in 0..3) {
|
||||
var word = keys[round * 4 + column]
|
||||
for (slot in column * 4 until column * 4 + 4) {
|
||||
val index = if (round == 0 || round == 1 || round == 16) slot else order[slot]
|
||||
val table = data[map + round * 16 + index].toInt() and 255
|
||||
require(table < 84)
|
||||
word = word xor tables[table * 256 + (state[index].toInt() and 255)]
|
||||
}
|
||||
next.putInt(word)
|
||||
}
|
||||
state = next.array()
|
||||
}
|
||||
for (i in 0..15) output[offset + i] = (state[i].toInt() xor previous[i].toInt()).toByte()
|
||||
previous = cipher.copyOfRange(offset, offset + 16)
|
||||
}
|
||||
val padding = output.last().toInt() and 255
|
||||
require(padding in 1..16 && output.takeLast(padding).all { (it.toInt() and 255) == padding })
|
||||
return output.copyOf(output.size - padding)
|
||||
}
|
||||
|
||||
fun decode(encoded: String, endpointIv: String): String {
|
||||
require(encoded.length <= 90000 && endpointIv.length <= 32)
|
||||
val clear = decrypt(Base64.getDecoder().decode(encoded), Base64.getDecoder().decode(endpointIv), false)
|
||||
require(clear.size > 128)
|
||||
val xml = clear.copyOf(clear.size - 128).toString(Charsets.UTF_8)
|
||||
val root = RockstarRos.parse(xml)
|
||||
require(root.tagName == "EncryptedResponse")
|
||||
val date = requireNotNull(RockstarRos.text(root, "CreationDate")).toLong()
|
||||
require(date in 0..0xffffffffL)
|
||||
val text = requireNotNull(RockstarRos.text(root, "Data"))
|
||||
require(text.length == 672 && text.all { it.digitToIntOrNull(16) != null })
|
||||
val cipher = ByteArray(text.length / 2) { i -> text.substring(i * 2, i * 2 + 2).toInt(16).toByte() }
|
||||
val iv = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN).put(data, data.size - 12, 12).putInt(date.toInt()).array()
|
||||
val material = decrypt(cipher, iv, true)
|
||||
require(material.size == 320)
|
||||
return material.joinToString("") { "%02X".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import org.w3c.dom.Element
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import javax.xml.XMLConstants
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
|
||||
internal object RockstarRos {
|
||||
const val HOST = "https://rgl-prod.ros.rockstargames.com"
|
||||
const val PUBLIC_HOST = "https://prod.ros.rockstargames.com"
|
||||
const val SERVICES = "/launcher/11/launcherservices/"
|
||||
private const val MAX_BYTES = 32 * 1024 * 1024
|
||||
|
||||
class RosException(message: String, val code: String = "", val status: Int = 0) : Exception(message)
|
||||
|
||||
class Reply(val status: Int, val body: String)
|
||||
|
||||
fun form(fields: List<Pair<String, String>>): String =
|
||||
fields.joinToString("&") { (k, v) -> "$k=" + URLEncoder.encode(v, "UTF-8") }
|
||||
|
||||
fun call(method: String, fields: List<Pair<String, String>>, host: String = HOST, headers: Map<String, String> = emptyMap()): Reply {
|
||||
val c = URL(host + SERVICES + method).openConnection() as HttpURLConnection
|
||||
c.requestMethod = "POST"
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
c.instanceFollowRedirects = false
|
||||
c.doOutput = true
|
||||
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
|
||||
c.setRequestProperty("User-Agent", RockstarAuth.USER_AGENT)
|
||||
for ((k, v) in headers) c.setRequestProperty(k, v)
|
||||
try {
|
||||
c.outputStream.use { it.write(form(fields).toByteArray(Charsets.UTF_8)) }
|
||||
val status = c.responseCode
|
||||
val stream = (if (status in 200..299) c.inputStream else c.errorStream)
|
||||
val bytes = stream?.use { input ->
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buf = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
out.write(buf, 0, n)
|
||||
if (out.size() > MAX_BYTES) throw RosException("$method: answer too large", status = status)
|
||||
}
|
||||
out.toByteArray()
|
||||
} ?: ByteArray(0)
|
||||
return Reply(status, bytes.toString(Charsets.UTF_8))
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
fun result(method: String, fields: List<Pair<String, String>>, host: String = HOST, headers: Map<String, String> = emptyMap()): Element {
|
||||
val reply = call(method, fields, host, headers)
|
||||
if (reply.status !in 200..299) throw RosException("$method: HTTP ${reply.status}", status = reply.status)
|
||||
val root = runCatching { parse(reply.body) }.getOrNull()
|
||||
?: throw RosException("$method: HTTP ${reply.status} invalid response", status = reply.status)
|
||||
if (text(root, "Status") != "1") {
|
||||
val error = first(root, "Error")
|
||||
val code = listOfNotNull(error?.getAttribute("Code")?.takeIf { it.isNotEmpty() }, error?.getAttribute("CodeEx")?.takeIf { it.isNotEmpty() }).joinToString("/")
|
||||
throw RosException("$method: ${code.ifEmpty { "HTTP ${reply.status}" }}", code, reply.status)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
fun parse(xml: String): Element {
|
||||
require(!xml.contains("<!DOCTYPE", ignoreCase = true)) { "XML document types are not supported" }
|
||||
val f = DocumentBuilderFactory.newInstance()
|
||||
f.isNamespaceAware = false
|
||||
runCatching { f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) }
|
||||
runCatching { f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) }
|
||||
runCatching { f.setFeature("http://xml.org/sax/features/external-general-entities", false) }
|
||||
runCatching { f.setFeature("http://xml.org/sax/features/external-parameter-entities", false) }
|
||||
runCatching { f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) }
|
||||
f.isExpandEntityReferences = false
|
||||
return f.newDocumentBuilder().parse(ByteArrayInputStream(xml.toByteArray(Charsets.UTF_8))).documentElement
|
||||
}
|
||||
|
||||
fun first(root: Element, tag: String): Element? = root.getElementsByTagName(tag).let { if (it.length > 0) it.item(0) as Element else null }
|
||||
|
||||
fun all(root: Element, tag: String): List<Element> = root.getElementsByTagName(tag).let { l -> (0 until l.length).map { l.item(it) as Element } }
|
||||
|
||||
fun text(root: Element, tag: String): String? = first(root, tag)?.textContent?.trim()
|
||||
|
||||
fun children(parent: Element, tag: String): List<Element> {
|
||||
val out = ArrayList<Element>()
|
||||
var n = parent.firstChild
|
||||
while (n != null) {
|
||||
if (n is Element && n.tagName == tag) out += n
|
||||
n = n.nextSibling
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.stores.rockstar
|
||||
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
|
||||
internal data class RockstarTitle(
|
||||
val id: String,
|
||||
val rosTitleId: Int,
|
||||
val name: String,
|
||||
val exe: String,
|
||||
val registryKey: String,
|
||||
val steamAppId: Int,
|
||||
val released: String,
|
||||
val platform: String = "pcros",
|
||||
val description: String = "",
|
||||
val page: String = "",
|
||||
)
|
||||
|
||||
internal object RockstarTitles {
|
||||
private const val ART = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
|
||||
|
||||
val all = listOf(
|
||||
RockstarTitle("gta5_gen9", 11, "Grand Theft Auto V Enhanced", "GTA5_Enhanced.exe", "Rockstar Games\\GTAV Enhanced", 3240220, "2025-03-04", platform = "pcrosalt",
|
||||
description = "Story mode and GTA Online with ray-traced visuals, faster loading and DualSense support.",
|
||||
page = "https://www.rockstargames.com/gta-v"),
|
||||
RockstarTitle("gta5", 11, "Grand Theft Auto V Legacy", "GTA5.exe", "Rockstar Games\\Grand Theft Auto V", 271590, "2015-04-14",
|
||||
description = "Three criminals, one city: the original PC release of Grand Theft Auto V.",
|
||||
page = "https://www.rockstargames.com/gta-v"),
|
||||
RockstarTitle("rdr2", 13, "Red Dead Redemption 2", "RDR2.exe", "Rockstar Games\\Red Dead Redemption 2", 1174180, "2019-11-05",
|
||||
description = "Arthur Morgan and the Van der Linde gang on the run at the end of the outlaw era.",
|
||||
page = "https://www.rockstargames.com/reddeadredemption2"),
|
||||
RockstarTitle("rdr", 8, "Red Dead Redemption", "RDR.exe", "Rockstar Games\\Red Dead Redemption", 2668510, "2024-10-29",
|
||||
description = "John Marston's story, with the Undead Nightmare expansion.",
|
||||
page = "https://www.rockstargames.com/reddeadredemption"),
|
||||
RockstarTitle("gta4", 1, "Grand Theft Auto IV: The Complete Edition", "GTAIV.exe", "Rockstar Games\\Grand Theft Auto IV", 12210, "2008-12-02",
|
||||
description = "Niko Bellic's Liberty City, with The Lost and Damned and The Ballad of Gay Tony.",
|
||||
page = "https://www.rockstargames.com/games/IV"),
|
||||
RockstarTitle("lanoire", 9, "L.A. Noire", "LANoire.exe", "Rockstar Games\\LANoireMTL", 110800, "2011-11-08",
|
||||
description = "A detective story in 1947 Los Angeles.",
|
||||
page = "https://www.rockstargames.com/games/lanoire"),
|
||||
RockstarTitle("lanoirevr", 24, "L.A. Noire: The VR Case Files", "LANoireVR.exe", "Rockstar Games\\LANoireVR", 722230, "2017-12-15",
|
||||
description = "Seven cases from L.A. Noire rebuilt for virtual reality."),
|
||||
RockstarTitle("mp3", 10, "Max Payne 3", "MaxPayne3.exe", "Rockstar Games\\MP3MTL", 204100, "2012-05-29",
|
||||
description = "Max Payne, years after New York, working private security in São Paulo.",
|
||||
page = "https://www.rockstargames.com/games/maxpayne3"),
|
||||
RockstarTitle("bully", 23, "Bully: Scholarship Edition", "Bully.exe", "Rockstar Games\\Bully", 12200, "2008-10-21",
|
||||
description = "Jimmy Hopkins against the bullies, teachers and cliques of Bullworth Academy.", page = "https://www.rockstargames.com/bully"),
|
||||
RockstarTitle("gta3unreal", 28, "Grand Theft Auto III – The Definitive Edition", "Gameface\\Binaries\\Win64\\LibertyCity.exe", "Rockstar Games\\GTA III - DE", 1546970, "2021-11-11",
|
||||
description = "Liberty City, remastered with new lighting, controls and visual detail."),
|
||||
RockstarTitle("gtavcunreal", 29, "Grand Theft Auto: Vice City – The Definitive Edition", "Gameface\\Binaries\\Win64\\ViceCity.exe", "Rockstar Games\\GTA Vice City - DE", 1546990, "2021-11-11",
|
||||
description = "Tommy Vercetti's 1980s Vice City, remastered with new lighting, controls and visual detail."),
|
||||
RockstarTitle("gtasaunreal", 30, "Grand Theft Auto: San Andreas – The Definitive Edition", "Gameface\\Binaries\\Win64\\SanAndreas.exe", "Rockstar Games\\GTA San Andreas - DE", 1547000, "2021-11-11",
|
||||
description = "CJ's return to San Andreas, remastered with new lighting, controls and visual detail."),
|
||||
RockstarTitle("gtasa", 18, "Grand Theft Auto: San Andreas", "gta_sa.exe", "Rockstar Games\\GTA: San Andreas", 12120, "2005-06-07",
|
||||
description = "Carl Johnson's return to Los Santos and the state of San Andreas.", page = "https://www.rockstargames.com/games/sanandreas"),
|
||||
RockstarTitle("gtavc", 27, "Grand Theft Auto: Vice City", "gta-vc.exe", "Rockstar Games\\Grand Theft Auto: Vice City", 12110, "2003-05-12",
|
||||
description = "Tommy Vercetti's rise through 1980s Vice City.", page = "https://www.rockstargames.com/games/vicecity"),
|
||||
RockstarTitle("gta3", 26, "Grand Theft Auto III", "gta3.exe", "Rockstar Games\\Grand Theft Auto III", 12100, "2002-05-20",
|
||||
description = "Claude's revenge in Liberty City, the game that took the series into 3D.", page = "https://www.rockstargames.com/games/grandtheftauto3"),
|
||||
)
|
||||
|
||||
private val byId = all.associateBy { it.id }
|
||||
|
||||
private val PARENTS = mapOf(
|
||||
"rdr2_sp" to "rdr2", "rdr2_rdo" to "rdr2", "rdr2_sp_rgl" to "rdr2", "rdr2_sp_steam" to "rdr2", "rdr2_sp_epic" to "rdr2",
|
||||
"gtatrilogy" to "gtasaunreal",
|
||||
)
|
||||
|
||||
fun forName(name: String): List<RockstarTitle> =
|
||||
if (name.equals("gtatrilogy", true)) listOf("gta3unreal", "gtavcunreal", "gtasaunreal").mapNotNull { byId[it] } else listOfNotNull(byId(name))
|
||||
|
||||
fun byId(id: String?): RockstarTitle? = id?.lowercase()?.let { byId[it] ?: byId[PARENTS[it]] }
|
||||
|
||||
fun cover(t: RockstarTitle) = "$ART${t.steamAppId}/library_600x900.jpg"
|
||||
fun hero(t: RockstarTitle) = "$ART${t.steamAppId}/library_hero.jpg"
|
||||
fun wide(t: RockstarTitle) = "$ART${t.steamAppId}/header.jpg"
|
||||
|
||||
fun item(t: RockstarTitle, owned: Boolean = false, extra: Map<String, String> = emptyMap()) = CatalogItem(
|
||||
store = Store.ROCKSTAR, id = t.id, title = t.name, imageUrl = hero(t), tallImageUrl = cover(t),
|
||||
storeUrl = t.page.ifEmpty { "https://store.rockstargames.com" }, developer = "Rockstar Games", publisher = "Rockstar Games",
|
||||
releaseDate = t.released, description = t.description, owned = owned, mature = true,
|
||||
extra = mapOf("rosTitleId" to t.rosTitleId.toString()) + extra,
|
||||
)
|
||||
}
|
||||
@@ -400,6 +400,7 @@ internal fun GameActions(
|
||||
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
|
||||
val downloadBytes = catalogSize(item)
|
||||
val launchSupported = store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(id)
|
||||
Actions {
|
||||
when {
|
||||
s.shortcutPicker && game != null -> {
|
||||
@@ -411,8 +412,8 @@ internal fun GameActions(
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
|
||||
PrimaryButton(
|
||||
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
|
||||
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
stringResource(if (!launchSupported) R.string.stores_rockstar_launch_unavailable else if (preparing) R.string.store_starting else R.string.stores_play),
|
||||
enabled = launchSupported && !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
|
||||
) {
|
||||
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
|
||||
|
||||
@@ -35,6 +35,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
|
||||
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
|
||||
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
|
||||
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
|
||||
@@ -52,6 +53,7 @@ internal fun sourceLabel(source: String): String = when (source) {
|
||||
Store.BATTLENET.id -> Store.BATTLENET.label
|
||||
Store.UBISOFT.id -> Store.UBISOFT.shortLabel
|
||||
Store.EA.id -> Store.EA.label
|
||||
Store.ROCKSTAR.id -> Store.ROCKSTAR.shortLabel
|
||||
else -> stringResource(R.string.source_added)
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
@@ -220,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
|
||||
val ctx = LocalContext.current
|
||||
ArtStrip(d.cover, d.name) {
|
||||
StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f))
|
||||
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
|
||||
if (d.state == DownloadState.INSTALLED && (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id))) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
|
||||
}
|
||||
}
|
||||
@@ -373,7 +374,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.clear(ctx, d.key) }
|
||||
}
|
||||
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
|
||||
DownloadState.INSTALLED -> if (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id)) Box(Modifier.bloomIn(true, 420)) {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
|
||||
}
|
||||
DownloadState.CANCELLED -> {}
|
||||
|
||||
@@ -1168,6 +1168,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
|
||||
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
|
||||
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
|
||||
Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00)
|
||||
null -> return base
|
||||
}
|
||||
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
|
||||
|
||||
Reference in new issue
Block a user