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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import androidx.compose.ui.text.buildAnnotatedString
import com.github.damontecres.wholphin.R
import com.github.damontecres.wholphin.WholphinApplication
import com.github.damontecres.wholphin.ui.abbreviateNumber
import com.github.damontecres.wholphin.ui.components.csfdInlineContentId
import com.github.damontecres.wholphin.ui.detail.CardGridItem
import com.github.damontecres.wholphin.ui.detail.music.artistsString
import com.github.damontecres.wholphin.ui.detail.series.SeasonEpisodeIds
Expand All @@ -34,6 +35,7 @@ import org.jellyfin.sdk.model.api.CollectionType
import org.jellyfin.sdk.model.extensions.ticks
import java.util.Locale
import java.util.UUID
import kotlin.math.roundToInt
import kotlin.time.Duration

/**
Expand Down Expand Up @@ -61,6 +63,9 @@ data class BaseItem(

val name get() = data.name

private val hasCsfdRating: Boolean
get() = data.providerIds?.any { it.key.equals("Csfd", ignoreCase = true) && !it.value.isNullOrBlank() } == true

val title get() = if (type == BaseItemKind.EPISODE) data.seriesName else name

val subtitle: String? by lazy {
Expand Down Expand Up @@ -238,12 +243,18 @@ data class BaseItem(
data.communityRating?.let {
buildAnnotatedString {
dot()
append(String.format(Locale.getDefault(), "%.1f", it))
appendInlineContent(id = "star")
if (hasCsfdRating) {
// The ČSFD plugin stores the ČSFD percentage / 10 as the community rating
appendInlineContent(id = csfdInlineContentId((it * 10).roundToInt()))
} else {
append(String.format(Locale.getDefault(), "%.1f", it))
appendInlineContent(id = "star")
}
}
},
// Only one rating is shown: ČSFD, else the community rating (IMDb/TMDb), else critics
criticRating =
data.criticRating?.let {
data.criticRating?.takeIf { data.communityRating == null }?.let {
buildAnnotatedString {
dot()
append("${it.toInt()}%")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ sealed interface HomeRowConfig {
override fun updateViewOptions(viewOptions: HomeRowViewOptions): Suggestions = this.copy(viewOptions = viewOptions)
}

/**
* ČSFD "TV tipy dňa" that exist in the user's library, best rated first.
* Needs the Jellyfin ČSFD plugin (endpoint `/Csfd/TvTips`).
*/
@Serializable
@SerialName("CsfdTvTips")
data class CsfdTvTips(
override val viewOptions: HomeRowViewOptions = HomeRowViewOptions.csfdTipsDefault,
) : HomeRowConfig {
override fun updateViewOptions(viewOptions: HomeRowViewOptions): CsfdTvTips = this.copy(viewOptions = viewOptions)
}

/**
* Fetch by parent ID such as a library, collection, or playlist with optional simple sorting
*/
Expand Down Expand Up @@ -233,6 +245,9 @@ data class HomeRowViewOptions(
aspectRatio = AspectRatio.WIDE,
)

/** Smaller cards than the other rows */
val csfdTipsDefault = HomeRowViewOptions(heightDp = Cards.HEIGHT_2X3_DP * 2 / 3)

val liveTvDefault =
HomeRowViewOptions(
heightDp = Cards.HEIGHT_LIVE_TV,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.github.damontecres.wholphin.services

import com.github.damontecres.wholphin.services.hilt.AuthOkHttpClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jellyfin.sdk.api.client.ApiClient
import timber.log.Timber
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

/**
* Gets the ČSFD "TV tipy dňa" from the Jellyfin ČSFD plugin (`/Csfd/TvTips`).
*
* The plugin already filters the tips to what is in the user's library, so the result is just item IDs, best rated first.
*/
@Singleton
class CsfdTvTipsService
@Inject
constructor(
private val api: ApiClient,
@param:AuthOkHttpClient private val okHttpClient: OkHttpClient,
) {
/**
* Returns the library item IDs of today's tips, or an empty list if the plugin is missing/unreachable
*/
suspend fun getItemIds(limit: Int): List<UUID> =
withContext(Dispatchers.IO) {
val baseUrl = api.baseUrl?.trimEnd('/') ?: return@withContext emptyList()
try {
val request = Request.Builder().url("$baseUrl/Csfd/TvTips?limit=$limit").build()
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
// 404 = plugin without TV tips support
Timber.w("ČSFD TV tips: HTTP %s", response.code)
return@withContext emptyList()
}
parseItemIds(response.body.string())
}
} catch (ex: Exception) {
Timber.w(ex, "ČSFD TV tips failed")
emptyList()
}
}

