Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package com.github.damontecres.wholphin.services

import com.github.damontecres.wholphin.data.model.BaseItem
import kotlinx.coroutines.delay
import org.jellyfin.sdk.api.client.ApiClient
import org.jellyfin.sdk.api.client.exception.TimeoutException
import org.jellyfin.sdk.api.client.extensions.mediaInfoApi
import org.jellyfin.sdk.api.client.extensions.userLibraryApi
import org.jellyfin.sdk.model.api.PlaybackInfoDto
import timber.log.Timber
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds

/**
* Resolves .strm files to populate the tracks & metadata
*/
@Singleton
class StrmFileHandler
@Inject
constructor(
private val api: ApiClient,
) {
/**
* Attempts to resolve a strm file is not yet resolved. This will attempt to resolve every media source.
*
* If the item is not a strm file, nothing happens
*
* @return the resolved item or null if could not be resolved
*/
suspend fun resolveStrmOrNull(item: BaseItem): BaseItem? {
if (shouldResolveStrm(item)) {
Timber.d("Resolving strm %s", item.id)
// Resolve the file as a while
resolve(item.id, null)
val resolvedItem = waitForUpdate(item.id) { shouldResolveStrm(it) }
// Resolve each media source that is unresolved
resolvedItem.data.mediaSources
.orEmpty()
.filter { it.mediaStreams.isNullOrEmpty() }
.forEach {
resolve(item.id, it.id)
}
return waitForUpdate(item.id) { shouldResolveStrm(it) }
}
return null
}

/**
* Attempts to resolve a specific media source in the strm file if is not yet resolved.
*
* If the item is not a strm file, nothing happens
*
* @return the resolved item or null if could not be resolved
*/
suspend fun resolveStrmOrNull(
item: BaseItem,
sourceId: String,
): BaseItem? {
if (shouldResolveStrm(item, sourceId)) {
Timber.d("Resolving strm %s", item.id)
resolve(item.id, sourceId)
return waitForUpdate(item.id) { shouldResolveStrm(it, sourceId) }
}
return null
}

/**
* Attempts to resolve a specific media source in the strm file if is not yet resolved.
*
* If the item is not a strm file, nothing happens
*
* @return the resolved item or the original item if does not need to be resolved
*/
suspend fun resolveStrm(item: BaseItem): BaseItem = resolveStrmOrNull(item) ?: item

private suspend fun resolve(
itemId: UUID,
mediaSourceId: String?,
) {
val response by
api.mediaInfoApi
.getPostedPlaybackInfo(
itemId,
PlaybackInfoDto(
deviceProfile = null,
mediaSourceId = mediaSourceId,
autoOpenLiveStream = false,
),
)
if (response.errorCode != null) {
throw IllegalStateException("Error: " + response.errorCode)
}
}

private suspend fun waitForUpdate(
itemId: UUID,
valid: (BaseItem) -> Boolean,
): BaseItem {
var count = 5
while (count > 0) {
Timber.v("Checking for streams in %s", itemId)
val fetchedItem =
api.userLibraryApi
.getItem(itemId)
.content
.let { BaseItem(it) }
if (!valid(fetchedItem)) {
Timber.d("Got updated streams for %s", itemId)
return fetchedItem
}
delay(2.seconds)
count--
}
Timber.w("Resolve timed out for %s", itemId)
throw TimeoutException("Resolve timed out for $itemId")
}

companion object {
fun isStrmFile(item: BaseItem): Boolean = item.data.path?.endsWith(".strm") == true

fun shouldResolveStrm(item: BaseItem): Boolean {
if (!isStrmFile(item)) {
return false
}
return item.data.mediaSources
.orEmpty()
.any { it.mediaStreams.isNullOrEmpty() }
}

fun shouldResolveStrm(
item: BaseItem,
sourceId: String,
): Boolean {
if (!isStrmFile(item)) {
return false
}
val source =
sourceId?.let { item.data.mediaSources?.firstOrNull { it.id == sourceId } }
?: item.data.mediaSources?.firstOrNull()
val streams = source?.mediaStreams
return streams.isNullOrEmpty()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package com.github.damontecres.wholphin.ui.components

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
Expand Down Expand Up @@ -102,3 +104,19 @@ fun DelayedLoadingPage(
}
}
}

@Composable
fun BoxScope.CornerLoadingIndicator(
showClock: Boolean,
modifier: Modifier = Modifier,
) {
Box(
modifier =
modifier
.padding(top = if (showClock) 40.dp else 20.dp, start = 20.dp)
.size(48.dp)
.align(Alignment.TopEnd),
) {
CircularProgress(Modifier.fillMaxSize())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ fun ExpandablePlayButtons(
firstFocus.tryRequestFocus()
}
}
val hasStreams =
remember(chooseVersionParams) {
chooseVersionParams?.chosenStreams?.source.let {
it == null || !it.mediaStreams.isNullOrEmpty()
}
}

var chooseVersion by remember { mutableStateOf<DialogParams?>(null) }

Expand All @@ -117,6 +123,7 @@ fun ExpandablePlayButtons(
resume = resumePosition,
icon = Icons.Default.PlayArrow,
onClick = playOnClick,
enabled = hasStreams,
modifier =
Modifier
.onFocusChanged(buttonOnFocusChanged)
Expand All @@ -130,6 +137,7 @@ fun ExpandablePlayButtons(
resume = Duration.ZERO,
icon = Icons.Default.Refresh,
onClick = playOnClick,
enabled = hasStreams,
modifier = Modifier.onFocusChanged(buttonOnFocusChanged),
mirrorIcon = true,
interactionSource = restartInteractionSource,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.github.damontecres.wholphin.ui.RequestOrRestoreFocus
import com.github.damontecres.wholphin.ui.components.ContextMenu
import com.github.damontecres.wholphin.ui.components.ContextMenuActions
import com.github.damontecres.wholphin.ui.components.ContextMenuDialog
import com.github.damontecres.wholphin.ui.components.CornerLoadingIndicator
import com.github.damontecres.wholphin.ui.components.ErrorMessage
import com.github.damontecres.wholphin.ui.components.ExpandablePlayButtons
import com.github.damontecres.wholphin.ui.components.HeaderUtils
Expand Down Expand Up @@ -171,6 +172,7 @@ fun EpisodeDetails(
canDelete = canDelete,
onConfirmDelete = { viewModel.deleteItem(ep) },
onChooseVersion = { contextActions.onChooseVersion.invoke(ep, it) },
strmLoading = state.strmLoading,
modifier = modifier,
)
}
Expand Down Expand Up @@ -228,6 +230,7 @@ fun EpisodeDetailsContent(
canDelete: Boolean,
onConfirmDelete: () -> Unit,
onChooseVersion: (MediaSourceInfo) -> Unit,
strmLoading: Boolean,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
Expand Down Expand Up @@ -305,5 +308,8 @@ fun EpisodeDetailsContent(
}
}
}
if (strmLoading) {
CornerLoadingIndicator(preferences.appPreferences.interfacePreferences.showClock)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import com.github.damontecres.wholphin.services.MediaManagementService
import com.github.damontecres.wholphin.services.NavigationManager
import com.github.damontecres.wholphin.services.ServerReportService
import com.github.damontecres.wholphin.services.StreamChoiceService
import com.github.damontecres.wholphin.services.StrmFileHandler
import com.github.damontecres.wholphin.services.ThemeSongPlayer
import com.github.damontecres.wholphin.services.UserPreferencesService
import com.github.damontecres.wholphin.services.deleteItem
Expand Down Expand Up @@ -58,6 +59,7 @@ class EpisodeViewModel
private val userPreferencesService: UserPreferencesService,
private val backdropService: BackdropService,
private val mediaManagementService: MediaManagementService,
private val strmFileHandler: StrmFileHandler,
@Assisted val itemId: UUID,
) : ViewModel() {
@AssistedFactory
Expand All @@ -71,7 +73,7 @@ class EpisodeViewModel
val canDelete = MutableStateFlow(false)

init {
init()
// init()
viewModelScope.launchDefault {
mediaManagementService.collectCanDelete(
state.map { (it.episode as? DataLoadingState.Success<BaseItem?>)?.data },
Expand Down Expand Up @@ -115,6 +117,33 @@ class EpisodeViewModel
)
}
backdropService.submit(item)
viewModelScope.launchIO {
try {
if (StrmFileHandler.shouldResolveStrm(item)) {
_state.update { it.copy(strmLoading = true) }
val result = strmFileHandler.resolveStrmOrNull(item)
if (result != null) {
Timber.d("Got updated item")
val chosenStreams =
itemPlaybackRepository.getSelectedTracks(
itemId,
result,
userPreferencesService.getCurrent(),
)
_state.update {
it.copy(
episode = DataLoadingState.Success(result),
chosenStreams = chosenStreams,
)
}
}
}
} catch (ex: Exception) {
Timber.e(ex, "Error checking strm file for %s", item.id)
} finally {
_state.update { it.copy(strmLoading = false) }
}
}
} catch (ex: CancellationException) {
throw ex
} catch (ex: Exception) {
Expand Down Expand Up @@ -216,4 +245,5 @@ class EpisodeViewModel
data class EpisodeState(
val episode: DataLoadingState<BaseItem> = DataLoadingState.Pending,
val chosenStreams: ChosenStreams? = null,
val strmLoading: Boolean = false,
)
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import com.github.damontecres.wholphin.ui.cards.SeasonCard
import com.github.damontecres.wholphin.ui.components.ContextMenu
import com.github.damontecres.wholphin.ui.components.ContextMenuActions
import com.github.damontecres.wholphin.ui.components.ContextMenuDialog
import com.github.damontecres.wholphin.ui.components.CornerLoadingIndicator
import com.github.damontecres.wholphin.ui.components.ErrorMessage
import com.github.damontecres.wholphin.ui.components.ExpandablePlayButtons
import com.github.damontecres.wholphin.ui.components.HeaderUtils
Expand Down Expand Up @@ -236,6 +237,7 @@ fun MovieDetails(
canDelete = state.canDelete,
onConfirmDelete = { state.movie?.let { viewModel.deleteItem(it) } },
onChooseVersion = { contextActions.onChooseVersion.invoke(movie, it) },
strmLoading = state.strmLoading,
modifier = modifier,
)
}
Expand Down Expand Up @@ -306,6 +308,7 @@ fun MovieDetailsContent(
canDelete: Boolean,
onConfirmDelete: () -> Unit,
onChooseVersion: (MediaSourceInfo) -> Unit,
strmLoading: Boolean,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
Expand Down Expand Up @@ -497,5 +500,8 @@ fun MovieDetailsContent(
}
}
}
if (strmLoading) {
CornerLoadingIndicator(preferences.appPreferences.interfacePreferences.showClock)
}
}
}
Loading
Loading