import * as api from '../plex/api'; import type { Hub, Item } from '../plex/types'; import type { Feature } from '../ui/Hero'; import type { PlexServer } from '../plex/client'; /** One shuffle per app session keeps features stable while browsing. */ const seed = Math.floor(Math.random() * 1e9); function shuffled(list: T[], salt = 0): T[] { const out = [...list]; let s = (seed + salt) % 2147483647 || 1; for (let i = out.length - 1; i > 0; i--) { s = (s * 48271) % 2147483647; const j = s % (i + 1); [out[i], out[j]] = [out[j], out[i]]; } return out; } const FEATURE_SOURCES: [RegExp, string][] = [ [/recentlyreleased|recentlyaired/, 'Recently released'], [/topunwatched|toprated/, 'Highly rated'], [/recentlyadded/, 'Recently added'], [/startwatching/, 'Start watching'], [/curated|genre|by\.actor|moreingenre/, 'Recommended'], ]; /** * Features interleave recently released, highly rated unwatched and * Plex-recommended titles; they need artwork and skip in-progress titles. */ export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] { const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) => shuffled( hubs .filter((h) => re.test(h.id)) .flatMap((h) => h.items) .filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary) .map((item) => ({ item, eyebrow })), salt, ), ); const out: Feature[] = []; const seen = new Set(); for (let round = 0; out.length < limit && round < 20; round++) { for (const pool of pools) { const f = pool[round]; if (f && !seen.has(f.item.id) && out.length < limit) { seen.add(f.item.id); out.push(f); } } } return out; } /** * New seasons, one card per show. Samples many seasons so a single series * import cannot fill the row. */ export async function recentSeasons(s: PlexServer, sectionId: string): Promise { const page = await api.libraryPage(s, sectionId, { type: 3, sort: 'addedAt:desc', start: 0, size: 100 }); const byShow = new Map(); for (const season of page.items) { if (!season.parentId) continue; const list = byShow.get(season.parentId) ?? []; list.push(season); byShow.set(season.parentId, list); } const out: Item[] = []; for (const [, seasons] of byShow) { if (out.length >= 18) break; // Several new seasons: show the series; one: the season itself. if (seasons.length > 1) { const first = seasons[0]; out.push({ ...first, id: first.parentId, type: 'show', title: first.parentTitle, thumb: first.parentThumb || first.thumb, key: `/library/metadata/${first.parentId}/children` }); } else out.push(seasons[0]); } return out; } export const HIDDEN_HUBS = /continue|ondeck|inprogress|playlists|music|photos|videos\.recent/;