Skip to content
Closed
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
26 changes: 23 additions & 3 deletions app/smartphone/src/main/java/com/m3u/smartphone/ui/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import com.m3u.data.repository.tv.ConnectionToTvValue
import com.m3u.data.repository.tv.TvRepository
import com.m3u.data.tv.model.RemoteDirection
import com.m3u.data.tv.model.TvInfo
import com.m3u.data.worker.ChannelDetailsWorker
import com.m3u.data.worker.SubscriptionWorker
import com.m3u.smartphone.ui.common.connect.RemoteControlSheetValue
import dagger.hilt.android.lifecycle.HiltViewModel
Expand Down Expand Up @@ -79,10 +80,11 @@ class AppViewModel @Inject constructor(
)
.flow
.map { data ->
data.pagingMap { channel ->
data.pagingMap { result ->
ChannelWithProgramme(
channel = channel,
programme = null
channel = result.channel,
programme = null,
matchedCast = result.matchedCast,
)
}
}
Expand Down Expand Up @@ -114,6 +116,23 @@ class AppViewModel @Inject constructor(
}
}.cachedIn(viewModelScope)

/**
* Resumes collecting channel descriptions on every start.
*
* Cheap to call: the worker asks for channels that still have no
* description and finishes at once when there are none, and KEEP means an
* ongoing sweep is never restarted. Hooked here rather than only after a
* subscription so a catalogue that was interrupted — a few tens of
* thousands of titles are not collected in one sitting — carries on by
* itself, without asking anyone to re-subscribe.
*/
private fun collectChannelDetails() {
viewModelScope.launch {
runCatching { ChannelDetailsWorker.enqueue(workManager) }
.onFailure { throwable -> timber.w(throwable, "details sweep not scheduled") }
}
}

