Add optional MDBList movie ratings

This commit is contained in:
ponzischeme89
2026-08-03 08:55:52 +12:00
parent b6b2a9c25a
commit 666da9c5d3
18 changed files with 840 additions and 4 deletions
+92 -3
View File
@@ -42,6 +42,7 @@ func (s *Server) adminRoutes() http.Handler {
mux.Handle("POST /admin/api/update-policy", s.adminAuth(s.handleAdminUpdatePolicy))
mux.Handle("POST /admin/api/request-policy", s.adminAuth(s.handleAdminRequestPolicy))
mux.Handle("POST /admin/api/playback-policy", s.adminAuth(s.handleAdminPlaybackPolicy))
mux.Handle("POST /admin/api/mdblist-settings", s.adminAuth(s.handleAdminMDBListSettings))
mux.Handle("POST /admin/api/features", s.adminAuth(s.handleAdminFeaturePolicy))
mux.Handle("POST /admin/api/release", s.releasePublishAuth(s.handleReleasePublish))
@@ -51,7 +52,7 @@ func (s *Server) adminRoutes() http.Handler {
var adminPages = map[string]bool{
"library": true, "recommendations": true, "requests": true,
"features": true, "playback": true, "maintenance": true, "updates": true, "engagement": true,
"imports": true, "logs": true,
"ratings": true, "imports": true, "logs": true,
}
func (s *Server) handleAdminRoot(w http.ResponseWriter, r *http.Request) {
@@ -171,6 +172,7 @@ type adminStatus struct {
ForYouRunning bool `json:"forYouRunning"`
RequestPolicy store.RequestPolicy `json:"requestPolicy"`
PlaybackPolicy store.PlaybackPolicy `json:"playbackPolicy"`
MDBList mdblistAdminSettings `json:"mdblist"`
Features featureResponse `json:"features"`
RequestUsers []store.KnownUser `json:"requestUsers"`
Clients []store.KnownClient `json:"clients"`
@@ -236,11 +238,98 @@ func (s *Server) handleAdminStatus(w http.ResponseWriter, r *http.Request) {
Features: featurePayload(s.currentFeaturePolicy(ctx), membyProtocolVersion),
RequestUsers: requestUsers,
Clients: clients,
SonarrReady: s.sonarr != nil,
RadarrReady: s.radarr != nil,
MDBList: func() mdblistAdminSettings {
settings, settingsErr := s.store.MDBListSettings(ctx)
if settingsErr != nil {
s.log.Warn("MDBList settings read failed", "error", settingsErr)
settings = store.DefaultMDBListSettings()
}
return publicMDBListSettings(settings)
}(),
SonarrReady: s.sonarr != nil,
RadarrReady: s.radarr != nil,
})
}
type mdblistAdminSettings struct {
Enabled bool `json:"enabled"`
APIKeyConfigured bool `json:"apiKeyConfigured"`
Sources []string `json:"sources"`
AvailableSources []string `json:"availableSources"`
}
type mdblistSettingsRequest struct {
Enabled bool `json:"enabled"`
APIKey string `json:"apiKey"`
ClearAPIKey bool `json:"clearApiKey"`
Sources []string `json:"sources"`
}
func publicMDBListSettings(settings store.MDBListSettings) mdblistAdminSettings {
return mdblistAdminSettings{
Enabled: settings.Enabled, APIKeyConfigured: settings.APIKey != "",
Sources: settings.Sources, AvailableSources: store.MDBListSources(),
}
}
func (s *Server) handleAdminMDBListSettings(w http.ResponseWriter, r *http.Request) {
var req mdblistSettingsRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "malformed request body")
return
}
current, err := s.store.MDBListSettings(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "could not read MDBList settings")
return
}
apiKey := current.APIKey
if req.ClearAPIKey {
apiKey = ""
} else if replacement := strings.TrimSpace(req.APIKey); replacement != "" {
apiKey = replacement
}
seen := map[string]bool{}
sources := make([]string, 0, len(req.Sources))
for _, source := range req.Sources {
source = strings.ToLower(strings.TrimSpace(source))
if source == "" || seen[source] {
continue
}
if !store.ValidMDBListSource(source) {
writeError(w, http.StatusBadRequest, "unknown MDBList rating source")
return
}
seen[source] = true
sources = append(sources, source)
}
if req.Enabled && apiKey == "" {
writeError(w, http.StatusBadRequest, "set an MDBList API key before enabling ratings")
return
}
if req.Enabled && len(sources) == 0 {
writeError(w, http.StatusBadRequest, "select at least one MDBList rating source")
return
}
if len(sources) == 0 {
sources = current.Sources
}
next := store.MDBListSettings{Enabled: req.Enabled, APIKey: apiKey, Sources: sources}
if err := s.store.SetMDBListSettings(r.Context(), next); err != nil {
s.log.Error("MDBList settings write failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not save MDBList settings")
return
}
stored, err := s.store.MDBListSettings(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "could not reload MDBList settings")
return
}
s.log.Info("MDBList settings changed", "enabled", stored.Enabled, "sources", len(stored.Sources),
"api_key_configured", stored.APIKey != "")
writeJSON(w, http.StatusOK, publicMDBListSettings(stored))
}
type playbackPolicyRequest struct {
PrerollEnabled bool `json:"prerollEnabled"`
PrerollDurationMs int64 `json:"prerollDurationMs"`
+78
View File
@@ -202,6 +202,9 @@
<a class="rail-link" href="/admin/features" data-section="features" title="Features">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h10M18 7h2M4 17h2m4 0h10M14 4v6M6 14v6"/></svg><span>Features</span>
</a>
<a class="rail-link" href="/admin/ratings" data-section="ratings" title="Movie ratings">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m12 3 2.1 5.4 5.9.4-4.6 3.8 1.5 5.7-4.9-3.2-4.9 3.2 1.5-5.7L4 8.8l5.9-.4L12 3Z"/></svg><span>Movie ratings</span>
</a>
<a class="rail-link" href="/admin/library" data-section="library" title="Library">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5.5h16v13H4zM8 5.5v13M4 10h4"/></svg><span>Library</span>
</a>
@@ -346,6 +349,36 @@
</table></div>
</section>
<section id="ratings" data-admin-page="ratings">
<h2>MDBList movie ratings</h2>
<p class="muted" style="margin-top:0">
Optionally enrich movie details with ratings fetched by the gateway. The API key
stays on this server, responses are cached for 24 hours, and failures never block a TV.
</p>
<div class="row" style="margin-bottom:14px">
<label style="display:flex;align-items:center;gap:9px">
<input type="checkbox" id="mdblist-enabled">
<span>Show external movie ratings</span>
</label>
<span id="mdblist-state" class="pill muted">off</span>
</div>
<div style="display:grid;gap:8px;margin-bottom:16px">
<label class="muted" for="mdblist-api-key">MDBList API key</label>
<div class="row">
<input type="password" id="mdblist-api-key" autocomplete="new-password" placeholder="Paste an API key">
<label style="display:flex;align-items:center;gap:7px">
<input type="checkbox" id="mdblist-clear-key"> Remove saved key
</label>
</div>
<span class="muted" style="font-size:12px">Leave the field blank to keep the currently saved key.</span>
</div>
<h2 style="margin-bottom:8px">Sources shown on TVs</h2>
<div id="mdblist-sources" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:9px;margin-bottom:16px">
<span class="muted">Loading sources…</span>
</div>
<button id="mdblist-save">Save ratings settings</button>
</section>
<section id="playback" data-admin-page="playback">
<h2>Playback experience</h2>
<p class="muted" style="margin-top:0">
@@ -458,6 +491,7 @@ const pageCopy = {
recommendations: ['Recommendations', 'Pressure-test personalised rows and title scores per user.'],
requests: ['Media requests', 'Control who can request missing movies and shows.'],
features: ['Features', 'Roll out, stop and recover optional TV behaviour from the server.'],
ratings: ['Movie ratings', 'Configure optional server-side MDBList ratings for movie details.'],
playback: ['Playback', 'Control server-driven playback presentation on every TV.'],
maintenance: ['Maintenance', 'Control gateway availability for every television.'],
updates: ['App updates', 'Publish optional or mandatory client update policy.'],
@@ -643,6 +677,33 @@ function renderStatus(status) {
renderFeatures(status.features || {}, status.clients || []);
const mdblist = status.mdblist || {};
const mdblistEnabled = document.getElementById('mdblist-enabled');
if (document.activeElement !== mdblistEnabled) mdblistEnabled.checked = Boolean(mdblist.enabled);
const mdblistState = document.getElementById('mdblist-state');
mdblistState.textContent = mdblist.enabled
? 'on · ' + ((mdblist.sources || []).length) + ' sources'
: (mdblist.apiKeyConfigured ? 'off · key saved' : 'off · no key');
mdblistState.className = 'pill ' + (mdblist.enabled ? 'ok' : 'muted');
const keyField = document.getElementById('mdblist-api-key');
keyField.placeholder = mdblist.apiKeyConfigured ? 'Saved key (leave blank to keep)' : 'Paste an API key';
const sourceNames = {
imdb:'IMDb', tomatoes:'Rotten Tomatoes', audience:'Rotten Tomatoes Audience',
metacritic:'Metacritic', letterboxd:'Letterboxd', rogerebert:'Roger Ebert',
tmdb:'TMDb', trakt:'Trakt', mal:'MyAnimeList',
score:'MDBList Score', score_average:'MDBList Average',
};
const sourceBox = document.getElementById('mdblist-sources');
if (!sourceBox.contains(document.activeElement)) {
const selectedSources = new Set(mdblist.sources || []);
sourceBox.innerHTML = (mdblist.availableSources || []).map((source) =>
'<label style="display:flex;align-items:center;gap:8px">' +
'<input type="checkbox" data-mdblist-source="' + escapeHtml(source) + '"' +
(selectedSources.has(source) ? ' checked' : '') + '>' +
'<span>' + escapeHtml(sourceNames[source] || source) + '</span></label>'
).join('') || '<span class="muted">No rating sources available.</span>';
}
const playback = status.playbackPolicy || {};
const prerollEnabled = document.getElementById('preroll-enabled');
const prerollDuration = document.getElementById('preroll-duration');
@@ -964,6 +1025,23 @@ document.getElementById('playback-save').addEventListener('click', () => {
}));
});
document.getElementById('mdblist-save').addEventListener('click', () => {
const sources = [...document.querySelectorAll('[data-mdblist-source]:checked')]
.map((box) => box.dataset.mdblistSource);
act(() => api('/admin/api/mdblist-settings', {
method: 'POST',
body: JSON.stringify({
enabled: document.getElementById('mdblist-enabled').checked,
apiKey: document.getElementById('mdblist-api-key').value.trim(),
clearApiKey: document.getElementById('mdblist-clear-key').checked,
sources,
}),
}).then(() => {
document.getElementById('mdblist-api-key').value = '';
document.getElementById('mdblist-clear-key').checked = false;
}));
});
function updatePolicyBody(enabled) {
return JSON.stringify({
enabled,
+14 -1
View File
@@ -323,7 +323,7 @@ func TestAdminPagesUseRealRoutes(t *testing.T) {
AdminToken: "secret", ReleasePublishToken: "release-secret",
})
for _, page := range []string{
"library", "recommendations", "requests", "maintenance",
"library", "recommendations", "requests", "ratings", "maintenance",
"updates", "engagement", "imports", "logs",
} {
req := httptest.NewRequest(http.MethodGet, "/admin/"+page, nil)
@@ -349,6 +349,19 @@ func TestAdminPagesUseRealRoutes(t *testing.T) {
}
}
func TestMDBListAdminStatusNeverExposesTheAPIKey(t *testing.T) {
view := publicMDBListSettings(store.MDBListSettings{
Enabled: true, APIKey: "super-secret", Sources: []string{"imdb"},
})
body, err := json.Marshal(view)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "super-secret") || !strings.Contains(string(body), `"apiKeyConfigured":true`) {
t.Fatalf("unsafe MDBList admin payload: %s", body)
}
}
func TestInstallerDestinationAllowsOnlyKnownAdminPages(t *testing.T) {
if got := cleanInstallerDestination("/admin/recommendations"); got != "/admin/recommendations" {
t.Fatalf("recommendation destination = %q", got)
+6
View File
@@ -27,6 +27,7 @@ import (
"github.com/ponzischeme89/memby/server/internal/emby"
"github.com/ponzischeme89/memby/server/internal/foryou"
serverlogging "github.com/ponzischeme89/memby/server/internal/logging"
"github.com/ponzischeme89/memby/server/internal/mdblist"
"github.com/ponzischeme89/memby/server/internal/radarr"
"github.com/ponzischeme89/memby/server/internal/recommend"
"github.com/ponzischeme89/memby/server/internal/sonarr"
@@ -42,11 +43,13 @@ type Server struct {
forYou *foryou.Service
sonarr *sonarr.Client
radarr *radarr.Client
mdblist *mdblist.Client
syncer syncerHandle
log *slog.Logger
events *serverlogging.Buffer
sonarrMu sync.Mutex
radarrMu sync.Mutex
mdblistMu sync.Mutex
// alertMu serialises the read-modify-write of the shared alert list. Its producers
// are events — a webhook, a finished sync, a health probe — none of them paced by
// this server, so two can land at once.
@@ -67,6 +70,7 @@ type Deps struct {
ForYou *foryou.Service
Sonarr *sonarr.Client
Radarr *radarr.Client
MDBList *mdblist.Client
Syncer syncerHandle
Log *slog.Logger
Events *serverlogging.Buffer
@@ -82,6 +86,7 @@ func New(cfg config.Config, deps Deps) *Server {
forYou: deps.ForYou,
sonarr: deps.Sonarr,
radarr: deps.Radarr,
mdblist: deps.MDBList,
syncer: deps.Syncer,
log: deps.Log,
events: deps.Events,
@@ -123,6 +128,7 @@ func (s *Server) Routes() http.Handler {
v1.Handle("GET /v1/features", s.authed(s.handleFeatures))
v1.Handle("GET /v1/items/{id}", s.authed(s.handleItem))
v1.Handle("GET /v1/items/{id}/ratings", s.authed(s.handleMovieRatings))
v1.Handle("GET /v1/items/{id}/season-finale", s.authed(s.handleSeasonFinale))
v1.Handle("GET /v1/items/{id}/episodes", s.authed(s.handleSeriesEpisodes))
v1.Handle("GET /v1/items/{id}/related", s.authed(s.handleRelated))
+210
View File
@@ -0,0 +1,210 @@
package api
import (
"context"
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
"github.com/ponzischeme89/memby/server/internal/mdblist"
"github.com/ponzischeme89/memby/server/internal/store"
)
const mdblistRatingsTTL = 24 * time.Hour
type movieRating struct {
Source string `json:"source"`
Name string `json:"name"`
Score string `json:"score"`
Scale string `json:"scale"`
}
type movieRatingsResponse struct {
Ratings []movieRating `json:"ratings"`
}
type ratingSource struct {
Name string
Scale string
Maximum float64
}
var movieRatingSources = map[string]ratingSource{
"imdb": {Name: "IMDb", Scale: "/10", Maximum: 10},
"tomatoes": {Name: "Rotten Tomatoes", Scale: "%", Maximum: 100},
"audience": {Name: "Rotten Tomatoes Audience", Scale: "%", Maximum: 100},
"metacritic": {Name: "Metacritic", Scale: "/100", Maximum: 100},
"letterboxd": {Name: "Letterboxd", Scale: "/5", Maximum: 5},
"rogerebert": {Name: "Roger Ebert", Scale: "/4", Maximum: 4},
"tmdb": {Name: "TMDb", Scale: "/10", Maximum: 10},
"trakt": {Name: "Trakt", Scale: "%", Maximum: 100},
"mal": {Name: "MyAnimeList", Scale: "/10", Maximum: 10},
"score": {Name: "MDBList Score", Scale: "/100", Maximum: 100},
"score_average": {
Name: "MDBList Average", Scale: "/100", Maximum: 100,
},
}
var movieRatingAliases = map[string]string{
"imdb": "imdb", "tomatoes": "tomatoes", "rottentomatoes": "tomatoes",
"rtomatoes": "tomatoes", "rttomatoes": "tomatoes",
"audience": "audience", "tomatoesaudience": "audience", "rtaudience": "audience",
"metacritic": "metacritic", "letterboxd": "letterboxd",
"rogerebert": "rogerebert", "roger_ebert": "rogerebert",
"tmdb": "tmdb", "trakt": "trakt", "mal": "mal", "myanimelist": "mal",
"score": "score", "score_average": "score_average", "scoreaverage": "score_average",
}
type ratingsEmbyItem struct {
Type string `json:"Type"`
ProviderIDs map[string]string `json:"ProviderIds"`
}
// handleMovieRatings is deliberately separate from handleItem. External ratings arrive
// after the essential metadata, and every failure path returns an empty successful
// response so MDBList can never prevent a detail page from opening.
func (s *Server) handleMovieRatings(w http.ResponseWriter, r *http.Request, sess store.Session) {
empty := movieRatingsResponse{Ratings: []movieRating{}}
itemID := strings.TrimSpace(r.PathValue("id"))
if itemID == "" {
writeJSON(w, http.StatusOK, empty)
return
}
if s.store == nil || s.emby == nil || s.cache == nil || s.mdblist == nil {
writeJSON(w, http.StatusOK, empty)
return
}
settings, err := s.store.MDBListSettings(r.Context())
if err != nil || !settings.Enabled || settings.APIKey == "" || len(settings.Sources) == 0 {
if err != nil && s.log != nil {
s.log.Warn("MDBList settings unavailable", "error", err)
}
writeJSON(w, http.StatusOK, empty)
return
}
rawItem, err := s.emby.Item(r.Context(), credentials(sess), itemID, "ProviderIds")
if err != nil {
s.logMDBListFailure("movie identifiers unavailable", itemID, err)
writeJSON(w, http.StatusOK, empty)
return
}
var item ratingsEmbyItem
if json.Unmarshal(rawItem, &item) != nil || !strings.EqualFold(item.Type, "Movie") {
writeJSON(w, http.StatusOK, empty)
return
}
provider, providerID := movieProvider(item.ProviderIDs)
if providerID == "" {
writeJSON(w, http.StatusOK, empty)
return
}
ratings, err := s.loadMDBListRatings(r.Context(), settings.APIKey, provider, providerID)
if err != nil {
s.logMDBListFailure("ratings unavailable", itemID, err)
writeJSON(w, http.StatusOK, empty)
return
}
writeJSON(w, http.StatusOK, movieRatingsResponse{
Ratings: selectedMovieRatings(settings.Sources, ratings),
})
}
func (s *Server) loadMDBListRatings(
ctx context.Context, apiKey, provider, providerID string,
) ([]mdblist.Rating, error) {
key := "mdblist:movie-ratings:v1:" + provider + ":" + providerID
if ratings, ok := s.cachedMDBListRatings(ctx, key); ok {
return ratings, nil
}
// A viewer can move focus rapidly and open the same title before the first request
// finishes. Double-checking under the lock keeps that from spending quota twice.
s.mdblistMu.Lock()
defer s.mdblistMu.Unlock()
if ratings, ok := s.cachedMDBListRatings(ctx, key); ok {
return ratings, nil
}
ratings, err := s.mdblist.Movie(ctx, apiKey, provider, providerID)
if err != nil {
return nil, err
}
if ratings == nil {
ratings = []mdblist.Rating{}
}
if raw, marshalErr := json.Marshal(ratings); marshalErr == nil {
if cacheErr := s.cache.Set(ctx, key, raw, mdblistRatingsTTL); cacheErr != nil && s.log != nil {
s.log.Warn("MDBList rating cache write failed", "error", cacheErr)
}
}
return ratings, nil
}
func (s *Server) cachedMDBListRatings(ctx context.Context, key string) ([]mdblist.Rating, bool) {
raw, err := s.cache.Get(ctx, key)
if err != nil {
return nil, false
}
var ratings []mdblist.Rating
if json.Unmarshal(raw, &ratings) != nil {
return nil, false
}
if ratings == nil {
ratings = []mdblist.Rating{}
}
return ratings, true
}
func (s *Server) logMDBListFailure(message, itemID string, err error) {
if s.log != nil {
s.log.Debug("MDBList "+message, "item", itemID, "error", err)
}
}
func movieProvider(ids map[string]string) (string, string) {
if id := strings.TrimSpace(providerID(ids, "tmdb")); id != "" {
return "tmdb", id
}
if id := strings.TrimSpace(providerID(ids, "imdb")); id != "" {
return "imdb", id
}
return "", ""
}
func selectedMovieRatings(selected []string, available []mdblist.Rating) []movieRating {
values := make(map[string]float64, len(available))
for _, rating := range available {
canonical := movieRatingAliases[strings.ToLower(strings.TrimSpace(rating.Source))]
source, known := movieRatingSources[canonical]
if !known || rating.Value <= 0 || rating.Value > source.Maximum {
continue
}
if _, exists := values[canonical]; !exists {
values[canonical] = rating.Value
}
}
result := make([]movieRating, 0, len(selected))
seen := map[string]bool{}
for _, id := range selected {
id = strings.ToLower(strings.TrimSpace(id))
source, known := movieRatingSources[id]
value, available := values[id]
if !known || !available || seen[id] {
continue
}
seen[id] = true
result = append(result, movieRating{
Source: id, Name: source.Name, Score: formatRatingScore(value), Scale: source.Scale,
})
}
if result == nil {
return []movieRating{}
}
return result
}
func formatRatingScore(value float64) string {
return strings.TrimRight(strings.TrimRight(strconv.FormatFloat(value, 'f', 2, 64), "0"), ".")
}
+39
View File
@@ -0,0 +1,39 @@
package api
import (
"testing"
"github.com/ponzischeme89/memby/server/internal/mdblist"
)
func TestSelectedMovieRatingsFiltersOrdersAndLabelsAvailableValues(t *testing.T) {
got := selectedMovieRatings(
[]string{"letterboxd", "imdb", "tomatoes", "rogerebert", "metacritic"},
[]mdblist.Rating{
{Source: "imdb", Value: 8.2},
{Source: "rttomatoes", Value: 91},
{Source: "letterboxd", Value: 4.15},
{Source: "rogerebert", Value: 0},
{Source: "metacritic", Value: 101},
},
)
if len(got) != 3 {
t.Fatalf("ratings = %+v", got)
}
if got[0] != (movieRating{Source: "letterboxd", Name: "Letterboxd", Score: "4.15", Scale: "/5"}) ||
got[1].Name != "IMDb" || got[1].Score != "8.2" || got[1].Scale != "/10" ||
got[2].Name != "Rotten Tomatoes" || got[2].Score != "91" || got[2].Scale != "%" {
t.Fatalf("formatted ratings = %+v", got)
}
}
func TestMovieProviderPrefersTMDBAndFallsBackToIMDb(t *testing.T) {
provider, id := movieProvider(map[string]string{"ImDb": "tt0111161", "TmDb": "278"})
if provider != "tmdb" || id != "278" {
t.Fatalf("provider = %q %q", provider, id)
}
provider, id = movieProvider(map[string]string{"IMDb": "tt0111161"})
if provider != "imdb" || id != "tt0111161" {
t.Fatalf("fallback provider = %q %q", provider, id)
}
}