diff --git a/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt b/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt index ffec1a696f..b31244c60c 100644 --- a/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt @@ -47,7 +47,7 @@ class DeviceCodeActivity : ComponentActivity() { private var code by mutableStateOf("") private var label by mutableStateOf("") private var message by mutableStateOf(null) - private var note by mutableStateOf(null) + private var paste = false private var agent = true private var url = "" private var display: Int? = null @@ -90,6 +90,18 @@ class DeviceCodeActivity : ComponentActivity() { } } + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus && paste && !inPip) tryPaste() + } + + /** Android hands the clipboard only to the app in front, which this float is once expanded. */ + private fun tryPaste() { + val text = runCatching { getSystemService(ClipboardManager::class.java)?.primaryClip?.getItemAt(0)?.coerceToText(this)?.toString() }.getOrNull() + if (text.isNullOrBlank()) return + if (onPaste?.invoke(this, text) == true) returnToApp() + } + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) inPip = isInPictureInPictureMode @@ -102,7 +114,7 @@ class DeviceCodeActivity : ComponentActivity() { label = intent.getStringExtra(EXTRA_LABEL) ?: getString(R.string.agent_step_github) agent = intent.getBooleanExtra(EXTRA_AGENT, true) message = intent.getStringExtra(EXTRA_MESSAGE) - note = intent.getStringExtra(EXTRA_NOTE) + paste = intent.getBooleanExtra(EXTRA_PASTE, false) display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 } if (agent) copy() } @@ -142,13 +154,14 @@ class DeviceCodeActivity : ComponentActivity() { ) { Text(label, style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant) val shown = message - if (shown != null) FitText(shown, maxSize = if (inPip) 22.sp else 32.sp, fontWeight = FontWeight.Bold, color = accent, - modifier = Modifier.fillMaxWidth()) + if (shown != null) Text(shown, fontSize = if (inPip) 12.sp else 22.sp, fontWeight = FontWeight.Bold, color = accent, + maxLines = 4, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth()) else FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent, modifier = Modifier.fillMaxWidth()) - Text(note ?: Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 2, textAlign = TextAlign.Center) + if (!paste) Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 2, textAlign = TextAlign.Center) if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy) + if (paste) PrimaryButton(stringResource(R.string.fm_paste), onClick = ::tryPaste) + else PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy) SecondaryButton(stringResource(R.string.common_close), onClick = ::finish) } } @@ -162,16 +175,21 @@ class DeviceCodeActivity : ComponentActivity() { private const val EXTRA_LABEL = "label" private const val EXTRA_AGENT = "agent" private const val EXTRA_MESSAGE = "message" - private const val EXTRA_NOTE = "note" + private const val EXTRA_PASTE = "paste" + + /** Takes what the user copied from the page; true once it was accepted. */ + @Volatile var onPaste: ((Context, String) -> Boolean)? = null private var current: WeakReference? = null - /** False when this device cannot float a window, so the caller opens the page itself. */ - /** [message] replaces the code for a page whose link already carries it; [note] replaces the address line. */ - fun show(context: Context, code: String, url: String, display: Int, label: String? = null, message: String? = null, note: String? = null): Boolean { + /** + * False when this device cannot float a window, so the caller opens the page itself. [message] + * replaces the code; [paste] shows a Paste button that hands the clipboard to [onPaste]. + */ + fun show(context: Context, code: String, url: String, display: Int, label: String? = null, message: String? = null, paste: Boolean = false): Boolean { if (!PairingGuideActivity.canFloat(context)) return false val intent = Intent(context, DeviceCodeActivity::class.java) .putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display) - .putExtra(EXTRA_AGENT, label == null).also { if (label != null) it.putExtra(EXTRA_LABEL, label); if (message != null) it.putExtra(EXTRA_MESSAGE, message); if (note != null) it.putExtra(EXTRA_NOTE, note) } + .putExtra(EXTRA_AGENT, label == null).also { if (label != null) it.putExtra(EXTRA_LABEL, label); if (message != null) it.putExtra(EXTRA_MESSAGE, message); it.putExtra(EXTRA_PASTE, paste) } .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return runCatching { if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle()) @@ -182,16 +200,13 @@ class DeviceCodeActivity : ComponentActivity() { fun close() { current?.get()?.finish() } + } - /** While the float is on screen, Android lets it bring DroidDeck back in front of the browser. */ - fun returnToApp(): Boolean { - val float = current?.get()?.takeIf { !it.isFinishing && !it.isDestroyed } ?: return false - val opened = runCatching { - float.startActivity(Intent(float, FrontEndActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) - }.isSuccess - float.finish() - return opened + private fun returnToApp() { + runCatching { + startActivity(Intent(this, FrontEndActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) } + finish() } } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index bdb334a9e7..7f01737493 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -1974,6 +1974,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (hasFocus) { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) applyLauncherFullscreen() + com.droiddeck.launcher.stores.epic.EpicCodeLogin.resumed(this) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index b40eed19d1..a1b54088eb 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -10,14 +10,16 @@ internal object LoginFlows { fun forStore(store: Store, state: String, browserUserAgent: String): StoreLoginActivity.Flow? = when (store) { Store.GOG -> GogFlow(state, browserUserAgent) + Store.EPIC -> epicFlow() Store.AMAZON -> amazonFlow() Store.GAMEJOLT -> gameJoltFlow(browserUserAgent) Store.UBISOFT -> ubisoftFlow(browserUserAgent) Store.EA -> eaFlow(browserUserAgent) Store.ROCKSTAR -> rockstarFlow(browserUserAgent) - Store.EPIC, Store.ITCH, Store.XBOX, Store.BATTLENET -> null + 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 } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 54571ab172..67b9a65c18 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -156,6 +156,15 @@ class StoreLoginActivity : ComponentActivity() { setTextColor(0xFFF2F4F7.toInt()); textSize = 16f; setPadding(dp(16), 0, dp(8), 0) layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) } + val browser = Button(this, null, android.R.attr.borderlessButtonStyle).apply { + text = getString(R.string.stores_login_in_browser); setTextColor(0xFFF2F4F7.toInt()); isAllCaps = false + visibility = if (store == Store.EPIC && clientUrl == null) View.VISIBLE else View.GONE + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dp(48)) + setOnClickListener { + com.droiddeck.launcher.stores.epic.EpicCodeLogin.begin(this@StoreLoginActivity) + finish() + } + } val reload = ImageButton(this).apply { setImageResource(android.R.drawable.ic_menu_rotate); setBackgroundColor(Color.TRANSPARENT) contentDescription = getString(R.string.stores_login_reload); layoutParams = LinearLayout.LayoutParams(dp(48), dp(48)) @@ -167,7 +176,7 @@ class StoreLoginActivity : ComponentActivity() { setOnClickListener { finish() } } topBar = bar; reloadButton = reload; closeButton = close - bar.addView(titleText); bar.addView(reload); bar.addView(close) + bar.addView(titleText); bar.addView(browser); bar.addView(reload); bar.addView(close) progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 100; isIndeterminate = false layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(3)) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt index 0ec674b1cf..fb9c5c8ab4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt @@ -1,10 +1,12 @@ package com.droiddeck.launcher.stores.epic import android.content.Context +import android.content.Intent import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.EpicLaunchSupport 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 @@ -17,9 +19,16 @@ import com.droiddeck.launcher.stores.mergeItems object EpicBackend : StoreBackend, EpicLaunchSupport { override val store: Store = Store.EPIC + init { + LoginFlows.epicFlow = { EpicLogin.create() } + } + override fun signIn(context: Context) { - StoreLoginActivity.floodColor = null - EpicDeviceLogin.begin(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) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCodeLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCodeLogin.kt new file mode 100644 index 0000000000..e648c97d24 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCodeLogin.kt @@ -0,0 +1,114 @@ +package com.droiddeck.launcher.stores.epic + +import android.app.Activity +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.Browser +import android.util.Log +import android.widget.Toast +import com.droiddeck.launcher.DeviceCodeActivity +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoresState +import org.json.JSONObject + +/** + * Epic's login page in the browser ends on the launcher's authorization code shown as text, since + * its page script keeps the launcher client from being sent back to an app; the user copies it and + * DroidDeck takes it from the clipboard when it is in front again. + */ +internal object EpicCodeLogin { + private const val TAG = "EpicCodeLogin" + private const val CHROME = "com.android.chrome" + private const val PENDING_MS = 15 * 60 * 1000L + private val ANY_CODE = Regex("(? offer(ctx, text) } + val floated = DeviceCodeActivity.show(app, "", url, 0, Store.EPIC.label, app.getString(R.string.epic_copy_code), paste = true) + if (!floated && !openBrowser(app, url)) { pendingUntil = 0; failed(app) } + } + }, "epic-code-login").apply { isDaemon = true }.start() + } + + /** Called when a DroidDeck window gains focus, the only moment Android lets it read the clipboard. */ + fun resumed(activity: Activity) { + if (System.currentTimeMillis() > pendingUntil) return + val text = runCatching { + activity.getSystemService(ClipboardManager::class.java)?.primaryClip?.getItemAt(0)?.coerceToText(activity)?.toString() + }.getOrNull() ?: return + offer(activity, text) + } + + private fun offer(context: Context, text: String): Boolean { + if (System.currentTimeMillis() > pendingUntil) return false + val trimmed = text.trim() + val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", trimmed))?.optString("code").orEmpty() + .ifEmpty { ANY_CODE.find(trimmed)?.value.orEmpty() } + if (code.isEmpty()) return false + pendingUntil = 0 + val app = context.applicationContext + runCatching { app.getSystemService(ClipboardManager::class.java)?.clearPrimaryClip() } + DeviceCodeActivity.close() + Thread({ + val problem = signIn(app, code) + main.post { + if (problem == null) StoresState.refresh(app) + else { + // Epic's codes last only minutes; the page in the signed-in browser hands out a fresh one. + Toast.makeText(app, problem, Toast.LENGTH_LONG).show() + begin(app) + } + } + }, "epic-code-login").apply { isDaemon = true }.start() + return true + } + + private fun signIn(app: Context, code: String): String? { + val answer = EpicNative.call("auth.signIn", JSONObject().put("code", code)) + val tokens = answer?.let(EpicCredentialStore.TokenResult::from) + if (tokens == null) { + Log.w(TAG, "code exchange failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}") + return app.getString(R.string.stores_login_error_generic) + } + return try { + EpicCredentialStore.save(app, tokens, merge = false) + null + } catch (e: Exception) { + Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}") + app.getString(R.string.stores_login_error_generic) + } + } + + private fun openBrowser(app: Context, url: String): Boolean { + for (pkg in listOf(CHROME, null)) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) + .addCategory(Intent.CATEGORY_BROWSABLE) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .putExtra(Browser.EXTRA_APPLICATION_ID, app.packageName) + if (pkg != null) intent.setPackage(pkg) + if (runCatching { app.startActivity(intent) }.isSuccess) return true + } + Log.w(TAG, "no browser took the sign-in") + return false + } + + private fun failed(app: Context) = Toast.makeText(app, R.string.stores_login_error_generic, Toast.LENGTH_LONG).show() +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDeviceLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDeviceLogin.kt deleted file mode 100644 index 993ed041f0..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDeviceLogin.kt +++ /dev/null @@ -1,135 +0,0 @@ -package com.droiddeck.launcher.stores.epic - -import android.app.Notification -import android.app.NotificationChannel -import android.app.NotificationManager -import android.app.PendingIntent -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.os.Handler -import android.os.Looper -import android.provider.Browser -import android.provider.Settings -import android.util.Log -import android.widget.Toast -import com.droiddeck.launcher.DeviceCodeActivity -import com.droiddeck.launcher.FrontEndActivity -import com.droiddeck.launcher.R -import com.droiddeck.launcher.stores.Store -import com.droiddeck.launcher.stores.StoresState -import org.json.JSONObject -import java.util.concurrent.atomic.AtomicInteger - -internal object EpicDeviceLogin { - private const val TAG = "EpicDeviceLogin" - private const val CHROME = "com.android.chrome" - private const val CHANNEL_ID = "epic_sign_in" - private const val NOTIFICATION_ID = 4109 - private const val NOTICE_TIMEOUT_MS = 60_000L - - private val attempt = AtomicInteger() - private val main = Handler(Looper.getMainLooper()) - - fun begin(context: Context) { - val app = context.applicationContext - val mine = attempt.incrementAndGet() - Thread({ run(app, mine) }, "epic-device-login").apply { isDaemon = true }.start() - } - - private fun run(app: Context, mine: Int) { - val start = EpicNative.call("auth.deviceStart") - val url = start?.optString("url").orEmpty() - val deviceCode = start?.optString("deviceCode").orEmpty() - val userCode = start?.optString("userCode").orEmpty() - if (url.isEmpty() || deviceCode.isEmpty()) { - Log.w(TAG, "device sign-in did not start: ${start?.optString("error").orEmpty().ifEmpty { "no answer" }}") - return fail(app, mine) - } - val floated = main.await { DeviceCodeActivity.show(app, userCode, url, 0, Store.EPIC.label, - app.getString(R.string.upd_stage_confirm), app.getString(R.string.epic_sign_in_fortnite_note)) } - if (!floated && !openBrowser(app, url)) return fail(app, mine) - val intervalMs = start!!.optLong("interval", 10).coerceAtLeast(1) * 1000 - val deadline = System.currentTimeMillis() + start.optLong("expiresIn", 600) * 1000 - while (attempt.get() == mine && System.currentTimeMillis() < deadline) { - Thread.sleep(intervalMs) - if (attempt.get() != mine) return - val answer = EpicNative.call("auth.devicePoll", JSONObject().put("deviceCode", deviceCode)) ?: continue - if (answer.optBoolean("pending")) continue - val tokens = EpicCredentialStore.TokenResult.from(answer) - if (tokens == null) { - Log.w(TAG, "device sign-in failed: ${answer.optString("error").ifEmpty { "no token" }}") - main.post { DeviceCodeActivity.close() } - return fail(app, mine) - } - try { - EpicCredentialStore.save(app, tokens, merge = false) - } catch (e: Exception) { - Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}") - return fail(app, mine) - } - main.post { - StoresState.refresh(app) - bringBack(app, tokens.displayName) - } - return - } - if (attempt.get() == mine) { - Log.w(TAG, "device sign-in expired before it was confirmed") - main.post { DeviceCodeActivity.close() } - } - } - - private fun openBrowser(app: Context, url: String): Boolean { - for (pkg in listOf(CHROME, null)) { - val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) - .addCategory(Intent.CATEGORY_BROWSABLE) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - .putExtra(Browser.EXTRA_APPLICATION_ID, app.packageName) - if (pkg != null) intent.setPackage(pkg) - if (runCatching { app.startActivity(intent) }.isSuccess) return true - } - Log.w(TAG, "no browser took the sign-in") - return false - } - - // Android lets an app in the background bring itself forward only while one of its windows is - // visible (the floating code) or it may draw over other apps; otherwise a tap on DroidDeck's - // own notification is what brings it back. - private fun bringBack(app: Context, name: String?) { - if (DeviceCodeActivity.returnToApp()) return - val front = Intent(app, FrontEndActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP) - if (Settings.canDrawOverlays(app) && runCatching { app.startActivity(front) }.isSuccess) return - val manager = app.getSystemService(NotificationManager::class.java) ?: return - val label = Store.EPIC.label - manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, app.getString(R.string.stores_login_title, label), NotificationManager.IMPORTANCE_HIGH)) - val open = PendingIntent.getActivity(app, NOTIFICATION_ID, front, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - val text = name?.let { app.getString(R.string.setup_signed_in, it) } ?: app.getString(R.string.setup_signed_in_unnamed) - runCatching { - manager.notify(NOTIFICATION_ID, Notification.Builder(app, CHANNEL_ID) - .setSmallIcon(R.drawable.ic_stat_session) - .setContentTitle(label) - .setContentText(text) - .setContentIntent(open) - .setAutoCancel(true) - .setTimeoutAfter(NOTICE_TIMEOUT_MS) - .setCategory(Notification.CATEGORY_STATUS) - .build()) - }.onFailure { Log.w(TAG, "could not post the return notice: ${it.javaClass.simpleName}") } - } - - private fun Handler.await(block: () -> Boolean): Boolean { - val done = java.util.concurrent.CountDownLatch(1) - var result = false - post { result = runCatching(block).getOrDefault(false); done.countDown() } - done.await() - return result - } - - private fun fail(app: Context, mine: Int) { - main.post { - if (attempt.get() == mine) Toast.makeText(app, R.string.stores_login_error_generic, Toast.LENGTH_LONG).show() - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt new file mode 100644 index 0000000000..ff804a85e3 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt @@ -0,0 +1,49 @@ +package com.droiddeck.launcher.stores.epic + +import android.util.Log +import android.webkit.WebView +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.StoreLoginActivity +import org.json.JSONObject + +internal class EpicLogin private constructor( + override val startUrl: String, + override val userAgent: String, + private val redirectPrefix: String, +) : StoreLoginActivity.Flow { + override val readsPage: Boolean get() = true + + override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix) + + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { + val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty() + if (code.isEmpty()) { + Log.w(TAG, "the redirect page carried no authorization code") + return activity.getString(R.string.stores_login_error_verification) + } + val answer = EpicNative.call("auth.signIn", JSONObject().put("code", code)) + val tokens = answer?.let(EpicCredentialStore.TokenResult::from) + if (tokens == null) { + Log.w(TAG, "code exchange failed: ${answer?.optString("error").orEmpty().ifEmpty { "no answer" }}") + return activity.getString(R.string.stores_login_error_generic) + } + return try { + EpicCredentialStore.save(activity, tokens, merge = false) + null + } catch (e: Exception) { + Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}") + activity.getString(R.string.stores_login_error_generic) + } + } + + companion object { + private const val TAG = "EpicLogin" + + fun create(): StoreLoginActivity.Flow? { + val config = EpicNative.call("auth.config") ?: return null + val start = config.optString("startUrl").ifEmpty { return null } + val prefix = config.optString("redirectPrefix").ifEmpty { return null } + return EpicLogin(start, config.optString("webViewUserAgent"), prefix) + } + } +} diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index e906c9e891..374547d9fd 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1736,7 +1736,8 @@ جارٍ التنزيل جارٍ التثبيت في انتظار تأكيدك - تسمي صفحة Epic تسجيل الدخول هذا Fortnite + اضغط مطولًا على الحروف والأرقام بعد authorizationCode وانسخها، ثم عد إلى هنا + المتصفح فشل التحديث لم يعرض Android تثبيت التحديث diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index c9362bfb53..d0367e0126 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1765,7 +1765,8 @@ Descargando Instalando Esperando tu confirmación - La página de Epic llama a este inicio de sesión Fortnite + Mantén presionadas las letras y números después de authorizationCode, cópialos y vuelve aquí + Navegador La actualización falló Android no ofreció instalar la actualización Falló la instalación de Decky: %1$s diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index e0bdabd0d9..3aec5ac408 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1684,7 +1684,8 @@ Изтегляне Инсталиране Изчакване на потвърждение от теб - Страницата на Epic нарича този вход Fortnite + Задръжте буквите и цифрите след authorizationCode, копирайте ги и се върнете тук + Браузър Актуализацията се провали Android не предложи инсталирането на актуализацията diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 63b86bd647..5487507487 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1710,7 +1710,8 @@ Stahování Instalování Čeká na vaše potvrzení - Stránka Epicu toto přihlášení nazývá Fortnite + Podržte písmena a čísla za authorizationCode, zkopírujte je a vraťte se sem + Prohlížeč Aktualizace se nezdařila Android nenabídl instalaci aktualizace diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 2a59661139..51d416fde9 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1684,7 +1684,8 @@ Downloader Installerer Venter på din bekræftelse - Epics side kalder dette login Fortnite + Tryk længe på bogstaverne og tallene efter authorizationCode, kopiér dem, og vend så tilbage hertil + Browser Opdateringen mislykkedes Android tilbød ikke at installere opdateringen diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 397fc84fc7..82e4781c4f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1676,7 +1676,8 @@ Herunterladen Installieren Warte auf deine Bestätigung - Epics Seite nennt diese Anmeldung Fortnite + Halte die Buchstaben und Zahlen nach authorizationCode gedrückt, kopiere sie und komm dann hierher zurück + Browser Das Update ist fehlgeschlagen Android hat die Installation des Updates nicht angeboten diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 29cb297536..09de57066a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1684,7 +1684,8 @@ Λήψη Εγκατάσταση Περιμένει να επιβεβαιώσετε - Η σελίδα της Epic ονομάζει αυτή τη σύνδεση Fortnite + Πατήστε παρατεταμένα τα γράμματα και τους αριθμούς μετά το authorizationCode, αντιγράψτε τα και επιστρέψτε εδώ + Πρόγραμμα περιήγησης Η ενημέρωση απέτυχε Το Android δεν πρότεινε την εγκατάσταση της ενημέρωσης diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b8dfd32fa8..5d3cdca3bd 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1697,7 +1697,8 @@ Descargando Instalando Esperando tu confirmación - La página de Epic llama a este inicio de sesión Fortnite + Mantén pulsadas las letras y números después de authorizationCode, cópialos y vuelve aquí + Navegador La actualización falló Android no ofreció instalar la actualización diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index fe3f7ad186..89371b8e0f 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1684,7 +1684,8 @@ Latausta Asennusta Odotetaan vahvistustasi - Epicin sivu kutsuu tätä kirjautumista nimellä Fortnite + Paina pitkään kirjaimia ja numeroita kohdan authorizationCode jälkeen, kopioi ne ja palaa tänne + Selain Päivitys epäonnistui Android ei tarjonnut päivityksen asentamista diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 4513e87f8f..745b2ad238 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1696,7 +1696,8 @@ Téléchargement Installation En attente de votre confirmation - La page d\'Epic appelle cette connexion Fortnite + Appuyez longuement sur les lettres et chiffres après authorizationCode, copiez-les, puis revenez ici + Navigateur La mise à jour a échoué Android n\'a pas proposé d\'installer la mise à jour diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 5d9f4a7a4b..429fd4da99 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1684,7 +1684,8 @@ डाउनलोड हो रहा है इंस्टॉल हो रहा है आपकी पुष्टि का इंतज़ार हो रहा है - Epic का पेज इस साइन-इन को Fortnite कहता है + authorizationCode के बाद के अक्षरों और अंकों को देर तक दबाएँ, कॉपी करें, फिर यहाँ लौटें + ब्राउज़र अपडेट विफल रहा Android ने अपडेट इंस्टॉल करने का विकल्प नहीं दिया diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 679d7e7161..4779fabd12 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1684,7 +1684,8 @@ Letöltés Telepítés Megerősítésre várakozás - Az Epic oldala ezt a bejelentkezést Fortnite-nak nevezi + Nyomd hosszan az authorizationCode utáni betűket és számokat, másold ki, majd térj vissza ide + Böngésző A frissítés sikertelen Az Android nem ajánlotta fel a frissítés telepítését diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 062546881b..20dbad88e2 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1672,7 +1672,8 @@ Mengunduh Menginstal Menunggu konfirmasi Anda - Halaman Epic menyebut proses masuk ini Fortnite + Tekan lama huruf dan angka setelah authorizationCode, salin, lalu kembali ke sini + Peramban Pembaruan gagal Android tidak menawarkan untuk menginstal pembaruan diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 8733f27e98..9d7d93c895 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1688,7 +1688,8 @@ Download Installazione In attesa della tua conferma - La pagina di Epic chiama questo accesso Fortnite + Tieni premute le lettere e i numeri dopo authorizationCode, copiali, poi torna qui + Browser Aggiornamento non riuscito Android non ha proposto di installare l\'aggiornamento diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a92602cf68..61d29acdbd 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1672,7 +1672,8 @@ ダウンロード中 インストール中 確認を待機中 - Epic のページではこのサインインが Fortnite と表示されます + authorizationCode の後の英数字を長押ししてコピーし、ここに戻ってください + ブラウザ アップデートに失敗しました Androidがアップデートのインストールを表示しませんでした diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index f538908c23..b428e24ac9 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1672,7 +1672,8 @@ 다운로드 중 설치 중 확인 대기 중 - Epic 페이지에는 이 로그인이 Fortnite로 표시됩니다 + authorizationCode 뒤의 문자와 숫자를 길게 눌러 복사한 다음 여기로 돌아오세요 + 브라우저 업데이트 실패 Android에서 업데이트 설치를 진행하지 않았습니다 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index d928b56009..36e8ed0350 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1672,7 +1672,8 @@ Memuat turun Memasang Menunggu pengesahan anda - Halaman Epic memanggil log masuk ini Fortnite + Tekan lama huruf dan nombor selepas authorizationCode, salin, kemudian kembali ke sini + Pelayar Kemas kini gagal Android tidak menawarkan untuk memasang kemas kini diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 7275d1a960..be44958596 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1684,7 +1684,8 @@ Laster ned Installerer Venter på at du bekrefter - Epics side kaller denne påloggingen Fortnite + Trykk lenge på bokstavene og tallene etter authorizationCode, kopier dem, og kom så tilbake hit + Nettleser Oppdateringen mislyktes Android tilbød ikke å installere oppdateringen diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index dd4d8225ce..a10363630b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1684,7 +1684,8 @@ Downloaden Installeren Wachten op je bevestiging - Epics pagina noemt deze aanmelding Fortnite + Houd de letters en cijfers na authorizationCode ingedrukt, kopieer ze en kom dan hier terug + Browser De update is mislukt Android heeft niet aangeboden om de update te installeren diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 86aaa12602..45a96f8db0 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1710,7 +1710,8 @@ Pobieranie Instalowanie Oczekiwanie na Twoje potwierdzenie - Strona Epic nazywa to logowanie Fortnite + Przytrzymaj litery i cyfry po authorizationCode, skopiuj je, a potem wróć tutaj + Przeglądarka Aktualizacja nie powiodła się Android nie zaproponował instalacji aktualizacji diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 6ef1f4e86d..6607382979 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1688,7 +1688,8 @@ A transferir A instalar A aguardar a sua confirmação - A página da Epic chama a este início de sessão Fortnite + Mantenha premidas as letras e números após authorizationCode, copie-os e volte aqui + Navegador A atualização falhou O Android não ofereceu a instalação da atualização diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1638bd5c77..0789219fce 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1696,7 +1696,8 @@ Baixando Instalando Aguardando sua confirmação - A página da Epic chama este login de Fortnite + Toque e segure as letras e números depois de authorizationCode, copie e volte aqui + Navegador A atualização falhou O Android não ofereceu a instalação da atualização diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 6218eaee44..1291b1c4b3 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1697,7 +1697,8 @@ Se descarcă Se instalează Se așteaptă confirmarea ta - Pagina Epic numește această conectare Fortnite + Apasă lung pe literele și cifrele de după authorizationCode, copiază-le, apoi revino aici + Browser Actualizarea a eșuat Android nu a oferit instalarea actualizării diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index d7d8cb606a..1dfcdc027e 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1710,7 +1710,8 @@ Загрузка Установка Ожидание вашего подтверждения - На странице Epic этот вход называется Fortnite + Нажмите и удерживайте буквы и цифры после authorizationCode, скопируйте их и вернитесь сюда + Браузер Ошибка обновления Android не предложил установить обновление diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 5335c60116..b5b201285d 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1684,7 +1684,8 @@ Laddar ned Installerar Väntar på att du bekräftar - Epics sida kallar den här inloggningen Fortnite + Tryck länge på bokstäverna och siffrorna efter authorizationCode, kopiera dem och kom sedan tillbaka hit + Webbläsare Uppdateringen misslyckades Android erbjöd inte att installera uppdateringen diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 285c834462..0c1e14c700 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1672,7 +1672,8 @@ กำลังดาวน์โหลด กำลังติดตั้ง กำลังรอให้คุณยืนยัน - หน้าของ Epic เรียกการลงชื่อเข้าใช้นี้ว่า Fortnite + กดค้างที่ตัวอักษรและตัวเลขหลัง authorizationCode คัดลอก แล้วกลับมาที่นี่ + เบราว์เซอร์ การอัปเดตล้มเหลว Android ไม่ได้เสนอให้ติดตั้งอัปเดต diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 4c33a234bc..a77c81b104 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1676,7 +1676,8 @@ İndiriliyor Yükleniyor Onayınız bekleniyor - Epic\'in sayfası bu girişi Fortnite olarak adlandırır + authorizationCode sonrasındaki harf ve rakamlara basılı tutun, kopyalayın, sonra buraya dönün + Tarayıcı Güncelleme başarısız oldu Android güncellemeyi yüklemeyi önermedi diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 8908bc292f..1e0081d36d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1710,7 +1710,8 @@ Завантаження Встановлення Очікування вашого підтвердження - На сторінці Epic цей вхід називається Fortnite + Утримуйте літери й цифри після authorizationCode, скопіюйте їх і поверніться сюди + Браузер Не вдалося оновити Android не запропонував встановити оновлення diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 9481e05c09..51b03388f3 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1672,7 +1672,8 @@ Đang tải Đang cài Đang chờ bạn xác nhận - Trang của Epic gọi lần đăng nhập này là Fortnite + Nhấn giữ các chữ và số sau authorizationCode, sao chép rồi quay lại đây + Trình duyệt Cập nhật thất bại Android không đề nghị cài bản cập nhật diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 22609c4343..859235de58 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1755,7 +1755,8 @@ 正在下载 正在安装 等待你确认 - Epic 页面会将此登录显示为 Fortnite + 长按 authorizationCode 后面的字母和数字并复制,然后返回这里 + 浏览器 更新失败 Android 未提供安装此更新的选项 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 0e2223c25b..1ba4c0033c 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1671,7 +1671,8 @@ 正在下載 正在安裝 正在等待你確認 - Epic 頁面會將此登入顯示為 Fortnite + 長按 authorizationCode 後面的字母和數字並複製,然後返回這裡 + 瀏覽器 更新失敗 Android 沒有提供安裝更新的選項 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 0725294eb6..1a5e4f72b2 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1671,7 +1671,8 @@ 正在下載 正在安裝 等待你確認 - Epic 頁面會將此登入顯示為 Fortnite + 長按 authorizationCode 後面的字母和數字並複製,然後返回這裡 + 瀏覽器 更新失敗 Android 未提供安裝此更新的選項 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3a71c82b84..4f555ee797 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1846,7 +1846,8 @@ Downloading Installing Waiting for you to confirm - Epic\'s page calls this sign-in Fortnite + Long-press the letters and numbers after authorizationCode, copy them, then come back here + Browser The update failed Android didn\'t offer to install the update diff --git a/app/src/main/rust/stores/JNI.md b/app/src/main/rust/stores/JNI.md index b2ff5a37dc..b87390ac8f 100644 --- a/app/src/main/rust/stores/JNI.md +++ b/app/src/main/rust/stores/JNI.md @@ -153,10 +153,10 @@ synchronous on the calling thread (network calls block: call them off the main t | op | request | answer | |---|---|---| -| `auth.config` | – | `webViewUserAgent` for the Epic client's embedded pages | -| `auth.deviceStart` | – | `url` (Epic's activation page for the browser), `userCode`, `deviceCode`, `interval` and `expiresIn` (seconds) | -| `auth.devicePoll` | `deviceCode` | `{"pending": true}` until the user confirms in the browser, then `access_token`, `refresh_token`?, `account_id`?, `display_name`?, `expires_at` (epoch ms) for the launcher client | -| `auth.refresh` | `refreshToken` | same as `auth.devicePoll` (absent fields: keep the stored ones) | +| `auth.config` | – | `startUrl`, `redirectPrefix`, `webViewUserAgent` for the login WebView | +| `auth.codeFromPage` | `text` (the redirect page body as the WebView returns it) | `code`, or `{}` | +| `auth.signIn` | `code` | `access_token`, `refresh_token`?, `account_id`?, `display_name`?, `expires_at` (epoch ms) | +| `auth.refresh` | `refreshToken` | same as `auth.signIn` (absent fields: keep the stored ones) | | `auth.exchange` | `accessToken` | `code` (single-use launch exchange code) | | `library.owned` | `accessToken` | `records[]` of `appName`, `namespace`, `catalogItemId` (all pages; filtered to installable Windows games). A refused token answers `{"error":…, "signIn": true}`; any failed page fails the whole call | | `catalog.details` | `accessToken`, `namespace`, `catalogItemId` | `details`: `title`, `developer`, `description`, `publisher`, `releaseDate`, `tall`, `wide`, `canRunOffline`, `dlc`, `mainGameId` | diff --git a/app/src/main/rust/stores/src/epic/account.rs b/app/src/main/rust/stores/src/epic/account.rs index 4dc37fb3be..81fe89d812 100644 --- a/app/src/main/rust/stores/src/epic/account.rs +++ b/app/src/main/rust/stores/src/epic/account.rs @@ -6,96 +6,16 @@ pub const CLIENT_ID: &str = "34a02cf8f4414e29b15921876da36f9a"; pub const CLIENT_SECRET: &str = "daafbccc737745039dffe53d94fc76cf"; const ACCOUNT_HOST: &str = "https://account-public-service-prod03.ol.epicgames.com"; -// Epic's login page diverts the launcher client to a welcome page that needs the desktop -// launcher's JS bridge, so a browser sign-in goes through this client's device grant and an -// exchange code instead. -const DEVICE_CLIENT_ID: &str = "98f7e42c2e3a4f86a74eb43fbb41ed39"; -const DEVICE_CLIENT_SECRET: &str = "0a2449a2-001a-451e-afec-3e812901c4d7"; +pub const REDIRECT_PREFIX: &str = "https://www.epicgames.com/id/api/redirect"; pub const WEBVIEW_USER_AGENT: &str = "UELauncher/11.0.1-14907503+++Portal+Release-Live Windows/10.0.19041.1.256.64bit"; const DEFAULT_EXPIRES_IN: i64 = 7200; -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DeviceStart { - pub url: String, - pub user_code: String, - pub device_code: String, - pub interval_s: i64, - pub expires_in_s: i64, -} - -pub fn parse_device_start(body: &Value) -> Option { - Some(DeviceStart { - url: non_empty(body, "verification_uri_complete")?, - user_code: non_empty(body, "user_code")?, - device_code: non_empty(body, "device_code")?, - interval_s: body.get("interval").and_then(Value::as_i64).unwrap_or(10).max(1), - expires_in_s: body.get("expires_in").and_then(Value::as_i64).unwrap_or(600), - }) -} - -pub fn device_start() -> Result { - let url = format!("{ACCOUNT_HOST}/account/api/oauth/token"); - let grant = vec![("grant_type".to_string(), "client_credentials".to_string())]; - let reply = net::send(Request::post(&url, Body::Form(grant)).basic(DEVICE_CLIENT_ID, DEVICE_CLIENT_SECRET))?; - if !reply.ok() { - return Err(format!("client token answered HTTP {}", reply.status)); - } - let body = reply.json().ok_or("client token answer is not JSON")?; - let client_token = non_empty(&body, "access_token").ok_or("client token answer has no token")?; - let url = format!("{ACCOUNT_HOST}/account/api/oauth/deviceAuthorization"); - let reply = net::send(Request::post(&url, Body::Form(Vec::new())).bearer(&client_token))?; - if !reply.ok() { - return Err(format!("device authorization answered HTTP {}", reply.status)); - } - parse_device_start(&reply.json().ok_or("device authorization answer is not JSON")?) - .ok_or_else(|| "device authorization answer is incomplete".into()) -} - -#[derive(Debug, PartialEq, Eq)] -pub enum DevicePoll { - Pending, - Done(Tokens), - Failed(String), -} - -fn pending(body: &Value) -> bool { - matches!( - net::str_of(body, "errorCode"), - "errors.com.epicgames.account.oauth.authorization_pending" | "errors.com.epicgames.common.slow_down" - ) || matches!(net::str_of(body, "error"), "authorization_pending" | "slow_down") -} - -pub fn device_poll(device_code: &str) -> DevicePoll { - let url = format!("{ACCOUNT_HOST}/account/api/oauth/token"); - let grant = vec![ - ("grant_type".to_string(), "device_code".to_string()), - ("device_code".to_string(), device_code.to_string()), - ]; - let reply = match net::send(Request::post(&url, Body::Form(grant)).basic(DEVICE_CLIENT_ID, DEVICE_CLIENT_SECRET)) { - Ok(r) => r, - Err(_) => return DevicePoll::Pending, - }; - let body = reply.json().unwrap_or(Value::Null); - if !reply.ok() { - if pending(&body) || reply.status >= 500 { - return DevicePoll::Pending; - } - let code = net::str_of(&body, "errorCode"); - return DevicePoll::Failed(if code.is_empty() { format!("device grant answered HTTP {}", reply.status) } else { code.to_string() }); - } - let Some(device_token) = non_empty(&body, "access_token") else { - return DevicePoll::Failed("device grant answer has no access token".into()); - }; - let result = exchange_code(&device_token).and_then(|code| token_request(&[("grant_type", "exchange_code"), ("exchange_code", &code)])); - let kill = format!("{ACCOUNT_HOST}/account/api/oauth/sessions/kill/{device_token}"); - let _ = net::send(Request::delete(&kill).bearer(&device_token)); - match result { - Ok(tokens) => DevicePoll::Done(tokens), - Err(e) => DevicePoll::Failed(e), - } +pub fn start_url() -> String { + let redirect = format!("{REDIRECT_PREFIX}?clientId={CLIENT_ID}&responseType=code"); + format!("https://www.epicgames.com/id/login?redirectUrl={}", net::percent_encode(&redirect)) } #[derive(Clone, Debug, PartialEq, Eq)] @@ -166,6 +86,10 @@ fn token_request(grant: &[(&str, &str)]) -> Result { parse_token_reply(&body, now_ms()).ok_or_else(|| "token answer has no access token".into()) } +pub fn sign_in_with_code(code: &str) -> Result { + token_request(&[("grant_type", "authorization_code"), ("code", code)]) +} + pub fn refresh(refresh_token: &str) -> Result { token_request(&[("grant_type", "refresh_token"), ("refresh_token", refresh_token)]) } @@ -180,35 +104,48 @@ pub fn exchange_code(access_token: &str) -> Result { non_empty(&body, "code").ok_or_else(|| "exchange answer has no code".into()) } +pub fn code_from_page_text(raw: &str) -> Option { + let mut text = raw.trim(); + if text.len() >= 2 && text.starts_with('"') && text.ends_with('"') { + text = &text[1..text.len() - 1]; + } + let text = text.replace("\\n", "").replace("\\r", "").replace("\\\"", "\""); + let key = "\"authorizationCode\""; + let mut from = 0; + while let Some(at) = text[from..].find(key) { + let rest = text[from + at + key.len()..].trim_start(); + from += at + key.len(); + let Some(rest) = rest.strip_prefix(':') else { continue }; + let Some(rest) = rest.trim_start().strip_prefix('"') else { continue }; + let Some(end) = rest.find('"') else { continue }; + let value = &rest[..end]; + if !value.is_empty() { + return Some(value.to_string()); + } + } + None +} + #[cfg(test)] mod tests { use super::*; #[test] - fn device_start_reads_epic_answer() { - let body = serde_json::json!({ - "user_code": "LQWFTNKF", "device_code": "U1BC", "verification_uri": "https://www.epicgames.com/activate", - "verification_uri_complete": "https://www.epicgames.com/activate?userCode=LQWFTNKF", - "expires_in": 600, "interval": 10, - }); + fn start_url_wraps_the_redirect() { assert_eq!( - parse_device_start(&body), - Some(DeviceStart { - url: "https://www.epicgames.com/activate?userCode=LQWFTNKF".into(), - user_code: "LQWFTNKF".into(), - device_code: "U1BC".into(), - interval_s: 10, - expires_in_s: 600, - }) + start_url(), + "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Fid%2Fapi%2Fredirect%3FclientId%3D34a02cf8f4414e29b15921876da36f9a%26responseType%3Dcode" ); - assert_eq!(parse_device_start(&serde_json::json!({ "user_code": "A", "device_code": "B" })), None); } #[test] - fn device_grant_waits_while_the_user_has_not_confirmed() { - assert!(pending(&serde_json::json!({ "errorCode": "errors.com.epicgames.account.oauth.authorization_pending" }))); - assert!(pending(&serde_json::json!({ "error": "slow_down" }))); - assert!(!pending(&serde_json::json!({ "errorCode": "errors.com.epicgames.account.oauth.authorization_code_not_found" }))); + fn code_from_the_redirect_page() { + let page = r#""{\"warning\":\"x\",\"redirectUrl\":\"https://localhost/launcher/authorized?code=abc\",\"authorizationCode\":\"0123abcd\",\"exchangeCode\":null,\"sid\":null}\n""#; + assert_eq!(code_from_page_text(page).as_deref(), Some("0123abcd")); + assert_eq!(code_from_page_text(r#"{"authorizationCode": "zz"}"#).as_deref(), Some("zz")); + assert_eq!(code_from_page_text(r#"{"authorizationCode":null}"#), None); + assert_eq!(code_from_page_text(r#"{"authorizationCode":""}"#), None); + assert_eq!(code_from_page_text("sign in"), None); } #[test] diff --git a/app/src/main/rust/stores/src/epic/net.rs b/app/src/main/rust/stores/src/epic/net.rs index 7fc2413701..7421815a52 100644 --- a/app/src/main/rust/stores/src/epic/net.rs +++ b/app/src/main/rust/stores/src/epic/net.rs @@ -28,7 +28,6 @@ pub enum Method { Get, Post, Put, - Delete, } pub enum Body { @@ -77,13 +76,6 @@ impl<'a> Request<'a> { } } - pub fn delete(url: &'a str) -> Self { - Request { - method: Method::Delete, - ..Request::get(url) - } - } - pub fn agent(mut self, agent: &'static str) -> Self { self.agent = Some(agent); self @@ -151,7 +143,6 @@ async fn send_async(request: Request<'_>) -> Result { Method::Get => client.get(request.url), Method::Post => client.post(request.url), Method::Put => client.put(request.url), - Method::Delete => client.delete(request.url), }; if let Some(token) = request.bearer { builder = builder.header(AUTHORIZATION, format!("Bearer {token}")); diff --git a/app/src/main/rust/stores/src/epic/service.rs b/app/src/main/rust/stores/src/epic/service.rs index 85e096d94b..2264f6c775 100644 --- a/app/src/main/rust/stores/src/epic/service.rs +++ b/app/src/main/rust/stores/src/epic/service.rs @@ -21,19 +21,17 @@ fn dispatch(op: &str, req: &Value) -> Value { let token = str_of(req, "accessToken"); match op { "auth.config" => json!({ + "startUrl": account::start_url(), + "redirectPrefix": account::REDIRECT_PREFIX, "webViewUserAgent": account::WEBVIEW_USER_AGENT, }), - "auth.deviceStart" => match account::device_start() { - Ok(d) => json!({ - "url": d.url, "userCode": d.user_code, "deviceCode": d.device_code, - "interval": d.interval_s, "expiresIn": d.expires_in_s, - }), - Err(e) => error(e), + "auth.codeFromPage" => match account::code_from_page_text(str_of(req, "text")) { + Some(code) => json!({ "code": code }), + None => json!({}), }, - "auth.devicePoll" => match account::device_poll(str_of(req, "deviceCode")) { - account::DevicePoll::Pending => json!({ "pending": true }), - account::DevicePoll::Done(t) => t.to_json(), - account::DevicePoll::Failed(e) => error(e), + "auth.signIn" => match account::sign_in_with_code(str_of(req, "code")) { + Ok(t) => t.to_json(), + Err(e) => error(e), }, "auth.refresh" => match account::refresh(str_of(req, "refreshToken")) { Ok(t) => t.to_json(), @@ -189,8 +187,8 @@ mod tests { let v: Value = serde_json::from_str(&call("locale", r#"{"language":"pt","region":"BR"}"#)).unwrap(); assert_eq!(v["key"], "pt-BR"); assert_eq!(v["launchLocale"], "pt"); - let v: Value = serde_json::from_str(&call("auth.config", "{}")).unwrap(); - assert!(v["webViewUserAgent"].as_str().unwrap().starts_with("UELauncher/")); + let v: Value = serde_json::from_str(&call("auth.codeFromPage", r#"{"text":"{\"authorizationCode\":\"c1\"}"}"#)).unwrap(); + assert_eq!(v["code"], "c1"); let v: Value = serde_json::from_str(&call("nope", "{}")).unwrap(); assert!(v["error"].is_string()); let v: Value = serde_json::from_str(&call("launch.args", r#"{"namespace":"ns","appName":"A"}"#)).unwrap();