Skip to content
Open
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
2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
<!-- Android 17+: required to reach self-hosted servers (Navidrome, Jellyfin) and cast devices on the LAN. -->
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
Expand Down
28 changes: 28 additions & 0 deletions app/src/main/java/com/theveloper/pixelplay/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import com.theveloper.pixelplay.data.github.GitHubAnnouncementPropertiesService
import com.theveloper.pixelplay.data.github.PlayStoreAnnouncementRemoteConfig
import com.theveloper.pixelplay.data.jellyfin.JellyfinRepository
import com.theveloper.pixelplay.data.navidrome.NavidromeRepository
import com.theveloper.pixelplay.data.preferences.AppThemeMode
import com.theveloper.pixelplay.data.preferences.NavBarStyle
import com.theveloper.pixelplay.data.preferences.sanitizeNavBarCornerRadius
Expand All @@ -127,6 +129,7 @@ import com.theveloper.pixelplay.presentation.components.PlayStoreAnnouncementDia
import com.theveloper.pixelplay.presentation.components.PlayStoreAnnouncementUiModel
import com.theveloper.pixelplay.presentation.components.UnifiedPlayerSheetV2
import com.theveloper.pixelplay.presentation.components.calculatePlayerSheetCollapsedTargetY
import com.theveloper.pixelplay.presentation.components.rememberLocalNetworkPermissionGate
import com.theveloper.pixelplay.presentation.components.resolveNavBarOccupiedHeight
import com.theveloper.pixelplay.presentation.components.resolveNavBarSurfaceHeight
import com.theveloper.pixelplay.presentation.components.sanitizeNavigationBarBottomInset
Expand All @@ -139,11 +142,14 @@ import com.theveloper.pixelplay.ui.theme.PixelPlayTheme
import com.theveloper.pixelplay.ui.theme.LocalShowScrollbar
import com.theveloper.pixelplay.utils.CrashHandler
import com.theveloper.pixelplay.utils.AppLocaleManager
import com.theveloper.pixelplay.utils.LocalNetworkAccess
import com.theveloper.pixelplay.utils.LogUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.math.roundToInt

Expand Down Expand Up @@ -185,6 +191,10 @@ class MainActivity : ComponentActivity() {
lateinit var themePreferencesRepository: ThemePreferencesRepository
@Inject
lateinit var syncManager: SyncManager
@Inject
lateinit var navidromeRepository: dagger.Lazy<NavidromeRepository>
@Inject
lateinit var jellyfinRepository: dagger.Lazy<JellyfinRepository>
// For handling shortcut navigation - using StateFlow so composables can observe changes
private val _pendingPlaylistNavigation = kotlinx.coroutines.flow.MutableStateFlow<String?>(null)
private val _pendingShuffleAll = kotlinx.coroutines.flow.MutableStateFlow(false)
Expand Down Expand Up @@ -280,6 +290,19 @@ class MainActivity : ComponentActivity() {
}
}

// Android 17+: servers configured before the app requested ACCESS_LOCAL_NETWORK
// (or after the user revoked it) silently time out. Ask once the app is usable.
val localNetworkGate = rememberLocalNetworkPermissionGate()
LaunchedEffect(showSetupScreen) {
if (showSetupScreen == false && LocalNetworkAccess.isPermissionRequired) {
val lanServerUrl = withContext(Dispatchers.IO) { savedSelfHostedServerUrls() }
.firstOrNull { LocalNetworkAccess.needsPermissionFor(this@MainActivity, it) }
if (lanServerUrl != null) {
localNetworkGate.ensureAccess(lanServerUrl) { }
}
}
}

