mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-16 22:26:16 -08:00
feat(portals): mark a full season as watched in one click (#1447)
* feat(portals): mark a full season as watched in one click Series detail pages on both Xtream and Stalker portals get a season-level watched toggle next to "Download season": marking writes full-progress rows for the unwatched episodes only (real durations survive), a fully watched season flips the action to unwatch-all. Persistence goes through new batch IPC channels (DB_SAVE/CLEAR_PLAYBACK_POSITIONS_BATCH, one SQLite transaction with onConflictDoUpdate().run(); the PWA data source rewrites its localStorage blob once). Stalker deliberately bypasses the batch IPC and loops the existing position-mutation queue so legacy-row reconciliation still runs and the queue coalesces to a single reload; partial failures surface a dedicated snackbar. Also removes the dead toggleEpisodeWatched store method, splits season-container/serial-details-playback under the max-lines cap (season-watch-toggle.util.ts, SerialDetailsSeasonWatchService), and classifies *.spec-data.ts fixtures under the test max-lines ceiling (baseline shrinks by main.preload.spec-data.ts). Closes #1442 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): guard stale season batches and split partial-unwatch feedback Review follow-up (Codex on #1447): - A season batch completing after the user navigated to another series or playlist no longer writes the old series' rows into the freshly reset position state (episode ids can collide across playlists); the Xtream host captures the playlist/series identity before awaiting and skips the rendered-state mutation when it changed. The DB write is unaffected — it carries its own playlistId. - A partially failed "mark season as unwatched" on Stalker now reports a dedicated SEASON_MARKED_UNWATCHED_PARTIAL message instead of the watch-direction "marked" text; translated into all 18 locales. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): exclude the playing episode from season marking and count partial saves Second review round (Codex on #1447): - The episode currently playing (inline or in an external session, or with a launch in flight) is excluded from a season's mark-watched batch: the player persists its live position every ~15 s and would immediately overwrite the just-written full-progress row. The button count reflects the exclusion and the action disables when nothing is markable. Unmarking still clears such an episode — the recreated in-progress row reflects live playback truthfully. - A Stalker StalkerSeriesPositionPartialSaveError (scoped watched row saved and published, only legacy cleanup failed) now counts as a watched success instead of feeding false total-failure feedback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): gate stale season-batch snackbars on the originating page Third review round (Codex on #1447): a batch resolving after the user navigated away no longer shows its contextless success/error snackbar on the newly opened detail page — the same ownership check that guards the state mutation now guards the feedback too. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): sync catalog progress badges after toggles and gate Stalker feedback Fourth review round (Codex on #1447): - Any Xtream watched toggle (single episode or season batch) now refreshes XtreamStore.loadAllPositions after persisting — the catalog reads series-progress badges from the store, which otherwise loads positions once per playlist, so returning from the detail kept stale badges. Skipped when the playlist changed mid-flight (the store then belongs to the other playlist; its own init reloads positions). - Stalker's season snackbars are gated on the captured playlist/series identity, matching the Xtream ownership guard — a batch draining after navigation no longer reports on the newly opened page. - Stalker season-toggle specs moved to stalker-series-view.season-watch .spec.ts with their own harness; both prior spec files sat at the 1200-line test ceiling. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: describe the season watched toggle in CLAUDE.md Fifth review round (Codex on #1447): the canonical Seasons entry in the VOD/Series detail section now covers the bulk toggle, its playing-episode exclusion, both persistence paths, catalog badge sync, and the stale-completion contract. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): let only the latest positions load patch the Xtream store Sixth review round (Codex on #1447): loadAllPositions is now latest-load-wins — a fetch superseded while in flight (playlist switch before getAllPlaybackPositions resolves) no longer patches the singleton store with the previous playlist's position maps, which could leave the new catalog showing the old playlist's progress badges. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: reflect the spec-data max-lines classification in CLAUDE.md and AGENTS.md Seventh review round (Codex on #1447): both canonical max-lines descriptions now list **/*.spec-data.ts among the test-ceiling globs so future agents neither treat these fixtures as production files nor remove the exemption unknowingly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): parse "N min" durations when marking episodes watched Eighth review round (Codex on #1447): Stalker VOD episodes report durations like "45 min", which parseDuration could not read — bulk (and single) mark-watched then persisted 1/1-second rows. The minute format now parses to seconds, matching what the removed legacy store method already handled. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): parse compound hour durations and cover the toggle end-to-end Ninth review round (Codex on #1447): - parseDuration now reads the compound "1h 30min" form the Xtream fixtures emit (hour group optional, so "45 min" keeps working) — bulk-marked episodes no longer persist a minutes-only duration. - New Playwright coverage exercises the season toggle through the real UI on both portals: Xtream (category → series detail → mark → reload-persistence → unmark) and Stalker (embedded-series flow, mark → unmark with the item's actual episode count). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): refresh Stalker catalog progress badges after watched toggles Tenth review round (Codex on #1447): the Stalker mirror of the Xtream catalog sync — StalkerCatalogFacadeService loads its position maps once per playlist and the runtime bridge only pushes external-player updates, so renderer-initiated toggles left grid badges stale. The series view now calls the facade's new ownership-checked refreshPositions after the season batch (including partial successes) and after single toggles; the reload is latest-load-wins like the Xtream store fix. Optional injection keeps collection-detail mounts outside the catalog working. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(portals): cover the season toggle batch IPC end-to-end in Electron Eleventh review round (Codex on #1447): the new Electron E2E marks a season through the real UI, asserts the eight SQLite rows written by DB_SAVE_PLAYBACK_POSITIONS_BATCH directly through the preload bridge, proves persistence with a full app relaunch (renderer and main process die, so state can only come from the database file), and clears again through DB_CLEAR_PLAYBACK_POSITIONS_BATCH back to zero rows. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(dashboard): keep watched rows out of the series resume target Twelfth review round (Codex on #1447): a watched position row — a natural finish or a manual/bulk "mark watched" marker — is a completion record, not resumable progress. Continue Watching no longer auto-plays such an episode at its end; the handoff stays detail-only and the series page's quick-start picks the first unwatched episode instead. Card progress bars and SxxEyy badges keep their current source. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(portals): fail closed on refresh reads and gate batch APIs by capability Thirteenth review round (Codex on #1447): - Position-cache refreshes now use a failure-propagating read (getAllPlaybackPositionsOrThrow through the Electron data source): a transient IPC failure rejects instead of masquerading as an empty list, so a populated store/facade cache stays stale-but-populated rather than being wiped. All load/refresh call sites handle the new rejection (init loads may retry on the next activation; post-toggle refreshes log and keep the snackbar flow). - The season-batch bridge methods joined playbackPositionStorageMethods, so a bridge lacking them degrades to the in-memory path wholesale instead of throwing mid-action. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
00000de798
commit
7fc9380bff
79 files changed
+3317
-199
No files matched your search
+225
@@ -11,13 +11,31 @@ import * as schema from '@iptvnator/shared/database/schema';
|
||||
import {
|
||||
clearAllPlaybackPositions,
|
||||
clearPlaybackPosition,
|
||||
clearPlaybackPositionsBatch,
|
||||
getAllPlaybackPositions,
|
||||
getPlaybackPosition,
|
||||
getRecentPlaybackPositions,
|
||||
getSeriesPlaybackPositions,
|
||||
savePlaybackPosition,
|
||||
savePlaybackPositionsBatch,
|
||||
} from './playback-position.operations';
|
||||
|
||||
/**
|
||||
* Batch saves upsert inside a synchronous transaction, so the insert chain
|
||||
* has to end in a synchronous `.run()` rather than resolving — exactly as
|
||||
* the better-sqlite3 driver requires (issue #1137). The wrapper exposes
|
||||
* both dispatch methods so the specs can assert the correct one is used.
|
||||
*/
|
||||
function createBatchUpsertDbMock(selectResultsByCall: unknown[][] = []) {
|
||||
const mock = createDbMock(selectResultsByCall);
|
||||
const insertExecute = jest.fn().mockResolvedValue(undefined);
|
||||
const onConflictDoUpdate = jest
|
||||
.fn()
|
||||
.mockReturnValue({ run: mock.insertRun, execute: insertExecute });
|
||||
mock.insertValues.mockReturnValue({ onConflictDoUpdate });
|
||||
return { ...mock, insertExecute, onConflictDoUpdate };
|
||||
}
|
||||
|
||||
describe('playback-position.operations', () => {
|
||||
beforeEach(() => {
|
||||
resetDrizzleMocks();
|
||||
@@ -138,6 +156,153 @@ describe('playback-position.operations', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('savePlaybackPositionsBatch', () => {
|
||||
it('returns a zero count without touching the database for empty input', async () => {
|
||||
const { db, select, insert, transaction } = createDbMock();
|
||||
|
||||
await expect(
|
||||
savePlaybackPositionsBatch(db, 'playlist-1', [])
|
||||
).resolves.toEqual({ success: true, count: 0 });
|
||||
|
||||
expect(select).not.toHaveBeenCalled();
|
||||
expect(insert).not.toHaveBeenCalled();
|
||||
expect(transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upserts every item inside one transaction with the composite conflict target', async () => {
|
||||
const {
|
||||
db,
|
||||
select,
|
||||
insert,
|
||||
insertValues,
|
||||
onConflictDoUpdate,
|
||||
insertRun,
|
||||
insertExecute,
|
||||
transaction,
|
||||
} = createBatchUpsertDbMock([[{ id: 'playlist-1' }]]);
|
||||
|
||||
const result = await savePlaybackPositionsBatch(db, 'playlist-1', [
|
||||
{
|
||||
contentXtreamId: 500,
|
||||
contentType: 'vod',
|
||||
positionSeconds: 120,
|
||||
durationSeconds: 3600,
|
||||
},
|
||||
{
|
||||
contentXtreamId: 42,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 7,
|
||||
seasonNumber: 2,
|
||||
episodeNumber: 5,
|
||||
positionSeconds: 480,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual({ success: true, count: 2 });
|
||||
// The playlist existence check runs exactly once for the whole
|
||||
// batch, and it must complete before the synchronous transaction
|
||||
// callback starts.
|
||||
expect(select).toHaveBeenCalledTimes(1);
|
||||
expect(select.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
transaction.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(transaction).toHaveBeenCalledTimes(1);
|
||||
expect(insert).toHaveBeenCalledTimes(2);
|
||||
expect(insert).toHaveBeenCalledWith(schema.playbackPositions);
|
||||
expect(insertValues).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 500,
|
||||
contentType: 'vod',
|
||||
positionSeconds: 120,
|
||||
durationSeconds: 3600,
|
||||
updatedAt: expect.objectContaining({ kind: 'sql' }),
|
||||
})
|
||||
);
|
||||
expect(insertValues).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
playlistId: 'playlist-1',
|
||||
contentXtreamId: 42,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 7,
|
||||
seasonNumber: 2,
|
||||
episodeNumber: 5,
|
||||
positionSeconds: 480,
|
||||
})
|
||||
);
|
||||
expect(onConflictDoUpdate).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
target: [
|
||||
schema.playbackPositions.contentXtreamId,
|
||||
schema.playbackPositions.playlistId,
|
||||
schema.playbackPositions.contentType,
|
||||
],
|
||||
set: expect.objectContaining({
|
||||
positionSeconds: 120,
|
||||
durationSeconds: 3600,
|
||||
updatedAt: expect.objectContaining({ kind: 'sql' }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(onConflictDoUpdate).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
set: expect.objectContaining({
|
||||
seriesXtreamId: 7,
|
||||
seasonNumber: 2,
|
||||
episodeNumber: 5,
|
||||
positionSeconds: 480,
|
||||
}),
|
||||
})
|
||||
);
|
||||
// Regression (issue #1137): the upsert must be dispatched with
|
||||
// synchronous `.run()`. `.execute()` defers to a promise that
|
||||
// never settles inside the synchronous transaction callback, so
|
||||
// the batch write would silently no-op.
|
||||
expect(insertExecute).not.toHaveBeenCalled();
|
||||
expect(insertRun).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('creates the missing playlist once, honoring the first item playlist type', async () => {
|
||||
const { db, insert, insertValues } = createBatchUpsertDbMock([[]]);
|
||||
|
||||
await savePlaybackPositionsBatch(db, 'playlist-xt', [
|
||||
{
|
||||
contentXtreamId: 1,
|
||||
contentType: 'vod',
|
||||
positionSeconds: 10,
|
||||
playlistType: 'xtream',
|
||||
},
|
||||
{
|
||||
contentXtreamId: 2,
|
||||
contentType: 'vod',
|
||||
positionSeconds: 20,
|
||||
},
|
||||
]);
|
||||
|
||||
// One playlist insert despite two items, then one position
|
||||
// upsert per item.
|
||||
expect(insert).toHaveBeenCalledTimes(3);
|
||||
expect(insert).toHaveBeenNthCalledWith(1, schema.playlists);
|
||||
expect(insertValues).toHaveBeenNthCalledWith(1, {
|
||||
id: 'playlist-xt',
|
||||
name: 'Imported Playlist',
|
||||
type: 'xtream',
|
||||
});
|
||||
expect(insert).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
schema.playbackPositions
|
||||
);
|
||||
expect(insert).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
schema.playbackPositions
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPlaybackPosition', () => {
|
||||
it('returns the matching row scoped by playlist, content, and type', async () => {
|
||||
const row = {
|
||||
@@ -275,4 +440,64 @@ describe('playback-position.operations', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearPlaybackPositionsBatch', () => {
|
||||
it('returns a zero count without touching the database for empty input', async () => {
|
||||
const { db, deleteFn, transaction } = createDbMock();
|
||||
|
||||
await expect(
|
||||
clearPlaybackPositionsBatch(db, 'playlist-1', [])
|
||||
).resolves.toEqual({ success: true, count: 0 });
|
||||
|
||||
expect(deleteFn).not.toHaveBeenCalled();
|
||||
expect(transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs one prepared placeholder delete per item inside a transaction', async () => {
|
||||
const {
|
||||
db,
|
||||
deleteFn,
|
||||
deletePrepare,
|
||||
deleteRun,
|
||||
deleteExecute,
|
||||
transaction,
|
||||
} = createDbMock();
|
||||
|
||||
await expect(
|
||||
clearPlaybackPositionsBatch(db, 'playlist-1', [
|
||||
{ contentXtreamId: 500, contentType: 'vod' },
|
||||
{ contentXtreamId: 42, contentType: 'episode' },
|
||||
])
|
||||
).resolves.toEqual({ success: true, count: 2 });
|
||||
|
||||
expect(deleteFn).toHaveBeenCalledWith(schema.playbackPositions);
|
||||
expect(deletePrepare).toHaveBeenCalledTimes(1);
|
||||
// The playlist id is bound directly; content id and type are
|
||||
// per-item placeholders.
|
||||
expect(mockDrizzle.eq).toHaveBeenCalledWith(
|
||||
schema.playbackPositions.playlistId,
|
||||
'playlist-1'
|
||||
);
|
||||
expect(mockDrizzle.sql.placeholder).toHaveBeenCalledWith(
|
||||
'contentXtreamId'
|
||||
);
|
||||
expect(mockDrizzle.sql.placeholder).toHaveBeenCalledWith(
|
||||
'contentType'
|
||||
);
|
||||
expect(transaction).toHaveBeenCalledTimes(1);
|
||||
// Regression (issue #1137): the prepared delete must be
|
||||
// dispatched with synchronous `.run()`. `.execute()` defers to a
|
||||
// promise that never settles inside the synchronous transaction
|
||||
// callback, so the batch delete would silently no-op.
|
||||
expect(deleteExecute).not.toHaveBeenCalled();
|
||||
expect(deleteRun).toHaveBeenNthCalledWith(1, {
|
||||
contentXtreamId: 500,
|
||||
contentType: 'vod',
|
||||
});
|
||||
expect(deleteRun).toHaveBeenNthCalledWith(2, {
|
||||
contentXtreamId: 42,
|
||||
contentType: 'episode',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -81,6 +81,96 @@ export async function savePlaybackPosition(
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function savePlaybackPositionsBatch(
|
||||
db: AppDatabase,
|
||||
playlistId: string,
|
||||
items: PlaybackPositionPayload[]
|
||||
): Promise<{ success: boolean; count: number }> {
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
return { success: true, count: 0 };
|
||||
}
|
||||
|
||||
// ensurePlaylistExists awaits, so it must run before the synchronous
|
||||
// transaction callback below.
|
||||
await ensurePlaylistExists(db, playlistId, items[0]?.playlistType);
|
||||
|
||||
await db.transaction(() => {
|
||||
for (const item of items) {
|
||||
// .run() (synchronous), NOT .execute(): the better-sqlite3
|
||||
// driver's .execute() defers the write to a resolved promise
|
||||
// that never settles inside this synchronous transaction
|
||||
// callback, so the upsert would silently do nothing. See the
|
||||
// matching note in recently-viewed.operations.ts (issue #1137).
|
||||
db.insert(schema.playbackPositions)
|
||||
.values({
|
||||
playlistId,
|
||||
contentXtreamId: item.contentXtreamId,
|
||||
contentType: item.contentType,
|
||||
seriesXtreamId: item.seriesXtreamId,
|
||||
seasonNumber: item.seasonNumber,
|
||||
episodeNumber: item.episodeNumber,
|
||||
positionSeconds: item.positionSeconds,
|
||||
durationSeconds: item.durationSeconds,
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [
|
||||
schema.playbackPositions.contentXtreamId,
|
||||
schema.playbackPositions.playlistId,
|
||||
schema.playbackPositions.contentType,
|
||||
],
|
||||
set: {
|
||||
seriesXtreamId: item.seriesXtreamId,
|
||||
seasonNumber: item.seasonNumber,
|
||||
episodeNumber: item.episodeNumber,
|
||||
positionSeconds: item.positionSeconds,
|
||||
durationSeconds: item.durationSeconds,
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
},
|
||||
})
|
||||
.run();
|
||||
}
|
||||
});
|
||||
|
||||
return { success: true, count: items.length };
|
||||
}
|
||||
|
||||
export async function clearPlaybackPositionsBatch(
|
||||
db: AppDatabase,
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<{ success: boolean; count: number }> {
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
return { success: true, count: 0 };
|
||||
}
|
||||
|
||||
const stmt = db
|
||||
.delete(schema.playbackPositions)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.playbackPositions.playlistId, playlistId),
|
||||
eq(
|
||||
schema.playbackPositions.contentXtreamId,
|
||||
sql.placeholder('contentXtreamId')
|
||||
),
|
||||
eq(
|
||||
schema.playbackPositions.contentType,
|
||||
sql.placeholder('contentType')
|
||||
)
|
||||
)
|
||||
)
|
||||
.prepare();
|
||||
|
||||
await db.transaction(() => {
|
||||
for (const { contentXtreamId, contentType } of items) {
|
||||
// .run(), not .execute() — see savePlaybackPositionsBatch.
|
||||
stmt.run({ contentXtreamId, contentType });
|
||||
}
|
||||
});
|
||||
|
||||
return { success: true, count: items.length };
|
||||
}
|
||||
|
||||
export async function getPlaybackPosition(
|
||||
db: AppDatabase,
|
||||
playlistId: string,
|
||||
|
||||
Reference in new issue
Block a user