private fun refreshProgrammes() {
viewModelScope.launch {
val playlists = playlistRepository.getAllAutoRefresh()
Expand All @@ -136,6 +155,7 @@ class AppViewModel @Inject constructor(

init {
refreshProgrammes()
collectChannelDetails()
tvRepository.connected
.onEach {
timber.d("connected tv changed: $it")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ internal fun ChannelGallery(
ChannelItem(
channel = channel,
programme = channelWithProgramme.programme,
matchedCast = channelWithProgramme.matchedCast,
cover = loadedUrl,
recently = recently,
zapping = zapping == channel,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ internal fun ChannelItem(
onClick: () -> Unit,
onLongClick: () -> Unit,
programme: Programme?,
/** Cast list when an actor, not the title, is why this row matched. */
matchedCast: String? = null,
modifier: Modifier = Modifier,
isVodOrSeriesPlaylist: Boolean = true
) {
Expand Down Expand Up @@ -189,6 +191,18 @@ internal fun ChannelItem(
},
supportingContent = {
when {
// Comes first: on a search for an actor, the title
// alone gives no clue why the row is in the list.
matchedCast != null -> {
Text(
text = matchedCast,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}

recently -> {
Text(
text = remember(channel.seen) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package com.m3u.smartphone.ui.material.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Star
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.m3u.data.database.model.Channel
import com.m3u.data.database.model.ChannelDetails
import com.m3u.i18n.R.string
import com.m3u.smartphone.ui.material.model.LocalSpacing

/**
* Synopsis, cast and rating for the channel a sheet was opened on.
*
* Shows nothing at all — not an error, not a placeholder — when the panel has
* no description to give. Live channels never have one, and a sheet opened to
* hide or favourite a channel should not be pushed around by an empty block.
*/
@Composable
fun ChannelDetailsSection(
channel: Channel?,
modifier: Modifier = Modifier,
) {
val viewModel: ChannelDetailsViewModel = hiltViewModel()
LaunchedEffect(channel?.id) { viewModel.load(channel) }
val state by viewModel.state.collectAsStateWithLifecycle()
val spacing = LocalSpacing.current

when (val current = state) {
ChannelDetailsState.Absent -> Unit

ChannelDetailsState.Loading -> {
if (channel == null) return
Text(
text = stringResource(string.ui_details_loading),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = modifier.padding(horizontal = spacing.medium),
)
}

is ChannelDetailsState.Content -> Column(
verticalArrangement = Arrangement.spacedBy(spacing.extraSmall),
modifier = modifier
.fillMaxWidth()
.padding(horizontal = spacing.medium),
) {
current.details.Headline()
current.details.cast?.let { cast ->
LabelledText(label = stringResource(string.ui_details_cast), value = cast)
}
current.details.director?.let { director ->
LabelledText(label = stringResource(string.ui_details_director), value = director)
}
current.details.plot?.let { plot ->
Text(
text = plot,
style = MaterialTheme.typography.bodyMedium,
// Long enough to be worth reading, short enough to leave
// the actions below reachable without scrolling.
maxLines = 6,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = spacing.extraSmall),
)
}
HorizontalDivider(modifier = Modifier.padding(top = spacing.small))
}
}
}

/** Year, genre and rating on one line — the things read at a glance. */
@Composable
private fun ChannelDetails.Headline() {
val spacing = LocalSpacing.current
val year = releaseDate?.take(4)?.takeIf { it.length == 4 && it.all(Char::isDigit) }
val summary = listOfNotNull(year, genre).joinToString(" · ")
if (summary.isBlank() && rating == null) return
Row(
horizontalArrangement = Arrangement.spacedBy(spacing.small),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
if (summary.isNotBlank()) {
Text(
text = summary,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
}
rating?.let { rating ->
Icon(
imageVector = Icons.Rounded.Star,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(16.dp),
)
Text(
text = rating,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}

@Composable
private fun LabelledText(label: String, value: String) {
Text(
text = "$label: $value",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.m3u.smartphone.ui.material.components

import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.m3u.data.database.model.Channel
import com.m3u.data.database.model.ChannelDetails
import com.m3u.data.repository.channel.ChannelDetailsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@Immutable
sealed interface ChannelDetailsState {
/** Nothing to show and nothing on its way — live channels, mostly. */
data object Absent : ChannelDetailsState

data object Loading : ChannelDetailsState

data class Content(val details: ChannelDetails) : ChannelDetailsState
}

/**
* Holds the description shown when a channel sheet opens.
*
* Cached values appear immediately; anything missing is fetched once, in the
* background, and lands through the database rather than being pushed here —
* so a sheet closed mid-request still keeps what it paid for.
*/
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class ChannelDetailsViewModel @Inject constructor(
private val repository: ChannelDetailsRepository,
) : ViewModel() {
private val channel = MutableStateFlow<Channel?>(null)
private var fetching: Job? = null

val state: StateFlow<ChannelDetailsState> = channel
.flatMapLatest { current ->
if (current == null) flowOf(null) else repository.observe(current)
}
.map { details ->
when {
details == null -> ChannelDetailsState.Loading
details.isEmpty -> ChannelDetailsState.Absent
else -> ChannelDetailsState.Content(details)
}
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ChannelDetailsState.Loading)

fun load(channel: Channel?) {
if (this.channel.value?.id == channel?.id) return
this.channel.value = channel
fetching?.cancel()
channel ?: return
fetching = viewModelScope.launch { repository.fetchIfMissing(channel) }
}
}

/**
* A row the panel answered for but had nothing to say about. Kept in the
* database so it is not asked again, shown as nothing at all.
*/
private val ChannelDetails.isEmpty: Boolean
get() = plot.isNullOrBlank() &&
cast.isNullOrBlank() &&
director.isNullOrBlank() &&
genre.isNullOrBlank() &&
rating.isNullOrBlank() &&
releaseDate.isNullOrBlank()
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ fun MediaSheet(
verticalArrangement = Arrangement.spacedBy(spacing.small),
modifier = Modifier.padding(spacing.medium)
) {
// Above the actions, so the description is what a long press
// shows first. Renders nothing when the channel has none.
ChannelDetailsSection(
channel = when (value) {
is MediaSheetValue.PlaylistScreen -> value.channel
is MediaSheetValue.FavoriteScreen -> value.channel
is MediaSheetValue.ForyouScreen -> null
}
)
when (value) {
is MediaSheetValue.ForyouScreen -> {
value.playlist?.let { playlist ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ import kotlin.time.Duration.Companion.seconds
data class ChannelWithProgramme(
val channel: Channel,
val programme: Programme?,
/**
* Set only on search results a cast list matched rather than the title,
* so the row can say why it is there. Null everywhere else.
*/
val matchedCast: String? = null,
)

@HiltViewModel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package com.m3u.core.foundation.util.basic

import androidx.compose.ui.text.capitalize
import androidx.compose.ui.text.intl.Locale
import java.text.Normalizer
import java.util.Locale as JavaLocale

fun String.title(): String {
if (this.isEmpty()) return this
Expand All @@ -20,4 +22,28 @@ fun String.startsWithAny(vararg prefix: String, ignoreCase: Boolean = false): Bo
fun String.startWithHttpScheme(): Boolean = startsWithAny(
"http://", "https://",
ignoreCase = true
)
)

/**
* Folds a string down to the form search compares against: no diacritics, no
* case.
*
* SQLite's LIKE ignores case for ASCII but never accents, so "prenom" cannot
* match "Le Prénom" however the query is written — and a catalogue in French
* has a lot of those. Titles are stored pre-folded in a dedicated column and
* the query is folded the same way, which keeps the comparison symmetric: with
* or without accents, either side matches.
*
* NFD splits an accented letter into its base letter plus a combining mark, so
* dropping the marks (Unicode category Mn) leaves the base letter behind.
* Scripts without combining marks — CJK among them — pass through untouched.
*
* Locale.ROOT on purpose: a Turkish locale lowercases 'I' to a dotless 'ı',
* which would quietly make titles unsearchable for those users.
*/
fun String.normalizeForSearch(): String = Normalizer
.normalize(this, Normalizer.Form.NFD)
.replace(COMBINING_MARKS, "")
.lowercase(JavaLocale.ROOT)

private val COMBINING_MARKS = Regex("\\p{Mn}+")
Loading