Modern Apps git

← Modern-Apps.git

uniflix: read TMDB catalog and artwork from static R2 copies first (#static-r2)

Commit
e22c4ccd24a9b026298d854a51ec3f39ea357829
Author
Vayun Mathur <[email protected]>
When
2026-11-13 22:39 UTC (22 days ago)
Parents
50cc670
What changed:
- TmdbApi reads every catalog page except search from
  https://static.maproj.org/tmdb/v1/<same path>.json first (trending,
  top and discover lists; movie and tv detail pages; seasons; movie
  recommendations) and falls back to api.maproj.org/api/tmdb/<path>
  when the copy is missing, failing, or older than its window: 6 h for
  lists (republished hourly), 7 days for title pages (rewritten by the
  server when fetched after 3 days). Search always uses the proxy.
- TmdbImageUrl now points at the static copy
  (static.maproj.org/tmdb/v1/image/<size>/<file>); RemoteImageFetchers
  retries a static artwork URL on the image proxy (proxyFor) when the
  copy does not exist yet or the static host is unreachable, and the
  proxy creates the copy for the next user.

Why: the TMDB catalog is the same for every user, but each home screen
cost the server six list requests plus one per poster, and each opened
title its detail, recommendations and artwork. The server
(location_share_server feat/static-r2, src/handlers/tmdb.rs) now keeps
the lists on R2 (hourly), prebuilds the detail pages and w342 posters
of every listed title, and copies any other page or image the first
time someone asks the proxy for it. So server work scales with the
number of distinct titles viewed per week, not with users.

Details: all requests still go through uniflixGet, so the existing fake
transport keeps tests hermetic (a static URL the fake answers without
Last-Modified is treated as stale and the proxy URL is used).

User-visible effect: none; artwork and pages load from Cloudflare's
edge once copied.

Verified: AddonModelsImageUrlTest updated (static URLs per size, proxy
fallback mapping, non-TMDB URLs untouched); C9TmdbSuccessTest and the
other TMDB tests exercise the fallback path through the fake transport.
Run via :uniflix:testDevUnitTest in the container build.

Diff

