mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-08 17:06:15 -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
@@ -30,6 +30,19 @@ export interface PortalPlaybackPositions {
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<void>;
|
||||
/**
|
||||
* Bulk variants for season-level watched toggles. Unlike the single
|
||||
* save/clear methods these REJECT on failure so callers can surface an
|
||||
* error instead of silently showing stale state.
|
||||
*/
|
||||
savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void>;
|
||||
clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
export const PORTAL_PLAYBACK_POSITIONS =
|
||||
|
||||
@@ -58,6 +58,9 @@ export class StalkerCatalogFacadeService implements StalkerPortalCatalogFacade<
|
||||
Map<number, PlaybackPositionData[]>
|
||||
>(new Map());
|
||||
private loadedPositionsForPlaylistId: string | null = null;
|
||||
// Latest-load-wins: a positions fetch superseded while in flight must
|
||||
// not patch the maps with another playlist's rows.
|
||||
private positionsLoadGeneration = 0;
|
||||
|
||||
readonly provider = 'stalker' as const;
|
||||
readonly contentType = this.stalkerStore.selectedContentType;
|
||||
@@ -138,7 +141,11 @@ export class StalkerCatalogFacadeService implements StalkerPortalCatalogFacade<
|
||||
}
|
||||
|
||||
this.loadedPositionsForPlaylistId = playlistId;
|
||||
void this.loadStalkerPositions(playlistId);
|
||||
void this.loadStalkerPositions(playlistId).catch(() => {
|
||||
// Allow a retry on the next playlist activation; the read
|
||||
// now rejects instead of masquerading as an empty list.
|
||||
this.loadedPositionsForPlaylistId = null;
|
||||
});
|
||||
});
|
||||
|
||||
const unsubscribe =
|
||||
@@ -345,9 +352,26 @@ export class StalkerCatalogFacadeService implements StalkerPortalCatalogFacade<
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read persisted positions after a renderer-initiated mutation (the
|
||||
* season watched batch or a single toggle): the once-per-playlist load
|
||||
* cannot see them and the runtime bridge only pushes external-player
|
||||
* updates, so grid progress badges would stay stale on return.
|
||||
*/
|
||||
async refreshPositions(playlistId: string): Promise<void> {
|
||||
if (this.playlist()?.id !== playlistId) {
|
||||
return;
|
||||
}
|
||||
await this.loadStalkerPositions(playlistId);
|
||||
}
|
||||
|
||||
private async loadStalkerPositions(playlistId: string): Promise<void> {
|
||||
const generation = ++this.positionsLoadGeneration;
|
||||
const positions =
|
||||
await this.playbackPositions.getAllPlaybackPositions(playlistId);
|
||||
if (generation !== this.positionsLoadGeneration) {
|
||||
return;
|
||||
}
|
||||
|
||||
const positionsMap = new Map<string, PlaybackPositionData>();
|
||||
const seriesMap = new Map<number, PlaybackPositionData[]>();
|
||||
|
||||
+4
@@ -209,11 +209,15 @@
|
||||
isVodSeriesSeasonsLoading() ||
|
||||
isCurrentSeasonLoading(seasonContainer?.selectedSeason())
|
||||
"
|
||||
[seasonWatchBatchRunning]="seasonWatchBatchRunning()"
|
||||
(seasonSelected)="onSeasonSelected($event)"
|
||||
(episodeClicked)="onEpisodeClicked($event)"
|
||||
(playbackToggleRequested)="
|
||||
handlePlaybackToggleRequestedFromUi($event)
|
||||
"
|
||||
(seasonPlaybackToggleRequested)="
|
||||
handleSeasonPlaybackToggleRequestedFromUi($event)
|
||||
"
|
||||
#seasonContainer
|
||||
/>
|
||||
}
|
||||
|
||||
+2
@@ -41,9 +41,11 @@ class StubSeasonContainerComponent {
|
||||
readonly isLoading = input(false);
|
||||
readonly downloadsEnabled = input(true);
|
||||
readonly downloadAdapter = input<SeasonEpisodeDownloadAdapter | null>(null);
|
||||
readonly seasonWatchBatchRunning = input(false);
|
||||
readonly seasonSelected = output<string>();
|
||||
readonly episodeClicked = output<unknown>();
|
||||
readonly playbackToggleRequested = output<unknown>();
|
||||
readonly seasonPlaybackToggleRequested = output<unknown>();
|
||||
readonly selectedSeason = signal<string | undefined>(undefined);
|
||||
}
|
||||
|
||||
|
||||
+134
-3
@@ -15,6 +15,7 @@ import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { Router } from '@angular/router';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { FavoritesButtonComponent } from '../stalker-favorites-button/stalker-favorites-button.component';
|
||||
import { StalkerCatalogFacadeService } from '../stalker-catalog-facade.service';
|
||||
import {
|
||||
DetailActionsTemplateDirective,
|
||||
DetailMetaTemplateDirective,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
ViewInPortalActionComponent,
|
||||
SeasonContainerComponent,
|
||||
SeasonContainerPlaybackToggleRequest,
|
||||
SeasonContainerSeasonPlaybackToggleRequest,
|
||||
} from '@iptvnator/ui/components';
|
||||
import {
|
||||
pickSeasonMarkedTitle,
|
||||
@@ -168,6 +170,10 @@ export class StalkerSeriesViewComponent implements OnDestroy {
|
||||
PlaybackPositionRuntimeBridgeService
|
||||
);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
// Optional: absent in collection-detail mounts outside the catalog.
|
||||
private readonly catalogFacade = inject(StalkerCatalogFacadeService, {
|
||||
optional: true,
|
||||
});
|
||||
private readonly translateService = inject(TranslateService);
|
||||
readonly backClicked = output<void>();
|
||||
private readonly logger = createLogger('StalkerSeriesView');
|
||||
@@ -201,6 +207,7 @@ export class StalkerSeriesViewComponent implements OnDestroy {
|
||||
private unsubscribePositionUpdates: (() => void) | null = null;
|
||||
readonly openingEpisodeId = signal<number | null>(null);
|
||||
readonly activeEpisodeId = signal<number | null>(null);
|
||||
readonly seasonWatchBatchRunning = signal(false);
|
||||
|
||||
/**
|
||||
* Optional input for VOD items with embedded series array (vclub mode)
|
||||
@@ -1075,10 +1082,17 @@ export class StalkerSeriesViewComponent implements OnDestroy {
|
||||
|
||||
if (request.nextPosition) {
|
||||
await this.persistSeriesPosition(playlistId, request.nextPosition);
|
||||
return;
|
||||
} else {
|
||||
await this.clearSeriesPosition(playlistId, request.contentXtreamId);
|
||||
}
|
||||
|
||||
await this.clearSeriesPosition(playlistId, request.contentXtreamId);
|
||||
// Keep the catalog grid's progress badge in sync (ownership-checked
|
||||
// inside the facade; no-op outside the catalog context). A failed
|
||||
// refresh keeps the cache populated-but-stale.
|
||||
await this.catalogFacade
|
||||
?.refreshPositions(playlistId)
|
||||
.catch((error: unknown) =>
|
||||
this.logger.warn('Catalog position refresh failed', error)
|
||||
);
|
||||
}
|
||||
|
||||
handlePlaybackToggleRequestedFromUi(
|
||||
@@ -1094,6 +1108,123 @@ export class StalkerSeriesViewComponent implements OnDestroy {
|
||||
);
|
||||
}
|
||||
|
||||
async handleSeasonPlaybackToggleRequested(
|
||||
request: SeasonContainerSeasonPlaybackToggleRequest
|
||||
): Promise<void> {
|
||||
const playlistId = this.stalkerStore.currentPlaylist()?._id;
|
||||
if (
|
||||
!playlistId ||
|
||||
request.requests.length === 0 ||
|
||||
this.seasonWatchBatchRunning()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// The mutation context already keeps a stale batch out of the next
|
||||
// series' state; the snackbars need the same ownership so feedback
|
||||
// for the old season is not presented on a newly opened page.
|
||||
const seriesXtreamId = this.toSeriesId(this.displayItem()?.id ?? 0);
|
||||
const stillCurrent = () =>
|
||||
this.stalkerStore.currentPlaylist()?._id === playlistId &&
|
||||
this.toSeriesId(this.displayItem()?.id ?? 0) === seriesXtreamId;
|
||||
|
||||
this.seasonWatchBatchRunning.set(true);
|
||||
try {
|
||||
// Enqueue every episode synchronously: each mutation chains on
|
||||
// the previous one's never-rejecting barrier, so the queue
|
||||
// serializes the writes (incl. per-episode legacy-row cleanup)
|
||||
// and reloads positions once after the whole chain drains.
|
||||
const outcomes = await Promise.all(
|
||||
request.requests.map((item) =>
|
||||
(item.nextPosition
|
||||
? this.persistSeriesPosition(
|
||||
playlistId,
|
||||
item.nextPosition
|
||||
)
|
||||
: this.clearSeriesPosition(
|
||||
playlistId,
|
||||
item.contentXtreamId
|
||||
)
|
||||
).then(
|
||||
() => true,
|
||||
// The scoped watched row was saved and published —
|
||||
// only the legacy-row cleanup failed. The episode IS
|
||||
// watched, so it must not count against the batch.
|
||||
(error: unknown) =>
|
||||
error instanceof
|
||||
StalkerSeriesPositionPartialSaveError
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const failed = outcomes.filter((ok) => !ok).length;
|
||||
const succeeded = outcomes.length - failed;
|
||||
if (failed > 0) {
|
||||
this.logger.error(
|
||||
`Season watched toggle: ${failed} of ${outcomes.length} episodes failed`
|
||||
);
|
||||
}
|
||||
if (succeeded > 0) {
|
||||
// Partial successes changed rows too — the catalog badge
|
||||
// must follow even when the user already moved on. A failed
|
||||
// refresh must not break the feedback flow below.
|
||||
await this.catalogFacade
|
||||
?.refreshPositions(playlistId)
|
||||
.catch((error: unknown) =>
|
||||
this.logger.warn(
|
||||
'Catalog position refresh failed',
|
||||
error
|
||||
)
|
||||
);
|
||||
}
|
||||
if (!stillCurrent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (failed === 0) {
|
||||
this.notifySeasonWatchToggle(
|
||||
request.markWatched
|
||||
? 'XTREAM.SEASON_MARKED_WATCHED'
|
||||
: 'XTREAM.SEASON_MARKED_UNWATCHED',
|
||||
{ count: succeeded }
|
||||
);
|
||||
} else if (succeeded > 0) {
|
||||
this.notifySeasonWatchToggle(
|
||||
request.markWatched
|
||||
? 'XTREAM.SEASON_MARKED_WATCHED_PARTIAL'
|
||||
: 'XTREAM.SEASON_MARKED_UNWATCHED_PARTIAL',
|
||||
{ count: succeeded, failed }
|
||||
);
|
||||
} else {
|
||||
this.notifySeasonWatchToggle(
|
||||
'XTREAM.SEASON_WATCH_UPDATE_FAILED'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
this.seasonWatchBatchRunning.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
handleSeasonPlaybackToggleRequestedFromUi(
|
||||
request: SeasonContainerSeasonPlaybackToggleRequest
|
||||
): void {
|
||||
void this.handleSeasonPlaybackToggleRequested(request).catch(
|
||||
(error: unknown) => {
|
||||
this.logger.error(
|
||||
'Failed to toggle season watched state',
|
||||
error
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private notifySeasonWatchToggle(key: string, params?: object): void {
|
||||
this.snackBar.open(
|
||||
this.translateService.instant(key, params),
|
||||
undefined,
|
||||
{ duration: 5000 }
|
||||
);
|
||||
}
|
||||
|
||||
private async loadSeriesPositions(
|
||||
context: SeriesPositionContext
|
||||
): Promise<void> {
|
||||
|
||||
+19
-12
@@ -153,22 +153,13 @@ describe('StalkerSeriesViewComponent position compatibility', () => {
|
||||
pendingLoad: Deferred<PlaybackPositionData[]>;
|
||||
secondPosition: PlaybackPositionData;
|
||||
}> {
|
||||
await startWithLoadedEpisode();
|
||||
fixture.componentInstance.vodSeriesSeasons.set([
|
||||
createSeason(SERIES_A_ID, [
|
||||
createProviderEpisode(),
|
||||
createProviderEpisode('provider-episode-2', 2),
|
||||
]),
|
||||
]);
|
||||
await settle();
|
||||
const [firstEpisode, secondEpisode] =
|
||||
fixture.componentInstance.mappedSeasons()['1'];
|
||||
const [firstId, secondId] = await startWithTwoLoadedEpisodes();
|
||||
const firstPosition = createPosition({
|
||||
contentXtreamId: Number(firstEpisode.id),
|
||||
contentXtreamId: firstId,
|
||||
positionSeconds: 15,
|
||||
});
|
||||
const secondPosition = createPosition({
|
||||
contentXtreamId: Number(secondEpisode.id),
|
||||
contentXtreamId: secondId,
|
||||
episodeNumber: 2,
|
||||
positionSeconds: 25,
|
||||
});
|
||||
@@ -1196,4 +1187,20 @@ describe('StalkerSeriesViewComponent position compatibility', () => {
|
||||
);
|
||||
expect(clearPlaybackPosition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
async function startWithTwoLoadedEpisodes(): Promise<[number, number]> {
|
||||
await startWithLoadedEpisode();
|
||||
fixture.componentInstance.vodSeriesSeasons.set([
|
||||
createSeason(SERIES_A_ID, [
|
||||
createProviderEpisode(),
|
||||
createProviderEpisode('provider-episode-2', 2),
|
||||
]),
|
||||
]);
|
||||
await settle();
|
||||
const [first, second] = fixture.componentInstance.mappedSeasons()['1'];
|
||||
return [Number(first.id), Number(second.id)];
|
||||
}
|
||||
|
||||
// Season-level bulk toggle coverage lives in
|
||||
// stalker-series-view.season-watch.spec.ts.
|
||||
});
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { Router } from '@angular/router';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import {
|
||||
PORTAL_EXTERNAL_PLAYBACK,
|
||||
PORTAL_PLAYBACK_POSITIONS,
|
||||
PORTAL_PLAYER,
|
||||
} from '@iptvnator/portal/shared/util';
|
||||
import {
|
||||
StalkerStore,
|
||||
type StalkerVodSource,
|
||||
type VodSeriesSeasonVm,
|
||||
} from '@iptvnator/portal/stalker/data-access';
|
||||
import type { PlaybackPositionData } from '@iptvnator/shared/interfaces';
|
||||
import {
|
||||
CrossPortalSimilarService,
|
||||
DownloadsService,
|
||||
PlaybackPositionRuntimeBridgeService,
|
||||
TmdbEnrichmentService,
|
||||
} from '@iptvnator/services';
|
||||
import { EMPTY, of } from 'rxjs';
|
||||
import { StalkerCatalogFacadeService } from '../stalker-catalog-facade.service';
|
||||
import { StalkerSeriesPositionPartialSaveError } from './stalker-series-position-compatibility';
|
||||
import { StalkerSeriesViewComponent } from './stalker-series-view.component';
|
||||
|
||||
const PLAYLIST_ID = 'playlist-1';
|
||||
const SERIES_A_ID = 100;
|
||||
const SERIES_B_ID = 200;
|
||||
|
||||
function createVodItem(seriesId: number): StalkerVodSource {
|
||||
return {
|
||||
id: String(seriesId),
|
||||
is_series: '1',
|
||||
info: {
|
||||
name: `Series ${seriesId}`,
|
||||
description: 'Lazy series',
|
||||
movie_image: 'poster.jpg',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createSeason(
|
||||
seriesId: number,
|
||||
episodes: VodSeriesSeasonVm['episodes'] = []
|
||||
): VodSeriesSeasonVm {
|
||||
return {
|
||||
id: 'season-1',
|
||||
video_id: String(seriesId),
|
||||
name: 'Season 1',
|
||||
season_number: '1',
|
||||
episodes,
|
||||
isLoading: false,
|
||||
isExpanded: false,
|
||||
};
|
||||
}
|
||||
|
||||
function createProviderEpisode(id = 'provider-episode-1', episodeNumber = 1) {
|
||||
return {
|
||||
id,
|
||||
series_number: episodeNumber,
|
||||
name: episodeNumber === 1 ? 'Pilot' : `Episode ${episodeNumber}`,
|
||||
};
|
||||
}
|
||||
|
||||
function createPosition(
|
||||
overrides: Partial<PlaybackPositionData> = {}
|
||||
): PlaybackPositionData {
|
||||
return {
|
||||
contentXtreamId: 0,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: SERIES_A_ID,
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 1,
|
||||
positionSeconds: 40,
|
||||
durationSeconds: 100,
|
||||
playlistId: PLAYLIST_ID,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('StalkerSeriesViewComponent season watched toggle', () => {
|
||||
let fixture: ComponentFixture<StalkerSeriesViewComponent>;
|
||||
let repositoryRows: PlaybackPositionData[];
|
||||
let repositoryOrder: string[];
|
||||
const selectedItem = signal<StalkerVodSource | null>(
|
||||
createVodItem(SERIES_A_ID)
|
||||
);
|
||||
const currentPlaylist = signal<{ _id: string } | null>({
|
||||
_id: PLAYLIST_ID,
|
||||
});
|
||||
const vodSeriesSeasonsResource = signal<unknown[]>([]);
|
||||
const getSeriesPlaybackPositions = jest.fn();
|
||||
const savePlaybackPosition = jest.fn();
|
||||
const clearPlaybackPosition = jest.fn();
|
||||
const savePlaybackPositionOrThrow = jest.fn();
|
||||
const clearPlaybackPositionOrThrow = jest.fn();
|
||||
const refreshPositions = jest.fn();
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
for (let pass = 0; pass < 4; pass++) {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
async function startWithTwoLoadedEpisodes(): Promise<[number, number]> {
|
||||
vodSeriesSeasonsResource.set([
|
||||
{
|
||||
id: 'season-1',
|
||||
video_id: String(SERIES_A_ID),
|
||||
name: 'Season 1',
|
||||
season_number: '1',
|
||||
},
|
||||
]);
|
||||
await settle();
|
||||
fixture.componentInstance.vodSeriesSeasons.set([
|
||||
createSeason(SERIES_A_ID, [
|
||||
createProviderEpisode(),
|
||||
createProviderEpisode('provider-episode-2', 2),
|
||||
]),
|
||||
]);
|
||||
await settle();
|
||||
const [first, second] = fixture.componentInstance.mappedSeasons()['1'];
|
||||
return [Number(first.id), Number(second.id)];
|
||||
}
|
||||
|
||||
function seasonToggleRequest(ids: number[], markWatched: boolean) {
|
||||
return {
|
||||
seasonKey: '1',
|
||||
markWatched,
|
||||
requests: ids.map((contentXtreamId, index) => ({
|
||||
contentXtreamId,
|
||||
nextPosition: markWatched
|
||||
? createPosition({
|
||||
contentXtreamId,
|
||||
episodeNumber: index + 1,
|
||||
positionSeconds: 100,
|
||||
})
|
||||
: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function snackBarCalls(): unknown[][] {
|
||||
return (TestBed.inject(MatSnackBar).open as jest.Mock).mock.calls;
|
||||
}
|
||||
|
||||
function expectSeasonToggleSnackbar(key: string): void {
|
||||
expect(TestBed.inject(MatSnackBar).open).toHaveBeenCalledWith(
|
||||
key,
|
||||
undefined,
|
||||
{ duration: 5000 }
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
repositoryRows = [];
|
||||
repositoryOrder = [];
|
||||
selectedItem.set(createVodItem(SERIES_A_ID));
|
||||
currentPlaylist.set({ _id: PLAYLIST_ID });
|
||||
vodSeriesSeasonsResource.set([]);
|
||||
|
||||
getSeriesPlaybackPositions.mockReset();
|
||||
getSeriesPlaybackPositions.mockImplementation(
|
||||
async (
|
||||
_playlistId: string,
|
||||
seriesXtreamId: number
|
||||
): Promise<PlaybackPositionData[]> =>
|
||||
repositoryRows.filter(
|
||||
(position) => position.seriesXtreamId === seriesXtreamId
|
||||
)
|
||||
);
|
||||
savePlaybackPosition.mockReset();
|
||||
savePlaybackPosition.mockImplementation(
|
||||
async (
|
||||
_playlistId: string,
|
||||
position: PlaybackPositionData
|
||||
): Promise<void> => {
|
||||
repositoryOrder.push(`save:${position.contentXtreamId}`);
|
||||
repositoryRows = repositoryRows.filter(
|
||||
(row) => row.contentXtreamId !== position.contentXtreamId
|
||||
);
|
||||
repositoryRows.push(position);
|
||||
}
|
||||
);
|
||||
clearPlaybackPosition.mockReset();
|
||||
clearPlaybackPosition.mockImplementation(
|
||||
async (
|
||||
_playlistId: string,
|
||||
contentXtreamId: number
|
||||
): Promise<void> => {
|
||||
repositoryOrder.push(`clear:${contentXtreamId}`);
|
||||
repositoryRows = repositoryRows.filter(
|
||||
(row) => row.contentXtreamId !== contentXtreamId
|
||||
);
|
||||
}
|
||||
);
|
||||
savePlaybackPositionOrThrow
|
||||
.mockReset()
|
||||
.mockImplementation(savePlaybackPosition);
|
||||
clearPlaybackPositionOrThrow
|
||||
.mockReset()
|
||||
.mockImplementation(clearPlaybackPosition);
|
||||
refreshPositions.mockReset();
|
||||
refreshPositions.mockResolvedValue(undefined);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [StalkerSeriesViewComponent],
|
||||
providers: [
|
||||
{
|
||||
provide: StalkerStore,
|
||||
useValue: {
|
||||
selectedItem,
|
||||
selectedContentType: signal<'series' | 'vod'>('vod'),
|
||||
currentPlaylist,
|
||||
getSerialSeasonsResource: () => [],
|
||||
getVodSeriesSeasonsResource: () =>
|
||||
vodSeriesSeasonsResource(),
|
||||
isVodSeriesSeasonsLoading: signal(false),
|
||||
isSerialSeasonsLoading: signal(false),
|
||||
fetchVodSeriesEpisodes: jest
|
||||
.fn()
|
||||
.mockResolvedValue([createProviderEpisode()]),
|
||||
resolveVodPlayback: jest.fn(),
|
||||
fetchLinkToPlay: jest.fn(),
|
||||
clearSelectedItem: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PORTAL_PLAYBACK_POSITIONS,
|
||||
useValue: {
|
||||
getSeriesPlaybackPositions,
|
||||
savePlaybackPosition,
|
||||
clearPlaybackPosition,
|
||||
savePlaybackPositionOrThrow,
|
||||
clearPlaybackPositionOrThrow,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PlaybackPositionRuntimeBridgeService,
|
||||
useValue: {
|
||||
onPlaybackPositionUpdate: jest
|
||||
.fn()
|
||||
.mockReturnValue(jest.fn()),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: PORTAL_EXTERNAL_PLAYBACK,
|
||||
useValue: { activeSession: signal(null) },
|
||||
},
|
||||
{
|
||||
provide: PORTAL_PLAYER,
|
||||
useValue: {
|
||||
isEmbeddedPlayer: jest.fn().mockReturnValue(true),
|
||||
openResolvedPlayback: jest.fn(),
|
||||
openExternalPlayback: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: CrossPortalSimilarService,
|
||||
useValue: {
|
||||
isAvailable: false,
|
||||
matchRecommendations: jest.fn(),
|
||||
buildLink: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: Router,
|
||||
useValue: {
|
||||
navigate: jest.fn(),
|
||||
navigateByUrl: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: DownloadsService,
|
||||
useValue: { startDownload: jest.fn() },
|
||||
},
|
||||
{
|
||||
provide: TmdbEnrichmentService,
|
||||
useValue: {
|
||||
isEnabled: () => false,
|
||||
getSeason: jest.fn(),
|
||||
getSeasonEpisodes: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: MatSnackBar,
|
||||
useValue: { open: jest.fn() },
|
||||
},
|
||||
{
|
||||
provide: StalkerCatalogFacadeService,
|
||||
useValue: { refreshPositions },
|
||||
},
|
||||
{
|
||||
provide: TranslateService,
|
||||
useValue: {
|
||||
instant: (key: string) => key,
|
||||
get: (key: string) => of(key),
|
||||
stream: (key: string) => of(key),
|
||||
onLangChange: EMPTY,
|
||||
onTranslationChange: EMPTY,
|
||||
onDefaultLangChange: EMPTY,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
.overrideComponent(StalkerSeriesViewComponent, {
|
||||
set: { template: '' },
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(StalkerSeriesViewComponent);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fixture.destroy();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('marks a season watched sequentially, counting failed legacy cleanup as watched', async () => {
|
||||
const [firstId, secondId] = await startWithTwoLoadedEpisodes();
|
||||
const loadsBefore = getSeriesPlaybackPositions.mock.calls.length;
|
||||
// The second episode saves its scoped row but fails legacy cleanup —
|
||||
// that outcome is still a watched episode, not a batch failure.
|
||||
savePlaybackPositionOrThrow.mockImplementation(
|
||||
async (playlistId: string, position: PlaybackPositionData) => {
|
||||
await savePlaybackPosition(playlistId, position);
|
||||
if (position.contentXtreamId === secondId) {
|
||||
throw new StalkerSeriesPositionPartialSaveError('cleanup');
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
await fixture.componentInstance.handleSeasonPlaybackToggleRequested(
|
||||
seasonToggleRequest([firstId, secondId], true)
|
||||
);
|
||||
|
||||
expect(repositoryOrder).toEqual([
|
||||
`save:${firstId}`,
|
||||
`save:${secondId}`,
|
||||
]);
|
||||
expect(getSeriesPlaybackPositions.mock.calls.length).toBe(loadsBefore);
|
||||
const positions = fixture.componentInstance.episodePlaybackPositions();
|
||||
expect(positions.get(secondId)?.positionSeconds).toBe(100);
|
||||
expectSeasonToggleSnackbar('XTREAM.SEASON_MARKED_WATCHED');
|
||||
// The catalog grid's progress badge source must follow the batch.
|
||||
expect(refreshPositions).toHaveBeenCalledWith(PLAYLIST_ID);
|
||||
expect(fixture.componentInstance.seasonWatchBatchRunning()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps surviving clears and reports a partial season unwatch failure', async () => {
|
||||
const [firstId, secondId] = await startWithTwoLoadedEpisodes();
|
||||
repositoryRows = [firstId, secondId].map((contentXtreamId, index) =>
|
||||
createPosition({
|
||||
contentXtreamId,
|
||||
episodeNumber: index + 1,
|
||||
positionSeconds: 100,
|
||||
})
|
||||
);
|
||||
selectedItem.set(createVodItem(SERIES_A_ID));
|
||||
await settle();
|
||||
clearPlaybackPositionOrThrow.mockImplementation(
|
||||
async (playlistId: string, contentXtreamId: number) => {
|
||||
if (contentXtreamId === secondId) {
|
||||
throw new Error('clear rejected');
|
||||
}
|
||||
return clearPlaybackPosition(playlistId, contentXtreamId);
|
||||
}
|
||||
);
|
||||
|
||||
await fixture.componentInstance.handleSeasonPlaybackToggleRequested(
|
||||
seasonToggleRequest([firstId, secondId], false)
|
||||
);
|
||||
|
||||
const positions = fixture.componentInstance.episodePlaybackPositions();
|
||||
expect(positions.has(firstId)).toBe(false);
|
||||
expect(positions.get(secondId)?.positionSeconds).toBe(100);
|
||||
expectSeasonToggleSnackbar('XTREAM.SEASON_MARKED_UNWATCHED_PARTIAL');
|
||||
// A partial success changed rows — the badge refresh still runs.
|
||||
expect(refreshPositions).toHaveBeenCalledWith(PLAYLIST_ID);
|
||||
});
|
||||
|
||||
it('suppresses feedback when the series changes while the batch drains', async () => {
|
||||
const [firstId, secondId] = await startWithTwoLoadedEpisodes();
|
||||
const callsBefore = snackBarCalls().length;
|
||||
|
||||
const pending =
|
||||
fixture.componentInstance.handleSeasonPlaybackToggleRequested(
|
||||
seasonToggleRequest([firstId, secondId], true)
|
||||
);
|
||||
// The user opens another series before the mutation queue drains.
|
||||
selectedItem.set(createVodItem(SERIES_B_ID));
|
||||
await pending;
|
||||
|
||||
expect(snackBarCalls().length).toBe(callsBefore);
|
||||
expect(fixture.componentInstance.seasonWatchBatchRunning()).toBe(false);
|
||||
});
|
||||
});
|
||||
+3
@@ -72,8 +72,11 @@ export function createPlaybackServiceMock() {
|
||||
getSeriesPlaybackPositions: jest.fn().mockResolvedValue([]),
|
||||
getRecentPlaybackPositions: jest.fn().mockResolvedValue([]),
|
||||
getAllPlaybackPositions: jest.fn().mockResolvedValue([]),
|
||||
getAllPlaybackPositionsOrThrow: jest.fn().mockResolvedValue([]),
|
||||
clearPlaybackPosition: jest.fn().mockResolvedValue(undefined),
|
||||
clearAllPlaybackPositions: jest.fn().mockResolvedValue(undefined),
|
||||
savePlaybackPositionsBatch: jest.fn().mockResolvedValue(undefined),
|
||||
clearPlaybackPositionsBatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -516,7 +516,9 @@ export class ElectronXtreamDataSource implements IXtreamDataSource {
|
||||
async getAllPlaybackPositions(
|
||||
playlistId: string
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
return this.playbackService.getAllPlaybackPositions(playlistId);
|
||||
// Failure-propagating on purpose: the store and catalog caches must
|
||||
// not mistake a failed read for an authoritative empty list.
|
||||
return this.playbackService.getAllPlaybackPositionsOrThrow(playlistId);
|
||||
}
|
||||
|
||||
async clearPlaybackPosition(
|
||||
@@ -531,6 +533,26 @@ export class ElectronXtreamDataSource implements IXtreamDataSource {
|
||||
);
|
||||
}
|
||||
|
||||
async savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void> {
|
||||
await this.playbackService.savePlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
}
|
||||
|
||||
async clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<void> {
|
||||
await this.playbackService.clearPlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Cleanup Operations
|
||||
// =========================================================================
|
||||
|
||||
+35
-3
@@ -123,9 +123,9 @@ describe('ElectronXtreamDataSource (user data delegation)', () => {
|
||||
harness.playbackService.getRecentPlaybackPositions.mockResolvedValue(
|
||||
[position]
|
||||
);
|
||||
harness.playbackService.getAllPlaybackPositions.mockResolvedValue([
|
||||
position,
|
||||
]);
|
||||
harness.playbackService.getAllPlaybackPositionsOrThrow.mockResolvedValue(
|
||||
[position]
|
||||
);
|
||||
|
||||
await harness.dataSource.savePlaybackPosition(playlistId, position);
|
||||
expect(
|
||||
@@ -149,9 +149,14 @@ describe('ElectronXtreamDataSource (user data delegation)', () => {
|
||||
harness.playbackService.getRecentPlaybackPositions
|
||||
).toHaveBeenCalledWith(playlistId, 5);
|
||||
|
||||
// The data source uses the failure-propagating read so cache
|
||||
// refreshes cannot mistake a swallowed error for an empty list.
|
||||
await expect(
|
||||
harness.dataSource.getAllPlaybackPositions(playlistId)
|
||||
).resolves.toEqual([position]);
|
||||
expect(
|
||||
harness.playbackService.getAllPlaybackPositionsOrThrow
|
||||
).toHaveBeenCalledWith(playlistId);
|
||||
|
||||
await harness.dataSource.clearPlaybackPosition(
|
||||
playlistId,
|
||||
@@ -162,6 +167,33 @@ describe('ElectronXtreamDataSource (user data delegation)', () => {
|
||||
harness.playbackService.clearPlaybackPosition
|
||||
).toHaveBeenCalledWith(playlistId, 202, 'vod');
|
||||
});
|
||||
|
||||
it('delegates batch playback position writes to the playback service', async () => {
|
||||
const items = [position];
|
||||
const clearItems: {
|
||||
contentXtreamId: number;
|
||||
contentType: 'vod' | 'episode';
|
||||
}[] = [
|
||||
{ contentXtreamId: 202, contentType: 'vod' },
|
||||
{ contentXtreamId: 303, contentType: 'episode' },
|
||||
];
|
||||
|
||||
await harness.dataSource.savePlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
expect(
|
||||
harness.playbackService.savePlaybackPositionsBatch
|
||||
).toHaveBeenCalledWith(playlistId, items);
|
||||
|
||||
await harness.dataSource.clearPlaybackPositionsBatch(
|
||||
playlistId,
|
||||
clearItems
|
||||
);
|
||||
expect(
|
||||
harness.playbackService.clearPlaybackPositionsBatch
|
||||
).toHaveBeenCalledWith(playlistId, clearItems);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanup operations', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { PlaybackPositionData } from '@iptvnator/shared/interfaces';
|
||||
import { PwaXtreamDataSource } from './pwa-xtream-data-source';
|
||||
import {
|
||||
XtreamApiService,
|
||||
@@ -601,4 +602,154 @@ describe('PwaXtreamDataSource', () => {
|
||||
]);
|
||||
expect(apiService.getStreams).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('playback position batches', () => {
|
||||
const storageKey = 'xtream-playback-positions';
|
||||
|
||||
const position = (
|
||||
overrides: Partial<PlaybackPositionData> = {}
|
||||
): PlaybackPositionData => ({
|
||||
contentXtreamId: 100,
|
||||
contentType: 'vod',
|
||||
positionSeconds: 42,
|
||||
durationSeconds: 5400,
|
||||
playlistId: 'playlist-1',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('writes a playback-position batch save as one storage write with upsert semantics', async () => {
|
||||
localStorage.setItem(
|
||||
storageKey,
|
||||
JSON.stringify({
|
||||
'playlist-1': [
|
||||
position({
|
||||
contentXtreamId: 100,
|
||||
contentType: 'episode',
|
||||
positionSeconds: 10,
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
],
|
||||
'playlist-2': [
|
||||
position({
|
||||
playlistId: 'playlist-2',
|
||||
contentXtreamId: 900,
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
],
|
||||
})
|
||||
);
|
||||
const setItemSpy = jest.spyOn(Storage.prototype, 'setItem');
|
||||
|
||||
await dataSource.savePlaybackPositionsBatch('playlist-1', [
|
||||
position({
|
||||
contentXtreamId: 100,
|
||||
contentType: 'episode',
|
||||
positionSeconds: 1200,
|
||||
}),
|
||||
position({
|
||||
contentXtreamId: 101,
|
||||
contentType: 'episode',
|
||||
positionSeconds: 1300,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(setItemSpy).toHaveBeenCalledTimes(1);
|
||||
setItemSpy.mockRestore();
|
||||
|
||||
const stored = JSON.parse(
|
||||
localStorage.getItem(storageKey) || '{}'
|
||||
);
|
||||
const playlistRows = stored[
|
||||
'playlist-1'
|
||||
] as PlaybackPositionData[];
|
||||
expect(playlistRows).toHaveLength(2);
|
||||
|
||||
const replaced = playlistRows.find(
|
||||
(row) => row.contentXtreamId === 100
|
||||
);
|
||||
const appended = playlistRows.find(
|
||||
(row) => row.contentXtreamId === 101
|
||||
);
|
||||
expect(replaced).toEqual(
|
||||
expect.objectContaining({
|
||||
contentType: 'episode',
|
||||
positionSeconds: 1200,
|
||||
})
|
||||
);
|
||||
expect(replaced?.updatedAt).not.toBe('2026-01-01T00:00:00.000Z');
|
||||
// The whole batch is stamped with one shared timestamp.
|
||||
expect(appended?.updatedAt).toBe(replaced?.updatedAt);
|
||||
expect(stored['playlist-2']).toEqual([
|
||||
expect.objectContaining({
|
||||
contentXtreamId: 900,
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('removes only the named rows in a single write on batch clear', async () => {
|
||||
localStorage.setItem(
|
||||
storageKey,
|
||||
JSON.stringify({
|
||||
'playlist-1': [
|
||||
position({
|
||||
contentXtreamId: 100,
|
||||
contentType: 'episode',
|
||||
}),
|
||||
position({
|
||||
contentXtreamId: 101,
|
||||
contentType: 'episode',
|
||||
}),
|
||||
position({ contentXtreamId: 202 }),
|
||||
],
|
||||
'playlist-2': [
|
||||
position({
|
||||
playlistId: 'playlist-2',
|
||||
contentXtreamId: 100,
|
||||
contentType: 'episode',
|
||||
}),
|
||||
],
|
||||
})
|
||||
);
|
||||
const setItemSpy = jest.spyOn(Storage.prototype, 'setItem');
|
||||
|
||||
await dataSource.clearPlaybackPositionsBatch('playlist-1', [
|
||||
{ contentXtreamId: 100, contentType: 'episode' },
|
||||
{ contentXtreamId: 101, contentType: 'episode' },
|
||||
]);
|
||||
|
||||
expect(setItemSpy).toHaveBeenCalledTimes(1);
|
||||
setItemSpy.mockRestore();
|
||||
|
||||
const stored = JSON.parse(
|
||||
localStorage.getItem(storageKey) || '{}'
|
||||
);
|
||||
expect(stored['playlist-1']).toEqual([
|
||||
expect.objectContaining({
|
||||
contentXtreamId: 202,
|
||||
contentType: 'vod',
|
||||
}),
|
||||
]);
|
||||
// Another playlist's row with the same episode key survives.
|
||||
expect(stored['playlist-2']).toEqual([
|
||||
expect.objectContaining({
|
||||
contentXtreamId: 100,
|
||||
contentType: 'episode',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips storage writes for empty batches and missing playlist buckets', async () => {
|
||||
const setItemSpy = jest.spyOn(Storage.prototype, 'setItem');
|
||||
|
||||
await dataSource.savePlaybackPositionsBatch('playlist-1', []);
|
||||
await dataSource.clearPlaybackPositionsBatch('playlist-1', []);
|
||||
await dataSource.clearPlaybackPositionsBatch('playlist-1', [
|
||||
{ contentXtreamId: 100, contentType: 'vod' },
|
||||
]);
|
||||
|
||||
expect(setItemSpy).not.toHaveBeenCalled();
|
||||
setItemSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -727,6 +727,59 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
|
||||
}
|
||||
}
|
||||
|
||||
async savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void> {
|
||||
if (items.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// One blob read + one write for the whole batch — the blob holds
|
||||
// every playlist's positions, so per-item saves would re-serialize
|
||||
// it N times.
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
const playlistPositions = allPositions[playlistId] ?? [];
|
||||
const updatedAt = new Date().toISOString();
|
||||
|
||||
const replacedKeys = new Set(
|
||||
items.map((item) => `${item.contentType}_${item.contentXtreamId}`)
|
||||
);
|
||||
allPositions[playlistId] = [
|
||||
...playlistPositions.filter(
|
||||
(p) =>
|
||||
!replacedKeys.has(`${p.contentType}_${p.contentXtreamId}`)
|
||||
),
|
||||
...items.map((item) => ({ ...item, updatedAt })),
|
||||
];
|
||||
|
||||
this.savePlaybackPositionsToStorage(allPositions);
|
||||
}
|
||||
|
||||
async clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<void> {
|
||||
if (items.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
const playlistPositions = allPositions[playlistId];
|
||||
if (!playlistPositions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const removedKeys = new Set(
|
||||
items.map((item) => `${item.contentType}_${item.contentXtreamId}`)
|
||||
);
|
||||
allPositions[playlistId] = playlistPositions.filter(
|
||||
(p) => !removedKeys.has(`${p.contentType}_${p.contentXtreamId}`)
|
||||
);
|
||||
|
||||
this.savePlaybackPositionsToStorage(allPositions);
|
||||
}
|
||||
|
||||
private getPlaybackPositionsFromStorage(): Record<
|
||||
string,
|
||||
PlaybackPositionData[]
|
||||
|
||||
@@ -430,6 +430,24 @@ export interface IXtreamDataSource {
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Save/update many playback positions at once (season-level "mark as
|
||||
* watched"). Rejects when nothing was persisted.
|
||||
*/
|
||||
savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Clear many playback positions at once (season-level "mark as
|
||||
* unwatched"). Rejects when nothing was cleared.
|
||||
*/
|
||||
clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<void>;
|
||||
|
||||
// =========================================================================
|
||||
// Cleanup Operations
|
||||
// =========================================================================
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { signalStore } from '@ngrx/signals';
|
||||
import { PlaybackPositionRuntimeBridgeService } from '@iptvnator/services';
|
||||
import type { PlaybackPositionData } from '@iptvnator/shared/interfaces';
|
||||
import { XTREAM_DATA_SOURCE } from '../../data-sources/xtream-data-source.interface';
|
||||
import { withPlaybackPositions } from './with-playback-positions.feature';
|
||||
|
||||
function position(
|
||||
contentXtreamId: number,
|
||||
playlistId: string
|
||||
): PlaybackPositionData {
|
||||
return {
|
||||
contentXtreamId,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 7,
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 1,
|
||||
positionSeconds: 50,
|
||||
durationSeconds: 100,
|
||||
playlistId,
|
||||
};
|
||||
}
|
||||
|
||||
describe('withPlaybackPositions', () => {
|
||||
const TestStore = signalStore(
|
||||
{ providedIn: 'root' },
|
||||
withPlaybackPositions()
|
||||
);
|
||||
const getAllPlaybackPositions = jest.fn();
|
||||
|
||||
function createStore() {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: XTREAM_DATA_SOURCE,
|
||||
useValue: { getAllPlaybackPositions },
|
||||
},
|
||||
{
|
||||
provide: PlaybackPositionRuntimeBridgeService,
|
||||
useValue: {
|
||||
onPlaybackPositionUpdate: jest
|
||||
.fn()
|
||||
.mockReturnValue(jest.fn()),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return TestBed.inject(TestStore);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
getAllPlaybackPositions.mockReset();
|
||||
});
|
||||
|
||||
it('loads positions into the store maps', async () => {
|
||||
getAllPlaybackPositions.mockResolvedValue([position(11, 'playlist-a')]);
|
||||
const store = createStore();
|
||||
|
||||
await store.loadAllPositions('playlist-a');
|
||||
|
||||
expect(store.playbackPositions().get('episode_11')).toBeDefined();
|
||||
expect(store.hasSeriesProgress(7)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the cached maps when a refresh read fails', async () => {
|
||||
getAllPlaybackPositions.mockResolvedValueOnce([
|
||||
position(11, 'playlist-a'),
|
||||
]);
|
||||
const store = createStore();
|
||||
await store.loadAllPositions('playlist-a');
|
||||
|
||||
getAllPlaybackPositions.mockRejectedValueOnce(new Error('ipc down'));
|
||||
await expect(store.loadAllPositions('playlist-a')).rejects.toThrow(
|
||||
'ipc down'
|
||||
);
|
||||
|
||||
expect(store.playbackPositions().get('episode_11')).toBeDefined();
|
||||
expect(store.hasSeriesProgress(7)).toBe(true);
|
||||
});
|
||||
|
||||
it('discards a superseded load so a late result cannot overwrite the newer playlist', async () => {
|
||||
let resolveFirst!: (rows: PlaybackPositionData[]) => void;
|
||||
getAllPlaybackPositions
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<PlaybackPositionData[]>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce([position(22, 'playlist-b')]);
|
||||
const store = createStore();
|
||||
|
||||
const stale = store.loadAllPositions('playlist-a');
|
||||
await store.loadAllPositions('playlist-b');
|
||||
|
||||
resolveFirst([position(11, 'playlist-a')]);
|
||||
await stale;
|
||||
|
||||
expect(store.playbackPositions().has('episode_11')).toBe(false);
|
||||
expect(store.playbackPositions().get('episode_22')).toBeDefined();
|
||||
});
|
||||
});
|
||||
+10
-130
@@ -6,7 +6,6 @@ import {
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { XtreamSerieEpisode } from '@iptvnator/shared/interfaces';
|
||||
import { PlaybackPositionRuntimeBridgeService } from '@iptvnator/services';
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
@@ -23,36 +22,6 @@ const initialState: PlaybackPositionsState = {
|
||||
seriesPositions: new Map(),
|
||||
};
|
||||
|
||||
function parseDuration(duration: string | number): number {
|
||||
if (typeof duration === 'number') return duration;
|
||||
if (!duration) return 0;
|
||||
|
||||
// Check for "min" format (e.g. "45 min")
|
||||
const minMatch = duration.match(/(\d+)\s*min/);
|
||||
if (minMatch) {
|
||||
return parseInt(minMatch[1], 10) * 60;
|
||||
}
|
||||
|
||||
// Check for "h:m:s" or "m:s" format
|
||||
if (duration.includes(':')) {
|
||||
const parts = duration.split(':').map((p) => parseInt(p, 10));
|
||||
if (parts.length === 3) {
|
||||
return parts[0] * 3600 + parts[1] * 60 + parts[2];
|
||||
} else if (parts.length === 2) {
|
||||
return parts[0] * 60 + parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try parsing as simple number (seconds or minutes? assume minutes if < 1000, seconds otherwise?)
|
||||
// Xtream usually returns seconds or "min" string
|
||||
const num = parseInt(duration, 10);
|
||||
if (!isNaN(num)) {
|
||||
return num;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function withPlaybackPositions() {
|
||||
return signalStoreFeature(
|
||||
withState(initialState),
|
||||
@@ -63,6 +32,12 @@ export function withPlaybackPositions() {
|
||||
const getPositionKey = (type: string, id: number) =>
|
||||
`${type}_${id}`;
|
||||
|
||||
// Latest-load-wins: a load that was superseded while its fetch
|
||||
// was in flight must not patch the store — after a playlist
|
||||
// switch the late result would overwrite the new playlist's
|
||||
// position maps with the old playlist's rows.
|
||||
let positionsLoadGeneration = 0;
|
||||
|
||||
return {
|
||||
/**
|
||||
* Get progress percentage for display (0-100)
|
||||
@@ -125,8 +100,12 @@ export function withPlaybackPositions() {
|
||||
* Load all playback positions for the playlist (for grid view)
|
||||
*/
|
||||
async loadAllPositions(playlistId: string): Promise<void> {
|
||||
const generation = ++positionsLoadGeneration;
|
||||
const positions =
|
||||
await dataSource.getAllPlaybackPositions(playlistId);
|
||||
if (generation !== positionsLoadGeneration) {
|
||||
return;
|
||||
}
|
||||
|
||||
const positionsMap = new Map<
|
||||
string,
|
||||
@@ -235,105 +214,6 @@ export function withPlaybackPositions() {
|
||||
updated.set(key, data);
|
||||
patchState(store, { playbackPositions: updated });
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle watched status for an episode
|
||||
*/
|
||||
async toggleEpisodeWatched(
|
||||
playlistId: string,
|
||||
episode: XtreamSerieEpisode,
|
||||
seriesId: number
|
||||
): Promise<void> {
|
||||
const id = Number(episode.id);
|
||||
const isWatched = this.isWatched(id, 'episode');
|
||||
|
||||
if (isWatched) {
|
||||
// Mark as unwatched
|
||||
await dataSource.clearPlaybackPosition(
|
||||
playlistId,
|
||||
id,
|
||||
'episode'
|
||||
);
|
||||
// Update state (remove from map)
|
||||
const key = getPositionKey('episode', id);
|
||||
const updated = new Map(store.playbackPositions());
|
||||
updated.delete(key);
|
||||
|
||||
// Update series map
|
||||
const seriesMap = new Map(store.seriesPositions());
|
||||
const seriesEpisodes = seriesMap.get(seriesId) || [];
|
||||
const filteredEpisodes = seriesEpisodes.filter(
|
||||
(p) => p.contentXtreamId !== id
|
||||
);
|
||||
if (filteredEpisodes.length === 0) {
|
||||
seriesMap.delete(seriesId);
|
||||
} else {
|
||||
seriesMap.set(seriesId, filteredEpisodes);
|
||||
}
|
||||
|
||||
patchState(store, {
|
||||
playbackPositions: updated,
|
||||
seriesPositions: seriesMap,
|
||||
});
|
||||
} else {
|
||||
// Mark as watched
|
||||
let duration = 0;
|
||||
const info = Array.isArray(episode.info)
|
||||
? null
|
||||
: episode.info;
|
||||
|
||||
if (info?.duration_secs) {
|
||||
duration = info.duration_secs;
|
||||
} else if (info?.duration) {
|
||||
duration = parseDuration(info.duration);
|
||||
}
|
||||
|
||||
if (duration === 0) duration = 1; // Fallback
|
||||
|
||||
// Setting position = duration indicates episode is fully watched
|
||||
const data: PlaybackPositionData = {
|
||||
contentXtreamId: id,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: seriesId,
|
||||
seasonNumber: Number(episode.season),
|
||||
episodeNumber: Number(episode.episode_num),
|
||||
positionSeconds: duration,
|
||||
durationSeconds: duration,
|
||||
playlistId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
// Use existing savePosition to handle state update and persistence
|
||||
// But we also need to update seriesPositions map which savePosition doesn't do for individual updates
|
||||
// actually savePosition only updates playbackPositions map.
|
||||
// We should probably update savePosition to also update series map, or do it here.
|
||||
// Let's do it here to be safe.
|
||||
|
||||
await dataSource.savePlaybackPosition(playlistId, data);
|
||||
|
||||
const key = getPositionKey('episode', id);
|
||||
const updated = new Map(store.playbackPositions());
|
||||
updated.set(key, data);
|
||||
|
||||
const seriesMap = new Map(store.seriesPositions());
|
||||
const seriesEpisodes = seriesMap.get(seriesId) || [];
|
||||
// Check if already exists
|
||||
const existingIdx = seriesEpisodes.findIndex(
|
||||
(p) => p.contentXtreamId === id
|
||||
);
|
||||
if (existingIdx >= 0) {
|
||||
seriesEpisodes[existingIdx] = data;
|
||||
} else {
|
||||
seriesEpisodes.push(data);
|
||||
}
|
||||
seriesMap.set(seriesId, seriesEpisodes);
|
||||
|
||||
patchState(store, {
|
||||
playbackPositions: updated,
|
||||
seriesPositions: seriesMap,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
|
||||
+36
@@ -110,6 +110,42 @@ describe('SerialDetailsPlaybackPositionState', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('bulk mutators', () => {
|
||||
it('updates many positions with a single map replacement', async () => {
|
||||
await loadPositions([position(1001)]);
|
||||
const before = state.positions();
|
||||
|
||||
state.updateMany([
|
||||
position(1002, { episodeNumber: 2 }),
|
||||
position(2001, { seasonNumber: 2 }),
|
||||
]);
|
||||
|
||||
expect(state.positions()).not.toBe(before);
|
||||
expect(state.positions().size).toBe(3);
|
||||
expect(state.positions().get(1002)?.episodeNumber).toBe(2);
|
||||
|
||||
state.updateMany([]);
|
||||
expect(state.positions().size).toBe(3);
|
||||
});
|
||||
|
||||
it('removes many positions and keeps the rest', async () => {
|
||||
await loadPositions([
|
||||
position(1001),
|
||||
position(1002),
|
||||
position(2001),
|
||||
]);
|
||||
|
||||
state.removeMany([1001, 2001]);
|
||||
|
||||
expect(state.positions().size).toBe(1);
|
||||
expect(state.positions().has(1002)).toBe(true);
|
||||
|
||||
const current = state.positions();
|
||||
state.removeMany([]);
|
||||
expect(state.positions()).toBe(current);
|
||||
});
|
||||
});
|
||||
|
||||
describe('takeResumeEpisode', () => {
|
||||
it('rejects targets before positions finish loading', () => {
|
||||
expect(
|
||||
|
||||
+22
@@ -117,12 +117,34 @@ export class SerialDetailsPlaybackPositionState {
|
||||
this.positions.set(updated);
|
||||
}
|
||||
|
||||
updateMany(positions: PlaybackPositionData[]): void {
|
||||
if (positions.length === 0) {
|
||||
return;
|
||||
}
|
||||
const updated = new Map(this.positions());
|
||||
for (const position of positions) {
|
||||
updated.set(position.contentXtreamId, position);
|
||||
}
|
||||
this.positions.set(updated);
|
||||
}
|
||||
|
||||
remove(contentXtreamId: number): void {
|
||||
const updated = new Map(this.positions());
|
||||
updated.delete(contentXtreamId);
|
||||
this.positions.set(updated);
|
||||
}
|
||||
|
||||
removeMany(contentXtreamIds: number[]): void {
|
||||
if (contentXtreamIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const updated = new Map(this.positions());
|
||||
for (const contentXtreamId of contentXtreamIds) {
|
||||
updated.delete(contentXtreamId);
|
||||
}
|
||||
this.positions.set(updated);
|
||||
}
|
||||
|
||||
async recordExternalLaunch(
|
||||
playback: ResolvedPortalPlayback,
|
||||
launch: Promise<ExternalPlayerSession | void>,
|
||||
|
||||
+54
-8
@@ -25,7 +25,10 @@ import {
|
||||
XtreamSerieDetails,
|
||||
XtreamSerieEpisode,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { SeasonContainerPlaybackToggleRequest } from '@iptvnator/ui/components';
|
||||
import {
|
||||
SeasonContainerPlaybackToggleRequest,
|
||||
SeasonContainerSeasonPlaybackToggleRequest,
|
||||
} from '@iptvnator/ui/components';
|
||||
import {
|
||||
getSeriesEpisodeMetadata,
|
||||
getSeriesPlaybackNavigation,
|
||||
@@ -35,6 +38,7 @@ import {
|
||||
} from '@iptvnator/ui/playback';
|
||||
import { XTREAM_SERIES_RESUME_TARGET } from './serial-details-resume-target.token';
|
||||
import { SerialDetailsPlaybackPositionState } from './serial-details-playback-position-state';
|
||||
import { SerialDetailsSeasonWatchService } from './serial-details-season-watch.service';
|
||||
|
||||
export type XtreamSerieDetailsView = XtreamSerieDetails & {
|
||||
readonly series_id: number;
|
||||
@@ -60,6 +64,7 @@ export class SerialDetailsPlaybackService {
|
||||
private readonly portalPlayer = inject(PORTAL_PLAYER);
|
||||
private readonly externalPlayback = inject(PORTAL_EXTERNAL_PLAYBACK);
|
||||
private readonly resumeTarget = inject(XTREAM_SERIES_RESUME_TARGET);
|
||||
private readonly seasonWatch = inject(SerialDetailsSeasonWatchService);
|
||||
|
||||
private readonly bindings = signal<SerialDetailsPlaybackBindings | null>(
|
||||
null
|
||||
@@ -77,6 +82,7 @@ export class SerialDetailsPlaybackService {
|
||||
readonly episodePlaybackPositions = this.playbackPositionState.positions;
|
||||
readonly openingEpisodeId = signal<number | null>(null);
|
||||
readonly activeEpisodeId = signal<number | null>(null);
|
||||
readonly seasonWatchBatchRunning = this.seasonWatch.batchRunning;
|
||||
|
||||
readonly quickStartAction = computed(() => {
|
||||
const item = this.selectedItem();
|
||||
@@ -326,15 +332,55 @@ export class SerialDetailsPlaybackService {
|
||||
request.nextPosition
|
||||
);
|
||||
this.playbackPositionState.update(request.nextPosition);
|
||||
} else {
|
||||
await this.playbackPositions.clearPlaybackPosition(
|
||||
playlistId,
|
||||
request.contentXtreamId,
|
||||
'episode'
|
||||
);
|
||||
this.playbackPositionState.remove(request.contentXtreamId);
|
||||
}
|
||||
await this.refreshStorePositions(playlistId);
|
||||
}
|
||||
|
||||
async handleSeasonPlaybackToggleRequested(
|
||||
request: SeasonContainerSeasonPlaybackToggleRequest
|
||||
): Promise<void> {
|
||||
const playlistId = this.currentPlaylistId();
|
||||
const seriesXtreamId = Number(this.selectedItem()?.series_id ?? 0);
|
||||
const persisted = await this.seasonWatch.handle(
|
||||
request,
|
||||
playlistId,
|
||||
this.playbackPositionState,
|
||||
() =>
|
||||
this.currentPlaylistId() === playlistId &&
|
||||
Number(this.selectedItem()?.series_id ?? 0) === seriesXtreamId
|
||||
);
|
||||
if (persisted) {
|
||||
await this.refreshStorePositions(playlistId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog reads series progress from XtreamStore, whose positions
|
||||
* load once per playlist (XtreamCatalogFacadeService.initialize), so a
|
||||
* toggle must push the change back or badges go stale on return. Skipped
|
||||
* after a playlist switch — the store then holds the other playlist.
|
||||
*/
|
||||
private async refreshStorePositions(playlistId: string): Promise<void> {
|
||||
if (this.currentPlaylistId() !== playlistId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.playbackPositions.clearPlaybackPosition(
|
||||
playlistId,
|
||||
request.contentXtreamId,
|
||||
'episode'
|
||||
);
|
||||
this.playbackPositionState.remove(request.contentXtreamId);
|
||||
try {
|
||||
await this.xtreamStore.loadAllPositions(playlistId);
|
||||
} catch (error) {
|
||||
// The toggle itself succeeded; a failed refresh keeps the store
|
||||
// populated-but-stale, which beats wiping it with a bad read.
|
||||
console.warn(
|
||||
'[SerialDetailsPlayback] Store position refresh failed',
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async loadSeriesPlaybackPositions(
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { PORTAL_PLAYBACK_POSITIONS } from '@iptvnator/portal/shared/util';
|
||||
import { PlaybackPositionData } from '@iptvnator/shared/interfaces';
|
||||
import { SeasonContainerSeasonPlaybackToggleRequest } from '@iptvnator/ui/components';
|
||||
import { SerialDetailsPlaybackPositionState } from './serial-details-playback-position-state';
|
||||
|
||||
/**
|
||||
* Season-level bulk watched toggle for the serial details view: one batch
|
||||
* persistence call, host state update, and user feedback.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SerialDetailsSeasonWatchService {
|
||||
private readonly playbackPositions = inject(PORTAL_PLAYBACK_POSITIONS);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly translate = inject(TranslateService);
|
||||
|
||||
readonly batchRunning = signal(false);
|
||||
|
||||
async handle(
|
||||
request: SeasonContainerSeasonPlaybackToggleRequest,
|
||||
playlistId: string,
|
||||
state: Pick<
|
||||
SerialDetailsPlaybackPositionState,
|
||||
'updateMany' | 'removeMany'
|
||||
>,
|
||||
// The component is reused across detail navigations and resets the
|
||||
// position state for the next series while a batch may still be in
|
||||
// flight; a stale completion must not write the old series' rows
|
||||
// into it (episode ids can collide across playlists) nor present
|
||||
// its contextless snackbar as feedback about the newly opened page.
|
||||
// The DB write itself is safe — it carries its own playlistId.
|
||||
stillCurrent: () => boolean
|
||||
): Promise<boolean> {
|
||||
if (!playlistId || request.requests.length === 0 || this.batchRunning()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.batchRunning.set(true);
|
||||
try {
|
||||
if (request.markWatched) {
|
||||
const positions = request.requests
|
||||
.map((item) => item.nextPosition)
|
||||
.filter(
|
||||
(position): position is PlaybackPositionData =>
|
||||
position !== null
|
||||
);
|
||||
await this.playbackPositions.savePlaybackPositionsBatch(
|
||||
playlistId,
|
||||
positions
|
||||
);
|
||||
if (!stillCurrent()) {
|
||||
return true;
|
||||
}
|
||||
state.updateMany(positions);
|
||||
this.notify('XTREAM.SEASON_MARKED_WATCHED', {
|
||||
count: positions.length,
|
||||
});
|
||||
} else {
|
||||
await this.playbackPositions.clearPlaybackPositionsBatch(
|
||||
playlistId,
|
||||
request.requests.map((item) => ({
|
||||
contentXtreamId: item.contentXtreamId,
|
||||
contentType: 'episode' as const,
|
||||
}))
|
||||
);
|
||||
if (!stillCurrent()) {
|
||||
return true;
|
||||
}
|
||||
state.removeMany(
|
||||
request.requests.map((item) => item.contentXtreamId)
|
||||
);
|
||||
this.notify('XTREAM.SEASON_MARKED_UNWATCHED');
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
// Nothing was confirmed persisted — keep the rendered state and
|
||||
// report instead of showing episodes as (un)watched.
|
||||
console.error(
|
||||
'[SerialDetailsSeasonWatch] Season watched toggle failed',
|
||||
error
|
||||
);
|
||||
if (stillCurrent()) {
|
||||
this.notify('XTREAM.SEASON_WATCH_UPDATE_FAILED');
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
this.batchRunning.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private notify(key: string, params?: object): void {
|
||||
this.snackBar.open(this.translate.instant(key, params), undefined, {
|
||||
duration: 5000,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -215,8 +215,12 @@
|
||||
inlinePlayback()?.contentInfo?.contentXtreamId ?? null
|
||||
"
|
||||
[seasonDescriptions]="seasonDescriptions()"
|
||||
[seasonWatchBatchRunning]="seasonWatchBatchRunning()"
|
||||
(episodeClicked)="playEpisode($event)"
|
||||
(playbackToggleRequested)="handlePlaybackToggleRequested($event)"
|
||||
(seasonPlaybackToggleRequested)="
|
||||
handleSeasonPlaybackToggleRequested($event)
|
||||
"
|
||||
(seasonSelected)="onSeasonSelected($event)"
|
||||
/>
|
||||
|
||||
|
||||
@@ -45,8 +45,10 @@ class StubSeasonContainerComponent {
|
||||
readonly activeEpisodeId = input<number | null>(null);
|
||||
readonly playingEpisodeId = input<number | null>(null);
|
||||
readonly seasonDescriptions = input<unknown>(null);
|
||||
readonly seasonWatchBatchRunning = input(false);
|
||||
readonly episodeClicked = output<unknown>();
|
||||
readonly playbackToggleRequested = output<unknown>();
|
||||
readonly seasonPlaybackToggleRequested = output<unknown>();
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -103,6 +105,9 @@ describe('SerialDetailsComponent', () => {
|
||||
const openExternalPlayback = jest.fn();
|
||||
const savePlaybackPosition = jest.fn();
|
||||
const clearPlaybackPosition = jest.fn();
|
||||
const savePlaybackPositionsBatch = jest.fn();
|
||||
const clearPlaybackPositionsBatch = jest.fn();
|
||||
const loadAllPositions = jest.fn();
|
||||
const isEmbeddedPlayer = jest.fn();
|
||||
const getSeriesPlaybackPositions = jest.fn().mockResolvedValue([]);
|
||||
let positionUpdateCallback: ((data: PlaybackPositionData) => void) | null =
|
||||
@@ -174,6 +179,12 @@ describe('SerialDetailsComponent', () => {
|
||||
savePlaybackPosition.mockResolvedValue(undefined);
|
||||
clearPlaybackPosition.mockReset();
|
||||
clearPlaybackPosition.mockResolvedValue(undefined);
|
||||
savePlaybackPositionsBatch.mockReset();
|
||||
savePlaybackPositionsBatch.mockResolvedValue(undefined);
|
||||
clearPlaybackPositionsBatch.mockReset();
|
||||
clearPlaybackPositionsBatch.mockResolvedValue(undefined);
|
||||
loadAllPositions.mockReset();
|
||||
loadAllPositions.mockResolvedValue(undefined);
|
||||
positionUpdateCallback = null;
|
||||
isEmbeddedPlayer.mockReset();
|
||||
isEmbeddedPlayer.mockReturnValue(false);
|
||||
@@ -219,6 +230,7 @@ describe('SerialDetailsComponent', () => {
|
||||
constructEpisodeStreamUrl,
|
||||
addRecentItem,
|
||||
backfillContentMetadata: jest.fn(),
|
||||
loadAllPositions,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -233,6 +245,8 @@ describe('SerialDetailsComponent', () => {
|
||||
getSeriesPlaybackPositions,
|
||||
savePlaybackPosition,
|
||||
clearPlaybackPosition,
|
||||
savePlaybackPositionsBatch,
|
||||
clearPlaybackPositionsBatch,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -890,6 +904,183 @@ describe('SerialDetailsComponent', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('marks a season watched through one batch save and updates rendered positions', async () => {
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
const playbackService = fixture.debugElement.injector.get(
|
||||
SerialDetailsPlaybackService
|
||||
);
|
||||
const snackBar = TestBed.inject(MatSnackBar);
|
||||
const seasonPosition = (contentXtreamId: number, episodeNumber: number) => ({
|
||||
playlistId: 'xtream-1',
|
||||
contentXtreamId,
|
||||
contentType: 'episode' as const,
|
||||
seriesXtreamId: 103,
|
||||
seasonNumber: 1,
|
||||
episodeNumber,
|
||||
positionSeconds: 1200,
|
||||
durationSeconds: 1200,
|
||||
});
|
||||
|
||||
await playbackService.handleSeasonPlaybackToggleRequested({
|
||||
seasonKey: '1',
|
||||
markWatched: true,
|
||||
requests: [
|
||||
{ contentXtreamId: 1001, nextPosition: seasonPosition(1001, 1) },
|
||||
{ contentXtreamId: 1002, nextPosition: seasonPosition(1002, 2) },
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(savePlaybackPositionsBatch).toHaveBeenCalledTimes(1);
|
||||
expect(savePlaybackPositionsBatch).toHaveBeenCalledWith('xtream-1', [
|
||||
expect.objectContaining({ contentXtreamId: 1001 }),
|
||||
expect.objectContaining({ contentXtreamId: 1002 }),
|
||||
]);
|
||||
expect(savePlaybackPosition).not.toHaveBeenCalled();
|
||||
expect(
|
||||
playbackService.episodePlaybackPositions().get(1001)
|
||||
).toEqual(expect.objectContaining({ positionSeconds: 1200 }));
|
||||
expect(
|
||||
playbackService.episodePlaybackPositions().get(1002)
|
||||
).toBeDefined();
|
||||
expect(snackBar.open).toHaveBeenCalledWith(
|
||||
'XTREAM.SEASON_MARKED_WATCHED',
|
||||
undefined,
|
||||
{ duration: 5000 }
|
||||
);
|
||||
// The catalog badge source must follow the batch.
|
||||
expect(loadAllPositions).toHaveBeenCalledWith('xtream-1');
|
||||
expect(playbackService.seasonWatchBatchRunning()).toBe(false);
|
||||
});
|
||||
|
||||
it('unwatches a season through one batch clear', async () => {
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
const playbackService = fixture.debugElement.injector.get(
|
||||
SerialDetailsPlaybackService
|
||||
);
|
||||
await playbackService.handleSeasonPlaybackToggleRequested({
|
||||
seasonKey: '1',
|
||||
markWatched: false,
|
||||
requests: [
|
||||
{ contentXtreamId: 1001, nextPosition: null },
|
||||
{ contentXtreamId: 1002, nextPosition: null },
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(clearPlaybackPositionsBatch).toHaveBeenCalledTimes(1);
|
||||
expect(clearPlaybackPositionsBatch).toHaveBeenCalledWith('xtream-1', [
|
||||
{ contentXtreamId: 1001, contentType: 'episode' },
|
||||
{ contentXtreamId: 1002, contentType: 'episode' },
|
||||
]);
|
||||
expect(clearPlaybackPosition).not.toHaveBeenCalled();
|
||||
expect(playbackService.episodePlaybackPositions().has(1001)).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('does not write a stale season batch into another playlist state', async () => {
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
let resolveBatch!: () => void;
|
||||
savePlaybackPositionsBatch.mockImplementation(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveBatch = resolve;
|
||||
})
|
||||
);
|
||||
const playbackService = fixture.debugElement.injector.get(
|
||||
SerialDetailsPlaybackService
|
||||
);
|
||||
const pending = playbackService.handleSeasonPlaybackToggleRequested({
|
||||
seasonKey: '1',
|
||||
markWatched: true,
|
||||
requests: [
|
||||
{
|
||||
contentXtreamId: 1001,
|
||||
nextPosition: {
|
||||
playlistId: 'xtream-1',
|
||||
contentXtreamId: 1001,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 103,
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 1,
|
||||
positionSeconds: 1200,
|
||||
durationSeconds: 1200,
|
||||
},
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
|
||||
// The user navigates to another playlist while the batch is pending.
|
||||
const initialPlaylist = currentPlaylist();
|
||||
currentPlaylist.set({ ...initialPlaylist, id: 'xtream-2' });
|
||||
resolveBatch();
|
||||
await pending;
|
||||
|
||||
expect(savePlaybackPositionsBatch).toHaveBeenCalledWith(
|
||||
'xtream-1',
|
||||
expect.anything()
|
||||
);
|
||||
expect(playbackService.episodePlaybackPositions().has(1001)).toBe(
|
||||
false
|
||||
);
|
||||
expect(TestBed.inject(MatSnackBar).open).not.toHaveBeenCalled();
|
||||
// The store now belongs to the other playlist — no stale refresh.
|
||||
expect(loadAllPositions).not.toHaveBeenCalled();
|
||||
expect(playbackService.seasonWatchBatchRunning()).toBe(false);
|
||||
currentPlaylist.set(initialPlaylist);
|
||||
});
|
||||
|
||||
it('keeps rendered positions and reports the error when the season batch fails', async () => {
|
||||
const consoleError = jest
|
||||
.spyOn(console, 'error')
|
||||
.mockImplementation(() => undefined);
|
||||
savePlaybackPositionsBatch.mockRejectedValue(
|
||||
new Error('batch failed')
|
||||
);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
const playbackService = fixture.debugElement.injector.get(
|
||||
SerialDetailsPlaybackService
|
||||
);
|
||||
const snackBar = TestBed.inject(MatSnackBar);
|
||||
await playbackService.handleSeasonPlaybackToggleRequested({
|
||||
seasonKey: '1',
|
||||
markWatched: true,
|
||||
requests: [
|
||||
{
|
||||
contentXtreamId: 1001,
|
||||
nextPosition: {
|
||||
playlistId: 'xtream-1',
|
||||
contentXtreamId: 1001,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 103,
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 1,
|
||||
positionSeconds: 1200,
|
||||
durationSeconds: 1200,
|
||||
},
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(playbackService.episodePlaybackPositions().has(1001)).toBe(
|
||||
false
|
||||
);
|
||||
expect(snackBar.open).toHaveBeenCalledWith(
|
||||
'XTREAM.SEASON_WATCH_UPDATE_FAILED',
|
||||
undefined,
|
||||
{ duration: 5000 }
|
||||
);
|
||||
expect(playbackService.seasonWatchBatchRunning()).toBe(false);
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it('passes inline episode metadata and autoplays only inside the current season', async () => {
|
||||
isEmbeddedPlayer.mockReturnValue(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
ViewInPortalActionComponent,
|
||||
SeasonContainerComponent,
|
||||
SeasonContainerPlaybackToggleRequest,
|
||||
SeasonContainerSeasonPlaybackToggleRequest,
|
||||
} from '@iptvnator/ui/components';
|
||||
import type { SeasonEpisodeDownloadAdapter } from '@iptvnator/portal/shared/data-access';
|
||||
import {
|
||||
@@ -52,6 +53,7 @@ import {
|
||||
SerialDetailsPlaybackService,
|
||||
type XtreamSerieDetailsView,
|
||||
} from './serial-details-playback.service';
|
||||
import { SerialDetailsSeasonWatchService } from './serial-details-season-watch.service';
|
||||
import {
|
||||
SimilarCatalogItem,
|
||||
matchRecommendationsToCatalog,
|
||||
@@ -76,7 +78,7 @@ import { createSerialPlaybackSessionKey } from './serial-playback-session-key';
|
||||
}
|
||||
`,
|
||||
],
|
||||
providers: [SerialDetailsPlaybackService],
|
||||
providers: [SerialDetailsPlaybackService, SerialDetailsSeasonWatchService],
|
||||
imports: [
|
||||
DetailActionsTemplateDirective,
|
||||
DetailMetaTemplateDirective,
|
||||
@@ -154,6 +156,7 @@ export class SerialDetailsComponent implements OnInit, OnDestroy {
|
||||
readonly inlinePlayback = this.playback.inlinePlayback;
|
||||
readonly episodePlaybackPositions = this.playback.episodePlaybackPositions;
|
||||
readonly openingEpisodeId = this.playback.openingEpisodeId;
|
||||
readonly seasonWatchBatchRunning = this.playback.seasonWatchBatchRunning;
|
||||
readonly activeEpisodeId = this.playback.activeEpisodeId;
|
||||
readonly quickStartAction = this.playback.quickStartAction;
|
||||
readonly inlineEpisodeMetadata = this.playback.inlineEpisodeMetadata;
|
||||
@@ -388,6 +391,12 @@ export class SerialDetailsComponent implements OnInit, OnDestroy {
|
||||
return this.playback.handlePlaybackToggleRequested(request);
|
||||
}
|
||||
|
||||
handleSeasonPlaybackToggleRequested(
|
||||
request: SeasonContainerSeasonPlaybackToggleRequest
|
||||
): Promise<void> {
|
||||
return this.playback.handleSeasonPlaybackToggleRequested(request);
|
||||
}
|
||||
|
||||
toggleFavorite(): void {
|
||||
const playlist = this.xtreamStore.currentPlaylist();
|
||||
if (!playlist) {
|
||||
|
||||
@@ -60,7 +60,7 @@ describe('XtreamCatalogFacadeService', () => {
|
||||
contentSortMode,
|
||||
minRating,
|
||||
currentPlaylist,
|
||||
loadAllPositions: jest.fn(),
|
||||
loadAllPositions: jest.fn().mockResolvedValue(undefined),
|
||||
setCategorySearchTerm: jest.fn(),
|
||||
setSelectedItem: jest.fn((item: Record<string, unknown> | null) => {
|
||||
selectedItem.set(item);
|
||||
|
||||
@@ -85,7 +85,11 @@ export class XtreamCatalogFacadeService implements PortalCatalogFacade<
|
||||
const playlistId = this.xtreamStore.currentPlaylist()?.id;
|
||||
if (playlistId && this.loadedPositionsPlaylistId !== playlistId) {
|
||||
this.loadedPositionsPlaylistId = playlistId;
|
||||
this.xtreamStore.loadAllPositions(playlistId);
|
||||
// A failed initial load leaves the maps empty (same as before);
|
||||
// the read now rejects instead of masquerading as empty.
|
||||
void this.xtreamStore.loadAllPositions(playlistId).catch(() => {
|
||||
this.loadedPositionsPlaylistId = null;
|
||||
});
|
||||
}
|
||||
|
||||
this.clearSelectedItem();
|
||||
|
||||
@@ -7,6 +7,23 @@ import { PlaybackPositionData } from '@iptvnator/shared/interfaces';
|
||||
import { RuntimeCapabilitiesService } from './runtime-capabilities.service';
|
||||
import { PlaybackPositionRuntimeBridgeService } from './playback-position-runtime-bridge.service';
|
||||
|
||||
const batchSaveItems: PlaybackPositionData[] = [
|
||||
createPosition(),
|
||||
createPosition({
|
||||
contentXtreamId: 101,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 200,
|
||||
}),
|
||||
];
|
||||
|
||||
const batchClearItems: {
|
||||
contentXtreamId: number;
|
||||
contentType: 'vod' | 'episode';
|
||||
}[] = [
|
||||
{ contentXtreamId: 100, contentType: 'vod' },
|
||||
{ contentXtreamId: 101, contentType: 'episode' },
|
||||
];
|
||||
|
||||
describe('PlaybackPositionRuntimeBridgeService', () => {
|
||||
let service: PlaybackPositionRuntimeBridgeService;
|
||||
let injector: DestroyableInjector;
|
||||
@@ -323,6 +340,108 @@ describe('PlaybackPositionRuntimeBridgeService', () => {
|
||||
await expect(operation.invokeLenient(service)).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([
|
||||
{
|
||||
name: 'batch save',
|
||||
items: batchSaveItems as unknown[],
|
||||
installBridge: (implementation: jest.Mock) => {
|
||||
window.electron = {
|
||||
...window.electron,
|
||||
dbSavePlaybackPositionsBatch: implementation,
|
||||
} as unknown as typeof window.electron;
|
||||
},
|
||||
invoke: (target: PlaybackPositionRuntimeBridgeService) =>
|
||||
target.savePlaybackPositionsBatch(
|
||||
'playlist-1',
|
||||
batchSaveItems
|
||||
),
|
||||
invokeEmpty: (target: PlaybackPositionRuntimeBridgeService) =>
|
||||
target.savePlaybackPositionsBatch('playlist-1', []),
|
||||
},
|
||||
{
|
||||
name: 'batch clear',
|
||||
items: batchClearItems as unknown[],
|
||||
installBridge: (implementation: jest.Mock) => {
|
||||
window.electron = {
|
||||
...window.electron,
|
||||
dbClearPlaybackPositionsBatch: implementation,
|
||||
} as unknown as typeof window.electron;
|
||||
},
|
||||
invoke: (target: PlaybackPositionRuntimeBridgeService) =>
|
||||
target.clearPlaybackPositionsBatch(
|
||||
'playlist-1',
|
||||
batchClearItems
|
||||
),
|
||||
invokeEmpty: (target: PlaybackPositionRuntimeBridgeService) =>
|
||||
target.clearPlaybackPositionsBatch('playlist-1', []),
|
||||
},
|
||||
])('$name persistence', (operation) => {
|
||||
it('silently no-ops when the storage capability is unavailable', async () => {
|
||||
const bridgeMethod = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true });
|
||||
operation.installBridge(bridgeMethod);
|
||||
|
||||
await expect(operation.invoke(service)).resolves.toBeUndefined();
|
||||
expect(bridgeMethod).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('silently no-ops on an empty item list', async () => {
|
||||
runtimeCapabilities.supportsPlaybackPositionStorage = true;
|
||||
const bridgeMethod = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true });
|
||||
operation.installBridge(bridgeMethod);
|
||||
|
||||
await expect(
|
||||
operation.invokeEmpty(service)
|
||||
).resolves.toBeUndefined();
|
||||
expect(bridgeMethod).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('invokes the batch bridge method with the playlist and items', async () => {
|
||||
runtimeCapabilities.supportsPlaybackPositionStorage = true;
|
||||
const bridgeMethod = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true });
|
||||
operation.installBridge(bridgeMethod);
|
||||
|
||||
await expect(operation.invoke(service)).resolves.toBeUndefined();
|
||||
expect(bridgeMethod).toHaveBeenCalledWith(
|
||||
'playlist-1',
|
||||
operation.items
|
||||
);
|
||||
});
|
||||
|
||||
it.each([{ success: false }, {}, undefined])(
|
||||
'rejects a non-success result %#',
|
||||
async (result) => {
|
||||
runtimeCapabilities.supportsPlaybackPositionStorage = true;
|
||||
operation.installBridge(jest.fn().mockResolvedValue(result));
|
||||
|
||||
await expect(operation.invoke(service)).rejects.toThrow(
|
||||
'did not succeed'
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects when the batch bridge method is unavailable', async () => {
|
||||
runtimeCapabilities.supportsPlaybackPositionStorage = true;
|
||||
|
||||
await expect(operation.invoke(service)).rejects.toThrow(
|
||||
'method is unavailable'
|
||||
);
|
||||
});
|
||||
|
||||
it('propagates rejected IPC', async () => {
|
||||
const error = new Error('database is locked');
|
||||
runtimeCapabilities.supportsPlaybackPositionStorage = true;
|
||||
operation.installBridge(jest.fn().mockRejectedValue(error));
|
||||
|
||||
await expect(operation.invoke(service)).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function createPosition(
|
||||
|
||||
@@ -33,6 +33,17 @@ type PlaybackPositionElectronBridge = Partial<{
|
||||
contentXtreamId: number,
|
||||
contentType: PlaybackPositionContentType
|
||||
) => Promise<{ success: boolean }>;
|
||||
dbSavePlaybackPositionsBatch: (
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
) => Promise<{ success: boolean }>;
|
||||
dbClearPlaybackPositionsBatch: (
|
||||
playlistId: string,
|
||||
items: {
|
||||
contentXtreamId: number;
|
||||
contentType: PlaybackPositionContentType;
|
||||
}[]
|
||||
) => Promise<{ success: boolean }>;
|
||||
onPlaybackPositionUpdate: (
|
||||
callback: (data: PlaybackPositionData) => void
|
||||
) => () => void;
|
||||
@@ -197,6 +208,57 @@ export class PlaybackPositionRuntimeBridgeService {
|
||||
}
|
||||
}
|
||||
|
||||
async savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void> {
|
||||
if (!this.supportsStorage || items.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bridge = this.bridge;
|
||||
if (typeof bridge?.dbSavePlaybackPositionsBatch !== 'function') {
|
||||
throw new Error(
|
||||
'Playback position batch save method is unavailable'
|
||||
);
|
||||
}
|
||||
|
||||
const result = await bridge.dbSavePlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
if (result?.success !== true) {
|
||||
throw new Error('Playback position batch save did not succeed');
|
||||
}
|
||||
}
|
||||
|
||||
async clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: {
|
||||
contentXtreamId: number;
|
||||
contentType: PlaybackPositionContentType;
|
||||
}[]
|
||||
): Promise<void> {
|
||||
if (!this.supportsStorage || items.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bridge = this.bridge;
|
||||
if (typeof bridge?.dbClearPlaybackPositionsBatch !== 'function') {
|
||||
throw new Error(
|
||||
'Playback position batch clear method is unavailable'
|
||||
);
|
||||
}
|
||||
|
||||
const result = await bridge.dbClearPlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
if (result?.success !== true) {
|
||||
throw new Error('Playback position batch clear did not succeed');
|
||||
}
|
||||
}
|
||||
|
||||
onPlaybackPositionUpdate(
|
||||
callback: (data: PlaybackPositionData) => void
|
||||
): (() => void) | undefined {
|
||||
|
||||
@@ -20,6 +20,8 @@ describe('PlaybackPositionService', () => {
|
||||
| 'getAllPlaybackPositions'
|
||||
| 'clearAllPlaybackPositions'
|
||||
| 'clearPlaybackPosition'
|
||||
| 'savePlaybackPositionsBatch'
|
||||
| 'clearPlaybackPositionsBatch'
|
||||
>
|
||||
>;
|
||||
|
||||
@@ -32,6 +34,8 @@ describe('PlaybackPositionService', () => {
|
||||
getAllPlaybackPositions: jest.fn().mockResolvedValue([]),
|
||||
clearAllPlaybackPositions: jest.fn().mockResolvedValue(undefined),
|
||||
clearPlaybackPosition: jest.fn().mockResolvedValue(undefined),
|
||||
savePlaybackPositionsBatch: jest.fn().mockResolvedValue(undefined),
|
||||
clearPlaybackPositionsBatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
injector = Injector.create({
|
||||
@@ -150,6 +154,54 @@ describe('PlaybackPositionService', () => {
|
||||
service.clearPlaybackPosition('playlist-1', 100, 'vod')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('delegates batch playback-position writes through the runtime bridge', async () => {
|
||||
const items = [
|
||||
createPosition(),
|
||||
createPosition({
|
||||
contentXtreamId: 101,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 200,
|
||||
}),
|
||||
];
|
||||
const clearItems: {
|
||||
contentXtreamId: number;
|
||||
contentType: 'vod' | 'episode';
|
||||
}[] = [
|
||||
{ contentXtreamId: 100, contentType: 'vod' },
|
||||
{ contentXtreamId: 101, contentType: 'episode' },
|
||||
];
|
||||
|
||||
await service.savePlaybackPositionsBatch('playlist-1', items);
|
||||
await service.clearPlaybackPositionsBatch('playlist-1', clearItems);
|
||||
|
||||
expect(bridge.savePlaybackPositionsBatch).toHaveBeenCalledWith(
|
||||
'playlist-1',
|
||||
items
|
||||
);
|
||||
expect(bridge.clearPlaybackPositionsBatch).toHaveBeenCalledWith(
|
||||
'playlist-1',
|
||||
clearItems
|
||||
);
|
||||
});
|
||||
|
||||
it('propagates batch failures to the caller instead of swallowing them', async () => {
|
||||
const saveError = new Error('batch save failed');
|
||||
const clearError = new Error('batch clear failed');
|
||||
bridge.savePlaybackPositionsBatch.mockRejectedValue(saveError);
|
||||
bridge.clearPlaybackPositionsBatch.mockRejectedValue(clearError);
|
||||
|
||||
await expect(
|
||||
service.savePlaybackPositionsBatch('playlist-1', [
|
||||
createPosition(),
|
||||
])
|
||||
).rejects.toBe(saveError);
|
||||
await expect(
|
||||
service.clearPlaybackPositionsBatch('playlist-1', [
|
||||
{ contentXtreamId: 100, contentType: 'vod' },
|
||||
])
|
||||
).rejects.toBe(clearError);
|
||||
});
|
||||
});
|
||||
|
||||
function createPosition(
|
||||
|
||||
@@ -84,6 +84,17 @@ export class PlaybackPositionService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Failure-propagating read for cache refreshes: a swallowed error would
|
||||
* surface as an authoritative empty list and let a transient IPC failure
|
||||
* wipe an already-populated position cache.
|
||||
*/
|
||||
getAllPlaybackPositionsOrThrow(
|
||||
playlistId: string
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
return this.playbackPositionBridge.getAllPlaybackPositions(playlistId);
|
||||
}
|
||||
|
||||
async clearAllPlaybackPositions(playlistId: string): Promise<void> {
|
||||
try {
|
||||
await this.playbackPositionBridge.clearAllPlaybackPositions(
|
||||
@@ -109,4 +120,27 @@ export class PlaybackPositionService {
|
||||
console.error('Error clearing playback position:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// The batch methods deliberately propagate failures (no swallow):
|
||||
// season-level bulk toggles must show an error and keep the UI state
|
||||
// untouched when nothing was persisted.
|
||||
savePlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: PlaybackPositionData[]
|
||||
): Promise<void> {
|
||||
return this.playbackPositionBridge.savePlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
}
|
||||
|
||||
clearPlaybackPositionsBatch(
|
||||
playlistId: string,
|
||||
items: { contentXtreamId: number; contentType: 'vod' | 'episode' }[]
|
||||
): Promise<void> {
|
||||
return this.playbackPositionBridge.clearPlaybackPositionsBatch(
|
||||
playlistId,
|
||||
items
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,8 @@ describe('RuntimeCapabilitiesService', () => {
|
||||
dbGetAllPlaybackPositions: jest.fn(),
|
||||
dbClearAllPlaybackPositions: jest.fn(),
|
||||
dbClearPlaybackPosition: jest.fn(),
|
||||
dbSavePlaybackPositionsBatch: jest.fn(),
|
||||
dbClearPlaybackPositionsBatch: jest.fn(),
|
||||
onPlaybackPositionUpdate: jest.fn(),
|
||||
dbDeleteXtreamContent: jest.fn(),
|
||||
dbRestoreXtreamUserData: jest.fn(),
|
||||
@@ -468,6 +470,15 @@ describe('RuntimeCapabilitiesService', () => {
|
||||
dbClearPlaybackPosition: jest.fn(),
|
||||
};
|
||||
|
||||
// The season-batch methods are part of the storage contract too.
|
||||
expect(service.supportsPlaybackPositionStorage).toBe(false);
|
||||
|
||||
testWindow.electron = {
|
||||
...testWindow.electron,
|
||||
dbSavePlaybackPositionsBatch: jest.fn(),
|
||||
dbClearPlaybackPositionsBatch: jest.fn(),
|
||||
};
|
||||
|
||||
expect(service.supportsPlaybackPositionStorage).toBe(true);
|
||||
expect(service.supportsPlaybackPositionUpdates).toBe(false);
|
||||
|
||||
@@ -523,6 +534,8 @@ function createXtreamSqliteBridge(): Record<string, jest.Mock> {
|
||||
dbAddRecentItem: jest.fn(),
|
||||
dbClearAllPlaybackPositions: jest.fn(),
|
||||
dbClearPlaybackPosition: jest.fn(),
|
||||
dbSavePlaybackPositionsBatch: jest.fn(),
|
||||
dbClearPlaybackPositionsBatch: jest.fn(),
|
||||
dbClearPlaylistRecentItems: jest.fn(),
|
||||
dbCreatePlaylist: jest.fn(),
|
||||
dbDeletePlaylist: jest.fn(),
|
||||
|
||||
@@ -5,6 +5,9 @@ export type RuntimeEnvironment = 'electron' | 'pwa';
|
||||
|
||||
type RuntimeElectronBridge = Partial<ElectronBridgeApi>;
|
||||
|
||||
// The full method set the position-storage layer may invoke — including the
|
||||
// season-batch variants, so a bridge lacking them degrades to the in-memory
|
||||
// path wholesale instead of throwing mid-action.
|
||||
const playbackPositionStorageMethods = [
|
||||
'dbSavePlaybackPosition',
|
||||
'dbGetPlaybackPosition',
|
||||
@@ -13,6 +16,8 @@ const playbackPositionStorageMethods = [
|
||||
'dbGetAllPlaybackPositions',
|
||||
'dbClearAllPlaybackPositions',
|
||||
'dbClearPlaybackPosition',
|
||||
'dbSavePlaybackPositionsBatch',
|
||||
'dbClearPlaybackPositionsBatch',
|
||||
];
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
|
||||
@@ -1066,6 +1066,17 @@ export interface ElectronBridgeApi {
|
||||
contentXtreamId: number,
|
||||
contentType: ElectronBridgePlaybackContentType
|
||||
) => Promise<ElectronBridgeResult>;
|
||||
dbSavePlaybackPositionsBatch: (
|
||||
playlistId: string,
|
||||
items: ElectronBridgePlaybackPositionInput[]
|
||||
) => Promise<ElectronBridgeResult>;
|
||||
dbClearPlaybackPositionsBatch: (
|
||||
playlistId: string,
|
||||
items: {
|
||||
contentXtreamId: number;
|
||||
contentType: ElectronBridgePlaybackContentType;
|
||||
}[]
|
||||
) => Promise<ElectronBridgeResult>;
|
||||
onPlaybackPositionUpdate: (
|
||||
callback: (data: PlaybackPositionData) => void
|
||||
) => () => void;
|
||||
|
||||
@@ -12,6 +12,16 @@ export function parseDuration(duration: string | number | undefined): number {
|
||||
return duration;
|
||||
}
|
||||
|
||||
// Providers report "45 min" (Stalker VOD) and "1h 30min" (Xtream) —
|
||||
// the hour component must not be dropped when both are present.
|
||||
const minutesMatch = duration.match(/(?:(\d+)\s*h\w*)?\s*(\d+)\s*min/);
|
||||
if (minutesMatch) {
|
||||
return (
|
||||
parseInt(minutesMatch[1] ?? '0', 10) * 3600 +
|
||||
parseInt(minutesMatch[2], 10) * 60
|
||||
);
|
||||
}
|
||||
|
||||
const parts = duration.split(':').map(Number);
|
||||
if (parts.length === 3) {
|
||||
return parts[0] * 3600 + parts[1] * 60 + parts[2];
|
||||
|
||||
@@ -7,6 +7,11 @@ describe('episode-progress.util', () => {
|
||||
it('parses duration strings', () => {
|
||||
expect(parseDuration('01:00:30')).toBe(3630);
|
||||
expect(parseDuration('45:12')).toBe(2712);
|
||||
// Stalker VOD episodes report minute strings; Xtream fixtures
|
||||
// report compound hour/minute strings.
|
||||
expect(parseDuration('45 min')).toBe(2700);
|
||||
expect(parseDuration('1h 30min')).toBe(5400);
|
||||
expect(parseDuration('2h 05min')).toBe(7500);
|
||||
expect(parseDuration(120)).toBe(120);
|
||||
expect(parseDuration(undefined)).toBe(0);
|
||||
});
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
[batchRunning]="downloadPresenter.batchRunning()"
|
||||
[seasonDisabled]="downloadPresenter.seasonDisabled()"
|
||||
[eligibleEpisodeCount]="downloadPresenter.eligibleEpisodeCount()"
|
||||
[watchToggleVisible]="seasonWatchToggleVisible()"
|
||||
[watchBatchRunning]="seasonWatchBatchRunning()"
|
||||
[seasonFullyWatched]="selectedSeasonFullyWatched()"
|
||||
[watchEligibleCount]="seasonWatchEligibleCount()"
|
||||
[viewToggleVisible]="hasSeasons() && !showSeasonEmptyState()"
|
||||
[viewMode]="viewMode()"
|
||||
(downloadSeason)="downloadPresenter.enqueueSeason()"
|
||||
(toggleSeasonWatched)="toggleSeasonWatched()"
|
||||
(viewModeChange)="setViewMode($event)"
|
||||
/>
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ const EN_TRANSLATIONS = JSON.parse(
|
||||
|
||||
const DOWNLOAD_TRANSLATIONS = {
|
||||
DOWNLOADS: EN_TRANSLATIONS['DOWNLOADS'],
|
||||
XTREAM: EN_TRANSLATIONS['XTREAM'],
|
||||
};
|
||||
|
||||
function createEpisode(
|
||||
@@ -1131,4 +1132,191 @@ describe('SeasonContainerComponent', () => {
|
||||
{ duration: 5000 }
|
||||
);
|
||||
});
|
||||
|
||||
describe('season watched toggle', () => {
|
||||
// The Stalker-style '45 min' format parses to 2700 seconds.
|
||||
const PARSED_DURATION = 2700;
|
||||
const parseableInfo = {
|
||||
duration: '45 min',
|
||||
plot: 'Pilot episode',
|
||||
movie_image: 'https://example.com/poster.jpg',
|
||||
};
|
||||
|
||||
const watchedPosition = (contentXtreamId: number) => ({
|
||||
contentXtreamId,
|
||||
contentType: 'episode' as const,
|
||||
seriesXtreamId: 20,
|
||||
positionSeconds: 100,
|
||||
durationSeconds: 100,
|
||||
playlistId: 'playlist-1',
|
||||
});
|
||||
|
||||
const toggleButton = (): HTMLButtonElement | null =>
|
||||
fixture.nativeElement.querySelector(
|
||||
'[data-test-id="toggle-season-watched"]'
|
||||
);
|
||||
|
||||
const threeEpisodes = () => ({
|
||||
'1': [
|
||||
createEpisode({ info: parseableInfo }),
|
||||
createEpisode({
|
||||
id: '102',
|
||||
episode_num: 2,
|
||||
info: parseableInfo,
|
||||
}),
|
||||
createEpisode({
|
||||
id: '103',
|
||||
episode_num: 3,
|
||||
info: parseableInfo,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
it('emits watched requests only for unwatched episodes with parsed durations', () => {
|
||||
const emitted: unknown[] = [];
|
||||
component.seasonPlaybackToggleRequested.subscribe((request) =>
|
||||
emitted.push(request)
|
||||
);
|
||||
setRequiredInputs(threeEpisodes());
|
||||
fixture.componentRef.setInput(
|
||||
'playbackPositions',
|
||||
new Map([[101, watchedPosition(101)]])
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = toggleButton();
|
||||
expect(button?.textContent).toContain(
|
||||
'Mark season as watched (2)'
|
||||
);
|
||||
button?.click();
|
||||
|
||||
expect(emitted).toEqual([
|
||||
{
|
||||
seasonKey: '1',
|
||||
markWatched: true,
|
||||
requests: [
|
||||
{
|
||||
contentXtreamId: 102,
|
||||
nextPosition: expect.objectContaining({
|
||||
contentXtreamId: 102,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 20,
|
||||
seasonNumber: 1,
|
||||
episodeNumber: 2,
|
||||
positionSeconds: PARSED_DURATION,
|
||||
durationSeconds: PARSED_DURATION,
|
||||
playlistId: 'playlist-1',
|
||||
}),
|
||||
},
|
||||
{
|
||||
contentXtreamId: 103,
|
||||
nextPosition: expect.objectContaining({
|
||||
contentXtreamId: 103,
|
||||
episodeNumber: 3,
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('flips to unwatch and emits null positions for every episode when the season is fully watched', () => {
|
||||
const emitted: {
|
||||
markWatched: boolean;
|
||||
requests: { contentXtreamId: number; nextPosition: unknown }[];
|
||||
}[] = [];
|
||||
component.seasonPlaybackToggleRequested.subscribe((request) =>
|
||||
emitted.push(request)
|
||||
);
|
||||
setRequiredInputs(threeEpisodes());
|
||||
fixture.componentRef.setInput(
|
||||
'playbackPositions',
|
||||
new Map([
|
||||
[101, watchedPosition(101)],
|
||||
[102, watchedPosition(102)],
|
||||
[103, watchedPosition(103)],
|
||||
])
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = toggleButton();
|
||||
expect(button?.textContent).toContain('Mark season as unwatched');
|
||||
expect(button?.querySelector('mat-icon')?.textContent).toContain(
|
||||
'remove_done'
|
||||
);
|
||||
button?.click();
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
expect(emitted[0].markWatched).toBe(false);
|
||||
expect(
|
||||
emitted[0].requests.map((request) => [
|
||||
request.contentXtreamId,
|
||||
request.nextPosition,
|
||||
])
|
||||
).toEqual([
|
||||
[101, null],
|
||||
[102, null],
|
||||
[103, null],
|
||||
]);
|
||||
});
|
||||
|
||||
it('never bulk-marks the playing episode and disables an empty action', () => {
|
||||
const emitted: {
|
||||
requests: { contentXtreamId: number }[];
|
||||
}[] = [];
|
||||
component.seasonPlaybackToggleRequested.subscribe((request) =>
|
||||
emitted.push(request)
|
||||
);
|
||||
setRequiredInputs(threeEpisodes());
|
||||
fixture.componentRef.setInput('playingEpisodeId', 102);
|
||||
fixture.componentRef.setInput(
|
||||
'playbackPositions',
|
||||
new Map([[101, watchedPosition(101)]])
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = toggleButton();
|
||||
// 103 is the only markable episode: 101 watched, 102 playing.
|
||||
expect(button?.textContent).toContain(
|
||||
'Mark season as watched (1)'
|
||||
);
|
||||
button?.click();
|
||||
expect(
|
||||
emitted[0].requests.map((item) => item.contentXtreamId)
|
||||
).toEqual([103]);
|
||||
|
||||
fixture.componentRef.setInput(
|
||||
'playbackPositions',
|
||||
new Map([
|
||||
[101, watchedPosition(101)],
|
||||
[103, watchedPosition(103)],
|
||||
])
|
||||
);
|
||||
fixture.detectChanges();
|
||||
expect(toggleButton()?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('disables the toggle and reports busy while the host batch is running', () => {
|
||||
setRequiredInputs(threeEpisodes());
|
||||
fixture.componentRef.setInput('seasonWatchBatchRunning', true);
|
||||
fixture.detectChanges();
|
||||
|
||||
const button = toggleButton();
|
||||
expect(button?.disabled).toBe(true);
|
||||
expect(button?.getAttribute('aria-busy')).toBe('true');
|
||||
expect(button?.querySelector('mat-spinner')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('hides the toggle without a playlist id and on empty seasons', () => {
|
||||
setRequiredInputs(threeEpisodes());
|
||||
fixture.componentRef.setInput('playlistId', '');
|
||||
fixture.detectChanges();
|
||||
expect(toggleButton()).toBeNull();
|
||||
|
||||
fixture.componentRef.setInput('playlistId', 'playlist-1');
|
||||
fixture.componentRef.setInput('seasons', {});
|
||||
fixture.detectChanges();
|
||||
expect(toggleButton()).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,23 +35,28 @@ import {
|
||||
EpisodeInfoDialogComponent,
|
||||
buildEpisodeInfoDialogData,
|
||||
} from './episode-info-dialog.component';
|
||||
import {
|
||||
formatEpisodePositionText,
|
||||
parseDuration,
|
||||
} from './episode-progress.util';
|
||||
import { formatEpisodePositionText } from './episode-progress.util';
|
||||
import { SeasonDownloadPresenter } from './season-download-presenter';
|
||||
import {
|
||||
type EpisodeViewMode,
|
||||
SeasonHeaderComponent,
|
||||
} from './season-header.component';
|
||||
import { SeasonTabsComponent } from './season-tabs.component';
|
||||
import {
|
||||
type SeasonContainerPlaybackToggleRequest,
|
||||
type SeasonContainerSeasonPlaybackToggleRequest,
|
||||
buildSeasonWatchToggleRequest,
|
||||
buildWatchedEpisodePosition,
|
||||
listMarkableEpisodes,
|
||||
resolveEpisodeInfo,
|
||||
} from './season-watch-toggle.util';
|
||||
|
||||
const EPISODE_VIEW_MODE_KEY = 'iptvnator_episode_view_mode';
|
||||
|
||||
export interface SeasonContainerPlaybackToggleRequest {
|
||||
contentXtreamId: number;
|
||||
nextPosition: PlaybackPositionData | null;
|
||||
}
|
||||
export type {
|
||||
SeasonContainerPlaybackToggleRequest,
|
||||
SeasonContainerSeasonPlaybackToggleRequest,
|
||||
} from './season-watch-toggle.util';
|
||||
|
||||
@Component({
|
||||
selector: 'app-season-container',
|
||||
@@ -94,10 +99,14 @@ export class SeasonContainerComponent implements OnInit {
|
||||
readonly playingEpisodeId = input<number | null>(null);
|
||||
/** Per-season descriptions (TMDB/provider), keyed by season key. */
|
||||
readonly seasonDescriptions = input<Record<string, string> | null>(null);
|
||||
/** True while a host is persisting a season-level watched toggle. */
|
||||
readonly seasonWatchBatchRunning = input(false);
|
||||
|
||||
readonly episodeClicked = output<XtreamSerieEpisode>();
|
||||
readonly playbackToggleRequested =
|
||||
output<SeasonContainerPlaybackToggleRequest>();
|
||||
readonly seasonPlaybackToggleRequested =
|
||||
output<SeasonContainerSeasonPlaybackToggleRequest>();
|
||||
readonly seasonSelected = output<string>();
|
||||
readonly viewMode = signal<EpisodeViewMode>('grid');
|
||||
|
||||
@@ -143,6 +152,51 @@ export class SeasonContainerComponent implements OnInit {
|
||||
return selected ? (this.seasons()[selected] ?? []) : [];
|
||||
});
|
||||
|
||||
readonly selectedSeasonUnwatchedCount = computed(
|
||||
() =>
|
||||
this.selectedSeasonEpisodes().filter(
|
||||
(episode) => !this.isEpisodeWatched(episode)
|
||||
).length
|
||||
);
|
||||
|
||||
readonly selectedSeasonFullyWatched = computed(
|
||||
() =>
|
||||
this.selectedSeasonEpisodes().length > 0 &&
|
||||
this.selectedSeasonUnwatchedCount() === 0
|
||||
);
|
||||
|
||||
/**
|
||||
* The episode currently playing (inline or externally) or launching is
|
||||
* never bulk-marked: the player persists its live position and would
|
||||
* immediately overwrite the full-progress row.
|
||||
*/
|
||||
private readonly seasonWatchExcludedIds = computed(() => {
|
||||
const ids = [
|
||||
this.playingEpisodeId(),
|
||||
this.activeEpisodeId(),
|
||||
this.openingEpisodeId(),
|
||||
].filter((id): id is number => id !== null);
|
||||
return new Set(ids);
|
||||
});
|
||||
|
||||
/** Count shown in the season toggle label: episodes the action touches. */
|
||||
readonly seasonWatchEligibleCount = computed(() =>
|
||||
this.selectedSeasonFullyWatched()
|
||||
? this.selectedSeasonEpisodes().length
|
||||
: listMarkableEpisodes(
|
||||
this.selectedSeasonEpisodes(),
|
||||
(episode) => this.isEpisodeWatched(episode),
|
||||
this.seasonWatchExcludedIds()
|
||||
).length
|
||||
);
|
||||
|
||||
readonly seasonWatchToggleVisible = computed(
|
||||
() =>
|
||||
this.sortedSeasonKeys().length > 0 &&
|
||||
this.selectedSeasonEpisodes().length > 0 &&
|
||||
!!this.playlistId()
|
||||
);
|
||||
|
||||
private readonly autoSelectKey = computed(
|
||||
() =>
|
||||
`${this.sortedSeasonKeys().join('|')}::${
|
||||
@@ -294,35 +348,44 @@ export class SeasonContainerComponent implements OnInit {
|
||||
return;
|
||||
}
|
||||
|
||||
const info = this.getEpisodeInfo(episode);
|
||||
const duration =
|
||||
info?.duration_secs || parseDuration(info?.duration) || 1;
|
||||
|
||||
this.playbackToggleRequested.emit({
|
||||
contentXtreamId,
|
||||
nextPosition: {
|
||||
contentXtreamId,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: this.seriesId(),
|
||||
seasonNumber: Number(
|
||||
episode.season || this.selectedSeason() || 1
|
||||
),
|
||||
episodeNumber: Number(episode.episode_num || 1),
|
||||
positionSeconds: duration,
|
||||
durationSeconds: duration,
|
||||
nextPosition: buildWatchedEpisodePosition({
|
||||
episode,
|
||||
seriesId: this.seriesId(),
|
||||
playlistId: this.playlistId(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
fallbackSeasonKey: this.selectedSeason(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
toggleSeasonWatched() {
|
||||
const seasonKey = this.selectedSeason();
|
||||
if (!seasonKey || !this.playlistId()) {
|
||||
this.logger.warn('Cannot toggle season watched: no season/playlist');
|
||||
return;
|
||||
}
|
||||
if (this.seasonWatchBatchRunning()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const request = buildSeasonWatchToggleRequest({
|
||||
episodes: this.selectedSeasonEpisodes(),
|
||||
seasonKey,
|
||||
seriesId: this.seriesId(),
|
||||
playlistId: this.playlistId(),
|
||||
isEpisodeWatched: (episode) => this.isEpisodeWatched(episode),
|
||||
excludedEpisodeIds: this.seasonWatchExcludedIds(),
|
||||
});
|
||||
if (request) {
|
||||
this.seasonPlaybackToggleRequested.emit(request);
|
||||
}
|
||||
}
|
||||
|
||||
getEpisodeInfo(
|
||||
episode: XtreamSerieEpisode
|
||||
): XtreamSerieEpisodeInfo | undefined {
|
||||
if (Array.isArray(episode.info) || !episode.info) {
|
||||
return undefined;
|
||||
}
|
||||
return episode.info;
|
||||
return resolveEpisodeInfo(episode);
|
||||
}
|
||||
|
||||
isEpisodeWatched(episode: XtreamSerieEpisode): boolean {
|
||||
|
||||
@@ -4,8 +4,46 @@
|
||||
{{ 'PORTALS.SEASONS_AND_EPISODES' | translate }}
|
||||
</h3>
|
||||
</div>
|
||||
@if (downloadVisible() || viewToggleVisible()) {
|
||||
@if (downloadVisible() || watchToggleVisible() || viewToggleVisible()) {
|
||||
<div class="section-header__actions">
|
||||
@if (watchToggleVisible()) {
|
||||
<button
|
||||
mat-stroked-button
|
||||
class="season-watch-toggle-button"
|
||||
data-test-id="toggle-season-watched"
|
||||
[disabled]="
|
||||
watchBatchRunning() ||
|
||||
(!seasonFullyWatched() && watchEligibleCount() === 0)
|
||||
"
|
||||
[attr.aria-label]="
|
||||
(seasonFullyWatched()
|
||||
? 'XTREAM.MARK_SEASON_UNWATCHED'
|
||||
: 'XTREAM.MARK_SEASON_WATCHED'
|
||||
) | translate: { count: watchEligibleCount() }
|
||||
"
|
||||
[attr.aria-busy]="watchBatchRunning() ? 'true' : null"
|
||||
(click)="toggleSeasonWatched.emit()"
|
||||
>
|
||||
@if (watchBatchRunning()) {
|
||||
<mat-spinner
|
||||
diameter="18"
|
||||
aria-hidden="true"
|
||||
></mat-spinner>
|
||||
} @else {
|
||||
<mat-icon>{{
|
||||
seasonFullyWatched() ? 'remove_done' : 'done_all'
|
||||
}}</mat-icon>
|
||||
}
|
||||
<span class="season-watch-toggle-button__label">
|
||||
{{
|
||||
(seasonFullyWatched()
|
||||
? 'XTREAM.MARK_SEASON_UNWATCHED'
|
||||
: 'XTREAM.MARK_SEASON_WATCHED'
|
||||
) | translate: { count: watchEligibleCount() }
|
||||
}}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (downloadVisible()) {
|
||||
<button
|
||||
mat-stroked-button
|
||||
|
||||
@@ -84,7 +84,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
.season-download-button {
|
||||
.season-download-button,
|
||||
.season-watch-toggle-button {
|
||||
min-height: 36px;
|
||||
|
||||
mat-spinner {
|
||||
|
||||
@@ -32,9 +32,14 @@ export class SeasonHeaderComponent {
|
||||
readonly batchRunning = input.required<boolean>();
|
||||
readonly seasonDisabled = input.required<boolean>();
|
||||
readonly eligibleEpisodeCount = input.required<number>();
|
||||
readonly watchToggleVisible = input.required<boolean>();
|
||||
readonly watchBatchRunning = input.required<boolean>();
|
||||
readonly seasonFullyWatched = input.required<boolean>();
|
||||
readonly watchEligibleCount = input.required<number>();
|
||||
readonly viewToggleVisible = input.required<boolean>();
|
||||
readonly viewMode = input.required<EpisodeViewMode>();
|
||||
|
||||
readonly downloadSeason = output<void>();
|
||||
readonly toggleSeasonWatched = output<void>();
|
||||
readonly viewModeChange = output<EpisodeViewMode>();
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
XtreamSerieEpisode,
|
||||
XtreamSerieEpisodeInfo,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { parseDuration } from './episode-progress.util';
|
||||
|
||||
export interface SeasonContainerPlaybackToggleRequest {
|
||||
contentXtreamId: number;
|
||||
nextPosition: PlaybackPositionData | null;
|
||||
}
|
||||
|
||||
export interface SeasonContainerSeasonPlaybackToggleRequest {
|
||||
seasonKey: string;
|
||||
markWatched: boolean;
|
||||
requests: SeasonContainerPlaybackToggleRequest[];
|
||||
}
|
||||
|
||||
export function resolveEpisodeInfo(
|
||||
episode: XtreamSerieEpisode
|
||||
): XtreamSerieEpisodeInfo | undefined {
|
||||
if (Array.isArray(episode.info) || !episode.info) {
|
||||
return undefined;
|
||||
}
|
||||
return episode.info;
|
||||
}
|
||||
|
||||
/** Full-progress position row marking one episode as watched. */
|
||||
export function buildWatchedEpisodePosition(options: {
|
||||
episode: XtreamSerieEpisode;
|
||||
seriesId: number;
|
||||
playlistId: string;
|
||||
fallbackSeasonKey: string | undefined;
|
||||
}): PlaybackPositionData {
|
||||
const { episode } = options;
|
||||
const contentXtreamId = Number(episode.id);
|
||||
const info = resolveEpisodeInfo(episode);
|
||||
const duration = info?.duration_secs || parseDuration(info?.duration) || 1;
|
||||
|
||||
return {
|
||||
contentXtreamId,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: options.seriesId,
|
||||
seasonNumber: Number(episode.season || options.fallbackSeasonKey || 1),
|
||||
episodeNumber: Number(episode.episode_num || 1),
|
||||
positionSeconds: duration,
|
||||
durationSeconds: duration,
|
||||
playlistId: options.playlistId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Episodes a mark-season-watched action would touch. */
|
||||
export function listMarkableEpisodes(
|
||||
episodes: readonly XtreamSerieEpisode[],
|
||||
isEpisodeWatched: (episode: XtreamSerieEpisode) => boolean,
|
||||
excludedEpisodeIds?: ReadonlySet<number>
|
||||
): XtreamSerieEpisode[] {
|
||||
return episodes.filter(
|
||||
(episode) =>
|
||||
!isEpisodeWatched(episode) &&
|
||||
!excludedEpisodeIds?.has(Number(episode.id))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Season-level bulk toggle request. Marking touches only unwatched episodes
|
||||
* so a watched episode's real duration is never overwritten with the parsed
|
||||
* fallback; unmarking clears every episode of the season. Returns null when
|
||||
* the action would touch nothing.
|
||||
*
|
||||
* `excludedEpisodeIds` (the episode playing inline or in an external
|
||||
* session, or one whose launch is in flight) is honored for MARKING only:
|
||||
* the player persists its real position every ~15 s, which would overwrite
|
||||
* a just-written full-progress row and silently flip the episode back to
|
||||
* in-progress. Unmarking still clears such an episode — the next position
|
||||
* tick recreating an in-progress row reflects the live playback truthfully.
|
||||
*/
|
||||
export function buildSeasonWatchToggleRequest(options: {
|
||||
episodes: readonly XtreamSerieEpisode[];
|
||||
seasonKey: string;
|
||||
seriesId: number;
|
||||
playlistId: string;
|
||||
isEpisodeWatched: (episode: XtreamSerieEpisode) => boolean;
|
||||
excludedEpisodeIds?: ReadonlySet<number>;
|
||||
}): SeasonContainerSeasonPlaybackToggleRequest | null {
|
||||
const markWatched = options.episodes.some(
|
||||
(episode) => !options.isEpisodeWatched(episode)
|
||||
);
|
||||
const targets = markWatched
|
||||
? listMarkableEpisodes(
|
||||
options.episodes,
|
||||
options.isEpisodeWatched,
|
||||
options.excludedEpisodeIds
|
||||
)
|
||||
: options.episodes;
|
||||
|
||||
const requests = targets.map((episode) => ({
|
||||
contentXtreamId: Number(episode.id),
|
||||
nextPosition: markWatched
|
||||
? buildWatchedEpisodePosition({
|
||||
episode,
|
||||
seriesId: options.seriesId,
|
||||
playlistId: options.playlistId,
|
||||
fallbackSeasonKey: options.seasonKey,
|
||||
})
|
||||
: null,
|
||||
}));
|
||||
if (requests.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { seasonKey: options.seasonKey, markWatched, requests };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type {
|
||||
PlaybackPositionData,
|
||||
PortalRecentItem,
|
||||
} from '@iptvnator/shared/interfaces';
|
||||
import { getRecentItemNavigationState } from './dashboard-navigation.util';
|
||||
|
||||
const recentSeries: PortalRecentItem = {
|
||||
id: 200,
|
||||
title: 'Shadow Bay',
|
||||
type: 'series',
|
||||
source: 'xtream',
|
||||
playlist_id: 'xtream-C',
|
||||
category_id: 30,
|
||||
xtream_id: 4000,
|
||||
viewed_at: '2026-05-01T09:00:00.000Z',
|
||||
};
|
||||
|
||||
function episodePosition(
|
||||
overrides: Partial<PlaybackPositionData> = {}
|
||||
): PlaybackPositionData {
|
||||
return {
|
||||
contentXtreamId: 4007,
|
||||
contentType: 'episode',
|
||||
seriesXtreamId: 4000,
|
||||
seasonNumber: 3,
|
||||
episodeNumber: 7,
|
||||
positionSeconds: 540,
|
||||
durationSeconds: 1800,
|
||||
playlistId: 'xtream-C',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type RecentNavigationState = {
|
||||
openCollectionDetailItem?: {
|
||||
item?: unknown;
|
||||
seriesResume?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
describe('getRecentItemNavigationState series resume target', () => {
|
||||
it('forwards an in-progress episode as the resume target', () => {
|
||||
const state = getRecentItemNavigationState(
|
||||
recentSeries,
|
||||
episodePosition()
|
||||
) as RecentNavigationState;
|
||||
|
||||
expect(state.openCollectionDetailItem?.seriesResume).toEqual({
|
||||
seriesXtreamId: 4000,
|
||||
contentXtreamId: 4007,
|
||||
seasonNumber: 3,
|
||||
episodeNumber: 7,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps watched rows out of resume selection', () => {
|
||||
// A watched row (natural finish or a manual/bulk "mark watched") is a
|
||||
// completion marker, not resumable progress — auto-playing it would
|
||||
// start the episode at its end. The handoff stays detail-only.
|
||||
const state = getRecentItemNavigationState(
|
||||
recentSeries,
|
||||
episodePosition({ positionSeconds: 1800 })
|
||||
) as RecentNavigationState;
|
||||
|
||||
expect(state.openCollectionDetailItem?.seriesResume).toBeUndefined();
|
||||
expect(state.openCollectionDetailItem?.item).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
buildXtreamNavigationTarget,
|
||||
getGlobalFavoriteNavigation,
|
||||
getRecentItemNavigation,
|
||||
isPortalPlaybackWatched,
|
||||
WorkspaceNavigationTarget,
|
||||
type SeriesResumeTarget,
|
||||
} from '@iptvnator/portal/shared/util';
|
||||
@@ -81,6 +82,14 @@ function buildRecentSeriesResumeTarget(
|
||||
return null;
|
||||
}
|
||||
|
||||
// A watched row is a completion marker (natural finish or a manual/bulk
|
||||
// "mark watched"), not resumable progress — auto-playing it would start
|
||||
// the episode at its end. Detail-only handoff lets the series page's
|
||||
// quick-start pick the first unwatched episode instead.
|
||||
if (isPortalPlaybackWatched(playbackPosition)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Episode-keyed recent rows make item.xtream_id an episode id, so only a
|
||||
// position row that names its parent series can produce a resume target;
|
||||
// legacy rows without seriesXtreamId stay detail-only.
|
||||
|
||||
Reference in new issue
Block a user