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
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.github.damontecres.wholphin.data.model

import androidx.compose.runtime.Immutable
import java.util.Locale
import java.util.UUID

/**
* A single rating from a third party source, such as from the MDBList Ratings server plugin
*
* @param source the source key used by the plugin, eg "imdb", "tomatoes", "popcorn"
* @param value the rating in the source's own scale, eg 7.3 for imdb (out of 10) or 95 for tomatoes (percent)
* @param score the rating normalized to 0-100 if available
* @param iconUrl URL to the source's icon on the server
*/
@Immutable
data class ExternalRating(
val source: String,
val value: Double,
val score: Int?,
val iconUrl: String? = null,
) {
/**
* The icon for this rating, or null if the source isn't known
*/
val icon: ExternalRatingIcon? get() = ExternalRatingIcon.forRating(this)

/**
* Text to display for the rating, formatted for the source's scale
*
* Some sources, such as TMDB, use a percentage for movies & series, but out of 10 for episodes
*/
val displayText: String
get() =
if (source in ALWAYS_PERCENT_SOURCES || (source in PERCENT_SOURCES && value > 10.0)) {
"${value.toInt()}%"
} else if (value <= 10.0) {
String.format(Locale.getDefault(), "%.1f", value)
} else {
value.toInt().toString()
}

companion object {
private val ALWAYS_PERCENT_SOURCES = setOf("tomatoes", "popcorn")
private val PERCENT_SOURCES = setOf("tmdb", "trakt")
}
}

/**
* The [ExternalRating]s for a specific item
*/
@Immutable
data class ExternalRatings(
val itemId: UUID? = null,
val ratings: List<ExternalRating> = emptyList(),
)

