Cache DNS answers and paint saved people before launch revalidation
Some checks failed
review/security-claude BLOCK: DnsConnectionRetry crashes app on Jellyfin WebSocket (NoSuchElementException)

This commit is contained in:
justinzeus 2026-11-07 00:09:57 +01:00
parent f4fb6e22c9
commit 327f631f0d
18 changed files with 763 additions and 44 deletions

View file

@ -32,6 +32,7 @@ import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import com.github.damontecres.wholphin.data.ServerRepository
import com.github.damontecres.wholphin.data.RestoredSession
import com.github.damontecres.wholphin.preferences.AppPreferences
import com.github.damontecres.wholphin.preferences.PlayerBackend
import com.github.damontecres.wholphin.services.AppUpgradeHandler
@ -576,12 +577,22 @@ class MainActivityViewModel
val restoredSession =
if (signInAutomatically) {
Timber.v("Sign in automatically")
serverRepository.restoreLastSession()
serverRepository.restoreSavedSession()
} else {
serverRepository.getMostRecentServer()
}
Timber.d("Restore last session result=%s", restoredSession)
setupNavigationManager.navigateTo(restoredSession.destination)
if (signInAutomatically && restoredSession is RestoredSession.Success) {
viewModelScope.launchDefault {
try {
serverRepository.revalidateSession(restoredSession.currentUser)
} catch (exception: Exception) {
if (exception is kotlinx.coroutines.CancellationException) throw exception
Timber.w(exception, "Saved launch session revalidation failed")
}
}
}
}
}
}

View file

@ -17,6 +17,7 @@ import org.acra.ktx.initAcra
import org.jellyfin.sdk.Jellyfin
import org.jellyfin.sdk.model.ServerVersion
import timber.log.Timber
import org.justinvisser.wolfskin.tv.NetworkStartup
import javax.inject.Inject
@OptIn(ExperimentalComposeRuntimeApi::class)
@ -54,6 +55,7 @@ class WholphinApplication :
override fun onCreate() {
super.onCreate()
networkStartup.start()
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy
@ -110,6 +112,9 @@ class WholphinApplication :
@Inject
lateinit var workerFactory: HiltWorkerFactory
@Inject
lateinit var networkStartup: NetworkStartup
override val workManagerConfiguration: Configuration
get() =
Configuration

View file

@ -8,6 +8,8 @@ import com.github.damontecres.wholphin.services.hilt.IoDispatcher
import com.github.damontecres.wholphin.util.WholphinDispatchers
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
@ -101,15 +103,7 @@ class ServerRepository
}
Timber.v("Changing user to ${user.name} on ${server.url}")
apiClient.update(baseUrl = server.url, accessToken = user.accessToken)
val userDto by apiClient.userApi.getCurrentUser()
val updatedServer =
try {
val sysInfo by apiClient.systemApi.getPublicSystemInfo()
server.copy(name = sysInfo.serverName, version = sysInfo.version)
} catch (ex: Exception) {
Timber.w(ex, "Exception fetching public system info")
server
}
val (updatedServer, userDto) = readSession(server)
var updatedUser =
user.copy(
id = userDto.id,
@ -125,6 +119,44 @@ class ServerRepository
return@withContext currentUser
}
/** Restore only an unprotected saved login; the launch picker must not wait for the network. */
suspend fun restoreSavedSession(): RestoredSession = withContext(ioDispatcher) {
val recent = mostRecentServerProvider.get()
if (recent !is MostRecentServer.ServerAndUser) return@withContext getMostRecentServerInternal(recent)
val saved = serverDao.getServer(recent.serverId) ?: return@withContext RestoredSession.None
val user = saved.users.firstOrNull { it.id == recent.userId }
if (user == null || user.isProtected) return@withContext RestoredSession.ServerOnly(saved.server)
apiClient.update(baseUrl = saved.server.url, accessToken = user.accessToken)
val current = CurrentUser(saved.server, user)
_currentUserDto.value = null
_current.value = current
RestoredSession.Success(current)
}
/** A late launch refresh must never replace a person selected while it was in flight. */
suspend fun revalidateSession(expected: CurrentUser) = withContext(ioDispatcher) {
val (server, userDto) = readSession(expected.server)
if (_current.value !== expected || userDto.id != expected.user.id) return@withContext
serverDao.addOrUpdateServer(server)
val user = serverDao.addOrUpdateUser(expected.user.copy(name = userDto.name))
if (_current.compareAndSet(expected, CurrentUser(server, user))) updateUserDto(userDto)
}
private suspend fun readSession(server: JellyfinServer): Pair<JellyfinServer, UserDto> = coroutineScope {
val system = async {
try {
val info by apiClient.systemApi.getPublicSystemInfo()
server.copy(name = info.serverName, version = info.version)
} catch (exception: Exception) {
if (exception is kotlinx.coroutines.CancellationException) throw exception
Timber.w(exception, "Exception fetching public system info")
server
}
}
val user by apiClient.userApi.getCurrentUser()
system.await() to user
}
/**
* Try to restore the most recent session
*

View file

@ -26,6 +26,9 @@ import org.jellyfin.sdk.api.okhttp.OkHttpFactory
import org.jellyfin.sdk.createJellyfin
import org.jellyfin.sdk.model.ClientInfo
import org.jellyfin.sdk.model.DeviceInfo
import org.justinvisser.wolfskin.conductarr.PersistentDns
import org.justinvisser.wolfskin.conductarr.DnsConnectionRetry
import java.io.File
import javax.inject.Qualifier
import javax.inject.Singleton
@ -91,12 +94,14 @@ object AppModule {
@StandardOkHttpClient
@Provides
@Singleton
fun okHttpClient() =
OkHttpClient
.Builder()
.apply {
// TODO user agent, timeouts, logging, etc
}.build()
fun okHttpClient(dns: PersistentDns) =
DnsConnectionRetry.configure(OkHttpClient.Builder(), dns).build()
/** Resolve filesDir lazily: Android may create it and lookup always runs off main. */
@Provides
@Singleton
fun dns(@ApplicationContext context: Context): PersistentDns =
PersistentDns(file = { File(context.filesDir, "wolfskin-dns.json") })
@AuthOkHttpClient
@Provides

View file

@ -4,6 +4,11 @@ import android.content.Context
import com.github.damontecres.wholphin.data.MostRecentServer
import com.github.damontecres.wholphin.services.hilt.AppModule
import com.github.damontecres.wholphin.services.hilt.DeviceModule
import com.github.damontecres.wholphin.services.hilt.StandardOkHttpClient
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import com.google.auto.service.AutoService
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
@ -73,10 +78,7 @@ class CrashReportSender : ReportSender {
private fun MostRecentServer.createApi(context: Context): ApiClient? =
(this as? MostRecentServer.ServerAndUser)?.let {
val okHttpClient =
OkHttpClient
.Builder()
.build()
val okHttpClient = EntryPointAccessors.fromApplication(context.applicationContext, CrashNetwork::class.java).client()
val okHttpFactory = OkHttpFactory(okHttpClient)
val api =
createJellyfin {
@ -89,3 +91,11 @@ private fun MostRecentServer.createApi(context: Context): ApiClient? =
}.createApi(baseUrl = serverUrl, accessToken = accessToken)
api
}
/** Crash reporting shares the application's DNS hints without borrowing authenticated headers. */
@EntryPoint
@InstallIn(SingletonComponent::class)
interface CrashNetwork {
@StandardOkHttpClient
fun client(): OkHttpClient
}