feat(ubisoft): Ubisoft Connect store with native sign-in, library, downloads and launch (#2322)

* feat(ubisoft): sign in to Ubisoft Connect and list the owned library

* feat(ubisoft): download games natively through Demux and Ubisoft's CDN

* fix(ubisoft): show the owned games on the store page

* fix(ctl): reach the agent bridge by broadcast when the shell has no content command

* feat(ubisoft): run Ubisoft games in one prefix with Ubisoft Connect installed and the game registered

* feat(ubisoft): launch games through a native stand-in for Ubisoft Connect's local service

* feat(ubisoft): document the launcher pipes, log why owned games have no download, drop the installer after extraction

* feat(ubisoft): Steam-owned Ubisoft games install through Steam, and the launch session carries the game's application id

* feat(ubisoft): answer Denuvo activations through Ubisoft's activation service and log unanswered pipe traffic

* feat(ubisoft): report installed chunks to the game and skip add-ons the account does not own

* fix(ubisoft): the overlay stays off, Ubisoft's install steps pick Windows components, and shared-prefix games keep their own settings

* fix(ubisoft): write the manifest's registry values, and pick the game's exe over Ubisoft's installer stubs

* fix(ubisoft): stream download slices, guard the launch hook, and keep per-game components in the shared prefix

* fix(ubisoft): direct launches in the shared prefix keep their own game id

* ci(ubisoft): build the launcher service after the prepared components are verified

* fix(ubisoft): verify reused files, drop syncs from a signed-out account, and clear activation requests before launch

* fix(ubisoft): fetch again a reused file whose slices cannot be checked
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-10 15:08:37 -05:00
1 parent d8ed02f2cf
commit 3c96df4ab1
49 files changed
+3960 -24

No files matched your search

@@ -61,6 +61,7 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.sync.Syncthing.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
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)
}
@@ -417,7 +417,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)
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
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
@@ -457,7 +457,11 @@ object AddedGames {
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
exeUncertain = sidecar == null && chosen == null && adopted == null && ranking.uncertain,
launchOptions = if (sidecar == null) SessionPrefs.addedGameLaunch(context, folder.path) else "",
launchOptions = when {
sidecar == null -> SessionPrefs.addedGameLaunch(context, folder.path)
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
else -> ""
},
single = single != null))
}
}
@@ -9,7 +9,7 @@ import java.io.File
import java.util.Locale
object WinCompSources {
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX }
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX, UBISOFT }
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
@@ -83,6 +83,13 @@ object WinCompSources {
}
}
/** The prerequisite installers a Ubisoft manifest lists, with `$INSTALL_DIR` dropped. */
internal fun ubisoftInstallRuns(setup: String?): List<String> {
val runs = setup?.let { runCatching { org.json.JSONObject(it).optJSONArray("installRuns") }.getOrNull() } ?: return emptyList()
return (0 until runs.length()).mapNotNull { runs.optJSONObject(it)?.optString("exe") }
.map { it.replace('\\', '/').removePrefix("\$INSTALL_DIR").trimStart('/') }.filter { it.isNotEmpty() }
}
fun forGame(context: Context, game: Library.SteamGame): List<Finding> {
val folder = game.gameFiles
val out = ArrayList<Finding>()
@@ -112,6 +119,12 @@ object WinCompSources {
if (parts.isEmpty()) out += Finding(null, original, Origin.AMAZON, false)
parts.forEach { out += Finding(it, original, Origin.AMAZON, true) }
}
store == Store.UBISOFT -> ubisoftInstallRuns(sidecar?.extra?.get(com.droiddeck.launcher.stores.ubisoft.UbisoftLaunch.SETUP)).forEach { exe ->
val parts = installer(exe)
val original = exe.substringAfterLast('/')
if (parts.isEmpty()) out += Finding(null, original, Origin.UBISOFT, false)
parts.forEach { out += Finding(it, original, Origin.UBISOFT, true) }
}
else -> {}
}
if (game.library == Library.ADDED && folder != null) SteamMatch.get(context, folder.path)?.let { match ->
@@ -196,6 +196,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
"usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe" to "usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -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.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> ""
} ?: 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 -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> 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 -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -13,12 +13,14 @@ internal object LoginFlows {
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
Store.EA -> eaFlow(browserUserAgent)
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var ubisoftFlow: (String) -> StoreLoginActivity.Flow? = { null }
@Volatile var eaFlow: (String) -> StoreLoginActivity.Flow? = { null }
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
@@ -8,6 +8,7 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
ITCH("itch", "Itch.io", "Itch.io"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
BATTLENET("battlenet", "Battle.net", "Battle.net"),
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
EA("ea", "EA", "EA");
val folder: String get() = if (this == ITCH) "itch" else shortLabel
@@ -3,7 +3,8 @@ package com.droiddeck.launcher.stores
import java.io.File
object StoreExe {
private val SKIP = listOf("redist", "unins", "setup", "crash", "report", "helper", "dotnet", "vcredist", "directx", "eac", "easyanticheat", "battleye", "launcher", "updater", "config")
private val SKIP = listOf("redist", "unins", "setup", "crash", "report", "helper", "dotnet", "vcredist", "directx", "eac", "easyanticheat", "battleye", "launcher", "updater", "config", "installer", "autorun")
private val SKIP_DIRS = setOf("installer_resources", "redist", "_commonredist", "support")
fun pick(folder: File, hint: String?, title: String): String {
val hinted = hint?.takeIf { it.isNotBlank() }?.replace('\\', '/')?.trimStart('/')?.let { File(folder, it) }
@@ -28,7 +29,7 @@ object StoreExe {
if (SKIP.none { lower.contains(it) }) out.add(f)
}
}
for (f in files) if (f.isDirectory && !f.name.startsWith(".")) collect(f, out, depth + 1)
for (f in files) if (f.isDirectory && !f.name.startsWith(".") && f.name.lowercase() !in SKIP_DIRS) collect(f, out, depth + 1)
}
private fun depth(root: File, f: File): Int = relative(root, f).count { it == '/' }
@@ -11,12 +11,14 @@ object StoreLaunch {
const val LAUNCHER = ".droiddeck-launch.bat"
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EA_ENV = ".droiddeck-ea-env"
/** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */
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
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT
val file = File(folder, LAUNCHER)
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
file.writeText(launcherText(sidecar))
@@ -52,6 +54,13 @@ 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.UBISOFT) {
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
lines += "\"$UBISOFT_SERVICE\" \"%~dp0$UBISOFT_LAUNCH\""
lines += "goto :eof"
lines += ":direct"
lines += run
} else if (sidecar.store == Store.EA) {
lines += "if not exist \"%~dp0$EA_ENV\" goto run"
lines += "for /f \"usebackq tokens=1,* delims==\" %%a in (\"%~dp0$EA_ENV\") do set \"%%a=%%b\""
@@ -84,6 +93,17 @@ 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
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
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
return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar)
}
fun refreshLauncher(folder: File, sidecar: StoreGameSidecar) {
if (sidecar.launcher != LAUNCHER) return
val file = File(folder, LAUNCHER)
@@ -76,6 +76,15 @@ object StoreLaunchRequests {
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason)
}
}
"ubisoft-launch" -> {
val id = request.optString("id")
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
else {
lastLaunched = Store.UBISOFT to id
runCatching { com.droiddeck.launcher.stores.ubisoft.UbisoftLaunch.prepare(app, id) }
.getOrElse { JSONObject().put("ok", false).put("reason", it.javaClass.simpleName) }
}
}
"cloud-down" -> {
val store = Store.byId(request.optString("store"))
val id = request.optString("id")
@@ -47,6 +47,9 @@ class StoreLoginActivity : ComponentActivity() {
?.takeIf { "Chrome/" in it }
?: "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; ${Build.MODEL}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36"
private const val PAGE_TRIES = 20
private const val PAGE_RETRY_MS = 500L
fun generateState(): String {
val bytes = ByteArray(24)
java.security.SecureRandom().nextBytes(bytes)
@@ -60,6 +63,8 @@ class StoreLoginActivity : ComponentActivity() {
fun isRedirect(url: String): Boolean
fun finish(activity: StoreLoginActivity, view: WebView, url: String): String?
val readsPage: Boolean get() = false
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
fun pageReady(result: String): Boolean = true
fun forgetSignIn(done: () -> Unit) = done()
}
@@ -323,6 +328,14 @@ class StoreLoginActivity : ComponentActivity() {
}
}
private fun readPage(view: WebView, f: Flow, left: Int) {
view.evaluateJavascript(f.pageScript) { json ->
val result = json ?: ""
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
else Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
}
}
private fun complete(view: WebView, url: String) {
if (!captured.compareAndSet(false, true)) return
val f = flow ?: return
@@ -332,11 +345,7 @@ class StoreLoginActivity : ComponentActivity() {
titleText.text = getString(R.string.stores_login_finishing)
if (!f.readsPage) view.stopLoading()
}
if (f.readsPage) {
view.evaluateJavascript("(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()") { json ->
Thread({ settle(f.finish(this, view, json ?: "")) }, "store-login").start()
}
} else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
}
private fun settle(problem: String?) {
@@ -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.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> {}
}
}
}, pool).exceptionally { error ->
@@ -113,7 +113,7 @@ object StoreSizes {
AmazonManifest.parse(bytes).totalInstallSize
}
Store.EA -> com.droiddeck.launcher.stores.ea.EaSizes.size(context, item)
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> 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,74 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONObject
import java.io.File
/**
* Answers Denuvo activations for a running Ubisoft game. droiddeck-upc.exe writes the challenge
* the game's aux DLL sends to `bridge-<product>/denuvo-<id>.req`; the answer goes to `.rsp`.
*/
object UbisoftActivation {
private const val POLL_MS = 250L
private const val IDLE_MS = 60_000L
private val watching = HashMap<Long, Long>()
fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product")
/** Starts answering the product's activations; stale requests are cleared before this returns. */
fun watch(app: Context, product: Long) {
val dir = bridge(app, product)
synchronized(watching) {
val running = watching.containsKey(product)
watching[product] = System.currentTimeMillis()
if (running) return
dir.mkdirs()
dir.listFiles()?.forEach { it.delete() }
}
Thread({
var idleSince = 0L
while (true) {
runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } }
.onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") }
val now = System.currentTimeMillis()
if (SessionState.running) idleSince = 0L
else if (idleSince == 0L) idleSince = now
else if (now - idleSince > IDLE_MS) synchronized(watching) {
if (now - (watching[product] ?: 0L) > IDLE_MS) { watching.remove(product); return@Thread }
}
runCatching { Thread.sleep(POLL_MS) }
}
}, "ubisoft-activation-$product").start()
}
private fun answer(app: Context, product: Long, request: File) {
val challenge = runCatching { request.readBytes() }.getOrNull() ?: return
request.delete()
val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp")
val token = activate(app, product, challenge)
val part = File(reply.path + ".part")
part.writeBytes(token ?: ByteArray(0))
part.renameTo(reply)
}
private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? {
val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") }
val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)
.put("productId", product).put("challenge", hex(challenge)))
answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let {
StoresState.logLine("Ubisoft: activation for $product: $it")
return null
}
val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex)
StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token")
return token
}
internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
internal fun unhex(s: String): ByteArray? =
if (s.length % 2 != 0) null else runCatching { ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } }.getOrNull()
}
@@ -0,0 +1,175 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/** UbiServices sessions: a ticket from Ubisoft's own web sign-in, exchanged for a launcher session that remember-me renews. */
object UbisoftAuth {
private const val TAG = "UbisoftAuth"
const val SESSIONS = "https://public-ubiservices.ubi.com/v3/profiles/sessions"
/** The web app and genome connect.ubisoft.com's sign-in page accepts. */
private const val WEB_APP_ID = "f35adcb5-1911-440c-b1c9-48fdc1701c68"
private const val WEB_GENOME_ID = "5b36b900-65d8-47f3-93c8-86bdaa48ab50"
/** The Ubisoft Connect PC app id; its sessions are accepted by the library GraphQL and Demux. */
const val APP_ID = "f68a4bb5-608a-4ff2-8123-be8ef797e0a6"
private const val REFRESH_MARGIN_MS = 10 * 60 * 1000L
private val lock = Any()
class Session(
val ticket: String,
val sessionId: String,
val profileId: String,
val userId: String,
val name: String,
val expiresAt: Long,
val rememberMe: String,
)
class Reply(val status: Int, val body: String, val headers: Map<String, String>) {
val ok get() = status in 200..299
}
private val loggedIn = "https://connect.ubisoft.com/logged-in.html?appId=$WEB_APP_ID&lang=en-US&genomeId=$WEB_GENOME_ID"
val loginUrl = "https://connect.ubisoft.com/login?appId=$WEB_APP_ID&genomeId=$WEB_GENOME_ID&lang=en-US&nextUrl=" + URLEncoder.encode(loggedIn, "UTF-8")
val SIGN_IN_URLS = listOf("https://connect.ubisoft.com", "https://account.ubisoft.com", "https://ubisoft.com")
fun isLoggedInPage(url: String) = url.startsWith("https://connect.ubisoft.com/logged-in.html")
/** Reads connect.ubisoft.com's stored sign-in; the WebAuth SDK keeps it under keys holding `loginData` and `rememberMe`. */
const val PAGE_SCRIPT = "(function(){try{var o={};for(var i=0;i<localStorage.length;i++){var k=localStorage.key(i);" +
"if(/loginData|rememberMe|lastProfile/i.test(k))o[k]=localStorage.getItem(k);}return JSON.stringify(o);}catch(e){return '';}})()"
internal fun request(url: String, method: String = "GET", authorization: String? = null, sessionId: String? = null, body: String? = null, extra: Map<String, String> = emptyMap()): Reply {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = method
c.connectTimeout = 15_000
c.readTimeout = 25_000
c.setRequestProperty("Ubi-AppId", APP_ID)
c.setRequestProperty("Ubi-RequestedPlatformType", "uplay")
c.setRequestProperty("Content-Type", "application/json")
c.setRequestProperty("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")
authorization?.let { c.setRequestProperty("Authorization", it) }
sessionId?.let { c.setRequestProperty("Ubi-SessionId", it) }
for ((k, v) in extra) c.setRequestProperty(k, v)
try {
if (body != null) {
c.doOutput = true
c.outputStream.use { it.write(body.toByteArray()) }
}
val status = c.responseCode
val text = (if (status in 200..299) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()
val headers = c.headerFields.filterKeys { it != null }.mapKeys { it.key.lowercase() }.mapValues { it.value.joinToString(",") }
return Reply(status, text, headers)
} finally {
c.disconnect()
}
}
/** POSTs a session request, replaying it once when UbiServices answers with a challenge. */
private fun session(authorization: String): Reply {
val body = JSONObject().put("rememberMe", true).toString()
val first = request(SESSIONS, "POST", authorization, body = body)
val challenge = first.headers["ubi-challenge"] ?: return first
return request(SESSIONS, "POST", authorization, body = body, extra = mapOf("Ubi-Challenge" to challenge))
}
internal fun parseSession(body: String, rememberFallback: String = ""): Session? {
val o = runCatching { JSONObject(body) }.getOrNull() ?: return null
val ticket = o.optString("ticket").takeIf { it.isNotEmpty() && it != "null" } ?: return null
return Session(
ticket = ticket,
sessionId = o.optString("sessionId"),
profileId = o.optString("profileId"),
userId = o.optString("userId"),
name = o.optString("nameOnPlatform"),
expiresAt = parseTime(o.optString("expiration")),
rememberMe = o.optString("rememberMeTicket").takeIf { it.isNotEmpty() && it != "null" } ?: rememberFallback,
)
}
internal fun parseTime(s: String): Long = runCatching { java.time.OffsetDateTime.parse(s).toInstant().toEpochMilli() }
.recoverCatching { java.time.Instant.parse(s).toEpochMilli() }.getOrDefault(System.currentTimeMillis() + 60 * 60 * 1000L)
/** Values the web sign-in stored, found wherever the SDK nests them. */
internal fun webValues(dump: String): Map<String, String> {
val out = HashMap<String, String>()
fun walk(v: Any?) {
when (v) {
is JSONObject -> v.keys().forEach { k ->
val x = v.opt(k)
if (x is String && x.isNotEmpty() && k !in out) {
val nested = if (x.startsWith("{") || x.startsWith("[")) runCatching { org.json.JSONTokener(x).nextValue() }.getOrNull() else null
if (nested != null) walk(nested) else out[k] = x
} else walk(x)
}
is JSONArray -> for (i in 0 until v.length()) walk(v.opt(i))
}
}
val top = runCatching { org.json.JSONTokener(dump).nextValue() }.getOrNull()
walk(if (top is String) runCatching { JSONObject(top) }.getOrNull() else top)
return out
}
/** Turns the page's stored sign-in into a launcher session; returns null on success or a reason. */
fun completeWebSignIn(context: Context, dump: String): String? {
val web = webValues(dump)
val ticket = web["ticket"]
val remember = web["rememberMeTicket"].orEmpty()
val fresh = when {
ticket != null -> session("ubi_v1 t=$ticket").let { r ->
parseSession(r.body, remember) ?: run { Log.w(TAG, "ticket exchange: ${r.status} ${r.body.take(200)}"); null }
}
else -> null
} ?: remember.takeIf { it.isNotEmpty() }?.let { rm -> parseSession(session("rm_v1 t=$rm").body, rm) }
?: return "no ticket"
save(context, fresh)
return null
}
private fun save(context: Context, s: Session) {
val name = s.name.ifEmpty { profileName(s) }
StoreAccounts.write(context.applicationContext, Store.UBISOFT, JSONObject()
.put("access_token", s.ticket)
.put("session_id", s.sessionId)
.put("profile_id", s.profileId)
.put("user_id", s.userId)
.put("display_name", name)
.put("expires_at", s.expiresAt)
.put("remember_me", s.rememberMe))
}
private fun profileName(s: Session): String = runCatching {
JSONObject(request("https://public-ubiservices.ubi.com/v3/profiles/me", authorization = "ubi_v1 t=${s.ticket}", sessionId = s.sessionId).body).optString("nameOnPlatform")
}.getOrDefault("")
fun load(context: Context): Session? {
val o = StoreAccounts.read(context.applicationContext, Store.UBISOFT) ?: return null
val ticket = o.optString("access_token").takeIf { it.isNotEmpty() } ?: return null
return Session(ticket, o.optString("session_id"), o.optString("profile_id"), o.optString("user_id"), o.optString("display_name"), o.optLong("expires_at"), o.optString("remember_me"))
}
/** A live session, renewed through remember-me shortly before it expires. */
fun current(context: Context): Session? = synchronized(lock) {
val s = load(context) ?: return null
if (s.expiresAt - System.currentTimeMillis() > REFRESH_MARGIN_MS || s.rememberMe.isEmpty()) return s
val renewed = runCatching { session("rm_v1 t=${s.rememberMe}") }.getOrNull()?.let { parseSession(it.body, s.rememberMe) }
if (renewed == null) {
Log.w(TAG, "remember-me renewal failed")
return if (s.expiresAt > System.currentTimeMillis()) s else null
}
save(context, Session(renewed.ticket, renewed.sessionId, renewed.profileId.ifEmpty { s.profileId }, renewed.userId.ifEmpty { s.userId },
renewed.name.ifEmpty { s.name }, renewed.expiresAt, renewed.rememberMe))
load(context)
}
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.UBISOFT) }
}
@@ -0,0 +1,246 @@
package com.droiddeck.launcher.stores.ubisoft
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.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.WebCookies
import org.json.JSONObject
object UbisoftBackend : StoreBackend {
override val store: Store = Store.UBISOFT
init {
LoginFlows.ubisoftFlow = { ua -> UbisoftLogin(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) {
UbisoftAuth.signOut(context.applicationContext)
UbisoftLibrary.reset()
runCatching { WebCookies.expire(UbisoftAuth.SIGN_IN_URLS, ".ubisoft.com", listOf("/")) {} }
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
Thread({ UbisoftLibrary.sync(app, force) }, "ubisoft-sync").start()
}
override fun loadShelves(context: Context, force: Boolean) {}
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
val app = context.applicationContext
item.extra[STEAM_APP]?.takeIf { item.extra["productId"] == null }?.let { steam ->
StoresState.logLine("Ubisoft: ${item.title} is owned on Steam; installing Steam app $steam")
installInSteam(app, steam)
return
}
if (!UbisoftNative.ready()) {
StoresState.logLine(UbisoftNative.ENGINE_MISSING)
StoresState.post { StoresState.problems[store] = UbisoftNative.ENGINE_MISSING }
return
}
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) { UbisoftInstaller(app, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
const val STEAM_APP = "steamAppId"
/** Steam asks to install a game it does not have when told to run it. */
private fun installInSteam(app: Context, steamAppId: String) {
if (com.droiddeck.launcher.session.SessionState.running) {
if (!com.droiddeck.launcher.session.SessionService.launchGame(app, steamAppId)) StoresState.logLine("Ubisoft: Steam is busy; install Steam app $steamAppId there")
return
}
app.startActivity(Intent(app, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(steamAppId))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
internal class UbisoftLogin(override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = UbisoftAuth.loginUrl
override val readsPage: Boolean get() = true
override val pageScript: String get() = UbisoftAuth.PAGE_SCRIPT
override fun pageReady(result: String): Boolean = result.contains("ticket", ignoreCase = true)
override fun isRedirect(url: String): Boolean = UbisoftAuth.isLoggedInPage(url)
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(UbisoftAuth.SIGN_IN_URLS, ".ubisoft.com", listOf("/")) { done() } }.onFailure { done() }
}
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? = try {
UbisoftAuth.completeWebSignIn(activity, url)?.let {
Log.w("UbisoftLogin", "sign-in incomplete: $it")
activity.getString(R.string.stores_login_error_verification)
}
} catch (e: Exception) {
Log.w("UbisoftLogin", "sign-in failed: ${e.javaClass.simpleName}")
activity.getString(R.string.stores_login_error_generic)
}
}
object UbisoftLibrary {
private const val GRAPHQL = "https://public-ubiservices.ubi.com/v1/profiles/me/uplay/graphql"
private const val PAGE = 50
private const val QUERY = "query OwnedGames(\$limit: Int, \$offset: Int) { viewer { games(limit: \$limit, offset: \$offset) { totalCount nodes { id spaceId name coverUrl backgroundUrl bannerUrl releaseDate } } } }"
private val generation = java.util.concurrent.atomic.AtomicInteger()
private val running = java.util.concurrent.atomic.AtomicReference<Int?>(null)
/** Forgets the signed-out account: its sync results are dropped and a new account may sync at once. */
fun reset() {
generation.incrementAndGet()
StoresState.post { StoresState.shelves.remove(Store.UBISOFT) }
}
private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() }
internal fun parsePage(body: String): Pair<List<CatalogItem>, Int> {
val o = JSONObject(body)
o.optJSONArray("errors")?.optJSONObject(0)?.let { throw IllegalStateException(it.optString("message")) }
val games = o.optJSONObject("data")?.optJSONObject("viewer")?.optJSONObject("games") ?: return emptyList<CatalogItem>() to 0
val nodes = games.optJSONArray("nodes")
val items = (0 until (nodes?.length() ?: 0)).mapNotNull { nodes!!.optJSONObject(it) }.mapNotNull { n ->
val space = n.optString("spaceId").takeIf { it.isNotEmpty() } ?: return@mapNotNull null
fun s(k: String) = n.optString(k).takeIf { it.isNotEmpty() && it != "null" }
CatalogItem(
Store.UBISOFT, space, n.optString("name").trim(), s("backgroundUrl") ?: s("bannerUrl"),
tallImageUrl = s("coverUrl"), releaseDate = s("releaseDate")?.take(10).orEmpty(), owned = true,
extra = mapOf("spaceId" to space, "gameId" to n.optString("id")),
)
}
return items to games.optInt("totalCount", items.size)
}
/** Base games with a manifest, by UbiServices space; add-ons and bundles share spaces with their game. */
internal fun ownedBySpace(owned: JSONObject?): Map<String, JSONObject> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
val games = (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optString("manifest").isNotEmpty() && it.optInt("productType") == 0 && it.optBoolean("owned", true) }
val out = LinkedHashMap<String, JSONObject>()
for (key in listOf("spaceId")) for (g in games) {
val space = g.optString(key).takeIf { it.isNotEmpty() } ?: continue
out.putIfAbsent(space, g)
}
return out
}
private val STEAM_ID = Regex("""^\s*steam_app_id:\s*['"]?(\d+)""", RegexOption.MULTILINE)
private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?Steam\b""", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
/** The Steam app of a product Ubisoft says is owned and installed through Steam. */
internal fun steamApp(configuration: String): String? =
if (THIRD_PARTY.containsMatchIn(configuration)) STEAM_ID.find(configuration)?.groupValues?.get(1) else null
/** Owned games Ubisoft delivers through Steam, by UbiServices space. */
internal fun steamBySpace(owned: JSONObject?): Map<String, String> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && it.optString("spaceId").isNotEmpty() }
.mapNotNull { o -> steamApp(o.optString("configuration"))?.let { o.optString("spaceId") to it } }.toMap()
}
private val RELATIVE = Regex("""relative:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE)
private val NAME = Regex("""^\s{1,4}name:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE)
/** The product's name from its configuration, following a localisation key such as `l1` to its default text. */
internal fun title(configuration: String): String? {
val raw = NAME.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
if (!Regex("""l\d+""").matches(raw)) return raw
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return raw
return Regex("""^\s+${raw}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim() ?: raw
}
/** The first launch path under `start_game` in a product's configuration. */
internal fun executable(configuration: String): String? {
val start = configuration.indexOf("start_game").takeIf { it >= 0 } ?: return null
return RELATIVE.find(configuration, start)?.groupValues?.get(1)?.trim()?.takeIf { it.endsWith(".exe", true) }
}
fun sync(app: Context, force: Boolean) {
val gen = generation.get()
if (running.getAndSet(gen) == gen) return
try {
val s = UbisoftAuth.current(app)
if (s == null) {
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_sign_in) }
return
}
if (StoresState.library[Store.UBISOFT].isNullOrEmpty()) post(gen) { StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list) }
val all = ArrayList<CatalogItem>()
var offset = 0
while (true) {
val body = JSONObject().put("operationName", "OwnedGames").put("query", QUERY)
.put("variables", JSONObject().put("limit", PAGE).put("offset", offset)).toString()
val reply = UbisoftAuth.request(GRAPHQL, "POST", "Ubi_v1 t=${s.ticket}", s.sessionId, body)
if (reply.status == 401) StoresState.markSignInExpired(Store.UBISOFT)
if (!reply.ok) throw IllegalStateException("library ${reply.status}")
val (items, total) = parsePage(reply.body)
all += items
offset += PAGE
if (items.isEmpty() || offset >= total) break
}
val owned = UbisoftNative.call("owned", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId))
owned?.optString("error")?.takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: ownership: $it") }
val bySpace = ownedBySpace(owned)
owned?.takeIf { it.optInt("manifestsAsked") > 0 }?.let {
StoresState.logLine("Ubisoft: latest manifests: ${it.optInt("manifestsFound")} of ${it.optInt("manifestsAsked")} ${it.optString("manifestError")}".trim())
}
fun download(o: JSONObject) = listOfNotNull(
"productId" to o.optLong("productId").toString(),
o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it },
o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it },
executable(o.optString("configuration"))?.let { "exe" to it },
)
val listed = all.distinctBy { it.id }
val onSteam = steamBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: onSteam[g.id]?.let { g.copy(extra = g.extra + (UbisoftBackend.STEAM_APP to it)) } ?: g }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
}
val games = (matched + unlisted).sortedBy { it.title.lowercase() }
StoresState.logLine("Ubisoft: ${bySpace.size} downloadable products; " +
games.filter { it.extra.containsKey("productId") }.joinToString(", ") { "${it.title}=${it.extra["productId"]}" })
post(gen) {
StoresState.status.remove(Store.UBISOFT)
StoresState.problems.remove(Store.UBISOFT)
StoresState.library[Store.UBISOFT] = games
StoresState.shelves[Store.UBISOFT] = com.droiddeck.launcher.stores.StoreShelves(
trending = games.sortedByDescending { it.extra.containsKey("productId") }, art = games.mapNotNull { it.imageUrl })
}
StoresState.logLine("Ubisoft: ${games.size} owned games; on Steam: " + games.filter { it.extra.containsKey(UbisoftBackend.STEAM_APP) }.joinToString(", ") { "${it.title}=${it.extra[UbisoftBackend.STEAM_APP]}" })
} catch (e: Exception) {
StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}")
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_failed) }
} finally {
running.compareAndSet(gen, null)
}
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/** The one prefix every Ubisoft game runs in, so Ubisoft Connect is installed and signed in once. */
object UbisoftConnect {
const val APP_ID = 2929927072L
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher/upc.exe").isFile
fun launchOptions(context: Context): String =
AddedGames.guestPath(context, prefix(context))?.let { "STEAM_COMPAT_DATA_PATH=$it %command%" }.orEmpty()
}
@@ -0,0 +1,104 @@
package com.droiddeck.launcher.stores.ubisoft
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.StoreLanguage
import com.droiddeck.launcher.stores.amazon.AmazonNative
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
internal class UbisoftInstaller(
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 s = UbisoftAuth.current(app) ?: throw IllegalStateException("Not signed in to Ubisoft")
val product = item.extra["productId"]?.toLongOrNull() ?: throw IllegalStateException("Ubisoft lists no download for ${item.title} on this account")
val cover = item.tallImageUrl ?: item.imageUrl
StoreInstalls.begin(folder, Store.UBISOFT, item.id, item.title, cover, item.imageUrl)
if (cancelled.get()) return null
val locale = StoreLanguage.localeFor(null, app)
val request = JSONObject()
.put("ticket", s.ticket)
.put("sessionId", s.sessionId)
.put("productId", product)
.put("manifest", item.extra["manifest"].orEmpty())
.put("folder", folder.absolutePath)
.put("language", "${locale.language}-${locale.country}")
val shown = AtomicLong(-1)
val downloading = AtomicBoolean(false)
val listener = object : AmazonNative.InstallListener {
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
override fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int) {
handle.stageProgress(doneBytes, totalBytes, files, filesTotal, bytes = true)
}
override fun onSizes(pendingBytes: Long, totalBytes: Long) { handle.diskSize(totalBytes) }
override fun onProgress(done: Long, total: Long, files: Int, filesTotal: Int) {
if (downloading.compareAndSet(false, true)) handle.stage(DownloadStage.DOWNLOAD)
while (true) {
val before = shown.get()
if (done < before) return
if (shown.compareAndSet(before, done)) break
}
handle.progress(done, total, "Downloading ($files/$filesTotal files)")
}
override fun onLog(line: String) { handle.log(line) }
override fun beforeReplace(): Boolean = true
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
}
val outcome = UbisoftNative.install(request, listener, cancelled)
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The Ubisoft install failed" })
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
val configured = resolve(folder, item.extra["exe"].orEmpty())
val exe = configured ?: StoreExe.pick(folder, null, item.title).ifEmpty { "game.exe" }
handle.log("ubisoft: exe=$exe")
val sidecar = StoreGameSidecar(
Store.UBISOFT, item.id, item.title, exe = exe,
installVersion = item.extra["manifest"].orEmpty(), installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, cloud = false,
extra = item.extra.filterKeys { it in KEPT } + listOfNotNull(
outcome.result?.optJSONArray("chunks")?.let { UbisoftLaunch.CHUNKS to it.toString() },
outcome.result?.optJSONObject("setup")?.let { UbisoftLaunch.SETUP to it.toString() },
),
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
}
internal companion object {
val KEPT = setOf("productId", "spaceId", "manifest", "appId")
/** A configured exe the way Windows finds it: any letter case, else the same file name anywhere in the install. */
fun resolve(folder: File, configured: String): String? {
val rel = configured.replace('\\', '/').trimStart('/').takeIf { it.isNotEmpty() } ?: return null
var at = folder
for (part in rel.split('/')) {
at = at.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return byName(folder, rel.substringAfterLast('/'))
}
return if (at.isFile) at.relativeTo(folder).invariantSeparatorsPath else byName(folder, rel.substringAfterLast('/'))
}
private fun byName(folder: File, name: String): String? =
folder.walkTopDown().maxDepth(5).firstOrNull { it.isFile && it.name.equals(name, ignoreCase = true) }?.relativeTo(folder)?.invariantSeparatorsPath
}
}
@@ -0,0 +1,86 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
/** What the launcher service hands a starting Ubisoft game: the account, its products and a fresh game ticket. */
object UbisoftLaunch {
private const val ENTITLEMENTS = "https://public-ubiservices.ubi.com/v1/profiles/me/global/ubiconnect/entitlement/api/entitlements"
private const val ME = "https://public-ubiservices.ubi.com/v3/users/me"
fun prepare(app: Context, id: String): JSONObject {
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { f ->
StoreGameSidecar.read(f)?.let { it.store == Store.UBISOFT && it.id == id } == true
} ?: return failure("not-installed")
val sidecar = StoreGameSidecar.read(folder) ?: return failure("not-installed")
val product = sidecar.extra["productId"]?.toLongOrNull() ?: return failure("no-product")
val s = UbisoftAuth.current(app) ?: return failure("signed-out")
val native = UbisoftNative.call("launch", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId).put("productId", product))
?: return failure("engine-missing")
native.optString("error").takeIf { it.isNotEmpty() }?.let {
StoresState.logLine("Ubisoft: launch ticket for $product: $it")
return failure("ticket: $it")
}
val auth = "Ubi_v1 t=${s.ticket}"
val me = runCatching { UbisoftAuth.request(ME, "GET", auth, s.sessionId) }.getOrNull()?.takeIf { it.ok }
?.let { runCatching { JSONObject(it.body) }.getOrNull() }
val account = JSONObject()
.put("userId", s.userId)
.put("username", me?.optString("username")?.takeIf { it.isNotEmpty() } ?: s.name)
.put("nameOnPlatform", me?.optString("nameOnPlatform")?.takeIf { it.isNotEmpty() } ?: s.name)
.put("email", me?.optString("email").orEmpty())
.put("country", me?.optString("country")?.takeIf { it.isNotEmpty() } ?: "US")
val appId = runCatching { UbisoftAuth.request(ENTITLEMENTS, "GET", auth, s.sessionId) }.getOrNull()?.takeIf { it.ok }
?.let { applicationId(it.body, product) } ?: sidecar.extra["appId"].orEmpty()
StoresState.logLine("Ubisoft: launch ticket for $product ready (${native.optJSONArray("owned")?.length() ?: 0} products, appId ${if (appId.isEmpty()) "unknown" else "found"})")
val language = com.droiddeck.launcher.stores.StoreLanguage.localeFor(null, app).let { "${it.language}-${it.country}" }
val cached = sidecar.extra[CHUNKS]?.let { runCatching { JSONArray(it) }.getOrNull() }
var setup = sidecar.extra[SETUP]?.let { runCatching { JSONObject(it) }.getOrNull() }
val chunks = if (cached != null && setup != null) cached else
UbisoftNative.call("chunks", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId).put("productId", product)
.put("manifest", sidecar.extra["manifest"] ?: sidecar.installVersion).put("folder", folder.path).put("language", language))
?.let { r ->
r.optString("error").takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: manifest for $product: $it") }
setup = r.optJSONObject("setup")
r.optJSONArray("chunks")
}?.also { c ->
runCatching {
StoreGameSidecar.read(folder)?.let { sc ->
sc.copy(extra = sc.extra + (CHUNKS to c.toString()) + listOfNotNull(setup?.let { SETUP to it.toString() })).write(folder)
}
com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, Store.UBISOFT, id)
?.let { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(app, it) }
}
} ?: cached
setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") }
UbisoftActivation.watch(app, product)
return JSONObject().put("ok", true)
.put("productId", product)
.put("ticket", native.optString("ticket"))
.put("owned", native.optJSONArray("owned") ?: JSONArray())
.put("products", native.optJSONArray("products") ?: JSONArray())
.put("account", account)
.put("appId", appId)
.put("language", language)
.put("chunks", chunks ?: JSONArray())
.put("registry", setup?.optJSONArray("registry") ?: JSONArray())
}
const val CHUNKS = "chunks"
const val SETUP = "setup"
/** The entitlement's `applicationId` for the product; the list sits under one of a few keys depending on the API version. */
internal fun applicationId(body: String, product: Long): String? {
val root = runCatching { JSONObject(body) }.getOrNull() ?: return null
val list = sequenceOf("items", "entitlements", "products", "games", "results").firstNotNullOfOrNull { root.optJSONArray(it) } ?: return null
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.firstOrNull { it.optLong("productId") == product }?.optString("applicationId")?.takeIf { it.isNotEmpty() }
}
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.stores.ubisoft
import android.util.Log
import com.droiddeck.launcher.stores.StoresNative
import com.droiddeck.launcher.stores.amazon.AmazonNative
import org.json.JSONObject
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object UbisoftNative {
private const val TAG = "UbisoftNative"
const val ENGINE_MISSING = "Ubisoft: the store engine is not available"
fun ready(): Boolean = StoresNative.ensureLoaded()
fun call(op: String, request: JSONObject): JSONObject? {
if (!ready()) return null
val text = try { nativeCall(op, request.toString()) } catch (t: Throwable) {
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
null
} ?: return null
return runCatching { JSONObject(text) }.getOrNull()
}
fun install(request: JSONObject, events: AmazonNative.InstallListener, cancelled: AtomicBoolean): AmazonNative.InstallOutcome {
if (!ready()) return AmazonNative.InstallOutcome(false, false, ENGINE_MISSING, null)
val done = CountDownLatch(1)
val holder = arrayOfNulls<AmazonNative.InstallOutcome>(1)
val bridge = object : AmazonNative.InstallListener by events {
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
holder[0] = AmazonNative.InstallOutcome(success, cancelled, error, result.takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() })
done.countDown()
}
}
val handle = try { nativeInstall(request.toString(), bridge) } catch (t: Throwable) {
return AmazonNative.InstallOutcome(false, false, "The Ubisoft install could not start: ${t.javaClass.simpleName}", null)
}
if (handle == 0L) return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The Ubisoft install could not start", null)
try {
var forwarded = false
while (true) {
val finished = try { done.await(250, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { cancelled.set(true); false }
if (finished) break
if (!forwarded && cancelled.get()) { nativeCancel(handle); forwarded = true }
}
} finally {
nativeRelease(handle)
}
return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The Ubisoft install ended without a result", null)
}
@JvmStatic private external fun nativeCall(op: String, request: String): String?
@JvmStatic private external fun nativeInstall(request: String, listener: AmazonNative.InstallListener): Long
@JvmStatic private external fun nativeCancel(handle: Long)
@JvmStatic private external fun nativeRelease(handle: Long)
}
@@ -33,6 +33,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
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))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
@@ -49,6 +50,7 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.ITCH.id -> Store.ITCH.label
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
Store.BATTLENET.id -> Store.BATTLENET.label
Store.UBISOFT.id -> Store.UBISOFT.shortLabel
Store.EA.id -> Store.EA.label
else -> stringResource(R.string.source_added)
}
@@ -1157,6 +1157,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
null -> return base
}
@@ -56,7 +56,7 @@ import java.io.File
private fun installable(name: String, all: Map<String, WinComponents.Component>): String = WinComponents.installable(name, all)
@Composable
private fun originName(origin: String): String = if (origin == WinCompSources.Origin.XBOX.name) "Xbox" else stringResource(
private fun originName(origin: String): String = if (origin == WinCompSources.Origin.XBOX.name) "Xbox" else if (origin == WinCompSources.Origin.UBISOFT.name) "Ubisoft Connect" else stringResource(
when (origin) {
WinCompSources.Origin.GOG.name -> R.string.wincomp_src_gog
WinCompSources.Origin.EPIC.name -> R.string.wincomp_src_epic
@@ -71,6 +71,7 @@ private fun autoReason(r: WinComponents.AutoReason): String = when (r.kind) {
WinCompSources.Origin.GOG.name -> stringResource(R.string.wincomp_auto_gog)
WinCompSources.Origin.EPIC.name -> stringResource(R.string.wincomp_auto_epic)
WinCompSources.Origin.AMAZON.name -> stringResource(R.string.wincomp_auto_amazon)
WinCompSources.Origin.UBISOFT.name -> "From Ubisoft's install steps for this game"
WinCompSources.Origin.XBOX.name -> "Xbox games install it with the game (${r.args.getOrElse(0) { "VC14" }})"
else -> ""
}