/**
* Icons served by the MDBList Ratings server plugin at `/Plugins/MdbListRatings/Assets/{fileName}`
*
* @param fileName the name of the asset file on the server
* @param aspectRatio width divided by height of the image
*/
enum class ExternalRatingIcon(
val fileName: String,
val aspectRatio: Float,
) {
IMDB("IMDb.png", 1.5f),
TMDB("TMDB.png", 1.38f),
TOMATOES_FRESH("Rotten_Tomatoes.png", 1f),
TOMATOES_ROTTEN("Rotten_Tomatoes_rotten.png", 1f),
POPCORN_FRESH("Rotten_Tomatoes_positive_audience.png", .76f),
POPCORN_ROTTEN("Rotten_Tomatoes_negative_audience.png", 1.32f),
METACRITIC("Metacritic.png", 1f),
METACRITIC_USER("mus2.png", 1f),
ROGER_EBERT("Roger_Ebert.png", 1f),
TRAKT("Trakt.png", 1f),
LETTERBOXD("letterboxd.png", 1f),
MYANIMELIST("mal.png", 1f),
ANILIST("anilist.png", 1f),
KINOPOISK("kinopoisk.png", 1f),
SIMKL("simkl.png", 1f),
TVMAZE("tvmaze.png", 3.16f),
;

companion object {
/**
* The fresh/rotten threshold matches the plugin's web UI
*/
private const val FRESH_THRESHOLD = 60

fun forRating(rating: ExternalRating): ExternalRatingIcon? {
val score = rating.score ?: rating.value.toInt()
return when (rating.source) {
"imdb" -> IMDB
"tmdb" -> TMDB
"tomatoes" -> if (score in 1..<FRESH_THRESHOLD) TOMATOES_ROTTEN else TOMATOES_FRESH
"popcorn" -> if (score in 1..<FRESH_THRESHOLD) POPCORN_ROTTEN else POPCORN_FRESH
"metacritic" -> METACRITIC
"metacriticuser" -> METACRITIC_USER
"rogerebert" -> ROGER_EBERT
"trakt" -> TRAKT
"letterboxd" -> LETTERBOXD
"myanimelist" -> MYANIMELIST
"anilist" -> ANILIST
"kinopoisk" -> KINOPOISK
"simkl" -> SIMKL
"tvmaze" -> TVMAZE
else -> null
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,10 @@ sealed interface AppPreference<Pref, T> {
AppMultiChoicePreference<AppPreferences, DisplayToggle>(
title = R.string.display_toggles_title,
summary = R.string.display_toggles_summary,
defaultValue = DisplayToggle.entries.filterNot { it == DisplayToggle.UNRECOGNIZED },
defaultValue =
DisplayToggle.entries.filterNot {
it == DisplayToggle.UNRECOGNIZED || it == DisplayToggle.MDBLIST_RATINGS
},
allValues = DisplayToggle.entries.filterNot { it == DisplayToggle.UNRECOGNIZED },
displayValues = R.array.display_toggle_types,
displayValuesSubtitles = R.array.display_toggle_types_subtitles,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
package com.github.damontecres.wholphin.services

import android.util.LruCache
import com.github.damontecres.wholphin.data.model.ExternalRating
import com.github.damontecres.wholphin.data.model.ExternalRatingIcon
import com.github.damontecres.wholphin.preferences.DisplayToggle
import com.github.damontecres.wholphin.services.hilt.AuthOkHttpClient
import com.github.damontecres.wholphin.util.WholphinDispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jellyfin.sdk.api.client.ApiClient
import timber.log.Timber
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.roundToInt

/**
* Fetches ratings from the third party [MDBList Ratings](https://github.com/Druidblack/Jellyfin.Plugin.MDBList_Ratings)
* server plugin, if it is installed
*
* The plugin caches all ratings from MDBList on the server, so this is a single request per item.
* The server admin's choice of which ratings to show and in what order is respected.
*/
@Singleton
class MdbListRatingsService
@Inject
constructor(
@param:AuthOkHttpClient private val okHttpClient: OkHttpClient,
private val api: ApiClient,
private val userPreferencesService: UserPreferencesService,
) {
private val json =
Json {
isLenient = true
ignoreUnknownKeys = true
}

/**
* Settings per server base URL, an absent plugin is stored as [PluginSettings.NOT_INSTALLED]
*/
private val settingsCache = ConcurrentHashMap<String, PluginSettings>()

private val ratingsCache = LruCache<UUID, List<ExternalRating>>(100)

/**
* Get the ratings for an item
*
* @return the ratings to display, or an empty list if disabled, the plugin isn't installed, or there are no ratings
*/
suspend fun getRatings(itemId: UUID): List<ExternalRating> =
withContext(WholphinDispatchers.IO) {
val enabled =
DisplayToggle.MDBLIST_RATINGS in
userPreferencesService
.getCurrent()
.appPreferences.interfacePreferences.displayTogglesList
if (!enabled) return@withContext emptyList()
ratingsCache.get(itemId)?.let { return@withContext it }
try {
val settings = getSettings() ?: return@withContext emptyList()
if (!settings.installed) return@withContext emptyList()
val ratings = fetchRatings(itemId, settings) ?: return@withContext emptyList()
ratingsCache.put(itemId, ratings)
ratings
} catch (ex: Exception) {
Timber.w(ex, "Error fetching MDBList ratings for %s", itemId)
emptyList()
}
}

private fun pluginUrl(path: String) =
api.baseUrl
?.toHttpUrlOrNull()
?.newBuilder()
?.addPathSegments("Plugins/MdbListRatings")
?.addPathSegments(path)

/**
* URL to an icon served by the plugin
*/
private fun iconUrl(icon: ExternalRatingIcon): String? = pluginUrl("Assets")?.addPathSegment(icon.fileName)?.build()?.toString()

@OptIn(ExperimentalSerializationApi::class)
private fun getSettings(): PluginSettings? {
val baseUrl = api.baseUrl ?: return null
settingsCache[baseUrl]?.let { return it }
val url = pluginUrl("WebClientSettings")?.build() ?: return null
val request =
Request
.Builder()
.url(url)
.get()
.build()
val settings =
okHttpClient.newCall(request).execute().use { res ->
if (res.isSuccessful) {
json.decodeFromStream<PluginSettings>(res.body.byteStream())
} else if (res.code == 404) {
Timber.i("MDBList Ratings plugin is not installed")
PluginSettings.NOT_INSTALLED
} else {
// Don't cache other errors so it can be retried
Timber.w("Error fetching MDBList plugin settings: %s", res.code)
return null
}
}
settingsCache[baseUrl] = settings
return settings
}

@OptIn(ExperimentalSerializationApi::class)
private fun fetchRatings(
itemId: UUID,
settings: PluginSettings,
): List<ExternalRating>? {
val url =
pluginUrl("CachedByItemId")
?.addQueryParameter("itemId", itemId.toString())
?.build() ?: return null
val request =
Request
.Builder()
.url(url)
.get()
.build()
val response =
okHttpClient.newCall(request).execute().use { res ->
if (!res.isSuccessful) {
Timber.w("Error fetching MDBList ratings for %s: %s", itemId, res.code)
return null
}
json.decodeFromStream<CachedRatingsResponse>(res.body.byteStream())
}
val ratings =
response.ratings
.mapNotNull { rating ->
val value = rating.value?.takeIf { it > 0 } ?: return@mapNotNull null
val external = ExternalRating(source = rating.source, value = value, score = rating.score?.roundToInt())
val icon = external.icon ?: return@mapNotNull null
external.copy(iconUrl = iconUrl(icon))
}
return settings.order?.let { order ->
ratings
.filter { it.source in order }
.sortedBy { order.indexOf(it.source) }
} ?: ratings
}

@Serializable
private data class PluginSettings(
val installed: Boolean = true,
val webAllRatingsMode: String = "all",
val webAllRatingsOrderCsv: String = "",
) {
/**
* The sources to show in order, or null to show all of them
*/
val order: List<String>?
get() =
if (webAllRatingsMode == "custom") {
webAllRatingsOrderCsv
.split(",")
.map { it.trim().lowercase() }
.filter { it.isNotBlank() }
.takeIf { it.isNotEmpty() }
} else {
null
}

companion object {
val NOT_INSTALLED = PluginSettings(installed = false)
}
}

@Serializable
private data class CachedRatingsResponse(
val ratings: List<CachedRating> = emptyList(),
)

@Serializable
private data class CachedRating(
val source: String,
val value: Double? = null,
val score: Double? = null,
)
}
Loading
Loading