Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ android {
}

dependencies {
implementation(libs.androidx.remote.core)
implementation(libs.androidx.remote.player.core)
implementation(libs.androidx.remote.player.view)
implementation("dev.rikka.shizuku:api:13.1.5")
implementation("dev.rikka.shizuku:provider:13.1.5")
implementation(project(":projection-plugin-api"))
Expand All @@ -57,6 +60,8 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.1")
implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:2.6.1")
testImplementation(libs.junit)
testImplementation(libs.androidx.remote.creation.android)
testImplementation(libs.androidx.remote.creation.core)
testImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-test-manifest")
debugImplementation(libs.androidx.compose.ui.tooling)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.shilapi.xcertplay.projection.plugin

import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import moe.feng.wheelplay.plugin.*
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.FutureTask
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.security.MessageDigest

internal data class PluginSettingsSnapshot(
val schema: PluginSettingsSchema,
val supportsRemoteCompose: Boolean,
val document: PluginSettingsDocument?,
val conflict: Boolean = false,
)

/** Blocking transport; callers must use a worker. No plugin classes cross this boundary. */
internal class PluginSettingsClient(
private val context: Context,
val plugin: InstalledProjectionPlugin,
private val isRegistered: () -> Boolean,
) {
val uri = ProjectionSettings.uri(requireNotNull(plugin.settingsProvider))

suspend fun requestAsync(method: String, extras: Bundle): PluginSettingsSnapshot = suspendCancellableCoroutine { continuation ->
val task = FutureTask<Unit> {
try { continuation.resumeWith(Result.success(request(method, extras))) }
catch (error: Exception) { continuation.resumeWith(Result.failure(error)) }
}
continuation.invokeOnCancellation { task.cancel(true); workers.remove(task) }
try { workers.execute(task) }
catch (error: Exception) { continuation.resumeWith(Result.failure(error)) }
}

companion object {
// A hung provider cannot create an unbounded number of blocked host threads.
private val workers = ThreadPoolExecutor(2, 2, 30, TimeUnit.SECONDS, ArrayBlockingQueue(16),
{ runnable -> Thread(runnable, "plugin-settings-io").apply { isDaemon = true } })
}

@Suppress("DEPRECATION")
fun checkIdentity() {
check(isRegistered()) { "Plugin changed or was removed" }
val pkg = context.packageManager.getPackageInfo(plugin.component.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
check(pkg.lastUpdateTime == plugin.updatedAt && pkg.longVersionCode == plugin.version &&
pkg.firstInstallTime == plugin.installedAt) { "Plugin was updated" }
val signer = pkg.signingInfo?.apkContentsSigners?.map {
MessageDigest.getInstance("SHA-256").digest(it.toByteArray()).joinToString("") { byte -> "%02x".format(byte) }
}?.sorted()?.joinToString(":").orEmpty()
check(signer.isNotEmpty() && signer == plugin.signer) { "Plugin signer changed" }
val provider = context.packageManager.resolveContentProvider(uri.authority!!, 0)
check(provider != null && provider.packageName == plugin.component.packageName &&
provider.applicationInfo.uid == plugin.uid && provider.enabled && provider.exported && provider.applicationInfo.enabled) {
"Plugin settings provider unavailable"
}
}

fun request(method: String = ProjectionSettings.GET, extras: Bundle = ProjectionSettings.request()): PluginSettingsSnapshot {
checkIdentity()
val response = requireNotNull(context.contentResolver.acquireUnstableContentProviderClient(uri)) {
"Plugin settings provider unavailable"
}.use { it.call(method, plugin.component.flattenToString(), extras) }
checkIdentity() // Discard replies from an APK that changed during the call.
requireNotNull(response)
require(response.getInt("version") == ProjectionSettings.VERSION) { "Unsupported settings protocol" }
val status = response.getString("status")
check(status == "ok" || status == "conflict") {
response.getString("message").orEmpty().take(256).ifBlank { "Plugin settings request failed" }
}
val schema = PluginSettingsSchema.fromJson(requireNotNull(response.getString("schema")))
val document = response.getByteArray("remote_document")?.let { bytes ->
require(response.getString("remote_version") == ProjectionSettings.REMOTE_COMPOSE_VERSION) {
"Unsupported Remote Compose version"
}
PluginSettingsDocument(bytes, response.getInt("remote_width"), response.getInt("remote_height"))
}
return PluginSettingsSnapshot(schema, response.getBoolean("supports_remote"), document, status == "conflict")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import android.os.Looper
import android.os.Build
import com.shilapi.xcertplay.projection.*
import moe.feng.wheelplay.plugin.ProjectionPlugin
import moe.feng.wheelplay.plugin.ProjectionSettings
import java.security.MessageDigest
import java.util.concurrent.CompletableFuture
import com.shilapi.xcertplay.shared.R as UiR
Expand All @@ -22,6 +23,7 @@ internal data class InstalledProjectionPlugin(
val problem: String?,
val installedAt: Long = 0,
val sourceId: String? = null,
val settingsProvider: String? = null,
) {
val id get() = PREFIX + component.flattenToString()
val consentKey get() = "$signer@$installedAt"
Expand Down Expand Up @@ -117,9 +119,19 @@ internal class ProjectionPluginRegistry(private val context: Context, private va
(it.permission == null || pm.checkPermission(it.permission, context.packageName) == PackageManager.PERMISSION_GRANTED)
}?.let { activity }
}
val settingsProvider = service.metaData?.getString(ProjectionSettings.META_PROVIDER)?.takeIf {
Regex("[A-Za-z][A-Za-z0-9_.]*").matches(it)
}?.takeIf { authority ->
pm.resolveContentProvider(authority, 0)?.let {
it.packageName == service.packageName && it.applicationInfo.uid == service.applicationInfo.uid &&
it.exported && it.enabled && it.applicationInfo.enabled &&
(it.readPermission == null || pm.checkPermission(it.readPermission, context.packageName) == PackageManager.PERMISSION_GRANTED) &&
(it.writePermission == null || pm.checkPermission(it.writePermission, context.packageName) == PackageManager.PERMISSION_GRANTED)
} == true
}
InstalledProjectionPlugin(component, service.loadLabel(pm).toString().take(120),
service.applicationInfo.uid, signer, pkg.lastUpdateTime, pkg.longVersionCode, settings, problem, pkg.firstInstallTime,
service.metaData?.getString(ProjectionPlugin.META_SOURCE_ID))
service.metaData?.getString(ProjectionPlugin.META_SOURCE_ID), settingsProvider)
}.getOrNull()
}.distinctBy { it.id }.sortedBy { it.name }
failures.entries.removeAll { it.value.plugin !in installed }
Expand Down
21 changes: 17 additions & 4 deletions common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.shilapi.xcertplay.projection.ProjectionSourceIds
import com.shilapi.xcertplay.projection.projectionSessions
import com.shilapi.xcertplay.projection.plugin.projectionPlugins
import com.shilapi.xcertplay.projection.plugin.RemotePluginSession
import com.shilapi.xcertplay.projection.plugin.InstalledProjectionPlugin
import com.shilapi.xcertplay.projection.ProjectionSession
import moe.feng.wheelplay.plugin.ProjectionPlugin
import com.shilapi.xcertplay.projection.registerProjectionSources
Expand Down Expand Up @@ -72,6 +73,7 @@ class WheelPlayActivity : AppCompatActivity() {
private val settingsModel by lazy { ViewModelProvider(this)[SettingsViewModel::class.java] }
private val settingsDialogs = SettingsDialogHost()
private var webBusy = false
private var embeddedPlugin by mutableStateOf<InstalledProjectionPlugin?>(null)
private var awaitingTeslaVpnConsent = false
private val localAndroidAutoSettings = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (!isFinishing && !isDestroyed) showLocalAndroidAutoSetup()
Expand Down Expand Up @@ -330,6 +332,15 @@ class WheelPlayActivity : AppCompatActivity() {
refreshSettings()
setContent {
WheelPlayScreen(page, aaConnection, uiState, settingsModel, settingsActions, settingsDialogs, dialogs, snackbar, ::dispatch)
embeddedPlugin?.let { plugin -> key(plugin) {
PluginSettingsDialog(plugin, lifecycle, onDismiss = { embeddedPlugin = null },
onExternal = plugin.settings?.let { component -> {
embeddedPlugin = null
if (projectionPlugins(this).entries().contains(plugin))
runCatching { startActivity(Intent().setComponent(component)) }
.onFailure { toast(getString(UiR.string.plugin_unavailable)) }
} })
} }
}
}

Expand Down Expand Up @@ -390,9 +401,10 @@ class WheelPlayActivity : AppCompatActivity() {
refreshUiState()
}
UiAction.PLUGIN_DISABLE -> { registry.setEnabled(plugin, false); refreshUiState() }
UiAction.PLUGIN_SETTINGS -> plugin.settings?.let { component ->
runCatching { startActivity(Intent().setComponent(component)) }.onFailure { toast(getString(UiR.string.plugin_unavailable)) }
}
UiAction.PLUGIN_SETTINGS -> if (plugin.settingsProvider != null) embeddedPlugin = plugin
else plugin.settings?.let { component ->
runCatching { startActivity(Intent().setComponent(component)) }.onFailure { toast(getString(UiR.string.plugin_unavailable)) }
}
UiAction.PLUGIN_CONNECT -> startProjectionSource(plugin.id)
else -> Unit
}
Expand Down Expand Up @@ -479,7 +491,8 @@ class WheelPlayActivity : AppCompatActivity() {
val plugins = registry.entries().map { plugin -> PluginUi(
plugin.id, plugin.name, plugin.component.packageName, plugin.sourceId == ProjectionPlugin.SOURCE_ICCOA_CARLINK,
registry.enabled(plugin), plugin.problem, registry.lastFailure(plugin.id)?.let { getString(UiR.string.projection_failed, it) },
plugin.settings != null, !(running && (state.source?.id == plugin.id || active?.descriptor?.id == plugin.id)),
plugin.settings != null || plugin.settingsProvider != null,
!(running && (state.source?.id == plugin.id || active?.descriptor?.id == plugin.id)),
) }
val addresses = if (WebSession.running && WebSession.error == null) WebSession.addresses(this) else emptyList()
val primary = addresses.firstOrNull()
Expand Down
Loading
Loading