companion object {
fun parseItemIds(json: String): List<UUID> =
(Json.parseToJsonElement(json) as? JsonArray)
.orEmpty()
.mapNotNull { tip ->
// The server may emit PascalCase or camelCase
runCatching {
val obj = tip.jsonObject
UUID.fromString((obj["ItemId"] ?: obj["itemId"])!!.jsonPrimitive.content)
}.getOrNull()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ class HomeSettingsService
private val imageUrlService: ImageUrlService,
private val suggestionService: SuggestionService,
private val displayPreferencesService: DisplayPreferencesService,
private val csfdTvTipsService: CsfdTvTipsService,
) {
@OptIn(ExperimentalSerializationApi::class)
val jsonParser =
Expand Down Expand Up @@ -315,7 +316,15 @@ class HomeSettingsService
config = HomeRowConfig.ContinueWatchingCombined(),
),
)
val rowConfig = continueWatchingRow + includedIds
val csfdTipsRow =
listOf(
HomeRowConfigDisplay(
id = includedIds.size + 2,
title = ResStringProvider(R.string.csfd_tv_tips),
config = HomeRowConfig.CsfdTvTips(),
),
)
val rowConfig = csfdTipsRow + continueWatchingRow + includedIds
return HomePageResolvedSettings(userId, rowConfig)
}

Expand Down Expand Up @@ -552,6 +561,14 @@ class HomeSettingsService
)
}

is HomeRowConfig.CsfdTvTips -> {
HomeRowConfigDisplay(
id = id,
title = ResStringProvider(R.string.csfd_tv_tips),
config,
)
}

is HomeRowConfig.Suggestions -> {
val title = getItemName(R.string.suggestions_for, config.parentId)
HomeRowConfigDisplay(
Expand Down Expand Up @@ -1161,6 +1178,30 @@ class HomeSettingsService
}
}

is HomeRowConfig.CsfdTvTips -> {
val title = ResStringProvider(R.string.csfd_tv_tips)
val ids = csfdTvTipsService.getItemIds(limit.coerceAtMost(10))
val items =
if (ids.isEmpty()) {
listOf()
} else {
// The plugin returns best rated first; the server does not keep the order of `ids`
val byId =
GetItemsRequestHandler
.execute(
api,
GetItemsRequest(
userId = userDto.id,
ids = ids,
fields = HomeItemFields,
),
).toBaseItems(row.viewOptions.useSeries)
.associateBy { it.id }
ids.mapNotNull { byId[it] }
}
Success(title, items, row.viewOptions, rowType = row)
}