// Check for crash log when app starts
LaunchedEffect(Unit) {
if (!isBenchmarkMode && CrashHandler.hasCrashLog()) {
Expand Down Expand Up @@ -359,6 +382,11 @@ class MainActivity : ComponentActivity() {
handleIntent(intent)
}

private fun savedSelfHostedServerUrls(): List<String> = listOfNotNull(
navidromeRepository.get().let { repo -> repo.serverUrl.takeIf { repo.isLoggedIn } },
jellyfinRepository.get().let { repo -> repo.serverUrl.takeIf { repo.isLoggedIn } }
)

private fun handleIntent(intent: Intent?) {
if (intent == null) return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Velocity
import com.theveloper.pixelplay.utils.LocalNetworkAccess
import com.theveloper.pixelplay.utils.shapes.RoundedStarShape
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
Expand Down Expand Up @@ -191,6 +192,10 @@ fun CastBottomSheet(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
add(Manifest.permission.NEARBY_WIFI_DEVICES)
}
if (LocalNetworkAccess.isPermissionRequired) {
// Android 17+: cast discovery and the local media server need LAN access.
add(LocalNetworkAccess.PERMISSION)
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
add(Manifest.permission.ACCESS_FINE_LOCATION)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.theveloper.pixelplay.presentation.components

import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import com.theveloper.pixelplay.utils.LocalNetworkAccess
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
* Asks for [LocalNetworkAccess.PERMISSION] right before the app talks to a server on the local
* network, so self-hosted servers keep working on Android 17+.
*/
class LocalNetworkPermissionGate internal constructor(
private val context: Context,
private val scope: CoroutineScope,
private val requestPermission: (onResult: (Boolean) -> Unit) -> Unit
) {
/**
* Calls [onResult] with `true` when [serverUrl] can be reached: it is not on the local
* network, the permission is not needed on this device, or the user granted it.
*/
fun ensureAccess(serverUrl: String?, onResult: (granted: Boolean) -> Unit) {
scope.launch {
if (LocalNetworkAccess.needsPermissionFor(context, serverUrl)) {
requestPermission(onResult)
} else {
onResult(true)
}
}
}
}

@Composable
fun rememberLocalNetworkPermissionGate(): LocalNetworkPermissionGate {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val pendingResult = remember { arrayOfNulls<(Boolean) -> Unit>(1) }
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
pendingResult[0]?.invoke(granted)
pendingResult[0] = null
}
return remember(context, scope, launcher) {
LocalNetworkPermissionGate(context, scope) { onResult ->
pendingResult[0] = onResult
launcher.launch(LocalNetworkAccess.PERMISSION)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import androidx.compose.runtime.LaunchedEffect
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 androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -73,9 +74,11 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.theveloper.pixelplay.R
import com.theveloper.pixelplay.presentation.components.rememberLocalNetworkPermissionGate
import com.theveloper.pixelplay.ui.theme.GoogleSansRounded
import com.theveloper.pixelplay.ui.theme.PixelPlayTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import racra.compose.smooth_corner_rect_library.AbsoluteSmoothCornerShape

@AndroidEntryPoint
Expand All @@ -102,12 +105,30 @@ fun JellyfinLoginScreen(
val loginState by viewModel.state.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
val focusManager = LocalFocusManager.current
val coroutineScope = rememberCoroutineScope()
val localNetworkGate = rememberLocalNetworkPermissionGate()

var serverUrl by remember { mutableStateOf("") }
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var passwordVisible by remember { mutableStateOf(false) }

// Android 17+ blocks LAN traffic without ACCESS_LOCAL_NETWORK: ask for it before connecting
// to a self-hosted server instead of letting the request time out.
fun submitLogin() {
localNetworkGate.ensureAccess(serverUrl) { granted ->
if (granted) {
viewModel.login(serverUrl, username, password)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar(
context.getString(R.string.auth_local_network_permission_denied)
)
}
}
}
}

LaunchedEffect(loginState) {
when (val state = loginState) {
is JellyfinLoginState.Success -> {
Expand Down Expand Up @@ -323,7 +344,7 @@ fun JellyfinLoginScreen(
onDone = {
focusManager.clearFocus()
if (serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank()) {
viewModel.login(serverUrl, username, password)
submitLogin()
}
}
),
Expand Down Expand Up @@ -370,7 +391,7 @@ fun JellyfinLoginScreen(
Button(
onClick = {
focusManager.clearFocus()
viewModel.login(serverUrl, username, password)
submitLogin()
},
enabled = !isLoading && serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank(),
shape = AbsoluteSmoothCornerShape(18.dp, 60),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import androidx.compose.runtime.LaunchedEffect
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 androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -73,9 +74,11 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import com.theveloper.pixelplay.R
import com.theveloper.pixelplay.presentation.components.rememberLocalNetworkPermissionGate
import com.theveloper.pixelplay.ui.theme.GoogleSansRounded
import com.theveloper.pixelplay.ui.theme.PixelPlayTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import racra.compose.smooth_corner_rect_library.AbsoluteSmoothCornerShape

@AndroidEntryPoint
Expand All @@ -102,12 +105,30 @@ fun NavidromeLoginScreen(
val loginState by viewModel.state.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
val focusManager = LocalFocusManager.current
val coroutineScope = rememberCoroutineScope()
val localNetworkGate = rememberLocalNetworkPermissionGate()

var serverUrl by remember { mutableStateOf("") }
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var passwordVisible by remember { mutableStateOf(false) }

// Android 17+ blocks LAN traffic without ACCESS_LOCAL_NETWORK: ask for it before connecting
// to a self-hosted server instead of letting the request time out.
fun submitLogin() {
localNetworkGate.ensureAccess(serverUrl) { granted ->
if (granted) {
viewModel.login(serverUrl, username, password)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar(
context.getString(R.string.auth_local_network_permission_denied)
)
}
}
}
}

LaunchedEffect(loginState) {
when (val state = loginState) {
is NavidromeLoginState.Success -> {
Expand Down Expand Up @@ -344,7 +365,7 @@ fun NavidromeLoginScreen(
onDone = {
focusManager.clearFocus()
if (serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank()) {
viewModel.login(serverUrl, username, password)
submitLogin()
}
}
),
Expand Down Expand Up @@ -391,7 +412,7 @@ fun NavidromeLoginScreen(
Button(
onClick = {
focusManager.clearFocus()
viewModel.login(serverUrl, username, password)
submitLogin()
},
enabled = !isLoading && serverUrl.isNotBlank() && username.isNotBlank() && password.isNotBlank(),
shape = AbsoluteSmoothCornerShape(18.dp, 60),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.theveloper.pixelplay.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.Inet6Address
import java.net.InetAddress
import java.net.URI

/**
* Android 17 (API 37) blocks traffic to the local network for apps targeting SDK 37 unless they
* hold the runtime permission [Manifest.permission.ACCESS_LOCAL_NETWORK] (NEARBY_DEVICES group).
* Without it, connections to a LAN server simply time out.
*
* See https://developer.android.com/privacy-and-security/local-network-permission
*/
object LocalNetworkAccess {

const val PERMISSION = Manifest.permission.ACCESS_LOCAL_NETWORK

val isPermissionRequired: Boolean
get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN

fun isGranted(context: Context): Boolean =
!isPermissionRequired ||
ContextCompat.checkSelfPermission(context, PERMISSION) == PackageManager.PERMISSION_GRANTED

/**
* True when the permission is required on this device, not granted yet, and [serverUrl]
* points to the local network.
*/
suspend fun needsPermissionFor(context: Context, serverUrl: String?): Boolean =
!isGranted(context) && isLocalNetworkUrl(serverUrl)

/**
* Whether [url] targets the local network: a private, link-local or unique-local address, a
* `.local` (mDNS) host, or a host name that resolves to one of those. Loopback is not local
* network traffic and is ignored. Resolution failures are treated as "not local".
*/
suspend fun isLocalNetworkUrl(url: String?): Boolean {
val host = extractHost(url) ?: return false
if (host.endsWith(".local", ignoreCase = true)) return true
return withContext(Dispatchers.IO) {
runCatching { InetAddress.getAllByName(host).any(::isLocalNetworkAddress) }
.getOrDefault(false)
}
}

internal fun extractHost(url: String?): String? {
val trimmed = url?.trim().orEmpty()
if (trimmed.isEmpty()) return null
val withScheme = if ("://" in trimmed) trimmed else "http://$trimmed"
return runCatching { URI(withScheme).host }
.getOrNull()
?.removeSurrounding("[", "]")
?.takeIf { it.isNotBlank() }
}

internal fun isLocalNetworkAddress(address: InetAddress): Boolean {
if (address.isLoopbackAddress || address.isAnyLocalAddress) return false
if (address.isSiteLocalAddress || address.isLinkLocalAddress) return true
// IPv6 unique local addresses (fc00::/7) are not covered by isSiteLocalAddress.
return address is Inet6Address && (address.address[0].toInt() and 0xFE) == 0xFC
}
}
1 change: 1 addition & 0 deletions app/src/main/res/values-es/strings_cloud_services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
<string name="auth_username_label">Usuario</string>
<string name="auth_username_placeholder">admin</string>
<string name="auth_welcome_toast">¡Bienvenido, %1$s!</string>
<string name="auth_local_network_permission_denied">Permite el acceso a «Dispositivos cercanos» para conectar con un servidor de tu red local</string>

<!-- Subsonic / Navidrome Auth -->
<string name="auth_navidrome_footer_msg">Compatible con Navidrome, Gonic, Airsonic y otros servidores Subsonic</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings_cloud_services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
<string name="auth_username_label">Username</string>
<string name="auth_username_placeholder">admin</string>
<string name="auth_welcome_toast">Welcome, %1$s!</string>
<string name="auth_local_network_permission_denied">Allow “Nearby devices” access to connect to a server on your local network</string>

<!-- Subsonic / Navidrome Auth -->
<string name="auth_navidrome_footer_msg">Compatible with Navidrome, Gonic, Airsonic, and other Subsonic-compatible servers</string>
Expand Down
Loading