mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
fix(epic): keep the in-app sign-in and add a browser fallback that takes Epic's code from the clipboard
This commit is contained in:
1 parent
de92fef457
commit
bc49b8ac34
45 files changed
+343
-320
No files matched your search
@@ -47,7 +47,7 @@ class DeviceCodeActivity : ComponentActivity() {
|
||||
private var code by mutableStateOf("")
|
||||
private var label by mutableStateOf("")
|
||||
private var message by mutableStateOf<String?>(null)
|
||||
private var note by mutableStateOf<String?>(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<DeviceCodeActivity>? = 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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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("(?<![0-9a-fA-F])[0-9a-fA-F]{32}(?![0-9a-fA-F])")
|
||||
|
||||
@Volatile private var pendingUntil = 0L
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
fun begin(context: Context) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val url = EpicNative.call("auth.config")?.optString("startUrl").orEmpty()
|
||||
if (url.isEmpty()) {
|
||||
Log.w(TAG, "no sign-in page")
|
||||
main.post { failed(app) }
|
||||
return@Thread
|
||||
}
|
||||
pendingUntil = System.currentTimeMillis() + PENDING_MS
|
||||
main.post {
|
||||
DeviceCodeActivity.onPaste = { ctx, text -> 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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1736,7 +1736,8 @@
|
||||
<string name="upd_stage_downloading">جارٍ التنزيل</string>
|
||||
<string name="upd_stage_installing">جارٍ التثبيت</string>
|
||||
<string name="upd_stage_confirm">في انتظار تأكيدك</string>
|
||||
<string name="epic_sign_in_fortnite_note">تسمي صفحة Epic تسجيل الدخول هذا Fortnite</string>
|
||||
<string name="epic_copy_code">اضغط مطولًا على الحروف والأرقام بعد authorizationCode وانسخها، ثم عد إلى هنا</string>
|
||||
<string name="stores_login_in_browser">المتصفح</string>
|
||||
<string name="upd_failed">فشل التحديث</string>
|
||||
<string name="upd_not_offered">لم يعرض Android تثبيت التحديث</string>
|
||||
|
||||
|
||||
@@ -1765,7 +1765,8 @@
|
||||
<string name="upd_stage_downloading">Descargando</string>
|
||||
<string name="upd_stage_installing">Instalando</string>
|
||||
<string name="upd_stage_confirm">Esperando tu confirmación</string>
|
||||
<string name="epic_sign_in_fortnite_note">La página de Epic llama a este inicio de sesión Fortnite</string>
|
||||
<string name="epic_copy_code">Mantén presionadas las letras y números después de authorizationCode, cópialos y vuelve aquí</string>
|
||||
<string name="stores_login_in_browser">Navegador</string>
|
||||
<string name="upd_failed">La actualización falló</string>
|
||||
<string name="upd_not_offered">Android no ofreció instalar la actualización</string>
|
||||
<string name="decky_install_failed">Falló la instalación de Decky: %1$s</string>
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Изтегляне</string>
|
||||
<string name="upd_stage_installing">Инсталиране</string>
|
||||
<string name="upd_stage_confirm">Изчакване на потвърждение от теб</string>
|
||||
<string name="epic_sign_in_fortnite_note">Страницата на Epic нарича този вход Fortnite</string>
|
||||
<string name="epic_copy_code">Задръжте буквите и цифрите след authorizationCode, копирайте ги и се върнете тук</string>
|
||||
<string name="stores_login_in_browser">Браузър</string>
|
||||
<string name="upd_failed">Актуализацията се провали</string>
|
||||
<string name="upd_not_offered">Android не предложи инсталирането на актуализацията</string>
|
||||
|
||||
|
||||
@@ -1710,7 +1710,8 @@
|
||||
<string name="upd_stage_downloading">Stahování</string>
|
||||
<string name="upd_stage_installing">Instalování</string>
|
||||
<string name="upd_stage_confirm">Čeká na vaše potvrzení</string>
|
||||
<string name="epic_sign_in_fortnite_note">Stránka Epicu toto přihlášení nazývá Fortnite</string>
|
||||
<string name="epic_copy_code">Podržte písmena a čísla za authorizationCode, zkopírujte je a vraťte se sem</string>
|
||||
<string name="stores_login_in_browser">Prohlížeč</string>
|
||||
<string name="upd_failed">Aktualizace se nezdařila</string>
|
||||
<string name="upd_not_offered">Android nenabídl instalaci aktualizace</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Downloader</string>
|
||||
<string name="upd_stage_installing">Installerer</string>
|
||||
<string name="upd_stage_confirm">Venter på din bekræftelse</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epics side kalder dette login Fortnite</string>
|
||||
<string name="epic_copy_code">Tryk længe på bogstaverne og tallene efter authorizationCode, kopiér dem, og vend så tilbage hertil</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">Opdateringen mislykkedes</string>
|
||||
<string name="upd_not_offered">Android tilbød ikke at installere opdateringen</string>
|
||||
|
||||
|
||||
@@ -1676,7 +1676,8 @@
|
||||
<string name="upd_stage_downloading">Herunterladen</string>
|
||||
<string name="upd_stage_installing">Installieren</string>
|
||||
<string name="upd_stage_confirm">Warte auf deine Bestätigung</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epics Seite nennt diese Anmeldung Fortnite</string>
|
||||
<string name="epic_copy_code">Halte die Buchstaben und Zahlen nach authorizationCode gedrückt, kopiere sie und komm dann hierher zurück</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">Das Update ist fehlgeschlagen</string>
|
||||
<string name="upd_not_offered">Android hat die Installation des Updates nicht angeboten</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Λήψη</string>
|
||||
<string name="upd_stage_installing">Εγκατάσταση</string>
|
||||
<string name="upd_stage_confirm">Περιμένει να επιβεβαιώσετε</string>
|
||||
<string name="epic_sign_in_fortnite_note">Η σελίδα της Epic ονομάζει αυτή τη σύνδεση Fortnite</string>
|
||||
<string name="epic_copy_code">Πατήστε παρατεταμένα τα γράμματα και τους αριθμούς μετά το authorizationCode, αντιγράψτε τα και επιστρέψτε εδώ</string>
|
||||
<string name="stores_login_in_browser">Πρόγραμμα περιήγησης</string>
|
||||
<string name="upd_failed">Η ενημέρωση απέτυχε</string>
|
||||
<string name="upd_not_offered">Το Android δεν πρότεινε την εγκατάσταση της ενημέρωσης</string>
|
||||
|
||||
|
||||
@@ -1697,7 +1697,8 @@
|
||||
<string name="upd_stage_downloading">Descargando</string>
|
||||
<string name="upd_stage_installing">Instalando</string>
|
||||
<string name="upd_stage_confirm">Esperando tu confirmación</string>
|
||||
<string name="epic_sign_in_fortnite_note">La página de Epic llama a este inicio de sesión Fortnite</string>
|
||||
<string name="epic_copy_code">Mantén pulsadas las letras y números después de authorizationCode, cópialos y vuelve aquí</string>
|
||||
<string name="stores_login_in_browser">Navegador</string>
|
||||
<string name="upd_failed">La actualización falló</string>
|
||||
<string name="upd_not_offered">Android no ofreció instalar la actualización</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Latausta</string>
|
||||
<string name="upd_stage_installing">Asennusta</string>
|
||||
<string name="upd_stage_confirm">Odotetaan vahvistustasi</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epicin sivu kutsuu tätä kirjautumista nimellä Fortnite</string>
|
||||
<string name="epic_copy_code">Paina pitkään kirjaimia ja numeroita kohdan authorizationCode jälkeen, kopioi ne ja palaa tänne</string>
|
||||
<string name="stores_login_in_browser">Selain</string>
|
||||
<string name="upd_failed">Päivitys epäonnistui</string>
|
||||
<string name="upd_not_offered">Android ei tarjonnut päivityksen asentamista</string>
|
||||
|
||||
|
||||
@@ -1696,7 +1696,8 @@
|
||||
<string name="upd_stage_downloading">Téléchargement</string>
|
||||
<string name="upd_stage_installing">Installation</string>
|
||||
<string name="upd_stage_confirm">En attente de votre confirmation</string>
|
||||
<string name="epic_sign_in_fortnite_note">La page d\'Epic appelle cette connexion Fortnite</string>
|
||||
<string name="epic_copy_code">Appuyez longuement sur les lettres et chiffres après authorizationCode, copiez-les, puis revenez ici</string>
|
||||
<string name="stores_login_in_browser">Navigateur</string>
|
||||
<string name="upd_failed">La mise à jour a échoué</string>
|
||||
<string name="upd_not_offered">Android n\'a pas proposé d\'installer la mise à jour</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">डाउनलोड हो रहा है</string>
|
||||
<string name="upd_stage_installing">इंस्टॉल हो रहा है</string>
|
||||
<string name="upd_stage_confirm">आपकी पुष्टि का इंतज़ार हो रहा है</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic का पेज इस साइन-इन को Fortnite कहता है</string>
|
||||
<string name="epic_copy_code">authorizationCode के बाद के अक्षरों और अंकों को देर तक दबाएँ, कॉपी करें, फिर यहाँ लौटें</string>
|
||||
<string name="stores_login_in_browser">ब्राउज़र</string>
|
||||
<string name="upd_failed">अपडेट विफल रहा</string>
|
||||
<string name="upd_not_offered">Android ने अपडेट इंस्टॉल करने का विकल्प नहीं दिया</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Letöltés</string>
|
||||
<string name="upd_stage_installing">Telepítés</string>
|
||||
<string name="upd_stage_confirm">Megerősítésre várakozás</string>
|
||||
<string name="epic_sign_in_fortnite_note">Az Epic oldala ezt a bejelentkezést Fortnite-nak nevezi</string>
|
||||
<string name="epic_copy_code">Nyomd hosszan az authorizationCode utáni betűket és számokat, másold ki, majd térj vissza ide</string>
|
||||
<string name="stores_login_in_browser">Böngésző</string>
|
||||
<string name="upd_failed">A frissítés sikertelen</string>
|
||||
<string name="upd_not_offered">Az Android nem ajánlotta fel a frissítés telepítését</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">Mengunduh</string>
|
||||
<string name="upd_stage_installing">Menginstal</string>
|
||||
<string name="upd_stage_confirm">Menunggu konfirmasi Anda</string>
|
||||
<string name="epic_sign_in_fortnite_note">Halaman Epic menyebut proses masuk ini Fortnite</string>
|
||||
<string name="epic_copy_code">Tekan lama huruf dan angka setelah authorizationCode, salin, lalu kembali ke sini</string>
|
||||
<string name="stores_login_in_browser">Peramban</string>
|
||||
<string name="upd_failed">Pembaruan gagal</string>
|
||||
<string name="upd_not_offered">Android tidak menawarkan untuk menginstal pembaruan</string>
|
||||
|
||||
|
||||
@@ -1688,7 +1688,8 @@
|
||||
<string name="upd_stage_downloading">Download</string>
|
||||
<string name="upd_stage_installing">Installazione</string>
|
||||
<string name="upd_stage_confirm">In attesa della tua conferma</string>
|
||||
<string name="epic_sign_in_fortnite_note">La pagina di Epic chiama questo accesso Fortnite</string>
|
||||
<string name="epic_copy_code">Tieni premute le lettere e i numeri dopo authorizationCode, copiali, poi torna qui</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">Aggiornamento non riuscito</string>
|
||||
<string name="upd_not_offered">Android non ha proposto di installare l\'aggiornamento</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">ダウンロード中</string>
|
||||
<string name="upd_stage_installing">インストール中</string>
|
||||
<string name="upd_stage_confirm">確認を待機中</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic のページではこのサインインが Fortnite と表示されます</string>
|
||||
<string name="epic_copy_code">authorizationCode の後の英数字を長押ししてコピーし、ここに戻ってください</string>
|
||||
<string name="stores_login_in_browser">ブラウザ</string>
|
||||
<string name="upd_failed">アップデートに失敗しました</string>
|
||||
<string name="upd_not_offered">Androidがアップデートのインストールを表示しませんでした</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">다운로드 중</string>
|
||||
<string name="upd_stage_installing">설치 중</string>
|
||||
<string name="upd_stage_confirm">확인 대기 중</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic 페이지에는 이 로그인이 Fortnite로 표시됩니다</string>
|
||||
<string name="epic_copy_code">authorizationCode 뒤의 문자와 숫자를 길게 눌러 복사한 다음 여기로 돌아오세요</string>
|
||||
<string name="stores_login_in_browser">브라우저</string>
|
||||
<string name="upd_failed">업데이트 실패</string>
|
||||
<string name="upd_not_offered">Android에서 업데이트 설치를 진행하지 않았습니다</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">Memuat turun</string>
|
||||
<string name="upd_stage_installing">Memasang</string>
|
||||
<string name="upd_stage_confirm">Menunggu pengesahan anda</string>
|
||||
<string name="epic_sign_in_fortnite_note">Halaman Epic memanggil log masuk ini Fortnite</string>
|
||||
<string name="epic_copy_code">Tekan lama huruf dan nombor selepas authorizationCode, salin, kemudian kembali ke sini</string>
|
||||
<string name="stores_login_in_browser">Pelayar</string>
|
||||
<string name="upd_failed">Kemas kini gagal</string>
|
||||
<string name="upd_not_offered">Android tidak menawarkan untuk memasang kemas kini</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Laster ned</string>
|
||||
<string name="upd_stage_installing">Installerer</string>
|
||||
<string name="upd_stage_confirm">Venter på at du bekrefter</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epics side kaller denne påloggingen Fortnite</string>
|
||||
<string name="epic_copy_code">Trykk lenge på bokstavene og tallene etter authorizationCode, kopier dem, og kom så tilbake hit</string>
|
||||
<string name="stores_login_in_browser">Nettleser</string>
|
||||
<string name="upd_failed">Oppdateringen mislyktes</string>
|
||||
<string name="upd_not_offered">Android tilbød ikke å installere oppdateringen</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Downloaden</string>
|
||||
<string name="upd_stage_installing">Installeren</string>
|
||||
<string name="upd_stage_confirm">Wachten op je bevestiging</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epics pagina noemt deze aanmelding Fortnite</string>
|
||||
<string name="epic_copy_code">Houd de letters en cijfers na authorizationCode ingedrukt, kopieer ze en kom dan hier terug</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">De update is mislukt</string>
|
||||
<string name="upd_not_offered">Android heeft niet aangeboden om de update te installeren</string>
|
||||
|
||||
|
||||
@@ -1710,7 +1710,8 @@
|
||||
<string name="upd_stage_downloading">Pobieranie</string>
|
||||
<string name="upd_stage_installing">Instalowanie</string>
|
||||
<string name="upd_stage_confirm">Oczekiwanie na Twoje potwierdzenie</string>
|
||||
<string name="epic_sign_in_fortnite_note">Strona Epic nazywa to logowanie Fortnite</string>
|
||||
<string name="epic_copy_code">Przytrzymaj litery i cyfry po authorizationCode, skopiuj je, a potem wróć tutaj</string>
|
||||
<string name="stores_login_in_browser">Przeglądarka</string>
|
||||
<string name="upd_failed">Aktualizacja nie powiodła się</string>
|
||||
<string name="upd_not_offered">Android nie zaproponował instalacji aktualizacji</string>
|
||||
|
||||
|
||||
@@ -1688,7 +1688,8 @@
|
||||
<string name="upd_stage_downloading">A transferir</string>
|
||||
<string name="upd_stage_installing">A instalar</string>
|
||||
<string name="upd_stage_confirm">A aguardar a sua confirmação</string>
|
||||
<string name="epic_sign_in_fortnite_note">A página da Epic chama a este início de sessão Fortnite</string>
|
||||
<string name="epic_copy_code">Mantenha premidas as letras e números após authorizationCode, copie-os e volte aqui</string>
|
||||
<string name="stores_login_in_browser">Navegador</string>
|
||||
<string name="upd_failed">A atualização falhou</string>
|
||||
<string name="upd_not_offered">O Android não ofereceu a instalação da atualização</string>
|
||||
|
||||
|
||||
@@ -1696,7 +1696,8 @@
|
||||
<string name="upd_stage_downloading">Baixando</string>
|
||||
<string name="upd_stage_installing">Instalando</string>
|
||||
<string name="upd_stage_confirm">Aguardando sua confirmação</string>
|
||||
<string name="epic_sign_in_fortnite_note">A página da Epic chama este login de Fortnite</string>
|
||||
<string name="epic_copy_code">Toque e segure as letras e números depois de authorizationCode, copie e volte aqui</string>
|
||||
<string name="stores_login_in_browser">Navegador</string>
|
||||
<string name="upd_failed">A atualização falhou</string>
|
||||
<string name="upd_not_offered">O Android não ofereceu a instalação da atualização</string>
|
||||
|
||||
|
||||
@@ -1697,7 +1697,8 @@
|
||||
<string name="upd_stage_downloading">Se descarcă</string>
|
||||
<string name="upd_stage_installing">Se instalează</string>
|
||||
<string name="upd_stage_confirm">Se așteaptă confirmarea ta</string>
|
||||
<string name="epic_sign_in_fortnite_note">Pagina Epic numește această conectare Fortnite</string>
|
||||
<string name="epic_copy_code">Apasă lung pe literele și cifrele de după authorizationCode, copiază-le, apoi revino aici</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">Actualizarea a eșuat</string>
|
||||
<string name="upd_not_offered">Android nu a oferit instalarea actualizării</string>
|
||||
|
||||
|
||||
@@ -1710,7 +1710,8 @@
|
||||
<string name="upd_stage_downloading">Загрузка</string>
|
||||
<string name="upd_stage_installing">Установка</string>
|
||||
<string name="upd_stage_confirm">Ожидание вашего подтверждения</string>
|
||||
<string name="epic_sign_in_fortnite_note">На странице Epic этот вход называется Fortnite</string>
|
||||
<string name="epic_copy_code">Нажмите и удерживайте буквы и цифры после authorizationCode, скопируйте их и вернитесь сюда</string>
|
||||
<string name="stores_login_in_browser">Браузер</string>
|
||||
<string name="upd_failed">Ошибка обновления</string>
|
||||
<string name="upd_not_offered">Android не предложил установить обновление</string>
|
||||
|
||||
|
||||
@@ -1684,7 +1684,8 @@
|
||||
<string name="upd_stage_downloading">Laddar ned</string>
|
||||
<string name="upd_stage_installing">Installerar</string>
|
||||
<string name="upd_stage_confirm">Väntar på att du bekräftar</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epics sida kallar den här inloggningen Fortnite</string>
|
||||
<string name="epic_copy_code">Tryck länge på bokstäverna och siffrorna efter authorizationCode, kopiera dem och kom sedan tillbaka hit</string>
|
||||
<string name="stores_login_in_browser">Webbläsare</string>
|
||||
<string name="upd_failed">Uppdateringen misslyckades</string>
|
||||
<string name="upd_not_offered">Android erbjöd inte att installera uppdateringen</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">กำลังดาวน์โหลด</string>
|
||||
<string name="upd_stage_installing">กำลังติดตั้ง</string>
|
||||
<string name="upd_stage_confirm">กำลังรอให้คุณยืนยัน</string>
|
||||
<string name="epic_sign_in_fortnite_note">หน้าของ Epic เรียกการลงชื่อเข้าใช้นี้ว่า Fortnite</string>
|
||||
<string name="epic_copy_code">กดค้างที่ตัวอักษรและตัวเลขหลัง authorizationCode คัดลอก แล้วกลับมาที่นี่</string>
|
||||
<string name="stores_login_in_browser">เบราว์เซอร์</string>
|
||||
<string name="upd_failed">การอัปเดตล้มเหลว</string>
|
||||
<string name="upd_not_offered">Android ไม่ได้เสนอให้ติดตั้งอัปเดต</string>
|
||||
|
||||
|
||||
@@ -1676,7 +1676,8 @@
|
||||
<string name="upd_stage_downloading">İndiriliyor</string>
|
||||
<string name="upd_stage_installing">Yükleniyor</string>
|
||||
<string name="upd_stage_confirm">Onayınız bekleniyor</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic\'in sayfası bu girişi Fortnite olarak adlandırır</string>
|
||||
<string name="epic_copy_code">authorizationCode sonrasındaki harf ve rakamlara basılı tutun, kopyalayın, sonra buraya dönün</string>
|
||||
<string name="stores_login_in_browser">Tarayıcı</string>
|
||||
<string name="upd_failed">Güncelleme başarısız oldu</string>
|
||||
<string name="upd_not_offered">Android güncellemeyi yüklemeyi önermedi</string>
|
||||
|
||||
|
||||
@@ -1710,7 +1710,8 @@
|
||||
<string name="upd_stage_downloading">Завантаження</string>
|
||||
<string name="upd_stage_installing">Встановлення</string>
|
||||
<string name="upd_stage_confirm">Очікування вашого підтвердження</string>
|
||||
<string name="epic_sign_in_fortnite_note">На сторінці Epic цей вхід називається Fortnite</string>
|
||||
<string name="epic_copy_code">Утримуйте літери й цифри після authorizationCode, скопіюйте їх і поверніться сюди</string>
|
||||
<string name="stores_login_in_browser">Браузер</string>
|
||||
<string name="upd_failed">Не вдалося оновити</string>
|
||||
<string name="upd_not_offered">Android не запропонував встановити оновлення</string>
|
||||
|
||||
|
||||
@@ -1672,7 +1672,8 @@
|
||||
<string name="upd_stage_downloading">Đang tải</string>
|
||||
<string name="upd_stage_installing">Đang cài</string>
|
||||
<string name="upd_stage_confirm">Đang chờ bạn xác nhận</string>
|
||||
<string name="epic_sign_in_fortnite_note">Trang của Epic gọi lần đăng nhập này là Fortnite</string>
|
||||
<string name="epic_copy_code">Nhấn giữ các chữ và số sau authorizationCode, sao chép rồi quay lại đây</string>
|
||||
<string name="stores_login_in_browser">Trình duyệt</string>
|
||||
<string name="upd_failed">Cập nhật thất bại</string>
|
||||
<string name="upd_not_offered">Android không đề nghị cài bản cập nhật</string>
|
||||
|
||||
|
||||
@@ -1755,7 +1755,8 @@
|
||||
<string name="upd_stage_downloading">正在下载</string>
|
||||
<string name="upd_stage_installing">正在安装</string>
|
||||
<string name="upd_stage_confirm">等待你确认</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic 页面会将此登录显示为 Fortnite</string>
|
||||
<string name="epic_copy_code">长按 authorizationCode 后面的字母和数字并复制,然后返回这里</string>
|
||||
<string name="stores_login_in_browser">浏览器</string>
|
||||
<string name="upd_failed">更新失败</string>
|
||||
<string name="upd_not_offered">Android 未提供安装此更新的选项</string>
|
||||
|
||||
|
||||
@@ -1671,7 +1671,8 @@
|
||||
<string name="upd_stage_downloading">正在下載</string>
|
||||
<string name="upd_stage_installing">正在安裝</string>
|
||||
<string name="upd_stage_confirm">正在等待你確認</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic 頁面會將此登入顯示為 Fortnite</string>
|
||||
<string name="epic_copy_code">長按 authorizationCode 後面的字母和數字並複製,然後返回這裡</string>
|
||||
<string name="stores_login_in_browser">瀏覽器</string>
|
||||
<string name="upd_failed">更新失敗</string>
|
||||
<string name="upd_not_offered">Android 沒有提供安裝更新的選項</string>
|
||||
|
||||
|
||||
@@ -1671,7 +1671,8 @@
|
||||
<string name="upd_stage_downloading">正在下載</string>
|
||||
<string name="upd_stage_installing">正在安裝</string>
|
||||
<string name="upd_stage_confirm">等待你確認</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic 頁面會將此登入顯示為 Fortnite</string>
|
||||
<string name="epic_copy_code">長按 authorizationCode 後面的字母和數字並複製,然後返回這裡</string>
|
||||
<string name="stores_login_in_browser">瀏覽器</string>
|
||||
<string name="upd_failed">更新失敗</string>
|
||||
<string name="upd_not_offered">Android 未提供安裝此更新的選項</string>
|
||||
|
||||
|
||||
@@ -1846,7 +1846,8 @@
|
||||
<string name="upd_stage_downloading">Downloading</string>
|
||||
<string name="upd_stage_installing">Installing</string>
|
||||
<string name="upd_stage_confirm">Waiting for you to confirm</string>
|
||||
<string name="epic_sign_in_fortnite_note">Epic\'s page calls this sign-in Fortnite</string>
|
||||
<string name="epic_copy_code">Long-press the letters and numbers after authorizationCode, copy them, then come back here</string>
|
||||
<string name="stores_login_in_browser">Browser</string>
|
||||
<string name="upd_failed">The update failed</string>
|
||||
<string name="upd_not_offered">Android didn\'t offer to install the update</string>
|
||||
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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<DeviceStart> {
|
||||
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<DeviceStart, String> {
|
||||
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<Tokens, String> {
|
||||
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<Tokens, String> {
|
||||
token_request(&[("grant_type", "authorization_code"), ("code", code)])
|
||||
}
|
||||
|
||||
pub fn refresh(refresh_token: &str) -> Result<Tokens, String> {
|
||||
token_request(&[("grant_type", "refresh_token"), ("refresh_token", refresh_token)])
|
||||
}
|
||||
@@ -180,35 +104,48 @@ pub fn exchange_code(access_token: &str) -> Result<String, String> {
|
||||
non_empty(&body, "code").ok_or_else(|| "exchange answer has no code".into())
|
||||
}
|
||||
|
||||
pub fn code_from_page_text(raw: &str) -> Option<String> {
|
||||
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("<html>sign in</html>"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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<Reply, String> {
|
||||
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}"));
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user