uniflix/src/main/java/com/vayunmathur/uniflix/data/RemoteImageFetchers.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/RemoteImageFetchers.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/RemoteImageFetchers.ktindex 4ed749d8af..dd944978d7 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/RemoteImageFetchers.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/RemoteImageFetchers.kt@@ -29,11 +29,18 @@ object RemoteImageFetchers {         }         if (!url.startsWith("http://") && !url.startsWith("https://")) return null         return withContext(Dispatchers.IO) {-            val resp = NetworkClient.execute(url)-            if (!resp.isSuccess) {-                throw java.io.IOException("HTTP ${resp.status} for $url")+            var resp = runCatching { NetworkClient.execute(url) }+            // TMDB artwork is read from its static R2 copy first; one that does not+            // exist yet (or an unreachable static host) falls back to the image proxy.+            val proxy = TmdbImageUrl.proxyFor(url)+            if (proxy != null && resp.getOrNull()?.isSuccess != true) {+                resp = runCatching { NetworkClient.execute(proxy) }             }-            FetchResult.Bytes(resp.bytes)+            val ok = resp.getOrThrow()+            if (!ok.isSuccess) {+                throw java.io.IOException("HTTP ${ok.status} for ${proxy ?: url}")+            }+            FetchResult.Bytes(ok.bytes)         }     } }
uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.ktindex 3e9b692dfc..614ae795ad 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt@@ -1,5 +1,7 @@ package com.vayunmathur.uniflix.data +import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.library.network.StaticMirror import com.vayunmathur.uniflix.domain.Episode import com.vayunmathur.uniflix.domain.MediaDetail import com.vayunmathur.uniflix.domain.MediaItem@@ -9,44 +11,60 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json -/** TMDB catalog client via the self-hosted proxy. Keyless: the server holds the TMDB API key. */+/**+ * TMDB catalog client via the self-hosted proxy. Keyless: the server holds the TMDB API key.+ *+ * Catalog pages are the same for every user, so the server also publishes them to R2+ * (location_share_server `src/handlers/tmdb.rs`): lists hourly, title pages whenever+ * someone fetches them. Every page except search is read from that static copy first+ * ([STATIC_BASE] + the same path + `.json`) and from the proxy when the copy is missing+ * or older than the page's freshness window.+ */ class TmdbApi {     private val json = Json { ignoreUnknownKeys = true }      private fun url(path: String): String = "$BASE$path" -    private suspend fun getItems(requestUrl: String): List<MediaItem> {-        val resp = uniflixGet(requestUrl)+    /** Static copy of [path] when present and fresh, else the proxy's answer. */+    private suspend fun catalogGet(path: String, maxAgeMs: Long): RawResponse {+        val static = runCatching { uniflixGet("$STATIC_BASE$path.json") }.getOrNull()+        if (static != null && StaticMirror.accept(static, maxAgeMs, System.currentTimeMillis())) return static+        return uniflixGet(url(path))+    }++    private fun decodeItems(resp: RawResponse): List<MediaItem> {         if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")         return json.decodeFromString(TmdbList.serializer(), resp.text).results.map { it.toMediaItem() }     } +    private suspend fun getList(path: String): List<MediaItem> = decodeItems(catalogGet(path, LIST_MAX_AGE_MS))+     suspend fun trendingMovies(): List<MediaItem> =-        getItems(url("/trending/movie"))+        getList("/trending/movie")      suspend fun trendingTv(): List<MediaItem> =-        getItems(url("/trending/tv"))+        getList("/trending/tv")      suspend fun topRatedMovies(): List<MediaItem> =-        getItems(url("/top/movie"))+        getList("/top/movie")      suspend fun topRatedTv(): List<MediaItem> =-        getItems(url("/top/tv"))+        getList("/top/tv")      suspend fun discoverMovies(): List<MediaItem> =-        getItems(url("/discover/movie"))+        getList("/discover/movie")      suspend fun discoverTv(): List<MediaItem> =-        getItems(url("/discover/tv"))+        getList("/discover/tv") +    /** Free-text search has unbounded keys: always the proxy. */     suspend fun search(query: String): List<MediaItem> {         val encoded = java.net.URLEncoder.encode(query, Charsets.UTF_8.name())-        return getItems(url("/search?query=$encoded"))+        return decodeItems(uniflixGet(url("/search?query=$encoded")))     }      suspend fun movieDetail(tmdbId: Int): MediaDetail {-        val requestUrl = url("/movie/$tmdbId")-        val resp = uniflixGet(requestUrl)+        val resp = catalogGet("/movie/$tmdbId", DETAIL_MAX_AGE_MS)         if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")         val dto = json.decodeFromString(TmdbMovieDetail.serializer(), resp.text)         val recs = runCatching { movieRecommendations(tmdbId) }.getOrDefault(emptyList())@@ -65,8 +83,7 @@ class TmdbApi {     }      suspend fun tvDetail(tmdbId: Int): MediaDetail {-        val requestUrl = url("/tv/$tmdbId")-        val resp = uniflixGet(requestUrl)+        val resp = catalogGet("/tv/$tmdbId", DETAIL_MAX_AGE_MS)         if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")         val dto = json.decodeFromString(TmdbTvDetail.serializer(), resp.text)         return MediaDetail(@@ -85,7 +102,7 @@ class TmdbApi {     }      suspend fun seasonEpisodes(tmdbId: Int, season: Int): List<Episode> {-        val resp = uniflixGet(url("/tv/$tmdbId/season/$season"))+        val resp = catalogGet("/tv/$tmdbId/season/$season", DETAIL_MAX_AGE_MS)         if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")         return json.decodeFromString(TmdbSeason.serializer(), resp.text).episodes.map {             Episode(season, it.episodeNumber, it.name, it.overview, it.stillPath)@@ -93,10 +110,17 @@ class TmdbApi {     }      private suspend fun movieRecommendations(tmdbId: Int): List<MediaItem> =-        getItems(url("/movie/$tmdbId/recommendations"))+        decodeItems(catalogGet("/movie/$tmdbId/recommendations", DETAIL_MAX_AGE_MS))      companion object {         private const val BASE = "https://api.maproj.org/api/tmdb"+        private const val STATIC_BASE = "${StaticMirror.BASE}/tmdb/v1"++        /** Lists are republished hourly; older means the server stopped. */+        private const val LIST_MAX_AGE_MS = 6L * 60 * 60 * 1000++        /** Title pages are rewritten when fetched after 3 days; refresh weekly. */+        private const val DETAIL_MAX_AGE_MS = 7L * 24 * 60 * 60 * 1000     } } 
uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.ktindex 96546e3a7a..cc6b462213 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt@@ -1,8 +1,17 @@ package com.vayunmathur.uniflix.data -/** TMDB artwork via the self-hosted image proxy — no direct image.tmdb.org. Sizes: w185/w342 cards, w500 search, original hero. */+import com.vayunmathur.library.network.StaticMirror++/**+ * TMDB artwork — no direct image.tmdb.org. Sizes: w185/w342 cards, w500 search, original hero.+ *+ * URLs point at the server's static copy on R2 (images are content-addressed, so a copy+ * never goes stale); [RemoteImageFetchers] falls back to the self-hosted image proxy+ * ([proxyFor]) when the copy does not exist yet, and the proxy then creates it.+ */ object TmdbImageUrl {-    private const val BASE = "https://api.maproj.org/api/tmdb/image/"+    private const val BASE = "${StaticMirror.BASE}/tmdb/v1/image/"+    private const val PROXY_BASE = "https://api.maproj.org/api/tmdb/image/"      fun poster(path: String?, size: String = "w342"): String? =         path?.let { "$BASE$size$it" }@@ -12,4 +21,8 @@ object TmdbImageUrl {      fun still(path: String?, size: String = "w185"): String? =         path?.let { "$BASE$size$it" }++    /** The image proxy URL for a static artwork [url], or null for any other URL. */+    fun proxyFor(url: String): String? =+        url.takeIf { it.startsWith(BASE) }?.let { PROXY_BASE + it.removePrefix(BASE) } }
uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.ktindex f59646bdb5..6bbe8dc7b2 100644--- a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt@@ -69,18 +69,23 @@ class AddonModelsImageUrlTest {         assertEquals("Ep", Episode(1, 1, "Ep").name)     } -    @Test fun imageUrlsUseProxyAndSizes() {+    @Test fun imageUrlsUseStaticCopyAndSizesWithProxyFallback() {         assertNull(TmdbImageUrl.poster(null))         assertNull(TmdbImageUrl.backdrop(null))         assertNull(TmdbImageUrl.still(null))         assertEquals(-            "https://api.maproj.org/api/tmdb/image/w342/p.jpg", TmdbImageUrl.poster("/p.jpg"))+            "https://static.maproj.org/tmdb/v1/image/w342/p.jpg", TmdbImageUrl.poster("/p.jpg"))         assertEquals(-            "https://api.maproj.org/api/tmdb/image/w500/p.jpg", TmdbImageUrl.poster("/p.jpg", "w500"))+            "https://static.maproj.org/tmdb/v1/image/w500/p.jpg", TmdbImageUrl.poster("/p.jpg", "w500"))         assertEquals(-            "https://api.maproj.org/api/tmdb/image/original/b.jpg", TmdbImageUrl.backdrop("/b.jpg"))+            "https://static.maproj.org/tmdb/v1/image/original/b.jpg", TmdbImageUrl.backdrop("/b.jpg"))         assertEquals(-            "https://api.maproj.org/api/tmdb/image/w185/s.jpg", TmdbImageUrl.still("/s.jpg"))+            "https://static.maproj.org/tmdb/v1/image/w185/s.jpg", TmdbImageUrl.still("/s.jpg"))+        // Fallback: same size + file on the image proxy; other URLs have none.+        assertEquals(+            "https://api.maproj.org/api/tmdb/image/w342/p.jpg",+            TmdbImageUrl.proxyFor(TmdbImageUrl.poster("/p.jpg")!!))+        assertNull(TmdbImageUrl.proxyFor("https://addons.example.com/poster.jpg"))     }      @Test fun normalizeBaseUrlAcceptsBareAndManifestForms() {