is HomeRowConfig.Suggestions -> {
val library =
api.userLibraryApi
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const val DEFAULT_PAGE_SIZE = 100
val DetailItemFields =
listOf(
ItemFields.OVERVIEW,
ItemFields.PROVIDER_IDS,
ItemFields.TRICKPLAY,
ItemFields.SORT_NAME,
ItemFields.CHAPTERS,
Expand All @@ -65,6 +66,7 @@ val DetailItemFields =
val SlimItemFields =
listOf(
ItemFields.OVERVIEW,
ItemFields.PROVIDER_IDS,
ItemFields.SORT_NAME,
ItemFields.MEDIA_SOURCE_COUNT,
ItemFields.CAN_DELETE,
Expand All @@ -78,6 +80,7 @@ val ItemRowFields = SlimItemFields + ItemFields.PRIMARY_IMAGE_ASPECT_RATIO
val HomeItemFields =
listOf(
ItemFields.OVERVIEW,
ItemFields.PROVIDER_IDS,
ItemFields.CAN_DELETE,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,22 @@ fun QuickDetailsText(
@Composable
fun rememberQuickDetailsContentMap(textStyle: TextStyle = MaterialTheme.typography.titleSmall) =
remember(textStyle) {
mapOf(
// One entry per possible ČSFD percentage, the id is built by csfdInlineContentId()
val csfd =
(0..100).associate { percent ->
csfdInlineContentId(percent) to
InlineTextContent(
Placeholder(
textStyle.fontSize * 3.2f,
textStyle.fontSize * 1.3f,
PlaceholderVerticalAlign.TextCenter,
),
) {
CsfdRating(percent, Modifier.fillMaxSize())
}
}
csfd +
mapOf(
"star" to
InlineTextContent(
Placeholder(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Icon
Expand Down Expand Up @@ -116,6 +117,46 @@ fun SimpleStarRating(
}
}

// ČSFD colours: red for 70%+, blue for 30-69%, dark grey ("odpad") below 30%
private val CsfdRed = Color(0xFFBA0305)
private val CsfdBlue = Color(0xFF658DB4)
private val CsfdGrey = Color(0xFF535353)

fun csfdColor(percent: Int): Color =
when {
percent >= 70 -> CsfdRed
percent >= 30 -> CsfdBlue
else -> CsfdGrey
}

fun csfdInlineContentId(percent: Int) = "csfd:${percent.coerceIn(0, 100)}"

/**
* ČSFD style rating: percentage in a rounded square coloured by the rating
*/
@Composable
fun CsfdRating(
percent: Int,
modifier: Modifier = Modifier,
) {
Box(
contentAlignment = Alignment.Center,
modifier =
modifier
.clip(RoundedCornerShape(4.dp))
.background(csfdColor(percent)),
) {
Text(
text = "$percent%",
color = Color.White,
fontWeight = FontWeight.Bold,
maxLines = 1,
fontSize = with(LocalDensity.current) { (LocalTextStyle.current.fontSize.toDp() * .8f).toSp() },
modifier = Modifier.padding(horizontal = 4.dp),
)
}
}

@Composable
fun TomatoRating(
rating: Float?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ fun HomeSettingsAddRow(
MetaRowType.CONTINUE_WATCHING,
MetaRowType.NEXT_UP,
MetaRowType.COMBINED_CONTINUE_WATCHING,
MetaRowType.CSFD_TV_TIPS,
),
) { index, type ->
HomeSettingsListItem(
Expand Down Expand Up @@ -97,6 +98,7 @@ enum class MetaRowType(
CONTINUE_WATCHING(R.string.continue_watching),
NEXT_UP(R.string.next_up),
COMBINED_CONTINUE_WATCHING(R.string.combine_continue_next),
CSFD_TV_TIPS(R.string.csfd_tv_tips),
FAVORITES(R.string.favorites),
DISCOVER(R.string.discover),
COLLECTION(R.string.collection),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ fun HomeSettingsPage(
MetaRowType.CONTINUE_WATCHING,
MetaRowType.NEXT_UP,
MetaRowType.COMBINED_CONTINUE_WATCHING,
MetaRowType.CSFD_TV_TIPS,
-> {
addRow { viewModel.addRow(it) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,14 @@ class HomeSettingsViewModel
)
}

MetaRowType.CSFD_TV_TIPS -> {
HomeRowConfigDisplay(
id = id,
title = ResStringProvider(R.string.csfd_tv_tips),
config = HomeRowConfig.CsfdTvTips(),
)
}

MetaRowType.FAVORITES,
MetaRowType.COLLECTION,
MetaRowType.PLAYLIST,
Expand Down Expand Up @@ -746,6 +754,11 @@ class HomeSettingsViewModel
is HomeRowConfig.TvChannels -> {
it.config.updateViewOptions(preset.liveTv)
}

is HomeRowConfig.CsfdTvTips -> {
// Keep tips small regardless of the preset
it.config
}
}
it.copy(config = newConfig)
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-sk/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@
<string name="video">Video</string>
<string name="videos">Videá</string>
<string name="watch_live">Sledovať naživo</string>
<string name="csfd_tv_tips">TV tipy dňa</string>
<plurals name="years_old">
<item quantity="one">vo veku %1$d roka</item>
<item quantity="few">vo veku %1$d rokov</item>
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@
<string name="video_scale">Video Scale</string>
<string name="video">Video</string>
<string name="videos">Videos</string>
<string name="watch_live">Watch live</string>g
<string name="watch_live">Watch live</string>
<string name="csfd_tv_tips">TV tips of the day</string>g
<plurals name="years_old">
<item quantity="zero">%1$d years old</item>
<item quantity="one">%1$d year old</item>
Expand Down
Loading