mirror of
https://github.com/austinried/subtracks.git
synced 2026-11-16 01:00:17 +01:00
net: simplify local network permission to explicit server actions
Remove the automatic root prompt, network observer, denial cache, custom rationale, and source-specific sync retry state. Test and Save now validate first and launch the system Nearby devices request only when the entered destination needs it; an existing server can be recovered through Edit Server. Keep the precise on-link check: resolve before reading the current networks, exclude cellular and VPN-routed destinations, honor longest-prefix VPN exclusions, and handle .local without attempting blocked mDNS resolution. Consolidate coverage into the SDK 37 Robolectric suite and delete the gate state-machine tests with the state machine.
This commit is contained in:
@@ -6,6 +6,7 @@ import android.net.ConnectivityManager
|
|||||||
import android.net.IpPrefix
|
import android.net.IpPrefix
|
||||||
import android.net.LinkAddress
|
import android.net.LinkAddress
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.RouteInfo
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.annotation.RequiresApi
|
import androidx.annotation.RequiresApi
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
@@ -15,76 +16,44 @@ import java.net.InetAddress
|
|||||||
|
|
||||||
internal const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK"
|
internal const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK"
|
||||||
|
|
||||||
private const val LOCAL_NETWORK_PERMISSION_SDK = 37
|
|
||||||
|
|
||||||
class LocalNetworkAccess(
|
class LocalNetworkAccess(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
) {
|
) {
|
||||||
private val deniedAddresses = mutableSetOf<String>()
|
@Suppress("DEPRECATION")
|
||||||
|
|
||||||
suspend fun requiresPermission(address: String): Boolean {
|
suspend fun requiresPermission(address: String): Boolean {
|
||||||
val granted = granted()
|
if (Build.VERSION.SDK_INT < 37 || granted()) return false
|
||||||
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK || granted) return false
|
|
||||||
val host = serverHost(address) ?: return false
|
val host = serverHost(address) ?: return false
|
||||||
return withContext(Dispatchers.IO) {
|
return withContext(Dispatchers.IO) {
|
||||||
val resolved = if (isLocalHostname(host)) emptyList() else resolve(host)
|
val resolved = if (isLocalHostname(host)) emptyList() else resolve(host)
|
||||||
val linkAddresses = currentLinkAddresses()
|
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return@withContext false
|
||||||
needsPermission(
|
val linkAddresses =
|
||||||
sdk = Build.VERSION.SDK_INT,
|
manager.allNetworks
|
||||||
granted = granted,
|
.filter { network -> manager.getNetworkCapabilities(network)?.isPhysicalLan == true }
|
||||||
host = host,
|
.flatMap { network -> manager.getLinkProperties(network)?.linkAddresses.orEmpty() }
|
||||||
hasEligibleInterface = linkAddresses.isNotEmpty(),
|
if (linkAddresses.isEmpty()) return@withContext false
|
||||||
resolved = resolved,
|
|
||||||
onLink = { candidate -> linkAddresses.any { it.contains(candidate) } },
|
|
||||||
vpnRouted = ::routedThroughVpn,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Synchronized
|
val vpnRoutes = activeVpnRoutes(manager)
|
||||||
fun markDenied(address: String) {
|
if (isLocalHostname(host)) {
|
||||||
deniedAddresses += normalizeServerAddress(address)
|
vpnRoutes.mayFallThroughToLan(linkAddresses)
|
||||||
|
} else {
|
||||||
|
resolved.any { candidate ->
|
||||||
|
linkAddresses.any { it.contains(candidate) } && !vpnRoutes.routesThroughVpn(candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun wasDenied(address: String): Boolean = normalizeServerAddress(address) in deniedAddresses
|
|
||||||
|
|
||||||
private fun granted(): Boolean =
|
private fun granted(): Boolean =
|
||||||
ContextCompat.checkSelfPermission(context, LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED
|
ContextCompat.checkSelfPermission(context, LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
private fun resolve(host: String): List<InetAddress> = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList())
|
private fun resolve(host: String): List<InetAddress> = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList())
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
private fun activeVpnRoutes(manager: ConnectivityManager): List<RouteInfo> {
|
||||||
private fun currentLinkAddresses(): List<LinkAddress> {
|
val network = manager.activeNetwork ?: return emptyList()
|
||||||
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return emptyList()
|
val capabilities = manager.getNetworkCapabilities(network) ?: return emptyList()
|
||||||
return manager.allNetworks
|
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return emptyList()
|
||||||
.filter { network -> manager.getNetworkCapabilities(network)?.isLocalNetworkInterface == true }
|
return manager.getLinkProperties(network)?.routes.orEmpty()
|
||||||
.flatMap { network -> manager.getLinkProperties(network)?.linkAddresses.orEmpty() }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
|
|
||||||
private fun routedThroughVpn(address: InetAddress): Boolean {
|
|
||||||
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return false
|
|
||||||
val network = manager.activeNetwork ?: return false
|
|
||||||
val capabilities = manager.getNetworkCapabilities(network) ?: return false
|
|
||||||
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return false
|
|
||||||
val properties = manager.getLinkProperties(network) ?: return false
|
|
||||||
return properties.routes.any { route -> route.destination.contains(address) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun needsPermission(
|
|
||||||
sdk: Int,
|
|
||||||
granted: Boolean,
|
|
||||||
host: String?,
|
|
||||||
hasEligibleInterface: Boolean,
|
|
||||||
resolved: List<InetAddress>,
|
|
||||||
onLink: (InetAddress) -> Boolean,
|
|
||||||
vpnRouted: (InetAddress) -> Boolean,
|
|
||||||
): Boolean {
|
|
||||||
if (sdk < LOCAL_NETWORK_PERMISSION_SDK || granted || host == null || !hasEligibleInterface) return false
|
|
||||||
if (isLocalHostname(host)) return true
|
|
||||||
return resolved.any { candidate -> !vpnRouted(candidate) && onLink(candidate) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun isLocalHostname(host: String): Boolean {
|
internal fun isLocalHostname(host: String): Boolean {
|
||||||
@@ -92,10 +61,23 @@ internal fun isLocalHostname(host: String): Boolean {
|
|||||||
return normalized == "local" || normalized.endsWith(".local")
|
return normalized == "local" || normalized.endsWith(".local")
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
|
@RequiresApi(37)
|
||||||
private fun LinkAddress.contains(address: InetAddress): Boolean = IpPrefix(this.address, prefixLength).contains(address)
|
private fun LinkAddress.contains(address: InetAddress): Boolean = IpPrefix(this.address, prefixLength).contains(address)
|
||||||
|
|
||||||
private val NetworkCapabilities.isLocalNetworkInterface: Boolean
|
@RequiresApi(37)
|
||||||
|
private fun List<RouteInfo>.routesThroughVpn(address: InetAddress): Boolean =
|
||||||
|
filter { it.matches(address) }
|
||||||
|
.maxByOrNull { it.destination.prefixLength }
|
||||||
|
?.type == RouteInfo.RTN_UNICAST
|
||||||
|
|
||||||
|
@RequiresApi(37)
|
||||||
|
private fun List<RouteInfo>.mayFallThroughToLan(linkAddresses: List<LinkAddress>): Boolean =
|
||||||
|
any { route ->
|
||||||
|
route.type != RouteInfo.RTN_UNICAST &&
|
||||||
|
linkAddresses.any { link -> route.matches(link.address) || link.contains(route.destination.address) }
|
||||||
|
} || linkAddresses.any { !routesThroughVpn(it.address) }
|
||||||
|
|
||||||
|
private val NetworkCapabilities.isPhysicalLan: Boolean
|
||||||
get() =
|
get() =
|
||||||
!hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
|
!hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
|
||||||
!hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
!hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||||
|
|||||||
@@ -71,9 +71,6 @@ class SourceRepository(
|
|||||||
private val _offline = MutableStateFlow(false)
|
private val _offline = MutableStateFlow(false)
|
||||||
val offline: StateFlow<Boolean> = _offline
|
val offline: StateFlow<Boolean> = _offline
|
||||||
|
|
||||||
private val _offlineLoaded = MutableStateFlow(false)
|
|
||||||
val offlineLoaded: StateFlow<Boolean> = _offlineLoaded
|
|
||||||
|
|
||||||
private val _activeSource = MutableStateFlow<Long?>(null)
|
private val _activeSource = MutableStateFlow<Long?>(null)
|
||||||
val activeSource: StateFlow<Long?> = _activeSource
|
val activeSource: StateFlow<Long?> = _activeSource
|
||||||
|
|
||||||
@@ -98,7 +95,6 @@ class SourceRepository(
|
|||||||
// Read the persisted flag before the source config can build a source or probe it, so a
|
// Read the persisted flag before the source config can build a source or probe it, so a
|
||||||
// cold start with offline on never touches the network.
|
// cold start with offline on never touches the network.
|
||||||
_offline.value = prefs.offlineMode().first()
|
_offline.value = prefs.offlineMode().first()
|
||||||
_offlineLoaded.value = true
|
|
||||||
var lastMode: NetworkMode? = null
|
var lastMode: NetworkMode? = null
|
||||||
combine(
|
combine(
|
||||||
db.sourcesDao().activeSubsonicConfig(),
|
db.sourcesDao().activeSubsonicConfig(),
|
||||||
|
|||||||
@@ -48,12 +48,6 @@ class SyncManager(
|
|||||||
private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)
|
private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)
|
||||||
val status: StateFlow<SyncStatus> = _status
|
val status: StateFlow<SyncStatus> = _status
|
||||||
|
|
||||||
private val _runningSource = MutableStateFlow<Long?>(null)
|
|
||||||
val runningSource: StateFlow<Long?> = _runningSource
|
|
||||||
|
|
||||||
private val _failedSource = MutableStateFlow<Long?>(null)
|
|
||||||
val failedSource: StateFlow<Long?> = _failedSource
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
for (silent in requests) {
|
for (silent in requests) {
|
||||||
@@ -88,11 +82,9 @@ class SyncManager(
|
|||||||
runCatching { preferences.setLastSyncAt(System.currentTimeMillis()) }
|
runCatching { preferences.setLastSyncAt(System.currentTimeMillis()) }
|
||||||
.onFailure { Log.w("sync", "could not record the sync attempt", it) }
|
.onFailure { Log.w("sync", "could not record the sync attempt", it) }
|
||||||
val startedAt = System.nanoTime()
|
val startedAt = System.nanoTime()
|
||||||
val source = sourceRepository.activeMusicSource()
|
|
||||||
_runningSource.value = source?.id
|
|
||||||
val result =
|
val result =
|
||||||
try {
|
try {
|
||||||
if (source == null) throw NoServerException()
|
val source = sourceRepository.activeMusicSource() ?: throw NoServerException()
|
||||||
Log.i("sync", "started (source ${source.id})")
|
Log.i("sync", "started (source ${source.id})")
|
||||||
serverActions.flush()
|
serverActions.flush()
|
||||||
val resetPoint = queueRepository.captureResetPoint()
|
val resetPoint = queueRepository.captureResetPoint()
|
||||||
@@ -107,7 +99,6 @@ class SyncManager(
|
|||||||
"${completed.playlists} playlists, ${completed.playlistSongs} playlist tracks, ${completed.pruned} pruned",
|
"${completed.playlists} playlists, ${completed.playlistSongs} playlist tracks, ${completed.pruned} pruned",
|
||||||
)
|
)
|
||||||
queueRepository.resetChangedOriginsAndClearPendingOrigins(changedOrigins, resetPoint, source.id)
|
queueRepository.resetChangedOriginsAndClearPendingOrigins(changedOrigins, resetPoint, source.id)
|
||||||
_failedSource.value = null
|
|
||||||
SyncStatus.Success
|
SyncStatus.Success
|
||||||
} catch (cancellation: CancellationException) {
|
} catch (cancellation: CancellationException) {
|
||||||
throw cancellation
|
throw cancellation
|
||||||
@@ -125,10 +116,7 @@ class SyncManager(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!silent) showMessage(message)
|
if (!silent) showMessage(message)
|
||||||
_failedSource.value = source?.id
|
|
||||||
SyncStatus.Failed(message)
|
SyncStatus.Failed(message)
|
||||||
} finally {
|
|
||||||
_runningSource.value = null
|
|
||||||
}
|
}
|
||||||
_status.value = result
|
_status.value = result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,8 +66,6 @@ import com.subtracks.data.model.Song
|
|||||||
import com.subtracks.data.repo.DownloadRepository
|
import com.subtracks.data.repo.DownloadRepository
|
||||||
import com.subtracks.data.repo.LibraryRepository
|
import com.subtracks.data.repo.LibraryRepository
|
||||||
import com.subtracks.data.repo.SourceRepository
|
import com.subtracks.data.repo.SourceRepository
|
||||||
import com.subtracks.data.sync.SyncManager
|
|
||||||
import com.subtracks.data.sync.SyncStatus
|
|
||||||
import com.subtracks.playback.PlaybackController
|
import com.subtracks.playback.PlaybackController
|
||||||
import com.subtracks.ui.components.AlbumInfoDialog
|
import com.subtracks.ui.components.AlbumInfoDialog
|
||||||
import com.subtracks.ui.components.ArtistChooserSheet
|
import com.subtracks.ui.components.ArtistChooserSheet
|
||||||
@@ -78,8 +76,6 @@ import com.subtracks.ui.components.LoadingState
|
|||||||
import com.subtracks.ui.components.MenuTarget
|
import com.subtracks.ui.components.MenuTarget
|
||||||
import com.subtracks.ui.components.PlaylistInfoDialog
|
import com.subtracks.ui.components.PlaylistInfoDialog
|
||||||
import com.subtracks.ui.components.SongInfoDialog
|
import com.subtracks.ui.components.SongInfoDialog
|
||||||
import com.subtracks.ui.components.rememberLocalNetworkGate
|
|
||||||
import com.subtracks.ui.components.rememberNetworkRevision
|
|
||||||
import com.subtracks.ui.components.statusBarScrim
|
import com.subtracks.ui.components.statusBarScrim
|
||||||
import com.subtracks.ui.downloads.DownloadsRoute
|
import com.subtracks.ui.downloads.DownloadsRoute
|
||||||
import com.subtracks.ui.home.HomeListRequest
|
import com.subtracks.ui.home.HomeListRequest
|
||||||
@@ -115,21 +111,6 @@ class RootViewModel(
|
|||||||
.activeSourceId()
|
.activeSourceId()
|
||||||
.map { it != null }
|
.map { it != null }
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
||||||
|
|
||||||
val serverAddress =
|
|
||||||
sourceRepository
|
|
||||||
.activeConfig()
|
|
||||||
.map { it?.address }
|
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
|
||||||
|
|
||||||
val activeSourceId =
|
|
||||||
sourceRepository
|
|
||||||
.activeSourceId()
|
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
|
||||||
|
|
||||||
val offline = sourceRepository.offline
|
|
||||||
|
|
||||||
val offlineLoaded = sourceRepository.offlineLoaded
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val NAVIGATION_DURATION_MS = 260
|
private const val NAVIGATION_DURATION_MS = 260
|
||||||
@@ -212,46 +193,6 @@ internal fun focusPops(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SubtracksRoot(root: RootViewModel = koinViewModel()) {
|
fun SubtracksRoot(root: RootViewModel = koinViewModel()) {
|
||||||
val localNetworkGate = rememberLocalNetworkGate()
|
|
||||||
val syncManager = koinInject<SyncManager>()
|
|
||||||
val serverAddress by root.serverAddress.collectAsStateWithLifecycle()
|
|
||||||
val activeSourceId by root.activeSourceId.collectAsStateWithLifecycle()
|
|
||||||
val offline by root.offline.collectAsStateWithLifecycle()
|
|
||||||
val offlineLoaded by root.offlineLoaded.collectAsStateWithLifecycle()
|
|
||||||
val networkRevision = rememberNetworkRevision()
|
|
||||||
LaunchedEffect(serverAddress, activeSourceId, networkRevision, offline, offlineLoaded) {
|
|
||||||
if (!offlineLoaded) return@LaunchedEffect
|
|
||||||
if (offline) {
|
|
||||||
localNetworkGate.cancel()
|
|
||||||
return@LaunchedEffect
|
|
||||||
}
|
|
||||||
val promptedSourceId = activeSourceId
|
|
||||||
val statusBeforePrompt = syncManager.status.value
|
|
||||||
localNetworkGate.run(
|
|
||||||
address = serverAddress,
|
|
||||||
onGranted = {
|
|
||||||
val status = syncManager.status.value
|
|
||||||
val raced =
|
|
||||||
when (status) {
|
|
||||||
is SyncStatus.Running -> {
|
|
||||||
syncManager.runningSource.value == promptedSourceId
|
|
||||||
}
|
|
||||||
|
|
||||||
is SyncStatus.Failed -> {
|
|
||||||
statusBeforePrompt !is SyncStatus.Failed &&
|
|
||||||
syncManager.failedSource.value == promptedSourceId
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (raced) syncManager.requestSync()
|
|
||||||
},
|
|
||||||
onNotNeeded = {},
|
|
||||||
automatic = true,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
when (val hasSource = root.hasSource.collectAsStateWithLifecycle().value) {
|
when (val hasSource = root.hasSource.collectAsStateWithLifecycle().value) {
|
||||||
null -> {
|
null -> {
|
||||||
LoadingState()
|
LoadingState()
|
||||||
|
|||||||
@@ -1,195 +0,0 @@
|
|||||||
package com.subtracks.ui.components
|
|
||||||
|
|
||||||
import android.net.ConnectivityManager
|
|
||||||
import android.net.LinkProperties
|
|
||||||
import android.net.Network
|
|
||||||
import android.net.NetworkCapabilities
|
|
||||||
import android.net.NetworkRequest
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.TextButton
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.DisposableEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import com.subtracks.R
|
|
||||||
import com.subtracks.data.net.LOCAL_NETWORK_PERMISSION
|
|
||||||
import com.subtracks.data.net.LocalNetworkAccess
|
|
||||||
import kotlinx.coroutines.CancellationException
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.ensureActive
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import org.koin.compose.koinInject
|
|
||||||
|
|
||||||
class LocalNetworkGate internal constructor(
|
|
||||||
private val scope: CoroutineScope,
|
|
||||||
private val requiresPermission: suspend (String) -> Boolean,
|
|
||||||
private val wasDenied: (String) -> Boolean,
|
|
||||||
private val requestPermission: (address: String, onGranted: () -> Unit, onDenied: () -> Unit) -> Unit,
|
|
||||||
private val clearPrompt: () -> Unit,
|
|
||||||
) {
|
|
||||||
private var generation = 0
|
|
||||||
private var check: Job? = null
|
|
||||||
|
|
||||||
fun run(
|
|
||||||
address: String?,
|
|
||||||
onGranted: () -> Unit,
|
|
||||||
onDenied: () -> Unit = {},
|
|
||||||
onNotNeeded: () -> Unit = onGranted,
|
|
||||||
automatic: Boolean = false,
|
|
||||||
) {
|
|
||||||
cancel()
|
|
||||||
if (address == null) {
|
|
||||||
onNotNeeded()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val current = generation
|
|
||||||
check =
|
|
||||||
scope.launch {
|
|
||||||
val required =
|
|
||||||
try {
|
|
||||||
requiresPermission(address)
|
|
||||||
} catch (cancellation: CancellationException) {
|
|
||||||
throw cancellation
|
|
||||||
} catch (_: Exception) {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
if (current != generation) return@launch
|
|
||||||
ensureActive()
|
|
||||||
if (required && !(automatic && wasDenied(address))) {
|
|
||||||
requestPermission(address, onGranted, onDenied)
|
|
||||||
} else {
|
|
||||||
onNotNeeded()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cancel() {
|
|
||||||
generation++
|
|
||||||
check?.cancel()
|
|
||||||
check = null
|
|
||||||
clearPrompt()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class PendingRequest(
|
|
||||||
val address: String,
|
|
||||||
val onGranted: () -> Unit,
|
|
||||||
val onDenied: () -> Unit,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun rememberLocalNetworkGate(): LocalNetworkGate {
|
|
||||||
val checker = koinInject<LocalNetworkAccess>()
|
|
||||||
val scope = rememberCoroutineScope()
|
|
||||||
var pending by remember { mutableStateOf<PendingRequest?>(null) }
|
|
||||||
var awaitingSystemPrompt by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
fun deny(request: PendingRequest) {
|
|
||||||
pending = null
|
|
||||||
checker.markDenied(request.address)
|
|
||||||
request.onDenied()
|
|
||||||
}
|
|
||||||
|
|
||||||
val launcher =
|
|
||||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
|
||||||
val request = pending
|
|
||||||
pending = null
|
|
||||||
awaitingSystemPrompt = false
|
|
||||||
if (request != null) {
|
|
||||||
if (granted) request.onGranted() else deny(request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val gate =
|
|
||||||
remember(scope, checker) {
|
|
||||||
LocalNetworkGate(
|
|
||||||
scope = scope,
|
|
||||||
requiresPermission = checker::requiresPermission,
|
|
||||||
wasDenied = checker::wasDenied,
|
|
||||||
requestPermission = { address, onGranted, onDenied ->
|
|
||||||
if (pending == null) pending = PendingRequest(address, onGranted, onDenied)
|
|
||||||
},
|
|
||||||
clearPrompt = {
|
|
||||||
if (!awaitingSystemPrompt) pending = null
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val request = pending
|
|
||||||
if (request != null && !awaitingSystemPrompt) {
|
|
||||||
AlertDialog(
|
|
||||||
onDismissRequest = { deny(request) },
|
|
||||||
title = { Text(stringResource(R.string.local_network_permission_title)) },
|
|
||||||
text = { Text(stringResource(R.string.local_network_permission_body)) },
|
|
||||||
confirmButton = {
|
|
||||||
TextButton(
|
|
||||||
onClick = {
|
|
||||||
awaitingSystemPrompt = true
|
|
||||||
launcher.launch(LOCAL_NETWORK_PERMISSION)
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
Text(stringResource(R.string.local_network_permission_continue))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
TextButton(
|
|
||||||
onClick = { deny(request) },
|
|
||||||
) {
|
|
||||||
Text(stringResource(R.string.actions_cancel))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return gate
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
internal fun rememberNetworkRevision(): Int {
|
|
||||||
val context = LocalContext.current
|
|
||||||
var revision by remember { mutableIntStateOf(0) }
|
|
||||||
DisposableEffect(context) {
|
|
||||||
val manager = context.getSystemService(ConnectivityManager::class.java)
|
|
||||||
val mainExecutor = ContextCompat.getMainExecutor(context)
|
|
||||||
val notifyChanged = { mainExecutor.execute { revision++ } }
|
|
||||||
val callback =
|
|
||||||
object : ConnectivityManager.NetworkCallback() {
|
|
||||||
override fun onAvailable(network: Network) {
|
|
||||||
notifyChanged()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLost(network: Network) {
|
|
||||||
notifyChanged()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLinkPropertiesChanged(
|
|
||||||
network: Network,
|
|
||||||
linkProperties: LinkProperties,
|
|
||||||
) {
|
|
||||||
notifyChanged()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCapabilitiesChanged(
|
|
||||||
network: Network,
|
|
||||||
networkCapabilities: NetworkCapabilities,
|
|
||||||
) {
|
|
||||||
notifyChanged()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
runCatching { manager?.registerNetworkCallback(NetworkRequest.Builder().build(), callback) }
|
|
||||||
onDispose {
|
|
||||||
if (manager != null) runCatching { manager.unregisterNetworkCallback(callback) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return revision
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.subtracks.ui.components
|
||||||
|
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.subtracks.data.net.LOCAL_NETWORK_PERMISSION
|
||||||
|
import com.subtracks.data.net.LocalNetworkAccess
|
||||||
|
import com.subtracks.data.prefs.UserPreferences
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import org.koin.compose.koinInject
|
||||||
|
|
||||||
|
private class PendingLocalNetworkAction(
|
||||||
|
val onGranted: () -> Unit,
|
||||||
|
val onDenied: () -> Unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberLocalNetworkRequest(): (String, () -> Unit, () -> Unit) -> Unit {
|
||||||
|
val access = koinInject<LocalNetworkAccess>()
|
||||||
|
val preferences = koinInject<UserPreferences>()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var pending by remember { mutableStateOf<PendingLocalNetworkAction?>(null) }
|
||||||
|
val launcher =
|
||||||
|
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
|
val action = pending
|
||||||
|
pending = null
|
||||||
|
if (granted) action?.onGranted?.invoke() else action?.onDenied?.invoke()
|
||||||
|
}
|
||||||
|
|
||||||
|
return { address, onGranted, onDenied ->
|
||||||
|
scope.launch {
|
||||||
|
val required =
|
||||||
|
try {
|
||||||
|
!preferences.offlineMode().first() && access.requiresPermission(address)
|
||||||
|
} catch (cancellation: CancellationException) {
|
||||||
|
throw cancellation
|
||||||
|
} catch (_: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
if (required) {
|
||||||
|
pending = PendingLocalNetworkAction(onGranted, onDenied)
|
||||||
|
launcher.launch(LOCAL_NETWORK_PERMISSION)
|
||||||
|
} else {
|
||||||
|
onGranted()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,7 +48,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.subtracks.R
|
import com.subtracks.R
|
||||||
import com.subtracks.ui.components.DismissOnRequest
|
import com.subtracks.ui.components.DismissOnRequest
|
||||||
import com.subtracks.ui.components.rememberLocalNetworkGate
|
import com.subtracks.ui.components.rememberLocalNetworkRequest
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.emptyFlow
|
import kotlinx.coroutines.flow.emptyFlow
|
||||||
import org.koin.compose.viewmodel.koinViewModel
|
import org.koin.compose.viewmodel.koinViewModel
|
||||||
@@ -63,43 +63,36 @@ fun AddSourceRoute(
|
|||||||
viewModel: AddSourceViewModel = koinViewModel(key = sourceId?.toString() ?: "new") { parametersOf(sourceId) },
|
viewModel: AddSourceViewModel = koinViewModel(key = sourceId?.toString() ?: "new") { parametersOf(sourceId) },
|
||||||
) {
|
) {
|
||||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||||
val offline by viewModel.offline.collectAsStateWithLifecycle()
|
val requestLocalNetwork = rememberLocalNetworkRequest()
|
||||||
val offlineLoaded by viewModel.offlineLoaded.collectAsStateWithLifecycle()
|
var checkingNetwork by remember { mutableStateOf(false) }
|
||||||
val localNetworkGate = rememberLocalNetworkGate()
|
|
||||||
var gatedBusy by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
fun runGated(
|
fun runGated(
|
||||||
onGranted: () -> Unit,
|
onGranted: () -> Unit,
|
||||||
onDenied: () -> Unit = onGranted,
|
onDenied: () -> Unit = onGranted,
|
||||||
) {
|
) {
|
||||||
if (!offlineLoaded || gatedBusy) return
|
if (checkingNetwork) return
|
||||||
gatedBusy = true
|
checkingNetwork = true
|
||||||
val address = state.address
|
val address = state.address
|
||||||
|
|
||||||
fun finish(action: () -> Unit) {
|
fun finish(action: () -> Unit) {
|
||||||
gatedBusy = false
|
checkingNetwork = false
|
||||||
if (viewModel.state.value.address == address) action()
|
if (viewModel.state.value.address == address) action()
|
||||||
}
|
}
|
||||||
|
|
||||||
if (offline) {
|
requestLocalNetwork(address, { finish(onGranted) }, { finish(onDenied) })
|
||||||
finish(onGranted)
|
|
||||||
} else {
|
|
||||||
localNetworkGate.run(
|
|
||||||
address = address,
|
|
||||||
onGranted = { finish(onGranted) },
|
|
||||||
onDenied = { finish(onDenied) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
AddSourceScreen(
|
AddSourceScreen(
|
||||||
state = if (gatedBusy || !offlineLoaded) state.copy(busy = true) else state,
|
state = if (checkingNetwork) state.copy(busy = true) else state,
|
||||||
onNameChange = viewModel::setName,
|
onNameChange = viewModel::setName,
|
||||||
onAddressChange = viewModel::setAddress,
|
onAddressChange = viewModel::setAddress,
|
||||||
onUsernameChange = viewModel::setUsername,
|
onUsernameChange = viewModel::setUsername,
|
||||||
onPasswordChange = viewModel::setPassword,
|
onPasswordChange = viewModel::setPassword,
|
||||||
onTokenAuthChange = viewModel::setTokenAuth,
|
onTokenAuthChange = viewModel::setTokenAuth,
|
||||||
onTest = { runGated(viewModel::testConnection, viewModel::localNetworkPermissionDenied) },
|
onTest = { runGated(viewModel::testConnection, viewModel::localNetworkPermissionDenied) },
|
||||||
onSave = { runGated({ viewModel.save(onSaved) }) },
|
onSave = {
|
||||||
|
if (viewModel.validateSave()) runGated({ viewModel.save(onSaved) })
|
||||||
|
},
|
||||||
onDelete = { viewModel.delete(onSaved) },
|
onDelete = { viewModel.delete(onSaved) },
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
dismissals = dismissals,
|
dismissals = dismissals,
|
||||||
@@ -239,6 +232,7 @@ fun AddSourceScreen(
|
|||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = state.address,
|
value = state.address,
|
||||||
onValueChange = onAddressChange,
|
onValueChange = onAddressChange,
|
||||||
|
enabled = !state.busy,
|
||||||
label = { Text(stringResource(R.string.settings_servers_fields_address)) },
|
label = { Text(stringResource(R.string.settings_servers_fields_address)) },
|
||||||
placeholder = { Text(stringResource(R.string.server_address_placeholder)) },
|
placeholder = { Text(stringResource(R.string.server_address_placeholder)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
|
|||||||
@@ -47,10 +47,6 @@ class AddSourceViewModel(
|
|||||||
private val _state = MutableStateFlow(AddSourceState(isEditing = sourceId != null))
|
private val _state = MutableStateFlow(AddSourceState(isEditing = sourceId != null))
|
||||||
val state: StateFlow<AddSourceState> = _state
|
val state: StateFlow<AddSourceState> = _state
|
||||||
|
|
||||||
val offline: StateFlow<Boolean> = sourceRepository.offline
|
|
||||||
|
|
||||||
val offlineLoaded: StateFlow<Boolean> = sourceRepository.offlineLoaded
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
sourceId?.let { id ->
|
sourceId?.let { id ->
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
@@ -122,12 +118,17 @@ class AddSourceViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun save(onSaved: () -> Unit) {
|
fun validateSave(): Boolean {
|
||||||
val validated = _state.value.validated()
|
val validated = _state.value.validated()
|
||||||
if (validated.nameError || validated.addressError) {
|
if (validated.nameError || validated.addressError) {
|
||||||
_state.value = validated
|
_state.value = validated
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun save(onSaved: () -> Unit) {
|
||||||
|
if (!validateSave()) return
|
||||||
_state.update { it.copy(busy = true, message = null) }
|
_state.update { it.copy(busy = true, message = null) }
|
||||||
val current = _state.value
|
val current = _state.value
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
|||||||
@@ -289,9 +289,6 @@
|
|||||||
<string name="delete_server_body">%1$s and its downloaded songs will be removed from this device.</string>
|
<string name="delete_server_body">%1$s and its downloaded songs will be removed from this device.</string>
|
||||||
<string name="connection_ok">Connection OK</string>
|
<string name="connection_ok">Connection OK</string>
|
||||||
<string name="connection_token_fallback">Server does not support token auth; using the password instead</string>
|
<string name="connection_token_fallback">Server does not support token auth; using the password instead</string>
|
||||||
<string name="local_network_permission_title">Allow local network access</string>
|
|
||||||
<string name="local_network_permission_body">Android blocks apps from reaching devices on your local network until you allow it. Your server is on this network, so Subtracks needs the Nearby devices permission to sync and play. Allow it on the next prompt.</string>
|
|
||||||
<string name="local_network_permission_continue">Continue</string>
|
|
||||||
<string name="local_network_permission_denied">Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server.</string>
|
<string name="local_network_permission_denied">Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server.</string>
|
||||||
<string name="connection_failed">Failed: %1$s</string>
|
<string name="connection_failed">Failed: %1$s</string>
|
||||||
<string name="save_failed">Could not save: %1$s</string>
|
<string name="save_failed">Could not save: %1$s</string>
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ import android.Manifest
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.ConnectivityManager
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.IpPrefix
|
||||||
import android.net.LinkAddress
|
import android.net.LinkAddress
|
||||||
import android.net.LinkProperties
|
import android.net.LinkProperties
|
||||||
import android.net.Network
|
import android.net.Network
|
||||||
import android.net.NetworkCapabilities
|
import android.net.NetworkCapabilities
|
||||||
import android.net.NetworkInfo
|
import android.net.NetworkInfo
|
||||||
|
import android.net.RouteInfo
|
||||||
import androidx.test.core.app.ApplicationProvider
|
import androidx.test.core.app.ApplicationProvider
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
@@ -31,6 +33,14 @@ import java.net.InetAddress
|
|||||||
class LocalNetworkAccessRobolectricTest {
|
class LocalNetworkAccessRobolectricTest {
|
||||||
private val application: Application = ApplicationProvider.getApplicationContext()
|
private val application: Application = ApplicationProvider.getApplicationContext()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Config(sdk = [36])
|
||||||
|
fun skipsBeforeAndroid17() =
|
||||||
|
runTest {
|
||||||
|
activateWifi()
|
||||||
|
assertFalse(checker().requiresPermission("http://10.0.0.5"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun requestsForAnAddressOnTheWifiSubnet() =
|
fun requestsForAnAddressOnTheWifiSubnet() =
|
||||||
runTest {
|
runTest {
|
||||||
@@ -74,24 +84,70 @@ class LocalNetworkAccessRobolectricTest {
|
|||||||
assertFalse(checker().requiresPermission("http://music.local"))
|
assertFalse(checker().requiresPermission("http://music.local"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsAnAddressRoutedThroughTheVpn() =
|
||||||
|
runTest {
|
||||||
|
addWifiNetwork()
|
||||||
|
activateVpn(route("10.0.0.0", 24))
|
||||||
|
assertFalse(checker().requiresPermission("http://10.0.0.5"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun requestsForALanAddressThatFallsThroughASplitTunnelVpn() =
|
fun requestsForALanAddressThatFallsThroughASplitTunnelVpn() =
|
||||||
runTest {
|
runTest {
|
||||||
addWifiNetwork()
|
addWifiNetwork()
|
||||||
activate(ConnectivityManager.TYPE_VPN, NetworkCapabilities.TRANSPORT_VPN, address = "100.64.0.2", prefix = 32)
|
activateVpn()
|
||||||
assertTrue(checker().requiresPermission("http://10.0.0.5"))
|
assertTrue(checker().requiresPermission("http://10.0.0.5"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun requestsForRoutesExcludedFromAFullTunnelVpn() =
|
||||||
|
runTest {
|
||||||
|
addWifiNetwork()
|
||||||
|
activateVpn(
|
||||||
|
route("0.0.0.0", 0),
|
||||||
|
route("10.0.0.5", 32, RouteInfo.RTN_THROW),
|
||||||
|
)
|
||||||
|
assertTrue(checker().requiresPermission("http://10.0.0.5"))
|
||||||
|
assertTrue(checker().requiresPermission("http://music.local"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipsADotLocalNameThroughAFullTunnelVpn() =
|
||||||
|
runTest {
|
||||||
|
addWifiNetwork()
|
||||||
|
activateVpn(route("0.0.0.0", 0))
|
||||||
|
assertFalse(checker().requiresPermission("http://music.local"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun requestsForDotLocalWhenOnlyIpv6UsesTheVpn() =
|
||||||
|
runTest {
|
||||||
|
addWifiNetwork()
|
||||||
|
activateVpn(route("::", 0))
|
||||||
|
assertTrue(checker().requiresPermission("http://music.local"))
|
||||||
|
}
|
||||||
|
|
||||||
private fun activateWifi() = activate(ConnectivityManager.TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI)
|
private fun activateWifi() = activate(ConnectivityManager.TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI)
|
||||||
|
|
||||||
|
private fun activateVpn(vararg routes: RouteInfo) =
|
||||||
|
activate(
|
||||||
|
ConnectivityManager.TYPE_VPN,
|
||||||
|
NetworkCapabilities.TRANSPORT_VPN,
|
||||||
|
address = "100.64.0.2",
|
||||||
|
prefix = 32,
|
||||||
|
routes = routes.toList(),
|
||||||
|
)
|
||||||
|
|
||||||
private fun activate(
|
private fun activate(
|
||||||
type: Int,
|
type: Int,
|
||||||
transport: Int,
|
transport: Int,
|
||||||
address: String = "10.0.0.2",
|
address: String = "10.0.0.2",
|
||||||
prefix: Int = 24,
|
prefix: Int = 24,
|
||||||
|
routes: List<RouteInfo> = emptyList(),
|
||||||
) {
|
) {
|
||||||
shadowOf(manager()).setActiveNetworkInfo(info(type))
|
shadowOf(manager()).setActiveNetworkInfo(info(type))
|
||||||
configure(manager().activeNetwork!!, transport, address, prefix)
|
configure(manager().activeNetwork!!, transport, address, prefix, routes)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun addWifiNetwork() {
|
private fun addWifiNetwork() {
|
||||||
@@ -105,6 +161,7 @@ class LocalNetworkAccessRobolectricTest {
|
|||||||
transport: Int,
|
transport: Int,
|
||||||
address: String,
|
address: String,
|
||||||
prefix: Int,
|
prefix: Int,
|
||||||
|
routes: List<RouteInfo> = emptyList(),
|
||||||
) {
|
) {
|
||||||
val capabilities = ShadowNetworkCapabilities.newInstance()
|
val capabilities = ShadowNetworkCapabilities.newInstance()
|
||||||
shadowOf(capabilities).addTransportType(transport)
|
shadowOf(capabilities).addTransportType(transport)
|
||||||
@@ -113,10 +170,22 @@ class LocalNetworkAccessRobolectricTest {
|
|||||||
network,
|
network,
|
||||||
LinkProperties().apply {
|
LinkProperties().apply {
|
||||||
setLinkAddresses(listOf(linkAddress(address, prefix)))
|
setLinkAddresses(listOf(linkAddress(address, prefix)))
|
||||||
|
routes.forEach { addRoute(it) }
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun route(
|
||||||
|
address: String,
|
||||||
|
prefix: Int,
|
||||||
|
type: Int = RouteInfo.RTN_UNICAST,
|
||||||
|
): RouteInfo =
|
||||||
|
ReflectionHelpers.callConstructor(
|
||||||
|
RouteInfo::class.java,
|
||||||
|
ReflectionHelpers.ClassParameter.from(IpPrefix::class.java, IpPrefix(InetAddress.getByName(address), prefix)),
|
||||||
|
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType!!, type),
|
||||||
|
)
|
||||||
|
|
||||||
private fun linkAddress(
|
private fun linkAddress(
|
||||||
address: String,
|
address: String,
|
||||||
prefix: Int,
|
prefix: Int,
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
package com.subtracks.data.net
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Test
|
|
||||||
import java.net.InetAddress
|
|
||||||
|
|
||||||
class LocalNetworkAccessTest {
|
|
||||||
@Test
|
|
||||||
fun treatsDotLocalHostnamesAsLocalNetwork() {
|
|
||||||
assertTrue(isLocalHostname("navidrome.local"))
|
|
||||||
assertTrue(isLocalHostname("NAVIDROME.LOCAL."))
|
|
||||||
assertTrue(isLocalHostname("local"))
|
|
||||||
assertFalse(isLocalHostname("navidrome.example.com"))
|
|
||||||
assertFalse(isLocalHostname("local.example.com"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun extractsTheHostFromAServerAddress() {
|
|
||||||
assertEquals("navidrome.example.com", serverHost("https://navidrome.example.com/music/"))
|
|
||||||
assertEquals("navidrome.example.com", serverHost("navidrome.example.com:4533"))
|
|
||||||
assertEquals("10.224.202.10", serverHost("http://10.224.202.10"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsTheCheckBeforeAndroid17() {
|
|
||||||
assertFalse(check(sdk = 36))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsTheCheckWhenThePermissionIsGranted() {
|
|
||||||
assertFalse(check(granted = true))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsAHostThatCannotBeParsed() {
|
|
||||||
assertFalse(check(host = null))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsWhenNoEligibleInterfaceExists() {
|
|
||||||
assertFalse(check(hasEligibleInterface = false))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun requestsForADotLocalNameWithAnEligibleInterface() {
|
|
||||||
assertTrue(check(host = "music.local", resolved = emptyList(), onLink = { false }))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsADotLocalNameWithoutAnEligibleInterface() {
|
|
||||||
assertFalse(check(host = "music.local", hasEligibleInterface = false))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun requestsForAnOnLinkAddress() {
|
|
||||||
assertTrue(check(onLink = { it == address("10.0.0.5") }))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsAnAddressThatIsNotOnLink() {
|
|
||||||
assertFalse(check(onLink = { false }))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsAnAddressRoutedThroughTheVpn() {
|
|
||||||
assertFalse(check(onLink = { true }, vpnRouted = { true }))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun requestsWhenAnyCandidateIsOnLinkAndNotVpnRouted() {
|
|
||||||
val onLink = address("10.0.0.5")
|
|
||||||
assertTrue(
|
|
||||||
check(
|
|
||||||
resolved = listOf(address("10.0.0.6"), onLink),
|
|
||||||
onLink = { it == onLink },
|
|
||||||
vpnRouted = { it != onLink },
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsWhenResolutionReturnedNothing() {
|
|
||||||
assertFalse(check(resolved = emptyList()))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun check(
|
|
||||||
sdk: Int = 37,
|
|
||||||
granted: Boolean = false,
|
|
||||||
host: String? = "10.0.0.5",
|
|
||||||
hasEligibleInterface: Boolean = true,
|
|
||||||
resolved: List<InetAddress> = listOf(address("10.0.0.5")),
|
|
||||||
onLink: (InetAddress) -> Boolean = { it == address("10.0.0.5") },
|
|
||||||
vpnRouted: (InetAddress) -> Boolean = { false },
|
|
||||||
): Boolean = needsPermission(sdk, granted, host, hasEligibleInterface, resolved, onLink, vpnRouted)
|
|
||||||
|
|
||||||
private fun address(value: String): InetAddress = InetAddress.getByName(value)
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package com.subtracks.ui.components
|
|
||||||
|
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
|
||||||
import kotlinx.coroutines.test.TestScope
|
|
||||||
import kotlinx.coroutines.test.advanceUntilIdle
|
|
||||||
import kotlinx.coroutines.test.runTest
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
|
||||||
class LocalNetworkGateTest {
|
|
||||||
@Test
|
|
||||||
fun runsTheActionWhenThePermissionIsNotNeeded() =
|
|
||||||
runTest {
|
|
||||||
var checked = 0
|
|
||||||
val gate =
|
|
||||||
gate(requires = {
|
|
||||||
checked++
|
|
||||||
false
|
|
||||||
})
|
|
||||||
var ran = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { ran = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertEquals(1, checked)
|
|
||||||
assertTrue(ran)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun runsTheNotNeededCallbackForANullAddress() =
|
|
||||||
runTest {
|
|
||||||
val gate = gate(requires = { error("should not check a null address") })
|
|
||||||
var notNeeded = false
|
|
||||||
gate.run(null, onGranted = { error("should not run") }, onNotNeeded = { notNeeded = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertTrue(notNeeded)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun runsTheActionOnGrant() =
|
|
||||||
runTest {
|
|
||||||
var requested: String? = null
|
|
||||||
val gate =
|
|
||||||
gate(
|
|
||||||
requires = { true },
|
|
||||||
request = { address, onGranted, _ ->
|
|
||||||
requested = address
|
|
||||||
onGranted()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
var ran = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { ran = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertEquals("http://10.0.0.5", requested)
|
|
||||||
assertTrue(ran)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun runsTheDeniedCallbackOnDenial() =
|
|
||||||
runTest {
|
|
||||||
val gate = gate(requires = { true }, request = { _, _, onDenied -> onDenied() })
|
|
||||||
var denied = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { error("should not run") }, onDenied = { denied = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertTrue(denied)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun skipsTheAutomaticRequestForADeniedAddress() =
|
|
||||||
runTest {
|
|
||||||
var requested = false
|
|
||||||
val gate = gate(requires = { true }, denied = { true }, request = { _, _, _ -> requested = true })
|
|
||||||
var notNeeded = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { error("should not run") }, onNotNeeded = { notNeeded = true }, automatic = true)
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertFalse(requested)
|
|
||||||
assertTrue(notNeeded)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun cancellingDropsTheResult() =
|
|
||||||
runTest {
|
|
||||||
val pending = CompletableDeferred<Boolean>()
|
|
||||||
var cleared = 0
|
|
||||||
val gate = gate(requires = { pending.await() }, clear = { cleared++ })
|
|
||||||
var ran = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { ran = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
gate.cancel()
|
|
||||||
pending.complete(true)
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertFalse(ran)
|
|
||||||
assertEquals(2, cleared)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun ignoresAnEarlierCheckWhenANewAddressStarts() =
|
|
||||||
runTest {
|
|
||||||
val first = CompletableDeferred<Boolean>()
|
|
||||||
val second = CompletableDeferred<Boolean>()
|
|
||||||
var requested: String? = null
|
|
||||||
val gate =
|
|
||||||
gate(
|
|
||||||
requires = { address -> if (address == "http://a") first.await() else second.await() },
|
|
||||||
request = { address, onGranted, _ ->
|
|
||||||
requested = address
|
|
||||||
onGranted()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
gate.run("http://a", onGranted = {})
|
|
||||||
advanceUntilIdle()
|
|
||||||
gate.run("http://b", onGranted = {})
|
|
||||||
advanceUntilIdle()
|
|
||||||
second.complete(true)
|
|
||||||
advanceUntilIdle()
|
|
||||||
first.complete(true)
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertEquals("http://b", requested)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun cancellingTheOwningScopeDropsTheResult() =
|
|
||||||
runTest {
|
|
||||||
val scope = CoroutineScope(StandardTestDispatcher(testScheduler))
|
|
||||||
val pending = CompletableDeferred<Boolean>()
|
|
||||||
val gate =
|
|
||||||
LocalNetworkGate(
|
|
||||||
scope = scope,
|
|
||||||
requiresPermission = { pending.await() },
|
|
||||||
wasDenied = { false },
|
|
||||||
requestPermission = { _, onGranted, _ -> onGranted() },
|
|
||||||
clearPrompt = {},
|
|
||||||
)
|
|
||||||
var ran = false
|
|
||||||
gate.run("http://10.0.0.5", onGranted = { ran = true })
|
|
||||||
advanceUntilIdle()
|
|
||||||
scope.cancel()
|
|
||||||
pending.complete(true)
|
|
||||||
advanceUntilIdle()
|
|
||||||
assertFalse(ran)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun TestScope.gate(
|
|
||||||
requires: suspend (String) -> Boolean,
|
|
||||||
denied: (String) -> Boolean = { false },
|
|
||||||
request: (String, () -> Unit, () -> Unit) -> Unit = { _, onGranted, _ -> onGranted() },
|
|
||||||
clear: () -> Unit = {},
|
|
||||||
) = LocalNetworkGate(
|
|
||||||
scope = this,
|
|
||||||
requiresPermission = requires,
|
|
||||||
wasDenied = denied,
|
|
||||||
requestPermission = request,
|
|
||||||
clearPrompt = clear,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user