All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.app.moviebase.provider.omdb.api.OmdbApi.kt Maven / Gradle / Ivy

There is a newer version: 1.1.2
Show newest version
package app.moviebase.provider.omdb.api

import app.moviebase.provider.core.remote.json
import app.moviebase.provider.omdb.OmdbWebConfig
import app.moviebase.provider.omdb.model.OmdbContent
import app.moviebase.provider.omdb.model.OmdbValue
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt

class OmdbApi(
    private val apiKey: String,
    private val client: HttpClient,
) {

    /**
     * Example: https://www.omdbapi.com/?i=tt3896198&apikey=fdb6f463
     *
     * /?i=tt1856101&tomatoes=true&apikey=323bb654
     */
    suspend fun getByImdb(imdbId: String): OmdbValue = client.get {
        val urlValue = "?i=$imdbId&tomatoes=true&apikey=$apiKey"
        url(OmdbWebConfig.BASE_URL + urlValue)
        json()
//        parameter("i", imdbId)
//        parameter("tomatoes", true)
//        parameter("apikey", apiKey)
    }.body()

    suspend fun getOmdbContent(imdbId: String): OmdbContent {
        val value = getByImdb(imdbId)
        return mapValue(value)
    }

    private fun mapValue(omdbValue: OmdbValue): OmdbContent {
        val imdbRating = omdbValue.imdbRating?.toFloatOrNull()?.toRatingNumber()
        val imdbVotes = omdbValue.imdbVotes?.replace(",", "")?.toIntOrNull()
        val metascoreRating = omdbValue.metascore?.toIntOrNull()?.validatePercent()
        val rtRating = omdbValue.ratings
            ?.findLast {
                it.source?.toLowerCase()?.startsWith("rotten") ?: false
            }
            ?.value
            ?.replace("%", "")
            ?.toIntOrNull()
            ?.validatePercent()

        return OmdbContent(
            imdbRating,
            imdbVotes,
            rtRating,
            metascoreRating,
            omdbValue.tomatoURL
        )
    }

    private fun Float.toRatingNumber(): Int {
        return (this * RATING_SCALE).toDouble().roundToInt()
    }

    private fun Int.validatePercent() = min(max(MIN_PERCENT_INT, this), MAX_PERCENT_INT)

    companion object {
        private const val RATING_SCALE = 10
        private const val MAX_PERCENT_INT = 100
        private const val MIN_PERCENT_INT = 0
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy