diff --git a/CHANGELOG.md b/CHANGELOG.md index fe77357..89d5b1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## 1.0.1 + +A quicker start, a Stop button, and recovery when the server drops out mid-video. + +- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second. +- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer. +- If your Plex server goes down while you're watching, the player waits for it once the buffered video runs out, then carries on from the same spot when the server is back. Before, it treated the video as finished and Play started it again from the beginning. Pressing Play while it waits tries to reconnect straight away. + +## 1.0.0 + +Kaleido is out of beta. This release reworks the show and season pages and smooths out watching a series. + +- Season pages show their episodes as a grid of cards, each with its still, description and watched state, in place of the long episode list. +- Click the season's name under the show's logo to switch to another season. +- Show pages list seasons once, as a row of posters. A show with only one season shows its episodes directly. +- Episodes you've watched stay marked as watched when you rewatch them and stop partway through. The leftover position only shows on the episode you're up to. +- When the next episode plays, whether automatically or with Next, it starts from the beginning instead of near the end of an earlier viewing. +- Click a show's name under a Continue Watching card to go to the show. +- Continue Watching starts at the first title when something new is added, instead of scrolling it off the left edge. +- Season posters outside their show's page, such as New Seasons, are labelled with the show's name. +- Season pages show the year the season aired, and their Play button agrees with the show page about which episode is next. +- Movie and episode pages show the runtime in their details, with the time left on the Resume button. + +## 0.1.0-beta.19 + +Up Next fixes. + +- Up Next now opens every time the credits start: going back to the credits and seeking into the episode brings it back when they come round again, and it always opens when an episode reaches the end. +- The back arrow and a full-screen button are back at the top of Up Next, so you can return to browsing (playback continues in the miniplayer) or leave full screen. +- Click the show's logo to go to its page, with playback moving to the miniplayer. +- The Play next episode countdown fills smoothly. +- The episode rows are sized to fill the screen instead of leaving a gap at the bottom. +- The backdrop now shows the next episode, and its description is easier to read over bright artwork. + ## 0.1.0-beta.18 A rebuilt Up Next screen that looks and works like the rest of Kaleido. diff --git a/package-lock.json b/package-lock.json index 0d3af2a..a12cc89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "0.1.0-beta.18", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "0.1.0-beta.18", + "version": "1.0.1", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index 22fdfd0..ffa1da4 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "0.1.0-beta.18", + "version": "1.0.1", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 1b9a740..fd8584e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "0.1.0-beta.18" +version = "1.0.1" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b8c8d87..c879aaf 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "0.1.0-beta.18" +version = "1.0.1" description = "Kaleido — a Plex client for Windows" authors = ["Elijah"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 951df20..e6ecb1d 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Kaleido", - "version": "0.1.0-beta.18", + "version": "1.0.1", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/app/format.ts b/src/app/format.ts index a41b82d..e4a7ba9 100644 --- a/src/app/format.ts +++ b/src/app/format.ts @@ -36,10 +36,19 @@ export function progress(item: Item): number { return Math.min(1, Math.max(0, item.viewOffset / item.duration)); } +/** + * Watched once Plex has counted a full play. A rewatch left partway through keeps the + * title watched; its position only matters for resuming (`resumable`). + */ export function isWatched(item: Item, percent = 90): boolean { if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount; - if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100; - return item.viewCount > 0; + if (item.viewCount > 0) return true; + return item.viewOffset > 0 && item.duration > 0 && item.viewOffset / item.duration >= percent / 100; +} + +/** Has a saved position worth resuming from (not one at the very end). */ +export function resumable(item: Item): boolean { + return item.viewOffset > 0 && item.duration > 0 && item.viewOffset < item.duration * 0.97; } export function remainingEpisodes(item: Item): number { diff --git a/src/app/keyboardNav.ts b/src/app/keyboardNav.ts index 8a77535..4e01527 100644 --- a/src/app/keyboardNav.ts +++ b/src/app/keyboardNav.ts @@ -1,9 +1,9 @@ /** * Arrow-key movement between titles, for keyboard users. Focus moves to the * nearest card in the pressed direction (by on-screen geometry), so it works - * the same across shelves, grids, episode lists and people rows. + * the same across shelves, grids and people rows. */ -const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link'; +const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link'; function center(r: DOMRect) { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index 5843ece..5094fb2 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -758,7 +758,7 @@ function MiniPlayer() {
- {(loading || st.buffering) && !st.error ? ( + {(loading || st.buffering || st.reconnecting) && !st.error ? ( ) : st.error ? ( Playback stopped @@ -965,10 +965,12 @@ export function PlayerOverlay() { {!st.fullscreen && }
- {(loading || st.buffering || st.seeking || preparing) && !st.error && ( + {(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
- {preparing && ( + {st.reconnecting ? ( +

Lost connection to {server?.name ?? 'the server'}

+ ) : preparing && (

Preparing {UPSCALING[st.enhance.active].label} upscaling First time on this computer only @@ -1023,6 +1025,8 @@ export function PlayerOverlay() {

+ {/* Balances Stop on the other side, so play/pause stays centred. */} +
+ {!fullscreen && }
@@ -90,7 +104,13 @@ export function PostPlay() { {upcoming || !contextReady ? 'Up next' : 'More to watch'} - + {item.grandparentId ? ( + + ) : ( + + )} {upcoming ? ( <>

{upcoming.title}

@@ -165,19 +185,36 @@ function NowPlaying({ item }: { item: Item }) { ); } -/** Play next episode. While autoplay counts down, a lighter fill sweeps across it. */ +/** + * Play next episode. While autoplay counts down, a lighter fill sweeps across it. + * The store counts in 50 ms steps; the fill is drawn every frame between them. + */ function PlayNext({ ref }: { ref: React.Ref }) { - const countdown = usePlayer((s) => s.countdown); - const total = usePlayer((s) => s.countdownTotal); - const counting = countdown !== null && total > 0; - const fill = counting ? (1 - countdown / total) * 100 : 0; + const counting = usePlayer((s) => s.countdown !== null && s.countdownTotal > 0); + const fill = useRef(null); + useEffect(() => { + if (!counting) return; + let last = { value: usePlayer.getState().countdown ?? 0, at: performance.now() }; + const unsubscribe = usePlayer.subscribe((s, prev) => { + if (s.countdown !== prev.countdown && s.countdown !== null) last = { value: s.countdown, at: performance.now() }; + }); + let raf = 0; + const draw = () => { + const { countdownTotal: total } = usePlayer.getState(); + // Run on from the last step, but never more than a couple of steps ahead (a held countdown stays held). + const remaining = Math.max(0, last.value - Math.min(performance.now() - last.at, 120) / 1000); + if (fill.current && total) fill.current.style.transform = `scaleX(${1 - remaining / total})`; + raf = requestAnimationFrame(draw); + }; + draw(); + return () => { + unsubscribe(); + cancelAnimationFrame(raf); + }; + }, [counting]); return ( - diff --git a/src/player/miniWindow.ts b/src/player/miniWindow.ts index 2f1966c..eebe2b2 100644 --- a/src/player/miniWindow.ts +++ b/src/player/miniWindow.ts @@ -30,6 +30,7 @@ interface PlayerView { duration: number; firstFrame: boolean; buffering: boolean; + reconnecting: boolean; error: string; } @@ -50,7 +51,8 @@ function view(st: PlayerView): MiniState { position: st.position, duration: st.duration, loading: !st.firstFrame && !st.error, - buffering: st.buffering, + // Waiting for the server to come back shows as buffering. + buffering: st.buffering || st.reconnecting, error: !!st.error, }; } diff --git a/src/player/store.test.ts b/src/player/store.test.ts index 26169bc..df87345 100644 --- a/src/player/store.test.ts +++ b/src/player/store.test.ts @@ -5,7 +5,7 @@ const harness = vi.hoisted(() => { const memory = new Map(); vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) }); vi.stubGlobal('document', Object.assign(new EventTarget(), { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } })); - return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true }; + return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true, identity: vi.fn() }; }); vi.mock('../platform/native', () => ({ @@ -20,7 +20,7 @@ vi.mock('./engine', () => ({ mpv: { } })); vi.mock('../app/session', async () => { const { create } = await import('zustand'); - return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only' }, connection: { local: true } })) }; + return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only', name: 'Test', get: harness.identity }, connection: { local: true } })) }; }); vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } })); vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() })); @@ -42,7 +42,11 @@ const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title: Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }], }); const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position }); -const eof = () => harness.event({ type: 'end-file', reason: 'eof' }); +/** The stream ending at `position` (by default the real end of the 100 s episode). */ +const eof = (position = 99.6) => { + usePlayer.setState({ position }); + harness.event({ type: 'end-file', reason: 'eof' }); +}; beforeEach(async () => { vi.useFakeTimers(); @@ -102,6 +106,14 @@ describe('Up Next playback lifecycle', () => { expect(next).toHaveBeenCalledOnce(); usePlayer.setState({ playNext: original }); }); + it('starts the next episode from the beginning, ignoring an earlier partial viewing', async () => { + const original = usePlayer.getState().play; + const spy = vi.fn().mockResolvedValue(undefined); + usePlayer.setState({ play: spy, nextUp: { ...episode('2'), viewOffset: 88000 } }); + await usePlayer.getState().playNext(); + expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: '2' }), expect.objectContaining({ resume: false })); + usePlayer.setState({ play: original }); + }); it('cancels autoplay while keeping the screen open, including across EOF', () => { time(81); usePlayer.getState().cancelCountdown(); @@ -109,13 +121,27 @@ describe('Up Next playback lifecycle', () => { vi.advanceTimersByTime(10000); expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true }); }); - it('returns to credits without reopening on the next time event or EOF', () => { + it('returns to credits without reopening while they play', () => { time(81); usePlayer.getState().dismissPostPlay(); time(82); - eof(); expect(usePlayer.getState()).toMatchObject({ postPlay: false, countdown: null }); }); + it('reopens at the end after returning to the credits', () => { + time(81); + usePlayer.getState().dismissPostPlay(); + eof(); + expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 }); + }); + it('reopens when the credits start again after seeking back into the episode', () => { + time(81); + usePlayer.getState().dismissPostPlay(); + usePlayer.getState().seek(40); + time(40); + expect(usePlayer.getState().postPlay).toBe(false); + time(80); + expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 }); + }); it.each(['hidden', 'mini'] as const)('holds the countdown while %s', (reason) => { time(81); if (reason === 'hidden') Object.assign(document, { hidden: true }); @@ -204,3 +230,51 @@ describe('Up Next playback lifecycle', () => { expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null }); }); }); + +describe('Losing the server mid-stream', () => { + it('waits for the server instead of ending when the stream is cut off early', () => { + eof(42); + expect(usePlayer.getState()).toMatchObject({ reconnecting: true, ended: false, postPlay: false }); + }); + it('resumes from where it stopped once the server answers again', async () => { + const original = usePlayer.getState().play; + const play = vi.fn().mockResolvedValue(undefined); + usePlayer.setState({ play }); + harness.identity.mockRejectedValueOnce(new Error('unreachable')); + eof(42); + await vi.advanceTimersByTimeAsync(2000); + expect(play).not.toHaveBeenCalled(); + expect(usePlayer.getState().reconnecting).toBe(true); + harness.identity.mockResolvedValueOnce({}); + await vi.advanceTimersByTimeAsync(3000); + expect(play).toHaveBeenCalledWith(expect.objectContaining({ id: '1' }), expect.objectContaining({ offsetMs: 42000, keepMini: true })); + expect(usePlayer.getState().reconnecting).toBe(false); + usePlayer.setState({ play: original }); + }); + it('tries straight away on Play instead of starting over', async () => { + const original = usePlayer.getState().play; + const play = vi.fn().mockResolvedValue(undefined); + usePlayer.setState({ play }); + harness.identity.mockResolvedValueOnce({}); + eof(42); + usePlayer.getState().togglePause(); + await vi.waitFor(() => expect(play).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ offsetMs: 42000 }))); + expect(mpv.command).not.toHaveBeenCalledWith('seek', '0.000', 'absolute+exact'); + usePlayer.setState({ play: original }); + }); + it('treats a second cut-off at the same place as the real end of the file', async () => { + harness.identity.mockResolvedValueOnce({}); + eof(42); + await vi.advanceTimersByTimeAsync(2000); + usePlayer.setState({ firstFrame: true }); + eof(42.5); + expect(usePlayer.getState()).toMatchObject({ reconnecting: false, ended: true }); + }); + it('stops waiting when the player is closed', async () => { + eof(42); + await usePlayer.getState().close(); + harness.identity.mockClear(); + await vi.advanceTimersByTimeAsync(10000); + expect(harness.identity).not.toHaveBeenCalled(); + }); +}); diff --git a/src/player/store.ts b/src/player/store.ts index 5107db3..0606a41 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -36,6 +36,8 @@ export interface PlayOptions { quality?: Quality; /** Keep these track choices (UI keys) instead of applying the preferences again. */ tracks?: { audioKey: string; subKey: string }; + /** Reloading the same title in place (after an outage): stay in the miniplayer if it's there. */ + keepMini?: boolean; } interface PlayerState { @@ -48,6 +50,8 @@ interface PlayerState { error: string; /** The server owner stopped this stream (error holds their message). */ terminated: boolean; + /** The stream was cut off before the end (the server went away); waiting for it to come back. */ + reconnecting: boolean; position: number; duration: number; cacheTime: number; @@ -597,7 +601,7 @@ function onEvent(e: MpvEvent) { } break; case 'eof-reached': - if (v === true) onEnded(); + if (v === true) onStreamEnd(); break; } break; @@ -618,11 +622,14 @@ function onEvent(e: MpvEvent) { // (Briefly: an unreachable server shouldn't hold up the error.) const failed = session; Promise.race([report('buffering'), new Promise((r) => setTimeout(() => r(false), 3000))]).then((terminated) => { - if (terminated || !usePlayer.getState().open || session !== failed) return; + const now = usePlayer.getState(); + if (terminated || !now.open || session !== failed) return; + // Partway through a stream that was playing, it's the connection that failed. + if (cutShort(now)) return onStreamEnd(); usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' }); fallbackAfterError(); }); - } else if (e.reason === 'eof') onEnded(); + } else if (e.reason === 'eof') onStreamEnd(); break; case 'log': noteMpvLog(e.level, e.prefix, e.text); @@ -647,8 +654,69 @@ function fallbackAfterError() { function maybeCredits(pos: number) { const st = usePlayer.getState(); - if (st.item?.type !== 'episode' || !st.firstFrame || st.postPlayDismissed) return; - if (st.item.markers.some((m) => m.type === 'credits' && pos * 1000 >= m.start && pos * 1000 < m.end)) openPostPlay(); + if (st.item?.type !== 'episode' || !st.firstFrame) return; + const inCredits = st.item.markers.some((m) => m.type === 'credits' && pos * 1000 >= m.start && pos * 1000 < m.end); + // Leaving the credits (seeking back into the episode) re-arms Up Next for the next time they start. + if (!inCredits) { + if (st.postPlayDismissed && !st.postPlay && !st.ended) usePlayer.setState({ postPlayDismissed: false }); + } else if (!st.postPlayDismissed) openPostPlay(); +} + +/** + * A streamed title stopping well short of its end means the connection went + * (mpv plays out its buffer, then sees the cut-off stream as the end of the file). + */ +const CUT_SHORT_MARGIN = 15; +let reconnectTimer: ReturnType | null = null; +/** Where the last cut-off happened, so a file that really does end early isn't retried forever. */ +let lastCutAt: number | null = null; + +function cutShort(st: PlayerState) { + return st.delivery?.mode !== 'local' && st.firstFrame && st.duration > 0 && st.position < st.duration - CUT_SHORT_MARGIN; +} + +/** The stream ran out: a real ending, or a lost connection to wait out. */ +function onStreamEnd() { + const st = usePlayer.getState(); + if (!cutShort(st)) return onEnded(); + if (st.reconnecting || st.ended) return; + // Cut off at the same place again once the server answered: the file itself ends there. + if (lastCutAt !== null && Math.abs(st.position - lastCutAt) < 5) return onEnded(); + lastCutAt = st.position; + usePlayer.setState({ reconnecting: true, buffering: false }); + keepAwake(false); + scheduleReconnect(2000); +} + +function stopReconnecting() { + if (reconnectTimer) clearTimeout(reconnectTimer); + reconnectTimer = null; +} + +function scheduleReconnect(delay: number) { + stopReconnecting(); + reconnectTimer = setTimeout(() => void tryReconnect(), delay); +} + +/** Resumes where the stream was cut off if the server answers; otherwise checks again shortly. */ +async function tryReconnect(): Promise { + stopReconnecting(); + const st = usePlayer.getState(); + const s = server(); + if (!st.open || !st.reconnecting || !st.item || !s) return false; + const reachable = await s.get('/identity', undefined, { timeout: 4000 }).then( + () => true, + () => false, + ); + const now = usePlayer.getState(); + if (!now.open || !now.reconnecting || now.item?.id !== st.item.id) return false; + if (!reachable) { + scheduleReconnect(3000); + return false; + } + usePlayer.setState({ reconnecting: false }); + await now.play(now.item, { offsetMs: now.position * 1000, mediaIndex: now.mediaIndex, quality: now.quality, tracks: currentTracks(now), keepMini: true }); + return true; } function onEnded() { @@ -657,7 +725,11 @@ function onEnded() { usePlayer.setState({ ended: true }); report('stopped'); checkScrobble(); - if (st.item?.type === 'episode') openPostPlay(); + // Reaching the end always offers Up Next, as on Android, even after watching the credits. + if (st.item?.type === 'episode' && !st.postPlay) { + usePlayer.setState({ postPlayDismissed: false }); + openPostPlay(); + } } export const usePlayer = create((set, get) => ({ @@ -669,6 +741,7 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, + reconnecting: false, position: 0, duration: 0, cacheTime: 0, @@ -712,6 +785,8 @@ export const usePlayer = create((set, get) => ({ return; } const previous = get(); + stopReconnecting(); + if (previous.item?.id !== input.id) lastCutAt = null; // The previous title's reporting ends here, against its own server. if (reportTimer) clearInterval(reportTimer); reportTimer = null; @@ -740,6 +815,7 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, + reconnecting: false, position: (opts.offsetMs ?? 0) / 1000, lastSeek: 0, duration: input.duration / 1000, @@ -761,7 +837,7 @@ export const usePlayer = create((set, get) => ({ subKey: opts.tracks?.subKey ?? '__init', video: null, fullscreen: fullscreenNow, - mini: false, + mini: opts.keepMini ? previous.open && previous.mini : false, videoGamma: '', enhance: { ...previous.enhance, bypass: false, preparing: false }, }); @@ -858,6 +934,9 @@ export const usePlayer = create((set, get) => ({ offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none', ].join(','); await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts); + // A file left paused at its end (keep-open) re-pauses as soon as it's unpaused + // above, so a reload in place (after an outage) would open paused: unpause again. + await mpv.set('pause', false); if (stale()) return; keepAwake(true); report('buffering'); @@ -876,6 +955,8 @@ export const usePlayer = create((set, get) => ({ loadToken++; const st = get(); stopCountdown(); + stopReconnecting(); + lastCutAt = null; if (reportTimer) clearInterval(reportTimer); reportTimer = null; if (st.item && !st.error) report('stopped'); @@ -893,7 +974,7 @@ export const usePlayer = create((set, get) => ({ await mpv.command('stop').catch(() => {}); await mpv.show(false).catch(() => {}); } - set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); + set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, reconnecting: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); // Closing the full player hands back the window it found; closing the // miniplayer leaves browsing as it is, full screen or not. if (!st.mini) { @@ -905,6 +986,13 @@ export const usePlayer = create((set, get) => ({ togglePause() { const st = get(); + // Play while the server is away: try it now rather than at the next check. + if (st.reconnecting) { + tryReconnect().then((resumed) => { + if (!resumed && get().reconnecting) toast(`Still can’t reach ${server()?.name ?? 'the server'}.`); + }); + return; + } if (st.ended) { st.seek(0); set({ ended: false }); @@ -1011,13 +1099,15 @@ export const usePlayer = create((set, get) => ({ const st = get(); stopCountdown(); if (!st.nextUp) return; - await st.play(st.nextUp, { resume: true, quality: st.quality }); + // Watching on through a season starts each episode from the top, never at a + // stale position left by an earlier, unfinished viewing. + await st.play(st.nextUp, { resume: false, quality: st.quality }); }, async playPrevious() { const st = get(); if (!st.prevUp) return; - await st.play(st.prevUp, { resume: true, quality: st.quality }); + await st.play(st.prevUp, { resume: false, quality: st.quality }); }, cancelCountdown() { diff --git a/src/plex/plex.test.ts b/src/plex/plex.test.ts index 8be9e2e..fdd06ff 100644 --- a/src/plex/plex.test.ts +++ b/src/plex/plex.test.ts @@ -3,7 +3,7 @@ import { parseItem, parseScores } from './parse'; import { isLocalAddress } from './account'; import { partAt } from './playback'; import { headerSafe } from './client'; -import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format'; +import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format'; import { buildFeatures } from '../screens/discover'; import type { Hub } from './types'; @@ -65,10 +65,16 @@ describe('parsing', () => { }); describe('watched rules', () => { - it('treats a resumed title as watched only past the threshold', () => { - expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false); - expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true); + it('keeps a title watched while it is being rewatched', () => { + expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(true); expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true); + expect(resumable(movie({ viewCount: 1, viewOffset: 3000000 }))).toBe(true); + }); + + it('counts an unplayed title as watched only past the threshold', () => { + expect(isWatched(movie({ viewOffset: 3000000 }), 90)).toBe(false); + expect(isWatched(movie({ viewOffset: 5700000 }), 90)).toBe(true); + expect(isWatched(movie({}), 90)).toBe(false); }); it('uses episode counts for shows', () => { diff --git a/src/screens/Item.tsx b/src/screens/Item.tsx index ebaf887..dba8e82 100644 --- a/src/screens/Item.tsx +++ b/src/screens/Item.tsx @@ -4,12 +4,12 @@ import type { Item } from '../plex/types'; import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -import { goBack, navigate, useRouter } from '../app/router'; -import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions'; -import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format'; +import { goBack, navigate } from '../app/router'; +import { canManage, itemMenu, openDialog, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions'; +import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, remainingEpisodes, resolutionLabel, resumable, technicalLine } from '../app/format'; import { Backdrop } from '../ui/Backdrop'; -import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; -import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives'; +import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; +import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives'; import { Icon } from '../ui/Icon'; import { openMenu } from '../ui/overlays'; import { useDownloads } from '../downloads/store'; @@ -255,11 +255,12 @@ function AboutPanel({ item }: { item: Item }) { // —— Movie —————————————————————————————————————————————————————————— function MovieDetail({ item }: { item: Item }) { - const resume = item.viewOffset > 0 && !isWatched(item); + const resume = resumable(item); return (
- + {/* The Resume button carries the time left; the facts give the runtime. */} +
- {p > 0 && !watched && ( - - - - )} -
-
-

- {ep.title} - {watched && } -

-
- {[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')} -
- {ep.summary &&

{ep.summary}

} -
- +
+ {episodes.map((ep) => ( + + ))}
); } -function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) { - const saved = useRouter((s) => s.current.state.season as string | undefined); - const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id); - useEffect(() => { - if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id); - }, [seasons, initialSeason]); - const episodes = useChildren(seasonId); - const season = seasons.find((s) => s.id === seasonId); - if (!seasons.length) return null; +function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) { return (
-
-

Episodes

- {showPicker && seasons.length > 1 && ( -