Proyecto App Windows
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
export default {
|
||||
displayName: 'portal-xtream-data-access',
|
||||
preset: '../../../../jest.preset.js',
|
||||
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
|
||||
coverageDirectory: '../../../../coverage/libs/portal/xtream/data-access',
|
||||
transform: {
|
||||
'^.+\\.(ts|mjs|js|html)$': [
|
||||
'jest-preset-angular',
|
||||
{
|
||||
tsconfig: '<rootDir>/tsconfig.spec.json',
|
||||
stringifyContentPathRegex: '\\.(html|svg)$',
|
||||
},
|
||||
],
|
||||
},
|
||||
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
|
||||
snapshotSerializers: [
|
||||
'jest-preset-angular/build/serializers/no-ng-attributes',
|
||||
'jest-preset-angular/build/serializers/ng-snapshot',
|
||||
'jest-preset-angular/build/serializers/html-comment',
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "portal-xtream-data-access",
|
||||
"$schema": "../../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/portal/xtream/data-access/src",
|
||||
"prefix": "lib",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:portal", "domain:xtream", "type:data-access"],
|
||||
"targets": {
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "libs/portal/xtream/data-access/jest.config.ts",
|
||||
"tsConfig": "libs/portal/xtream/data-access/tsconfig.spec.json"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './lib/account-info/account-info.interface';
|
||||
export * from './lib/data-sources';
|
||||
export * from './lib/services';
|
||||
export * from './lib/stores';
|
||||
export * from './lib/with-favorites.feature';
|
||||
export { withRecentItems } from './lib/with-recent-items';
|
||||
export * from './lib/xtream-state';
|
||||
@@ -0,0 +1,29 @@
|
||||
interface ServerInfo {
|
||||
https_port: string;
|
||||
port: string;
|
||||
rtmp_port: string;
|
||||
server_protocol: string;
|
||||
time_now: string;
|
||||
timestamp_now: number;
|
||||
timezone: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface UserInfo {
|
||||
active_cons: string;
|
||||
allowed_output_formats: string[];
|
||||
auth: number;
|
||||
created_at: string;
|
||||
exp_date: string;
|
||||
is_trial: string;
|
||||
max_connections: string;
|
||||
message: string;
|
||||
password: string;
|
||||
status: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface XtreamAccountInfo {
|
||||
server_info: ServerInfo;
|
||||
user_info: UserInfo;
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
DatabaseService,
|
||||
PlaybackPositionService,
|
||||
XtreamPendingRestoreService,
|
||||
XtreamImportStatus,
|
||||
} from 'services';
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
PlaylistMeta,
|
||||
XtreamPendingRestoreState,
|
||||
XtreamCategory,
|
||||
XtreamLiveStream,
|
||||
XtreamSerieItem,
|
||||
XtreamVodStream,
|
||||
} from 'shared-interfaces';
|
||||
import {
|
||||
CategoryType,
|
||||
StreamType,
|
||||
XtreamApiService,
|
||||
XtreamCredentials,
|
||||
} from '../services/xtream-api.service';
|
||||
import {
|
||||
DbCategoryType,
|
||||
IXtreamDataSource,
|
||||
mapCategoryTypeToDbType,
|
||||
ProgressCallback,
|
||||
XtreamOperationOptions,
|
||||
XtreamCategoryFromDb,
|
||||
XtreamContentItem,
|
||||
XtreamPlaylistData,
|
||||
} from './xtream-data-source.interface';
|
||||
|
||||
/**
|
||||
* Electron implementation of the Xtream data source.
|
||||
* Uses DB-first strategy: check DB, fetch API if needed, cache to DB.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ElectronXtreamDataSource implements IXtreamDataSource {
|
||||
private readonly dbService = inject(DatabaseService);
|
||||
private readonly playbackService = inject(PlaybackPositionService);
|
||||
private readonly pendingRestoreService = inject(
|
||||
XtreamPendingRestoreService
|
||||
);
|
||||
private readonly apiService = inject(XtreamApiService);
|
||||
private readonly categoryRequests = new Map<
|
||||
string,
|
||||
Promise<XtreamCategoryFromDb[]>
|
||||
>();
|
||||
private readonly contentRequests = new Map<
|
||||
string,
|
||||
Promise<XtreamContentItem[]>
|
||||
>();
|
||||
|
||||
private mapCategoryTypeToImportType(
|
||||
type: CategoryType
|
||||
): 'live' | 'movie' | 'series' {
|
||||
switch (type) {
|
||||
case 'live':
|
||||
return 'live';
|
||||
case 'vod':
|
||||
return 'movie';
|
||||
case 'series':
|
||||
return 'series';
|
||||
}
|
||||
}
|
||||
|
||||
private async getImportStatus(
|
||||
playlistId: string,
|
||||
type: 'live' | 'movie' | 'series'
|
||||
): Promise<XtreamImportStatus> {
|
||||
return this.dbService.getXtreamImportStatus(playlistId, type);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Playlist Operations
|
||||
// =========================================================================
|
||||
|
||||
async getPlaylist(playlistId: string): Promise<XtreamPlaylistData | null> {
|
||||
const playlist = await this.dbService.getPlaylistById(playlistId);
|
||||
return playlist as XtreamPlaylistData | null;
|
||||
}
|
||||
|
||||
async createPlaylist(playlist: XtreamPlaylistData): Promise<void> {
|
||||
await this.dbService.createPlaylist({
|
||||
_id: playlist.id,
|
||||
title: playlist.name,
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
} as unknown as PlaylistMeta);
|
||||
}
|
||||
|
||||
async updatePlaylist(
|
||||
playlistId: string,
|
||||
updates: Partial<XtreamPlaylistData>
|
||||
): Promise<void> {
|
||||
await this.dbService.updateXtreamPlaylistDetails({
|
||||
id: playlistId,
|
||||
title: updates.name,
|
||||
username: updates.username,
|
||||
password: updates.password,
|
||||
serverUrl: updates.serverUrl,
|
||||
});
|
||||
}
|
||||
|
||||
async deletePlaylist(playlistId: string): Promise<void> {
|
||||
await this.dbService.deletePlaylist(playlistId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Category Operations
|
||||
// =========================================================================
|
||||
|
||||
async hasCategories(
|
||||
playlistId: string,
|
||||
type: DbCategoryType
|
||||
): Promise<boolean> {
|
||||
return this.dbService.hasXtreamCategories(playlistId, type);
|
||||
}
|
||||
|
||||
async getCategories(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: CategoryType,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamCategoryFromDb[]> {
|
||||
const dbType = mapCategoryTypeToDbType(type);
|
||||
const requestKey = `${playlistId}:${dbType}`;
|
||||
const inFlightRequest = this.categoryRequests.get(requestKey);
|
||||
|
||||
if (inFlightRequest) {
|
||||
return inFlightRequest;
|
||||
}
|
||||
|
||||
const request = this.loadCategories(
|
||||
playlistId,
|
||||
credentials,
|
||||
type,
|
||||
dbType,
|
||||
options
|
||||
).finally(() => {
|
||||
this.categoryRequests.delete(requestKey);
|
||||
});
|
||||
|
||||
this.categoryRequests.set(requestKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
private async loadCategories(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: CategoryType,
|
||||
dbType: DbCategoryType,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamCategoryFromDb[]> {
|
||||
const importType = this.mapCategoryTypeToImportType(type);
|
||||
const importStatus = await this.getImportStatus(playlistId, importType);
|
||||
// Fetch from DB directly — avoids a separate 'has' round-trip.
|
||||
// An empty result means the cache is cold; proceed to fetch from API.
|
||||
const cached = await this.dbService.getXtreamCategories(
|
||||
playlistId,
|
||||
dbType
|
||||
);
|
||||
if (importStatus === 'completed' && cached.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Fetch from API and cache
|
||||
options?.onPhaseChange?.('loading-categories');
|
||||
const remoteData = await this.apiService.getCategories(
|
||||
credentials,
|
||||
type,
|
||||
{
|
||||
sessionId: options?.sessionId,
|
||||
}
|
||||
);
|
||||
|
||||
if (remoteData && Array.isArray(remoteData) && remoteData.length > 0) {
|
||||
// Check if there are saved hidden categories to restore
|
||||
const hiddenCategoryXtreamIds = this.getHiddenCategoryXtreamIds(
|
||||
playlistId,
|
||||
dbType
|
||||
);
|
||||
|
||||
options?.onPhaseChange?.('saving-categories');
|
||||
await this.dbService.saveXtreamCategories(
|
||||
playlistId,
|
||||
remoteData,
|
||||
dbType,
|
||||
hiddenCategoryXtreamIds
|
||||
);
|
||||
}
|
||||
|
||||
// Return from cache (now populated)
|
||||
return this.dbService.getXtreamCategories(playlistId, dbType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get hidden category xtreamIds from localStorage for a specific playlist and type
|
||||
* Used to restore visibility preferences after playlist refresh
|
||||
*/
|
||||
private getHiddenCategoryXtreamIds(
|
||||
playlistId: string,
|
||||
type: 'live' | 'movies' | 'series'
|
||||
): number[] | undefined {
|
||||
const restoreData = this.pendingRestoreService.get(playlistId);
|
||||
const hiddenCategories = restoreData?.hiddenCategories;
|
||||
|
||||
if (!hiddenCategories || hiddenCategories.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return hiddenCategories
|
||||
.filter((category) => category.categoryType === type)
|
||||
.map((category) => category.xtreamId);
|
||||
}
|
||||
|
||||
async getAllCategories(
|
||||
playlistId: string,
|
||||
type: DbCategoryType
|
||||
): Promise<XtreamCategoryFromDb[]> {
|
||||
return this.dbService.getAllXtreamCategories(playlistId, type);
|
||||
}
|
||||
|
||||
async saveCategories(
|
||||
playlistId: string,
|
||||
categories: XtreamCategory[],
|
||||
type: DbCategoryType
|
||||
): Promise<void> {
|
||||
await this.dbService.saveXtreamCategories(playlistId, categories, type);
|
||||
}
|
||||
|
||||
async updateCategoryVisibility(
|
||||
categoryIds: number[],
|
||||
hidden: boolean
|
||||
): Promise<void> {
|
||||
await this.dbService.updateCategoryVisibility(categoryIds, hidden);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Content/Stream Operations
|
||||
// =========================================================================
|
||||
|
||||
async hasContent(
|
||||
playlistId: string,
|
||||
type: 'live' | 'movie' | 'series'
|
||||
): Promise<boolean> {
|
||||
return this.dbService.hasXtreamContent(playlistId, type);
|
||||
}
|
||||
|
||||
async getContent(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: StreamType,
|
||||
onProgress?: (count: number) => void,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamContentItem[]> {
|
||||
const requestKey = `${playlistId}:${type}`;
|
||||
const inFlightRequest = this.contentRequests.get(requestKey);
|
||||
|
||||
if (inFlightRequest) {
|
||||
return inFlightRequest;
|
||||
}
|
||||
|
||||
const request = this.loadContent(
|
||||
playlistId,
|
||||
credentials,
|
||||
type,
|
||||
onProgress,
|
||||
onTotal,
|
||||
options
|
||||
).finally(() => {
|
||||
this.contentRequests.delete(requestKey);
|
||||
});
|
||||
|
||||
this.contentRequests.set(requestKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
private async loadContent(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: StreamType,
|
||||
onProgress?: (count: number) => void,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamContentItem[]> {
|
||||
const importStatus = await this.getImportStatus(playlistId, type);
|
||||
// Fetch from DB directly — avoids a separate 'has' round-trip.
|
||||
// An empty result means the cache is cold; proceed to fetch from API.
|
||||
const cached = await this.dbService.getXtreamContent(playlistId, type);
|
||||
if (importStatus === 'completed' && cached.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Fetch from API
|
||||
options?.onPhaseChange?.(
|
||||
type === 'live'
|
||||
? 'loading-live'
|
||||
: type === 'movie'
|
||||
? 'loading-movies'
|
||||
: 'loading-series'
|
||||
);
|
||||
const remoteData = await this.apiService.getStreams(credentials, type, {
|
||||
sessionId: options?.sessionId,
|
||||
});
|
||||
|
||||
if (remoteData && Array.isArray(remoteData) && remoteData.length > 0) {
|
||||
// Report total items to import
|
||||
if (onTotal) {
|
||||
onTotal(remoteData.length);
|
||||
}
|
||||
|
||||
// Save to cache with progress tracking
|
||||
await this.dbService.saveXtreamContent(
|
||||
playlistId,
|
||||
remoteData as
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[],
|
||||
type,
|
||||
onProgress,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
// Return from cache (now populated)
|
||||
return this.dbService.getXtreamContent(playlistId, type);
|
||||
}
|
||||
|
||||
async saveContent(
|
||||
playlistId: string,
|
||||
streams:
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[]
|
||||
| XtreamContentItem[],
|
||||
type: 'live' | 'movie' | 'series',
|
||||
onProgress?: ProgressCallback,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<number> {
|
||||
return this.dbService.saveXtreamContent(
|
||||
playlistId,
|
||||
streams,
|
||||
type,
|
||||
onProgress,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Search Operations
|
||||
// =========================================================================
|
||||
|
||||
async searchContent(
|
||||
playlistId: string,
|
||||
searchTerm: string,
|
||||
types: string[],
|
||||
excludeHidden?: boolean
|
||||
): Promise<XtreamContentItem[]> {
|
||||
return this.dbService.searchXtreamContent(
|
||||
playlistId,
|
||||
searchTerm,
|
||||
types,
|
||||
excludeHidden
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Favorites Operations
|
||||
// =========================================================================
|
||||
|
||||
async getFavorites(playlistId: string): Promise<XtreamContentItem[]> {
|
||||
return this.dbService.getFavorites(playlistId);
|
||||
}
|
||||
|
||||
async addFavorite(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
backdropUrl?: string
|
||||
): Promise<void> {
|
||||
await this.dbService.addToFavorites(contentId, playlistId, backdropUrl);
|
||||
}
|
||||
|
||||
async removeFavorite(contentId: number, playlistId: string): Promise<void> {
|
||||
await this.dbService.removeFromFavorites(contentId, playlistId);
|
||||
}
|
||||
|
||||
async isFavorite(contentId: number, playlistId: string): Promise<boolean> {
|
||||
return this.dbService.isFavorite(contentId, playlistId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Recently Viewed Operations
|
||||
// =========================================================================
|
||||
|
||||
async getRecentItems(playlistId: string): Promise<XtreamContentItem[]> {
|
||||
return this.dbService.getRecentItems(playlistId);
|
||||
}
|
||||
|
||||
async addRecentItem(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
backdropUrl?: string
|
||||
): Promise<void> {
|
||||
await this.dbService.addRecentItem(contentId, playlistId, backdropUrl);
|
||||
}
|
||||
|
||||
async removeRecentItem(
|
||||
contentId: number,
|
||||
playlistId: string
|
||||
): Promise<void> {
|
||||
await this.dbService.removeRecentItem(contentId, playlistId);
|
||||
}
|
||||
|
||||
async clearRecentItems(playlistId: string): Promise<void> {
|
||||
await this.dbService.clearPlaylistRecentItems(playlistId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Content Lookup
|
||||
// =========================================================================
|
||||
|
||||
async getContentByXtreamId(
|
||||
xtreamId: number,
|
||||
playlistId: string,
|
||||
contentType?: 'live' | 'movie' | 'series'
|
||||
): Promise<XtreamContentItem | null> {
|
||||
return this.dbService.getContentByXtreamId(
|
||||
xtreamId,
|
||||
playlistId,
|
||||
contentType
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Playback Position Operations
|
||||
// =========================================================================
|
||||
|
||||
async savePlaybackPosition(
|
||||
playlistId: string,
|
||||
data: PlaybackPositionData
|
||||
): Promise<void> {
|
||||
await this.playbackService.savePlaybackPosition(playlistId, data);
|
||||
}
|
||||
|
||||
async getPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<PlaybackPositionData | null> {
|
||||
return this.playbackService.getPlaybackPosition(
|
||||
playlistId,
|
||||
contentXtreamId,
|
||||
contentType
|
||||
);
|
||||
}
|
||||
|
||||
async getSeriesPlaybackPositions(
|
||||
playlistId: string,
|
||||
seriesXtreamId: number
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
return this.playbackService.getSeriesPlaybackPositions(
|
||||
playlistId,
|
||||
seriesXtreamId
|
||||
);
|
||||
}
|
||||
|
||||
async getRecentPlaybackPositions(
|
||||
playlistId: string,
|
||||
limit?: number
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
return this.playbackService.getRecentPlaybackPositions(
|
||||
playlistId,
|
||||
limit
|
||||
);
|
||||
}
|
||||
|
||||
async getAllPlaybackPositions(
|
||||
playlistId: string
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
return this.playbackService.getAllPlaybackPositions(playlistId);
|
||||
}
|
||||
|
||||
async clearPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<void> {
|
||||
await this.playbackService.clearPlaybackPosition(
|
||||
playlistId,
|
||||
contentXtreamId,
|
||||
contentType
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Cleanup Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* No-op for Electron: DB-backed storage has no in-memory session cache to clear.
|
||||
*/
|
||||
clearSessionCache(playlistId: string): void {
|
||||
void playlistId;
|
||||
// Electron uses the DB as its cache layer; no in-memory state to evict.
|
||||
}
|
||||
|
||||
async clearPlaylistContent(
|
||||
playlistId: string
|
||||
): Promise<XtreamPendingRestoreState> {
|
||||
const [result, playbackPositions] = await Promise.all([
|
||||
this.dbService.deleteXtreamPlaylistContent(playlistId),
|
||||
this.playbackService.getAllPlaybackPositions(playlistId),
|
||||
]);
|
||||
|
||||
return {
|
||||
hiddenCategories: result.hiddenCategories,
|
||||
favorites: result.favorites,
|
||||
recentlyViewed: result.recentlyViewed,
|
||||
playbackPositions,
|
||||
};
|
||||
}
|
||||
|
||||
async restoreUserData(
|
||||
playlistId: string,
|
||||
restoreState: XtreamPendingRestoreState,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<void> {
|
||||
await this.dbService.restoreXtreamUserData(
|
||||
playlistId,
|
||||
restoreState.favorites,
|
||||
restoreState.recentlyViewed,
|
||||
options
|
||||
);
|
||||
|
||||
await this.playbackService.clearAllPlaybackPositions(playlistId);
|
||||
|
||||
for (const playbackPosition of restoreState.playbackPositions) {
|
||||
await this.playbackService.savePlaybackPosition(
|
||||
playlistId,
|
||||
playbackPosition
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { inject, Provider } from '@angular/core';
|
||||
import { ElectronXtreamDataSource } from './electron-xtream-data-source';
|
||||
import { PwaXtreamDataSource } from './pwa-xtream-data-source';
|
||||
import { IXtreamDataSource, XTREAM_DATA_SOURCE } from './xtream-data-source.interface';
|
||||
|
||||
// Re-export all types and interfaces
|
||||
export * from './xtream-data-source.interface';
|
||||
export { ElectronXtreamDataSource } from './electron-xtream-data-source';
|
||||
export { PwaXtreamDataSource } from './pwa-xtream-data-source';
|
||||
|
||||
/**
|
||||
* Factory function that returns the appropriate data source based on environment.
|
||||
* - Electron: Uses DatabaseService for DB-first caching
|
||||
* - PWA: Uses API-only with in-memory caching and localStorage for user data
|
||||
*/
|
||||
export function xtreamDataSourceFactory(): IXtreamDataSource {
|
||||
// Check if we're in Electron environment
|
||||
if (typeof window !== 'undefined' && window.electron) {
|
||||
return inject(ElectronXtreamDataSource);
|
||||
}
|
||||
|
||||
// Default to PWA implementation
|
||||
return inject(PwaXtreamDataSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider for the Xtream data source.
|
||||
* Add this to your app providers to enable the data source abstraction.
|
||||
*/
|
||||
export function provideXtreamDataSource(): Provider[] {
|
||||
return [
|
||||
ElectronXtreamDataSource,
|
||||
PwaXtreamDataSource,
|
||||
{
|
||||
provide: XTREAM_DATA_SOURCE,
|
||||
useFactory: xtreamDataSourceFactory,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
XtreamPendingRestoreState,
|
||||
XtreamCategory,
|
||||
XtreamLiveStream,
|
||||
XtreamSerieItem,
|
||||
XtreamVodStream,
|
||||
} from 'shared-interfaces';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
import {
|
||||
CategoryType,
|
||||
StreamType,
|
||||
XtreamApiService,
|
||||
XtreamCredentials,
|
||||
} from '../services/xtream-api.service';
|
||||
import {
|
||||
DbCategoryType,
|
||||
IXtreamDataSource,
|
||||
ProgressCallback,
|
||||
XtreamOperationOptions,
|
||||
XtreamCategoryFromDb,
|
||||
XtreamContentItem,
|
||||
XtreamPlaylistData,
|
||||
} from './xtream-data-source.interface';
|
||||
|
||||
/**
|
||||
* LocalStorage keys for PWA persistence
|
||||
*/
|
||||
const STORAGE_KEYS = {
|
||||
FAVORITES: 'xtream-favorites',
|
||||
RECENT_ITEMS: 'xtream-recent-items',
|
||||
PLAYLISTS: 'xtream-playlists',
|
||||
PLAYBACK_POSITIONS: 'xtream-playback-positions',
|
||||
};
|
||||
|
||||
interface XtreamCachedContentItem {
|
||||
readonly added?: string;
|
||||
readonly category_id?: string | number;
|
||||
readonly id?: number;
|
||||
readonly name?: string;
|
||||
readonly poster_url?: string;
|
||||
readonly series_id?: number;
|
||||
readonly stream_display_name?: string;
|
||||
readonly stream_id?: number;
|
||||
readonly stream_icon?: string;
|
||||
readonly title?: string;
|
||||
readonly type?: string;
|
||||
readonly viewed_at?: string;
|
||||
}
|
||||
|
||||
interface StoredRecentItem {
|
||||
readonly id: number;
|
||||
readonly viewedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* PWA implementation of the Xtream data source.
|
||||
* Uses API-only strategy: always fetch from API, no database caching.
|
||||
* Favorites and recently viewed are stored in localStorage.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PwaXtreamDataSource implements IXtreamDataSource {
|
||||
private readonly apiService = inject(XtreamApiService);
|
||||
private readonly logger = createLogger('PwaXtreamDataSource');
|
||||
|
||||
// In-memory cache for the current session
|
||||
private categoryCache = new Map<string, XtreamCategory[]>();
|
||||
private contentCache = new Map<string, XtreamCachedContentItem[]>();
|
||||
|
||||
// =========================================================================
|
||||
// Playlist Operations (localStorage)
|
||||
// =========================================================================
|
||||
|
||||
async getPlaylist(playlistId: string): Promise<XtreamPlaylistData | null> {
|
||||
const playlists = this.getPlaylistsFromStorage();
|
||||
return playlists.find((p) => p.id === playlistId) || null;
|
||||
}
|
||||
|
||||
async createPlaylist(playlist: XtreamPlaylistData): Promise<void> {
|
||||
const playlists = this.getPlaylistsFromStorage();
|
||||
playlists.push(playlist);
|
||||
this.savePlaylistsToStorage(playlists);
|
||||
}
|
||||
|
||||
async updatePlaylist(
|
||||
playlistId: string,
|
||||
updates: Partial<XtreamPlaylistData>
|
||||
): Promise<void> {
|
||||
const playlists = this.getPlaylistsFromStorage();
|
||||
const index = playlists.findIndex((p) => p.id === playlistId);
|
||||
if (index !== -1) {
|
||||
playlists[index] = { ...playlists[index], ...updates };
|
||||
this.savePlaylistsToStorage(playlists);
|
||||
}
|
||||
}
|
||||
|
||||
async deletePlaylist(playlistId: string): Promise<void> {
|
||||
const playlists = this.getPlaylistsFromStorage();
|
||||
const filtered = playlists.filter((p) => p.id !== playlistId);
|
||||
this.savePlaylistsToStorage(filtered);
|
||||
|
||||
// Also clear favorites and recent items for this playlist
|
||||
this.clearFavoritesForPlaylist(playlistId);
|
||||
this.clearRecentItemsForPlaylist(playlistId);
|
||||
this.clearPlaybackPositionsForPlaylist(playlistId);
|
||||
|
||||
// Clear cache
|
||||
this.clearCacheForPlaylist(playlistId);
|
||||
}
|
||||
|
||||
private getPlaylistsFromStorage(): XtreamPlaylistData[] {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.PLAYLISTS);
|
||||
return data ? JSON.parse(data) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private savePlaylistsToStorage(playlists: XtreamPlaylistData[]): void {
|
||||
localStorage.setItem(STORAGE_KEYS.PLAYLISTS, JSON.stringify(playlists));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Category Operations (API + in-memory cache)
|
||||
// =========================================================================
|
||||
|
||||
async hasCategories(
|
||||
playlistId: string,
|
||||
type: DbCategoryType
|
||||
): Promise<boolean> {
|
||||
const cacheKey = `${playlistId}-${type}-categories`;
|
||||
return this.categoryCache.has(cacheKey);
|
||||
}
|
||||
|
||||
async getCategories(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: CategoryType,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamCategory[]> {
|
||||
void options;
|
||||
const cacheKey = `${playlistId}-${type}-categories`;
|
||||
|
||||
// Check in-memory cache first
|
||||
const cachedCategories = this.categoryCache.get(cacheKey);
|
||||
if (cachedCategories) {
|
||||
return cachedCategories;
|
||||
}
|
||||
|
||||
// Fetch from API
|
||||
const categories = await this.apiService.getCategories(
|
||||
credentials,
|
||||
type
|
||||
);
|
||||
|
||||
// Cache in memory
|
||||
this.categoryCache.set(cacheKey, categories);
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
async getAllCategories(
|
||||
playlistId: string,
|
||||
type: DbCategoryType
|
||||
): Promise<XtreamCategoryFromDb[]> {
|
||||
void playlistId;
|
||||
void type;
|
||||
// PWA doesn't track hidden categories - return empty
|
||||
return [];
|
||||
}
|
||||
|
||||
async saveCategories(
|
||||
playlistId: string,
|
||||
categories: XtreamCategory[],
|
||||
type: DbCategoryType
|
||||
): Promise<void> {
|
||||
// In PWA mode, we just cache in memory
|
||||
const cacheKey = `${playlistId}-${type}-categories`;
|
||||
this.categoryCache.set(cacheKey, categories);
|
||||
}
|
||||
|
||||
async updateCategoryVisibility(
|
||||
categoryIds: number[],
|
||||
hidden: boolean
|
||||
): Promise<void> {
|
||||
void categoryIds;
|
||||
void hidden;
|
||||
// Category visibility is not supported in PWA mode
|
||||
this.logger.warn('Category visibility not supported in PWA mode');
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Content/Stream Operations (API + in-memory cache)
|
||||
// =========================================================================
|
||||
|
||||
async hasContent(
|
||||
playlistId: string,
|
||||
type: 'live' | 'movie' | 'series'
|
||||
): Promise<boolean> {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
return this.contentCache.has(cacheKey);
|
||||
}
|
||||
|
||||
async getContent(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: StreamType,
|
||||
onProgress?: (count: number) => void,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamLiveStream[] | XtreamVodStream[] | XtreamSerieItem[]> {
|
||||
void options;
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
|
||||
// Check in-memory cache first
|
||||
const cachedContent = this.contentCache.get(cacheKey);
|
||||
if (cachedContent) {
|
||||
return cachedContent as
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[];
|
||||
}
|
||||
|
||||
// Fetch from API
|
||||
const content = await this.apiService.getStreams(credentials, type);
|
||||
|
||||
// Report total and progress (PWA doesn't have incremental save, so report all at once)
|
||||
if (onTotal) {
|
||||
onTotal(content.length);
|
||||
}
|
||||
if (onProgress) {
|
||||
onProgress(content.length);
|
||||
}
|
||||
|
||||
// Cache in memory
|
||||
this.contentCache.set(cacheKey, content);
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
async saveContent(
|
||||
playlistId: string,
|
||||
streams:
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[]
|
||||
| XtreamContentItem[],
|
||||
type: 'live' | 'movie' | 'series',
|
||||
onProgress?: ProgressCallback,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<number> {
|
||||
void options;
|
||||
// In PWA mode, we just cache in memory
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
this.contentCache.set(cacheKey, streams);
|
||||
|
||||
if (onProgress) {
|
||||
onProgress(streams.length);
|
||||
}
|
||||
|
||||
return streams.length;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Search Operations (in-memory filter)
|
||||
// =========================================================================
|
||||
|
||||
async searchContent(
|
||||
playlistId: string,
|
||||
searchTerm: string,
|
||||
types: string[],
|
||||
excludeHidden?: boolean
|
||||
): Promise<XtreamContentItem[]> {
|
||||
void excludeHidden;
|
||||
const results: XtreamCachedContentItem[] = [];
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
|
||||
for (const type of types) {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
const content = this.contentCache.get(cacheKey) || [];
|
||||
|
||||
const filtered = content.filter((item) => {
|
||||
const title =
|
||||
item.name || item.title || item.stream_display_name || '';
|
||||
return title.toLowerCase().includes(searchLower);
|
||||
});
|
||||
|
||||
results.push(...filtered);
|
||||
}
|
||||
|
||||
return results as XtreamContentItem[];
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Favorites Operations (localStorage)
|
||||
// =========================================================================
|
||||
|
||||
async getFavorites(playlistId: string): Promise<XtreamContentItem[]> {
|
||||
const allFavorites = this.getFavoritesFromStorage();
|
||||
const playlistFavorites = allFavorites[playlistId] || [];
|
||||
|
||||
// Match favorites with cached content
|
||||
const results: XtreamCachedContentItem[] = [];
|
||||
for (const type of ['live', 'movie', 'series']) {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
const content = this.contentCache.get(cacheKey) || [];
|
||||
|
||||
for (const item of content) {
|
||||
const itemId = item.stream_id || item.series_id || item.id;
|
||||
if (playlistFavorites.includes(itemId)) {
|
||||
results.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results as XtreamContentItem[];
|
||||
}
|
||||
|
||||
async addFavorite(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
// PWA uses localStorage with no content table, so backdrop persistence
|
||||
// is electron-only. Accept the param for interface parity.
|
||||
_backdropUrl?: string
|
||||
): Promise<void> {
|
||||
const allFavorites = this.getFavoritesFromStorage();
|
||||
if (!allFavorites[playlistId]) {
|
||||
allFavorites[playlistId] = [];
|
||||
}
|
||||
if (!allFavorites[playlistId].includes(contentId)) {
|
||||
allFavorites[playlistId].push(contentId);
|
||||
}
|
||||
this.saveFavoritesToStorage(allFavorites);
|
||||
}
|
||||
|
||||
async removeFavorite(contentId: number, playlistId: string): Promise<void> {
|
||||
const allFavorites = this.getFavoritesFromStorage();
|
||||
if (allFavorites[playlistId]) {
|
||||
allFavorites[playlistId] = allFavorites[playlistId].filter(
|
||||
(id: number) => id !== contentId
|
||||
);
|
||||
}
|
||||
this.saveFavoritesToStorage(allFavorites);
|
||||
}
|
||||
|
||||
async isFavorite(contentId: number, playlistId: string): Promise<boolean> {
|
||||
const allFavorites = this.getFavoritesFromStorage();
|
||||
return (allFavorites[playlistId] || []).includes(contentId);
|
||||
}
|
||||
|
||||
private getFavoritesFromStorage(): Record<string, number[]> {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.FAVORITES);
|
||||
return data ? JSON.parse(data) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
private saveFavoritesToStorage(favorites: Record<string, number[]>): void {
|
||||
localStorage.setItem(STORAGE_KEYS.FAVORITES, JSON.stringify(favorites));
|
||||
}
|
||||
|
||||
private clearFavoritesForPlaylist(playlistId: string): void {
|
||||
const allFavorites = this.getFavoritesFromStorage();
|
||||
delete allFavorites[playlistId];
|
||||
this.saveFavoritesToStorage(allFavorites);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Playback Position Operations (localStorage)
|
||||
// =========================================================================
|
||||
|
||||
async savePlaybackPosition(
|
||||
playlistId: string,
|
||||
data: PlaybackPositionData
|
||||
): Promise<void> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
if (!allPositions[playlistId]) {
|
||||
allPositions[playlistId] = [];
|
||||
}
|
||||
|
||||
// Remove existing entry if present
|
||||
allPositions[playlistId] = allPositions[playlistId].filter(
|
||||
(p) =>
|
||||
!(
|
||||
p.contentXtreamId === data.contentXtreamId &&
|
||||
p.contentType === data.contentType
|
||||
)
|
||||
);
|
||||
|
||||
// Add new entry
|
||||
allPositions[playlistId].push({
|
||||
...data,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
this.savePlaybackPositionsToStorage(allPositions);
|
||||
}
|
||||
|
||||
async getPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<PlaybackPositionData | null> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
const playlistPositions = allPositions[playlistId] || [];
|
||||
|
||||
return (
|
||||
playlistPositions.find(
|
||||
(p) =>
|
||||
p.contentXtreamId === contentXtreamId &&
|
||||
p.contentType === contentType
|
||||
) || null
|
||||
);
|
||||
}
|
||||
|
||||
async getSeriesPlaybackPositions(
|
||||
playlistId: string,
|
||||
seriesXtreamId: number
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
const playlistPositions = allPositions[playlistId] || [];
|
||||
|
||||
return playlistPositions.filter(
|
||||
(p) =>
|
||||
p.contentType === 'episode' &&
|
||||
p.seriesXtreamId === seriesXtreamId
|
||||
);
|
||||
}
|
||||
|
||||
async getRecentPlaybackPositions(
|
||||
playlistId: string,
|
||||
limit?: number
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
const playlistPositions = allPositions[playlistId] || [];
|
||||
|
||||
// Sort by updatedAt descending
|
||||
playlistPositions.sort(
|
||||
(a, b) =>
|
||||
new Date(b.updatedAt).getTime() -
|
||||
new Date(a.updatedAt).getTime()
|
||||
);
|
||||
|
||||
return limit ? playlistPositions.slice(0, limit) : playlistPositions;
|
||||
}
|
||||
|
||||
async getAllPlaybackPositions(
|
||||
playlistId: string
|
||||
): Promise<PlaybackPositionData[]> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
return allPositions[playlistId] || [];
|
||||
}
|
||||
|
||||
async clearPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<void> {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
if (allPositions[playlistId]) {
|
||||
allPositions[playlistId] = allPositions[playlistId].filter(
|
||||
(p) =>
|
||||
!(
|
||||
p.contentXtreamId === contentXtreamId &&
|
||||
p.contentType === contentType
|
||||
)
|
||||
);
|
||||
this.savePlaybackPositionsToStorage(allPositions);
|
||||
}
|
||||
}
|
||||
|
||||
private getPlaybackPositionsFromStorage(): Record<
|
||||
string,
|
||||
PlaybackPositionData[]
|
||||
> {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.PLAYBACK_POSITIONS);
|
||||
return data ? JSON.parse(data) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
private savePlaybackPositionsToStorage(
|
||||
positions: Record<string, PlaybackPositionData[]>
|
||||
): void {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEYS.PLAYBACK_POSITIONS,
|
||||
JSON.stringify(positions)
|
||||
);
|
||||
}
|
||||
|
||||
private clearPlaybackPositionsForPlaylist(playlistId: string): void {
|
||||
const allPositions = this.getPlaybackPositionsFromStorage();
|
||||
delete allPositions[playlistId];
|
||||
this.savePlaybackPositionsToStorage(allPositions);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Recently Viewed Operations (localStorage)
|
||||
// =========================================================================
|
||||
|
||||
async getRecentItems(playlistId: string): Promise<XtreamContentItem[]> {
|
||||
const allRecent = this.getRecentItemsFromStorage();
|
||||
const playlistRecent = allRecent[playlistId] || [];
|
||||
|
||||
// Match recent items with cached content
|
||||
const results: (XtreamCachedContentItem & { viewed_at: string })[] = [];
|
||||
for (const type of ['live', 'movie', 'series']) {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
const content = this.contentCache.get(cacheKey) || [];
|
||||
|
||||
for (const item of content) {
|
||||
const itemId = item.stream_id || item.series_id || item.id;
|
||||
const recentEntry = playlistRecent.find((r) => r.id === itemId);
|
||||
if (recentEntry) {
|
||||
results.push({
|
||||
...item,
|
||||
viewed_at: recentEntry.viewedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by viewed_at descending
|
||||
results.sort(
|
||||
(a, b) =>
|
||||
new Date(b.viewed_at).getTime() -
|
||||
new Date(a.viewed_at).getTime()
|
||||
);
|
||||
|
||||
return results as XtreamContentItem[];
|
||||
}
|
||||
|
||||
async addRecentItem(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
_backdropUrl?: string
|
||||
): Promise<void> {
|
||||
const allRecent = this.getRecentItemsFromStorage();
|
||||
if (!allRecent[playlistId]) {
|
||||
allRecent[playlistId] = [];
|
||||
}
|
||||
|
||||
// Remove existing entry if present
|
||||
allRecent[playlistId] = allRecent[playlistId].filter(
|
||||
(r) => r.id !== contentId
|
||||
);
|
||||
|
||||
// Add new entry at the beginning
|
||||
allRecent[playlistId].unshift({
|
||||
id: contentId,
|
||||
viewedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
// Keep only last 50 items
|
||||
allRecent[playlistId] = allRecent[playlistId].slice(0, 50);
|
||||
|
||||
this.saveRecentItemsToStorage(allRecent);
|
||||
}
|
||||
|
||||
async removeRecentItem(
|
||||
contentId: number,
|
||||
playlistId: string
|
||||
): Promise<void> {
|
||||
const allRecent = this.getRecentItemsFromStorage();
|
||||
if (allRecent[playlistId]) {
|
||||
allRecent[playlistId] = allRecent[playlistId].filter(
|
||||
(r) => r.id !== contentId
|
||||
);
|
||||
}
|
||||
this.saveRecentItemsToStorage(allRecent);
|
||||
}
|
||||
|
||||
async clearRecentItems(playlistId: string): Promise<void> {
|
||||
this.clearRecentItemsForPlaylist(playlistId);
|
||||
}
|
||||
|
||||
private getRecentItemsFromStorage(): Record<string, StoredRecentItem[]> {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.RECENT_ITEMS);
|
||||
return data ? JSON.parse(data) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
private saveRecentItemsToStorage(
|
||||
recentItems: Record<string, StoredRecentItem[]>
|
||||
): void {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEYS.RECENT_ITEMS,
|
||||
JSON.stringify(recentItems)
|
||||
);
|
||||
}
|
||||
|
||||
private clearRecentItemsForPlaylist(playlistId: string): void {
|
||||
const allRecent = this.getRecentItemsFromStorage();
|
||||
delete allRecent[playlistId];
|
||||
this.saveRecentItemsToStorage(allRecent);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Content Lookup
|
||||
// =========================================================================
|
||||
|
||||
async getContentByXtreamId(
|
||||
xtreamId: number,
|
||||
playlistId: string,
|
||||
contentType?: 'live' | 'movie' | 'series'
|
||||
): Promise<XtreamContentItem | null> {
|
||||
const types = contentType
|
||||
? [contentType]
|
||||
: (['live', 'movie', 'series'] as const);
|
||||
|
||||
for (const type of types) {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
const content = this.contentCache.get(cacheKey) || [];
|
||||
|
||||
const found = content.find((item) => {
|
||||
const itemXtreamId =
|
||||
item.stream_id || item.series_id || item.id;
|
||||
return itemXtreamId === xtreamId;
|
||||
});
|
||||
|
||||
if (found) {
|
||||
return found as XtreamContentItem;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private findContentIdentity(
|
||||
playlistId: string,
|
||||
xtreamId: number,
|
||||
contentType?: 'live' | 'movie' | 'series'
|
||||
): { contentType: 'live' | 'movie' | 'series'; xtreamId: number } | null {
|
||||
const types = contentType
|
||||
? [contentType]
|
||||
: (['live', 'movie', 'series'] as const);
|
||||
|
||||
for (const type of types) {
|
||||
const cacheKey = `${playlistId}-${type}-content`;
|
||||
const content = this.contentCache.get(cacheKey) || [];
|
||||
|
||||
const found = content.find((item) => {
|
||||
const itemXtreamId =
|
||||
item.stream_id || item.series_id || item.id;
|
||||
return itemXtreamId === xtreamId;
|
||||
});
|
||||
|
||||
if (found) {
|
||||
return {
|
||||
contentType: type,
|
||||
xtreamId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Cleanup Operations
|
||||
// =========================================================================
|
||||
|
||||
async clearPlaylistContent(
|
||||
playlistId: string
|
||||
): Promise<XtreamPendingRestoreState> {
|
||||
// Get current favorites and recent items
|
||||
const favorites = this.getFavoritesFromStorage();
|
||||
const recentItems = this.getRecentItemsFromStorage();
|
||||
const playbackPositions =
|
||||
await this.getAllPlaybackPositions(playlistId);
|
||||
|
||||
const typedFavorites = (favorites[playlistId] || [])
|
||||
.map((xtreamId) => this.findContentIdentity(playlistId, xtreamId))
|
||||
.filter(
|
||||
(
|
||||
value
|
||||
): value is {
|
||||
contentType: 'live' | 'movie' | 'series';
|
||||
xtreamId: number;
|
||||
} => value !== null
|
||||
);
|
||||
|
||||
const typedRecentlyViewed = (recentItems[playlistId] || [])
|
||||
.map((item) => {
|
||||
const identity = this.findContentIdentity(playlistId, item.id);
|
||||
|
||||
if (!identity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...identity,
|
||||
viewedAt: item.viewedAt,
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(
|
||||
value
|
||||
): value is {
|
||||
contentType: 'live' | 'movie' | 'series';
|
||||
xtreamId: number;
|
||||
viewedAt: string;
|
||||
} => value !== null
|
||||
);
|
||||
|
||||
// Clear in-memory cache
|
||||
this.clearCacheForPlaylist(playlistId);
|
||||
|
||||
return {
|
||||
hiddenCategories: [],
|
||||
favorites: typedFavorites,
|
||||
recentlyViewed: typedRecentlyViewed,
|
||||
playbackPositions,
|
||||
};
|
||||
}
|
||||
|
||||
async restoreUserData(
|
||||
playlistId: string,
|
||||
restoreState: XtreamPendingRestoreState,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<void> {
|
||||
void options;
|
||||
// Restore favorites
|
||||
const favorites = this.getFavoritesFromStorage();
|
||||
favorites[playlistId] = restoreState.favorites.map(
|
||||
(item) => item.xtreamId
|
||||
);
|
||||
this.saveFavoritesToStorage(favorites);
|
||||
|
||||
// Restore recent items
|
||||
const recentItems = this.getRecentItemsFromStorage();
|
||||
recentItems[playlistId] = restoreState.recentlyViewed.map((item) => ({
|
||||
id: item.xtreamId,
|
||||
viewedAt: item.viewedAt,
|
||||
}));
|
||||
this.saveRecentItemsToStorage(recentItems);
|
||||
|
||||
// Restore playback positions
|
||||
this.clearPlaybackPositionsForPlaylist(playlistId);
|
||||
const playbackPositions = this.getPlaybackPositionsFromStorage();
|
||||
playbackPositions[playlistId] = restoreState.playbackPositions.map(
|
||||
(position) => ({
|
||||
...position,
|
||||
updatedAt: position.updatedAt ?? new Date().toISOString(),
|
||||
})
|
||||
);
|
||||
this.savePlaybackPositionsToStorage(playbackPositions);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Cache Management
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Clear in-memory cache entries for a specific playlist.
|
||||
* Called by the store when switching playlists to prevent stale data bleed.
|
||||
*/
|
||||
clearSessionCache(playlistId: string): void {
|
||||
this.clearCacheForPlaylist(playlistId);
|
||||
}
|
||||
|
||||
private clearCacheForPlaylist(playlistId: string): void {
|
||||
const keysToDelete: string[] = [];
|
||||
|
||||
this.categoryCache.forEach((_, key) => {
|
||||
if (key.startsWith(playlistId)) {
|
||||
keysToDelete.push(key);
|
||||
}
|
||||
});
|
||||
keysToDelete.forEach((key) => this.categoryCache.delete(key));
|
||||
|
||||
const contentKeysToDelete: string[] = [];
|
||||
this.contentCache.forEach((_, key) => {
|
||||
if (key.startsWith(playlistId)) {
|
||||
contentKeysToDelete.push(key);
|
||||
}
|
||||
});
|
||||
contentKeysToDelete.forEach((key) => this.contentCache.delete(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all in-memory caches
|
||||
*/
|
||||
clearAllCaches(): void {
|
||||
this.categoryCache.clear();
|
||||
this.contentCache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
XtreamPendingRestoreState,
|
||||
XtreamCategory,
|
||||
XtreamLiveStream,
|
||||
XtreamSerieItem,
|
||||
XtreamVodStream,
|
||||
} from 'shared-interfaces';
|
||||
import type { DbOperationEvent } from 'services';
|
||||
import {
|
||||
CategoryType,
|
||||
StreamType,
|
||||
XtreamCredentials,
|
||||
} from '../services/xtream-api.service';
|
||||
|
||||
// Re-export for backward compatibility
|
||||
export { PlaybackPositionData };
|
||||
|
||||
/**
|
||||
* Playlist representation in the data source
|
||||
*/
|
||||
export interface XtreamPlaylistData {
|
||||
id: string;
|
||||
name: string;
|
||||
title?: string; // Alias for name, used in some templates
|
||||
updateDate?: number;
|
||||
serverUrl: string;
|
||||
username: string;
|
||||
password: string;
|
||||
type: string;
|
||||
userAgent?: string;
|
||||
referrer?: string;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Content item from the data source.
|
||||
* Includes fields from XtreamItem for template compatibility.
|
||||
*/
|
||||
export interface XtreamContentItem {
|
||||
// Core DB fields
|
||||
id: number;
|
||||
category_id: number | string; // Can be number (DB) or string (API)
|
||||
title: string;
|
||||
rating: string;
|
||||
added: string;
|
||||
poster_url: string;
|
||||
epg_channel_id?: string | null;
|
||||
tv_archive?: number | null;
|
||||
tv_archive_duration?: number | null;
|
||||
direct_source?: string | null;
|
||||
xtream_id: number;
|
||||
type: string;
|
||||
added_at?: string;
|
||||
viewed_at?: string;
|
||||
position?: number | null;
|
||||
|
||||
// XtreamItem compatibility fields (optional for search/navigation)
|
||||
num?: number;
|
||||
name?: string;
|
||||
stream_type?: 'live' | 'movie';
|
||||
stream_id?: number;
|
||||
stream_icon?: string;
|
||||
custom_sid?: string;
|
||||
rating_imdb?: string;
|
||||
|
||||
// Global search result fields
|
||||
description?: string;
|
||||
playlist_id?: string;
|
||||
playlist_name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Category from the database with additional fields
|
||||
*/
|
||||
export interface XtreamCategoryFromDb {
|
||||
id: number;
|
||||
name: string;
|
||||
playlist_id: string;
|
||||
type: 'movies' | 'live' | 'series';
|
||||
xtream_id: number;
|
||||
hidden: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recently viewed item with playlist info
|
||||
*/
|
||||
export interface RecentlyViewedItem extends XtreamContentItem {
|
||||
viewed_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Database category type mapping (differs from API type)
|
||||
*/
|
||||
export type DbCategoryType = 'live' | 'movies' | 'series';
|
||||
|
||||
/**
|
||||
* Maps CategoryType to DbCategoryType
|
||||
*/
|
||||
export function mapCategoryTypeToDbType(type: CategoryType): DbCategoryType {
|
||||
switch (type) {
|
||||
case 'live':
|
||||
return 'live';
|
||||
case 'vod':
|
||||
return 'movies';
|
||||
case 'series':
|
||||
return 'series';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps StreamType to DbCategoryType for content storage
|
||||
*/
|
||||
export function mapStreamTypeToDbType(
|
||||
type: StreamType
|
||||
): 'live' | 'movie' | 'series' {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Progress callback for bulk operations
|
||||
*/
|
||||
export type ProgressCallback = (count: number) => void;
|
||||
|
||||
export interface XtreamOperationOptions {
|
||||
operationId?: string;
|
||||
sessionId?: string;
|
||||
onEvent?: (event: DbOperationEvent) => void;
|
||||
onPhaseChange?: (phase: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract interface for Xtream data source.
|
||||
* Allows different implementations for Electron (DB-first) and PWA (API-only).
|
||||
*/
|
||||
export interface IXtreamDataSource {
|
||||
// =========================================================================
|
||||
// Playlist Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get playlist by ID
|
||||
*/
|
||||
getPlaylist(playlistId: string): Promise<XtreamPlaylistData | null>;
|
||||
|
||||
/**
|
||||
* Create a new playlist
|
||||
*/
|
||||
createPlaylist(playlist: XtreamPlaylistData): Promise<void>;
|
||||
|
||||
/**
|
||||
* Update playlist details
|
||||
*/
|
||||
updatePlaylist(
|
||||
playlistId: string,
|
||||
updates: Partial<XtreamPlaylistData>
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Delete a playlist and all its data
|
||||
*/
|
||||
deletePlaylist(playlistId: string): Promise<void>;
|
||||
|
||||
// =========================================================================
|
||||
// Category Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Check if categories exist for a playlist and type
|
||||
*/
|
||||
hasCategories(playlistId: string, type: DbCategoryType): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Get categories for a playlist and type
|
||||
* Returns only visible categories by default
|
||||
*/
|
||||
getCategories(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: CategoryType,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<XtreamCategory[] | XtreamCategoryFromDb[]>;
|
||||
|
||||
/**
|
||||
* Get all categories including hidden (for management)
|
||||
*/
|
||||
getAllCategories(
|
||||
playlistId: string,
|
||||
type: DbCategoryType
|
||||
): Promise<XtreamCategoryFromDb[]>;
|
||||
|
||||
/**
|
||||
* Save categories in bulk
|
||||
*/
|
||||
saveCategories(
|
||||
playlistId: string,
|
||||
categories: XtreamCategory[],
|
||||
type: DbCategoryType
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Update category visibility
|
||||
*/
|
||||
updateCategoryVisibility(
|
||||
categoryIds: number[],
|
||||
hidden: boolean
|
||||
): Promise<void>;
|
||||
|
||||
// =========================================================================
|
||||
// Content/Stream Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Check if content exists for a playlist and type
|
||||
*/
|
||||
hasContent(
|
||||
playlistId: string,
|
||||
type: 'live' | 'movie' | 'series'
|
||||
): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Get content/streams for a playlist and type
|
||||
* @param onProgress - Optional callback for import progress (count)
|
||||
* @param onTotal - Optional callback for total items to import
|
||||
*/
|
||||
getContent(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
type: StreamType,
|
||||
onProgress?: ProgressCallback,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[]
|
||||
| XtreamContentItem[]
|
||||
>;
|
||||
|
||||
/**
|
||||
* Save content in bulk
|
||||
*/
|
||||
saveContent(
|
||||
playlistId: string,
|
||||
streams:
|
||||
| XtreamLiveStream[]
|
||||
| XtreamVodStream[]
|
||||
| XtreamSerieItem[]
|
||||
| XtreamContentItem[],
|
||||
type: 'live' | 'movie' | 'series',
|
||||
onProgress?: ProgressCallback,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<number>;
|
||||
|
||||
// =========================================================================
|
||||
// Search Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Search content within a playlist
|
||||
*/
|
||||
searchContent(
|
||||
playlistId: string,
|
||||
searchTerm: string,
|
||||
types: string[],
|
||||
excludeHidden?: boolean
|
||||
): Promise<XtreamContentItem[]>;
|
||||
|
||||
// =========================================================================
|
||||
// Favorites Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get all favorites for a playlist
|
||||
*/
|
||||
getFavorites(playlistId: string): Promise<XtreamContentItem[]>;
|
||||
|
||||
/**
|
||||
* Add content to favorites.
|
||||
* @param backdropUrl optionally persisted to `content.backdrop_url` when
|
||||
* the row doesn't already have one. Enables the dashboard hero to surface
|
||||
* a cinematic backdrop without a separate round-trip.
|
||||
*/
|
||||
addFavorite(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
backdropUrl?: string
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Remove content from favorites
|
||||
*/
|
||||
removeFavorite(contentId: number, playlistId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Check if content is favorited
|
||||
*/
|
||||
isFavorite(contentId: number, playlistId: string): Promise<boolean>;
|
||||
|
||||
// =========================================================================
|
||||
// Recently Viewed Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get recently viewed items for a playlist
|
||||
*/
|
||||
getRecentItems(playlistId: string): Promise<XtreamContentItem[]>;
|
||||
|
||||
/**
|
||||
* Add item to recently viewed. See `addFavorite` for `backdropUrl`.
|
||||
*/
|
||||
addRecentItem(
|
||||
contentId: number,
|
||||
playlistId: string,
|
||||
backdropUrl?: string
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Remove item from recently viewed
|
||||
*/
|
||||
removeRecentItem(contentId: number, playlistId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Clear recently viewed for a playlist
|
||||
*/
|
||||
clearRecentItems(playlistId: string): Promise<void>;
|
||||
|
||||
// =========================================================================
|
||||
// Content Lookup
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get content by xtream ID
|
||||
*/
|
||||
getContentByXtreamId(
|
||||
xtreamId: number,
|
||||
playlistId: string,
|
||||
contentType?: 'live' | 'movie' | 'series'
|
||||
): Promise<XtreamContentItem | null>;
|
||||
|
||||
// =========================================================================
|
||||
// Playback Position Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Save/update playback position for content
|
||||
*/
|
||||
savePlaybackPosition(
|
||||
playlistId: string,
|
||||
data: PlaybackPositionData
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Get playback position for a specific content item
|
||||
*/
|
||||
getPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<PlaybackPositionData | null>;
|
||||
|
||||
/**
|
||||
* Get all episode positions for a series (for highlighting watched episodes)
|
||||
*/
|
||||
getSeriesPlaybackPositions(
|
||||
playlistId: string,
|
||||
seriesXtreamId: number
|
||||
): Promise<PlaybackPositionData[]>;
|
||||
|
||||
/**
|
||||
* Get recently watched items with positions (for "Continue Watching" section)
|
||||
*/
|
||||
getRecentPlaybackPositions(
|
||||
playlistId: string,
|
||||
limit?: number
|
||||
): Promise<PlaybackPositionData[]>;
|
||||
|
||||
/**
|
||||
* Get all playback positions for a playlist (for grid view)
|
||||
*/
|
||||
getAllPlaybackPositions(
|
||||
playlistId: string
|
||||
): Promise<PlaybackPositionData[]>;
|
||||
|
||||
/**
|
||||
* Clear playback position (mark as unwatched)
|
||||
*/
|
||||
clearPlaybackPosition(
|
||||
playlistId: string,
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): Promise<void>;
|
||||
|
||||
// =========================================================================
|
||||
// Cleanup Operations
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Clear any in-memory session cache for a playlist.
|
||||
* Called when the store resets for a playlist switch so stale data
|
||||
* cannot bleed into the new session (relevant for the PWA implementation).
|
||||
*/
|
||||
clearSessionCache(playlistId: string): void;
|
||||
|
||||
/**
|
||||
* Clear all content and categories for a playlist (for refresh)
|
||||
* Returns user data (favorites, recently viewed) for restoration
|
||||
*/
|
||||
clearPlaylistContent(
|
||||
playlistId: string
|
||||
): Promise<XtreamPendingRestoreState>;
|
||||
|
||||
/**
|
||||
* Restore user data after refresh
|
||||
*/
|
||||
restoreUserData(
|
||||
playlistId: string,
|
||||
restoreState: XtreamPendingRestoreState,
|
||||
options?: XtreamOperationOptions
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injection token for the data source
|
||||
*/
|
||||
export const XTREAM_DATA_SOURCE = new InjectionToken<IXtreamDataSource>(
|
||||
'XtreamDataSource'
|
||||
);
|
||||
@@ -0,0 +1,85 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { EpgQueueService } from './epg-queue.service';
|
||||
import { XtreamApiService } from './xtream-api.service';
|
||||
|
||||
describe('EpgQueueService', () => {
|
||||
let service: EpgQueueService;
|
||||
let xtreamApi: { getShortEpg: jest.Mock };
|
||||
|
||||
const credentials = {
|
||||
serverUrl: 'https://xtream.example.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
|
||||
xtreamApi = {
|
||||
getShortEpg: jest.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
EpgQueueService,
|
||||
{
|
||||
provide: XtreamApiService,
|
||||
useValue: xtreamApi,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(EpgQueueService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('caches empty EPG responses and does not immediately refetch them', async () => {
|
||||
xtreamApi.getShortEpg.mockResolvedValue([]);
|
||||
|
||||
await (service as unknown as { fetchEpg: (credentials: typeof credentials, streamId: number) => Promise<void> }).fetchEpg(
|
||||
credentials,
|
||||
101
|
||||
);
|
||||
|
||||
expect(service.getCached(101)).toEqual([]);
|
||||
expect(xtreamApi.getShortEpg).toHaveBeenCalledWith(
|
||||
credentials,
|
||||
101,
|
||||
3,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
);
|
||||
expect(
|
||||
(service as unknown as { shouldFetch: (streamId: number) => boolean }).shouldFetch(
|
||||
101
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('applies a cooldown after EPG request failures', async () => {
|
||||
xtreamApi.getShortEpg.mockRejectedValue(new Error('EPG failed'));
|
||||
|
||||
await (service as unknown as { fetchEpg: (credentials: typeof credentials, streamId: number) => Promise<void> }).fetchEpg(
|
||||
credentials,
|
||||
202
|
||||
);
|
||||
|
||||
expect(
|
||||
(service as unknown as { shouldFetch: (streamId: number) => boolean }).shouldFetch(
|
||||
202
|
||||
)
|
||||
).toBe(false);
|
||||
|
||||
jest.advanceTimersByTime(60_001);
|
||||
|
||||
expect(
|
||||
(service as unknown as { shouldFetch: (streamId: number) => boolean }).shouldFetch(
|
||||
202
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { inject, Injectable, OnDestroy } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
import { EpgItem } from 'shared-interfaces';
|
||||
import { XtreamApiService, XtreamCredentials } from './xtream-api.service';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
interface CacheEntry {
|
||||
data: EpgItem[];
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Throttled EPG request queue with concurrency control, inter-request
|
||||
* delay, and in-memory caching. Prevents Xtream providers from
|
||||
* rate-limiting / banning the client when scrolling through large
|
||||
* channel lists.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class EpgQueueService implements OnDestroy {
|
||||
private readonly apiService = inject(XtreamApiService);
|
||||
private readonly logger = createLogger('EpgQueueService');
|
||||
private readonly previewLimit = 3;
|
||||
|
||||
private readonly cache = new Map<number, CacheEntry>();
|
||||
private queue: number[] = [];
|
||||
private readonly inFlight = new Set<number>();
|
||||
private visibleSet = new Set<number>();
|
||||
private processing = false;
|
||||
private readonly failureTimestamps = new Map<number, number>();
|
||||
|
||||
private readonly maxConcurrency = 2;
|
||||
private readonly delayMs = 200;
|
||||
private readonly cacheTtlMs = 5 * 60 * 1000; // 5 minutes
|
||||
private readonly failureCooldownMs = 60 * 1000;
|
||||
|
||||
/** Emits EPG results as they arrive. */
|
||||
readonly epgResult$ = new Subject<{ streamId: number; items: EpgItem[] }>();
|
||||
|
||||
/** Return cached EPG items if still valid, otherwise null. */
|
||||
getCached(streamId: number): EpgItem[] | null {
|
||||
const entry = this.cache.get(streamId);
|
||||
if (!entry) return null;
|
||||
if (Date.now() - entry.timestamp > this.cacheTtlMs) {
|
||||
this.cache.delete(streamId);
|
||||
return null;
|
||||
}
|
||||
return entry.data;
|
||||
}
|
||||
|
||||
private isFailureCoolingDown(streamId: number): boolean {
|
||||
const timestamp = this.failureTimestamps.get(streamId);
|
||||
if (timestamp == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Date.now() - timestamp > this.failureCooldownMs) {
|
||||
this.failureTimestamps.delete(streamId);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private shouldFetch(streamId: number): boolean {
|
||||
return (
|
||||
this.getCached(streamId) === null &&
|
||||
!this.isFailureCoolingDown(streamId) &&
|
||||
!this.inFlight.has(streamId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue stream IDs for EPG fetching.
|
||||
*
|
||||
* - IDs already cached or in-flight are skipped.
|
||||
* - The internal queue is replaced so that stale IDs (no longer in
|
||||
* `visibleIds`) are dropped on next dequeue.
|
||||
*/
|
||||
enqueue(
|
||||
streamIds: number[],
|
||||
visibleIds: Set<number>,
|
||||
credentials: XtreamCredentials
|
||||
): void {
|
||||
this.visibleSet = visibleIds;
|
||||
|
||||
const toFetch = streamIds.filter(
|
||||
(id) => this.shouldFetch(id)
|
||||
);
|
||||
|
||||
// Replace the queue – any previously queued but now-invisible IDs
|
||||
// will be skipped during processing via the visibleSet check.
|
||||
this.queue = toFetch;
|
||||
|
||||
if (!this.processing) {
|
||||
this.processQueue(credentials);
|
||||
}
|
||||
}
|
||||
|
||||
private async processQueue(credentials: XtreamCredentials): Promise<void> {
|
||||
this.processing = true;
|
||||
|
||||
while (this.queue.length > 0) {
|
||||
// Wait until a concurrency slot is available
|
||||
if (this.inFlight.size >= this.maxConcurrency) {
|
||||
await this.delay(this.delayMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
const streamId = this.queue.shift();
|
||||
if (streamId == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Drop stale entries that are no longer visible
|
||||
if (!this.visibleSet.has(streamId)) continue;
|
||||
|
||||
// Skip if it got cached or cooled down while queued (e.g. duplicate/failure)
|
||||
if (!this.shouldFetch(streamId)) continue;
|
||||
|
||||
this.inFlight.add(streamId);
|
||||
this.fetchEpg(credentials, streamId);
|
||||
|
||||
// Space out requests
|
||||
await this.delay(this.delayMs);
|
||||
}
|
||||
|
||||
this.processing = false;
|
||||
}
|
||||
|
||||
private async fetchEpg(
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number
|
||||
): Promise<void> {
|
||||
try {
|
||||
const items = await this.apiService.getShortEpg(
|
||||
credentials,
|
||||
streamId,
|
||||
this.previewLimit,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
);
|
||||
this.cache.set(streamId, {
|
||||
data: items,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
this.failureTimestamps.delete(streamId);
|
||||
this.epgResult$.next({ streamId, items });
|
||||
} catch (error) {
|
||||
this.failureTimestamps.set(streamId, Date.now());
|
||||
this.logger.error(
|
||||
`Failed to load EPG for stream ${streamId}`,
|
||||
error
|
||||
);
|
||||
} finally {
|
||||
this.inFlight.delete(streamId);
|
||||
}
|
||||
}
|
||||
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.epgResult$.complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface FavoriteItem {
|
||||
content_id: number;
|
||||
playlist_id: string;
|
||||
type: 'live' | 'movie' | 'vod' | 'series';
|
||||
title: string;
|
||||
stream_icon?: string;
|
||||
poster_url?: string;
|
||||
added_at?: string;
|
||||
category_id: number;
|
||||
xtream_id: number;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { from, map, Observable } from 'rxjs';
|
||||
import { DatabaseService } from 'services';
|
||||
import { FavoriteItem } from './favorite-item.interface';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class FavoritesService {
|
||||
private dbService = inject(DatabaseService);
|
||||
|
||||
async addToFavorites(item: {
|
||||
content_id: number;
|
||||
playlist_id: string;
|
||||
backdrop_url?: string;
|
||||
}): Promise<void> {
|
||||
await this.dbService.addToFavorites(
|
||||
item.content_id,
|
||||
item.playlist_id,
|
||||
item.backdrop_url
|
||||
);
|
||||
}
|
||||
|
||||
async removeFromFavorites(
|
||||
contentId: number,
|
||||
playlistId: string
|
||||
): Promise<void> {
|
||||
await this.dbService.removeFromFavorites(contentId, playlistId);
|
||||
}
|
||||
|
||||
async isFavorite(contentId: number, playlistId: string): Promise<boolean> {
|
||||
return await this.dbService.isFavorite(contentId, playlistId);
|
||||
}
|
||||
|
||||
getFavorites(playlistId: string): Observable<FavoriteItem[]> {
|
||||
return from(this.dbService.getFavorites(playlistId)).pipe(
|
||||
map((items) =>
|
||||
items.map((item) => ({
|
||||
content_id: item.id,
|
||||
playlist_id: playlistId,
|
||||
type: item.type as FavoriteItem['type'],
|
||||
title: item.title,
|
||||
poster_url: item.poster_url,
|
||||
added_at: item.added_at,
|
||||
category_id: item.category_id,
|
||||
xtream_id: item.xtream_id,
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './epg-queue.service';
|
||||
export * from './favorite-item.interface';
|
||||
export * from './favorites.service';
|
||||
export * from './xtream-api.service';
|
||||
export * from './xtream-url.service';
|
||||
@@ -0,0 +1,251 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { DataService } from 'services';
|
||||
import { XTREAM_REQUEST } from 'shared-interfaces';
|
||||
import { XtreamApiService, XtreamCredentials } from './xtream-api.service';
|
||||
|
||||
describe('XtreamApiService', () => {
|
||||
let service: XtreamApiService;
|
||||
let dataService: {
|
||||
sendIpcEvent: jest.Mock<Promise<unknown>, [string, unknown]>;
|
||||
};
|
||||
|
||||
const credentials: XtreamCredentials = {
|
||||
serverUrl: 'http://demo.example',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
dataService = {
|
||||
sendIpcEvent: jest.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
XtreamApiService,
|
||||
{ provide: DataService, useValue: dataService },
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(XtreamApiService);
|
||||
});
|
||||
|
||||
it('falls back to the legacy full-epg action and normalizes the response', async () => {
|
||||
dataService.sendIpcEvent.mockImplementation(
|
||||
async (_type: string, payload: unknown) => {
|
||||
const action = (
|
||||
payload as {
|
||||
params: { action: string };
|
||||
}
|
||||
).params.action;
|
||||
|
||||
if (action === 'get_simple_data_table') {
|
||||
return { payload: { epg_listings: [] } };
|
||||
}
|
||||
|
||||
return {
|
||||
payload: {
|
||||
epg_listings: [
|
||||
{
|
||||
id: 'later',
|
||||
epg_id: 'channel-101.mock',
|
||||
title: Buffer.from('Later Show').toString(
|
||||
'base64'
|
||||
),
|
||||
description: Buffer.from(
|
||||
'Later description'
|
||||
).toString('base64'),
|
||||
start: '2026-04-04 11:00:00',
|
||||
end: '2026-04-04 11:30:00',
|
||||
start_timestamp: '1775300400',
|
||||
stop_timestamp: '1775302200',
|
||||
channel_id: 'channel-101.mock',
|
||||
},
|
||||
{
|
||||
id: 'current',
|
||||
epg_id: 'channel-101.mock',
|
||||
title: Buffer.from('Current Show').toString(
|
||||
'base64'
|
||||
),
|
||||
description: Buffer.from(
|
||||
'Current description'
|
||||
).toString('base64'),
|
||||
start: '2026-04-04 10:30:00',
|
||||
end: '2026-04-04 11:00:00',
|
||||
start_timestamp: '1775298600',
|
||||
stop_timestamp: '1775300400',
|
||||
channel_id: 'channel-101.mock',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
const items = await service.getFullEpg(credentials, 101);
|
||||
|
||||
expect(dataService.sendIpcEvent).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
XTREAM_REQUEST,
|
||||
expect.objectContaining({
|
||||
url: 'http://demo.example',
|
||||
params: expect.objectContaining({
|
||||
action: 'get_simple_data_table',
|
||||
stream_id: '101',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(dataService.sendIpcEvent).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
XTREAM_REQUEST,
|
||||
expect.objectContaining({
|
||||
params: expect.objectContaining({
|
||||
action: 'get_simple_date_table',
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items.map((item) => item.title)).toEqual([
|
||||
'Current Show',
|
||||
'Later Show',
|
||||
]);
|
||||
expect(items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
description: 'Current description',
|
||||
start: '2026-04-04T10:30:00.000Z',
|
||||
stop: '2026-04-04T11:00:00.000Z',
|
||||
start_timestamp: '1775298600',
|
||||
stop_timestamp: '1775300400',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('normalizes short epg items from unix timestamps for display', async () => {
|
||||
const startTimestamp = Math.floor(
|
||||
Date.parse('2026-04-05T05:30:00.000Z') / 1000
|
||||
);
|
||||
const stopTimestamp = Math.floor(
|
||||
Date.parse('2026-04-05T06:00:00.000Z') / 1000
|
||||
);
|
||||
|
||||
dataService.sendIpcEvent.mockResolvedValue({
|
||||
payload: {
|
||||
epg_listings: [
|
||||
{
|
||||
id: 'current',
|
||||
epg_id: 'channel-101.mock',
|
||||
title: Buffer.from('Current Show').toString('base64'),
|
||||
description: Buffer.from(
|
||||
'Current description'
|
||||
).toString('base64'),
|
||||
start: '2026-04-05 03:00:00',
|
||||
end: '2026-04-05 03:30:00',
|
||||
start_timestamp: String(startTimestamp),
|
||||
stop_timestamp: String(stopTimestamp),
|
||||
channel_id: 'channel-101.mock',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const items = await service.getShortEpg(credentials, 101, 4);
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({
|
||||
title: 'Current Show',
|
||||
description: 'Current description',
|
||||
start: '2026-04-05T05:30:00.000Z',
|
||||
stop: '2026-04-05T06:00:00.000Z',
|
||||
start_timestamp: String(startTimestamp),
|
||||
stop_timestamp: String(stopTimestamp),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('falls back to parsed short epg date strings when unix timestamps are absent', async () => {
|
||||
const rawStart = '2026-04-05 03:00:00';
|
||||
const rawStop = '2026-04-05 03:30:00';
|
||||
|
||||
dataService.sendIpcEvent.mockResolvedValue({
|
||||
payload: {
|
||||
epg_listings: [
|
||||
{
|
||||
id: 'current',
|
||||
epg_id: 'channel-101.mock',
|
||||
title: Buffer.from('Current Show').toString('base64'),
|
||||
description: Buffer.from(
|
||||
'Current description'
|
||||
).toString('base64'),
|
||||
start: rawStart,
|
||||
end: rawStop,
|
||||
channel_id: 'channel-101.mock',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const items = await service.getShortEpg(credentials, 101, 4);
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({
|
||||
start: new Date(rawStart.replace(' ', 'T')).toISOString(),
|
||||
stop: new Date(rawStop.replace(' ', 'T')).toISOString(),
|
||||
start_timestamp: '',
|
||||
stop_timestamp: '',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes short and full epg items consistently for the same timestamps', async () => {
|
||||
const startTimestamp = Math.floor(
|
||||
Date.parse('2026-04-05T05:30:00.000Z') / 1000
|
||||
);
|
||||
const stopTimestamp = Math.floor(
|
||||
Date.parse('2026-04-05T06:00:00.000Z') / 1000
|
||||
);
|
||||
|
||||
dataService.sendIpcEvent.mockImplementation(
|
||||
async (_type: string, payload: unknown) => {
|
||||
const action = (
|
||||
payload as {
|
||||
params: { action: string };
|
||||
}
|
||||
).params.action;
|
||||
|
||||
const listing = {
|
||||
id: 'current',
|
||||
epg_id: 'channel-101.mock',
|
||||
title: Buffer.from('Current Show').toString('base64'),
|
||||
description: Buffer.from('Current description').toString(
|
||||
'base64'
|
||||
),
|
||||
start: '2026-04-05 03:00:00',
|
||||
end: '2026-04-05 03:30:00',
|
||||
start_timestamp: String(startTimestamp),
|
||||
stop_timestamp: String(stopTimestamp),
|
||||
channel_id: 'channel-101.mock',
|
||||
};
|
||||
|
||||
if (action === 'get_short_epg') {
|
||||
return { payload: { epg_listings: [listing] } };
|
||||
}
|
||||
|
||||
return {
|
||||
payload: {
|
||||
epg_listings: [listing],
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
const shortItems = await service.getShortEpg(credentials, 101, 4);
|
||||
const fullItems = await service.getFullEpg(credentials, 101);
|
||||
|
||||
expect(shortItems[0].start).toBe(fullItems[0].start);
|
||||
expect(shortItems[0].stop).toBe(fullItems[0].stop);
|
||||
expect(shortItems[0].start_timestamp).toBe(fullItems[0].start_timestamp);
|
||||
expect(shortItems[0].stop_timestamp).toBe(fullItems[0].stop_timestamp);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,507 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { DataService } from 'services';
|
||||
import {
|
||||
EpgItem,
|
||||
XtreamCategory,
|
||||
XtreamCodeActions,
|
||||
XtreamLiveStream,
|
||||
XtreamSerieDetails,
|
||||
XtreamSerieItem,
|
||||
XtreamVodDetails,
|
||||
XtreamVodStream,
|
||||
XTREAM_REQUEST,
|
||||
} from 'shared-interfaces';
|
||||
import { XtreamAccountInfo } from '../account-info/account-info.interface';
|
||||
|
||||
/**
|
||||
* Xtream API credentials
|
||||
*/
|
||||
export interface XtreamCredentials {
|
||||
serverUrl: string;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Category type mapping for API calls
|
||||
*/
|
||||
export type CategoryType = 'live' | 'vod' | 'series';
|
||||
|
||||
/**
|
||||
* Stream type mapping for API calls
|
||||
*/
|
||||
export type StreamType = 'live' | 'movie' | 'series';
|
||||
|
||||
export interface XtreamRequestOptions {
|
||||
requestId?: string;
|
||||
sessionId?: string;
|
||||
suppressErrorLog?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw EPG listing from API (before decoding)
|
||||
*/
|
||||
interface RawEpgListing {
|
||||
id?: string;
|
||||
epg_id?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
stop?: string;
|
||||
start_timestamp?: string;
|
||||
stop_timestamp?: string;
|
||||
channel_id?: string;
|
||||
lang?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* EPG API response
|
||||
*/
|
||||
interface EpgResponse {
|
||||
epg_listings?: RawEpgListing[] | Record<string, RawEpgListing>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for all Xtream Codes API interactions.
|
||||
* Extracts API communication logic from the XtreamStore.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class XtreamApiService {
|
||||
private readonly dataService = inject(DataService);
|
||||
|
||||
async cancelSession(sessionId: string): Promise<boolean> {
|
||||
if (!sessionId || typeof window.electron?.xtreamCancelSession !== 'function') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await window.electron.xtreamCancelSession(sessionId);
|
||||
return result.success;
|
||||
} catch (error) {
|
||||
console.error('Failed to cancel Xtream session:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get account/portal status
|
||||
*/
|
||||
async getAccountInfo(
|
||||
credentials: XtreamCredentials,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamAccountInfo> {
|
||||
return this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
action: XtreamCodeActions.GetAccountInfo,
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get categories by type
|
||||
*/
|
||||
async getCategories(
|
||||
credentials: XtreamCredentials,
|
||||
type: CategoryType,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamCategory[]> {
|
||||
const actionMap: Record<CategoryType, XtreamCodeActions> = {
|
||||
live: XtreamCodeActions.GetLiveCategories,
|
||||
vod: XtreamCodeActions.GetVodCategories,
|
||||
series: XtreamCodeActions.GetSeriesCategories,
|
||||
};
|
||||
|
||||
const response = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: actionMap[type],
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return Array.isArray(response) ? response : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get live streams
|
||||
*/
|
||||
async getLiveStreams(
|
||||
credentials: XtreamCredentials,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamLiveStream[]> {
|
||||
const response = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetLiveStreams,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return Array.isArray(response) ? response : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get VOD streams
|
||||
*/
|
||||
async getVodStreams(
|
||||
credentials: XtreamCredentials,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamVodStream[]> {
|
||||
const response = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetVodStreams,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return Array.isArray(response) ? response : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get series items
|
||||
*/
|
||||
async getSeriesStreams(
|
||||
credentials: XtreamCredentials,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamSerieItem[]> {
|
||||
const response = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetSeries,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return Array.isArray(response) ? response : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get streams by type (unified method)
|
||||
*/
|
||||
async getStreams(
|
||||
credentials: XtreamCredentials,
|
||||
type: StreamType,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamLiveStream[] | XtreamVodStream[] | XtreamSerieItem[]> {
|
||||
switch (type) {
|
||||
case 'live':
|
||||
return this.getLiveStreams(credentials, options);
|
||||
case 'movie':
|
||||
return this.getVodStreams(credentials, options);
|
||||
case 'series':
|
||||
return this.getSeriesStreams(credentials, options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get VOD details
|
||||
*/
|
||||
async getVodInfo(
|
||||
credentials: XtreamCredentials,
|
||||
vodId: string | number,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamVodDetails> {
|
||||
return this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetVodInfo,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
vod_id: vodId,
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get series details
|
||||
*/
|
||||
async getSeriesInfo(
|
||||
credentials: XtreamCredentials,
|
||||
seriesId: string | number,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<XtreamSerieDetails> {
|
||||
return this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetSeriesInfo,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
series_id: seriesId,
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get short EPG for a stream
|
||||
* Returns decoded EPG items (title and description are base64 decoded)
|
||||
*/
|
||||
async getShortEpg(
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
limit = 10,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<EpgItem[]> {
|
||||
const response: EpgResponse = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetShortEpg,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
stream_id: streamId,
|
||||
limit,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return this.normalizeShortEpgItems(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full EPG schedule for a stream.
|
||||
* Uses the documented endpoint with a fallback for older typoed panels.
|
||||
*/
|
||||
async getFullEpg(
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<EpgItem[]> {
|
||||
try {
|
||||
const response: EpgResponse = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetSimpleDataTable,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
stream_id: streamId,
|
||||
},
|
||||
options
|
||||
);
|
||||
const items = this.normalizeFullEpgItems(response);
|
||||
if (items.length > 0) {
|
||||
return items;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the legacy typo endpoint below.
|
||||
}
|
||||
|
||||
const fallbackResponse: EpgResponse = await this.sendRequest(
|
||||
credentials.serverUrl,
|
||||
{
|
||||
action: XtreamCodeActions.GetSimpleDateTable,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
stream_id: streamId,
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
return this.normalizeFullEpgItems(fallbackResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode base64 unicode string (used for EPG data)
|
||||
*/
|
||||
private decodeBase64Unicode(str: string): string {
|
||||
try {
|
||||
return decodeURIComponent(
|
||||
Array.prototype.map
|
||||
.call(atob(str), (c: string) => {
|
||||
return (
|
||||
'%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
|
||||
);
|
||||
})
|
||||
.join('')
|
||||
);
|
||||
} catch {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
private getEpgListings(response: EpgResponse | null | undefined): RawEpgListing[] {
|
||||
const listings = response?.epg_listings;
|
||||
if (!listings) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(listings)) {
|
||||
return listings;
|
||||
}
|
||||
|
||||
return Object.values(listings);
|
||||
}
|
||||
|
||||
private normalizeShortEpgItems(response: EpgResponse): EpgItem[] {
|
||||
return this.getEpgListings(response)
|
||||
.map((item, index) => {
|
||||
const startTimestamp = this.parseUnixTimestamp(
|
||||
item.start_timestamp
|
||||
);
|
||||
const stopTimestamp = this.parseUnixTimestamp(
|
||||
item.stop_timestamp
|
||||
);
|
||||
const normalizedStart =
|
||||
this.toIsoString(startTimestamp) ??
|
||||
this.normalizeDateString(item.start);
|
||||
const normalizedStop =
|
||||
this.toIsoString(stopTimestamp) ??
|
||||
this.normalizeDateString(item.stop ?? item.end);
|
||||
|
||||
return {
|
||||
id: String(item.id ?? index),
|
||||
epg_id: String(item.epg_id ?? ''),
|
||||
title: this.decodeBase64Unicode(
|
||||
String(item.title ?? '')
|
||||
).trim(),
|
||||
description: this.decodeBase64Unicode(
|
||||
String(item.description ?? '')
|
||||
).trim(),
|
||||
lang: String(item.lang ?? ''),
|
||||
start: normalizedStart,
|
||||
end: normalizedStop,
|
||||
stop: normalizedStop,
|
||||
channel_id: String(item.channel_id ?? ''),
|
||||
start_timestamp: String(startTimestamp ?? ''),
|
||||
stop_timestamp: String(stopTimestamp ?? ''),
|
||||
} satisfies EpgItem;
|
||||
})
|
||||
.filter((item) => Boolean(item.start) && Boolean(item.stop))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
this.getEpgItemTimestampMs(left.start, left.start_timestamp) -
|
||||
this.getEpgItemTimestampMs(
|
||||
right.start,
|
||||
right.start_timestamp
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private normalizeFullEpgItems(response: EpgResponse): EpgItem[] {
|
||||
return this.getEpgListings(response)
|
||||
.map((item, index) => {
|
||||
const startTimestamp = this.parseUnixTimestamp(
|
||||
item.start_timestamp
|
||||
);
|
||||
const stopTimestamp = this.parseUnixTimestamp(
|
||||
item.stop_timestamp
|
||||
);
|
||||
const normalizedStart =
|
||||
this.toIsoString(startTimestamp) ??
|
||||
this.normalizeDateString(item.start);
|
||||
const normalizedStop =
|
||||
this.toIsoString(stopTimestamp) ??
|
||||
this.normalizeDateString(item.stop ?? item.end);
|
||||
|
||||
return {
|
||||
id: String(item.id ?? index),
|
||||
epg_id: String(item.epg_id ?? item.channel_id ?? ''),
|
||||
title: this.decodeBase64Unicode(
|
||||
String(item.title ?? '')
|
||||
).trim(),
|
||||
description: this.decodeBase64Unicode(
|
||||
String(item.description ?? '')
|
||||
).trim(),
|
||||
lang: String(item.lang ?? ''),
|
||||
start: normalizedStart,
|
||||
end: normalizedStop,
|
||||
stop: normalizedStop,
|
||||
channel_id: String(item.channel_id ?? ''),
|
||||
start_timestamp: String(startTimestamp ?? ''),
|
||||
stop_timestamp: String(stopTimestamp ?? ''),
|
||||
} satisfies EpgItem;
|
||||
})
|
||||
.filter((item) => Boolean(item.start) && Boolean(item.stop))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
this.getEpgItemTimestampMs(left.start, left.start_timestamp) -
|
||||
this.getEpgItemTimestampMs(
|
||||
right.start,
|
||||
right.start_timestamp
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private parseUnixTimestamp(value: unknown): number | null {
|
||||
const parsed = Number.parseInt(String(value ?? ''), 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
private toIsoString(timestamp: number | null): string | null {
|
||||
return timestamp ? new Date(timestamp * 1000).toISOString() : null;
|
||||
}
|
||||
|
||||
private normalizeDateString(value: unknown): string {
|
||||
const rawValue = String(value ?? '').trim();
|
||||
if (!rawValue) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const parsed = Date.parse(rawValue.replace(' ', 'T'));
|
||||
return Number.isFinite(parsed)
|
||||
? new Date(parsed).toISOString()
|
||||
: rawValue;
|
||||
}
|
||||
|
||||
private getEpgItemTimestampMs(
|
||||
isoValue: string,
|
||||
unixTimestampValue: string
|
||||
): number {
|
||||
const unixTimestamp = this.parseUnixTimestamp(unixTimestampValue);
|
||||
if (unixTimestamp) {
|
||||
return unixTimestamp * 1000;
|
||||
}
|
||||
|
||||
return Date.parse(isoValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send request via IPC to avoid CORS issues
|
||||
*/
|
||||
private async sendRequest<TResponse>(
|
||||
url: string,
|
||||
params: Record<string, string | number>,
|
||||
options?: XtreamRequestOptions
|
||||
): Promise<TResponse> {
|
||||
const serializedParams: Record<string, string> = {};
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
serializedParams[key] = String(value);
|
||||
});
|
||||
|
||||
const response = (await this.dataService.sendIpcEvent(XTREAM_REQUEST, {
|
||||
url,
|
||||
params: serializedParams,
|
||||
requestId: options?.requestId,
|
||||
sessionId: options?.sessionId,
|
||||
suppressErrorLog: options?.suppressErrorLog,
|
||||
})) as {
|
||||
message?: string;
|
||||
payload?: unknown;
|
||||
type?: string;
|
||||
};
|
||||
|
||||
// The IPC layer catches errors and returns { type: 'ERROR', message, status }
|
||||
// instead of rejecting. Convert that back into a thrown error so callers
|
||||
// can handle it with .catch() / try-catch.
|
||||
if (response?.type === 'ERROR' || (!response?.payload && response?.message)) {
|
||||
throw new Error(response?.message ?? 'Request failed');
|
||||
}
|
||||
|
||||
return response?.payload as TResponse;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { DatabaseService, SettingsStore } from 'services';
|
||||
import { XtreamCredentials } from './xtream-api.service';
|
||||
import { XtreamUrlService } from './xtream-url.service';
|
||||
|
||||
describe('XtreamUrlService', () => {
|
||||
let service: XtreamUrlService;
|
||||
let databaseService: {
|
||||
getAppState: jest.Mock<Promise<string | null>, [string]>;
|
||||
setAppState: jest.Mock<Promise<void>, [string, string]>;
|
||||
};
|
||||
|
||||
const credentials: XtreamCredentials = {
|
||||
serverUrl: 'http://demo.example',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
};
|
||||
const originalElectron = window.electron;
|
||||
|
||||
beforeEach(() => {
|
||||
databaseService = {
|
||||
getAppState: jest.fn().mockResolvedValue(null),
|
||||
setAppState: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
XtreamUrlService,
|
||||
{ provide: DatabaseService, useValue: databaseService },
|
||||
{
|
||||
provide: SettingsStore,
|
||||
useValue: {
|
||||
streamFormat: signal('ts'),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(XtreamUrlService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.electron = originalElectron;
|
||||
});
|
||||
|
||||
it('detects the legacy catchup scheme once and then uses the cached result', async () => {
|
||||
const xtreamProbeUrl = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ status: 404 })
|
||||
.mockResolvedValueOnce({ status: 302 });
|
||||
window.electron = {
|
||||
xtreamProbeUrl,
|
||||
} as typeof window.electron;
|
||||
|
||||
const firstUrl = await service.resolveCatchupUrl(
|
||||
'playlist-1',
|
||||
credentials,
|
||||
101,
|
||||
1775296800,
|
||||
1775300400
|
||||
);
|
||||
const secondUrl = await service.resolveCatchupUrl(
|
||||
'playlist-1',
|
||||
credentials,
|
||||
101,
|
||||
1775296800,
|
||||
1775300400
|
||||
);
|
||||
|
||||
expect(firstUrl).toContain('/streaming/timeshift.php?');
|
||||
expect(secondUrl).toBe(firstUrl);
|
||||
expect(xtreamProbeUrl).toHaveBeenCalledTimes(2);
|
||||
expect(databaseService.setAppState).toHaveBeenCalledWith(
|
||||
'xtream-catchup-scheme:playlist-1',
|
||||
'legacy'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
XtreamSerieEpisode,
|
||||
XtreamVodDetails,
|
||||
} from 'shared-interfaces';
|
||||
import { DatabaseService, SettingsStore } from 'services';
|
||||
import { XtreamCredentials } from './xtream-api.service';
|
||||
|
||||
/**
|
||||
* Extended playlist with optional HTTP headers
|
||||
*/
|
||||
export interface XtreamPlaylistWithHeaders extends XtreamCredentials {
|
||||
id: string;
|
||||
name: string;
|
||||
type?: string;
|
||||
userAgent?: string;
|
||||
referrer?: string;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live stream item with xtream_id
|
||||
*/
|
||||
export interface LiveStreamItem {
|
||||
xtream_id: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type XtreamVodStreamLike = XtreamVodDetails & {
|
||||
readonly stream_id?: number;
|
||||
};
|
||||
|
||||
type XtreamCatchupScheme = 'rest' | 'legacy';
|
||||
|
||||
type XtreamProbeApi = {
|
||||
xtreamProbeUrl?: (
|
||||
url: string,
|
||||
method?: 'GET' | 'HEAD'
|
||||
) => Promise<{ status: number }>;
|
||||
};
|
||||
|
||||
const XTREAM_CATCHUP_SCHEME_KEY_PREFIX = 'xtream-catchup-scheme:';
|
||||
|
||||
/**
|
||||
* Service for constructing Xtream stream URLs.
|
||||
* Handles URL construction for live streams, VOD, and series episodes.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class XtreamUrlService {
|
||||
private readonly databaseService = inject(DatabaseService);
|
||||
private readonly settingsStore = inject(SettingsStore);
|
||||
private readonly catchupSchemeCache = new Map<string, XtreamCatchupScheme>();
|
||||
private readonly catchupSchemeRequests = new Map<
|
||||
string,
|
||||
Promise<XtreamCatchupScheme>
|
||||
>();
|
||||
|
||||
/**
|
||||
* Construct live stream URL
|
||||
* Format: {serverUrl}/live/{username}/{password}/{streamId}.{format}
|
||||
*/
|
||||
constructLiveUrl(
|
||||
credentials: XtreamCredentials,
|
||||
xtreamId: number,
|
||||
format?: string
|
||||
): string {
|
||||
const streamFormat =
|
||||
format ?? this.settingsStore.streamFormat() ?? 'ts';
|
||||
return `${credentials.serverUrl}/live/${credentials.username}/${credentials.password}/${xtreamId}.${streamFormat}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct VOD stream URL
|
||||
* Format: {serverUrl}/movie/{username}/{password}/{streamId}.{extension}
|
||||
*/
|
||||
constructVodUrl(
|
||||
credentials: XtreamCredentials,
|
||||
vodItem: XtreamVodDetails
|
||||
): string {
|
||||
const vod = vodItem as XtreamVodStreamLike;
|
||||
const streamId = vod.movie_data?.stream_id ?? vod.stream_id;
|
||||
const extension = vodItem.movie_data?.container_extension;
|
||||
if (!streamId || !extension) {
|
||||
return '';
|
||||
}
|
||||
return `${credentials.serverUrl}/movie/${credentials.username}/${credentials.password}/${streamId}.${extension}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct series episode stream URL
|
||||
* Format: {serverUrl}/series/{username}/{password}/{episodeId}.{extension}
|
||||
*/
|
||||
constructEpisodeUrl(
|
||||
credentials: XtreamCredentials,
|
||||
episode: XtreamSerieEpisode
|
||||
): string {
|
||||
return `${credentials.serverUrl}/series/${credentials.username}/${credentials.password}/${episode.id}.${episode.container_extension}`;
|
||||
}
|
||||
|
||||
constructCatchupUrl(
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
startTimestamp: number,
|
||||
stopTimestamp: number,
|
||||
scheme: XtreamCatchupScheme
|
||||
): string {
|
||||
const durationMinutes = Math.max(
|
||||
1,
|
||||
Math.round((stopTimestamp - startTimestamp) / 60)
|
||||
);
|
||||
const timeString = this.formatCatchupStartTime(startTimestamp);
|
||||
|
||||
if (scheme === 'legacy') {
|
||||
const params = new URLSearchParams({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
stream: String(streamId),
|
||||
start: timeString,
|
||||
duration: String(durationMinutes),
|
||||
});
|
||||
return `${credentials.serverUrl}/streaming/timeshift.php?${params.toString()}`;
|
||||
}
|
||||
|
||||
return `${credentials.serverUrl}/timeshift/${credentials.username}/${credentials.password}/${durationMinutes}/${timeString}/${streamId}.ts`;
|
||||
}
|
||||
|
||||
async resolveCatchupUrl(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
startTimestamp: number,
|
||||
stopTimestamp: number
|
||||
): Promise<string> {
|
||||
const scheme = await this.getCatchupScheme(
|
||||
playlistId,
|
||||
credentials,
|
||||
streamId,
|
||||
startTimestamp,
|
||||
stopTimestamp
|
||||
);
|
||||
|
||||
return this.constructCatchupUrl(
|
||||
credentials,
|
||||
streamId,
|
||||
startTimestamp,
|
||||
stopTimestamp,
|
||||
scheme
|
||||
);
|
||||
}
|
||||
|
||||
private async getCatchupScheme(
|
||||
playlistId: string,
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
startTimestamp: number,
|
||||
stopTimestamp: number
|
||||
): Promise<XtreamCatchupScheme> {
|
||||
const cacheKey = `${XTREAM_CATCHUP_SCHEME_KEY_PREFIX}${playlistId}`;
|
||||
const cached = this.catchupSchemeCache.get(cacheKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const persisted = await this.databaseService.getAppState(cacheKey);
|
||||
if (persisted === 'rest' || persisted === 'legacy') {
|
||||
this.catchupSchemeCache.set(cacheKey, persisted);
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const inFlightRequest = this.catchupSchemeRequests.get(cacheKey);
|
||||
if (inFlightRequest) {
|
||||
return inFlightRequest;
|
||||
}
|
||||
|
||||
const request = this.detectCatchupScheme(
|
||||
cacheKey,
|
||||
credentials,
|
||||
streamId,
|
||||
startTimestamp,
|
||||
stopTimestamp
|
||||
).finally(() => {
|
||||
this.catchupSchemeRequests.delete(cacheKey);
|
||||
});
|
||||
|
||||
this.catchupSchemeRequests.set(cacheKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
private async detectCatchupScheme(
|
||||
cacheKey: string,
|
||||
credentials: XtreamCredentials,
|
||||
streamId: number,
|
||||
startTimestamp: number,
|
||||
stopTimestamp: number
|
||||
): Promise<XtreamCatchupScheme> {
|
||||
const restUrl = this.constructCatchupUrl(
|
||||
credentials,
|
||||
streamId,
|
||||
startTimestamp,
|
||||
stopTimestamp,
|
||||
'rest'
|
||||
);
|
||||
const legacyUrl = this.constructCatchupUrl(
|
||||
credentials,
|
||||
streamId,
|
||||
startTimestamp,
|
||||
stopTimestamp,
|
||||
'legacy'
|
||||
);
|
||||
|
||||
const restStatus = await this.probeCatchupUrl(restUrl);
|
||||
let detectedScheme: XtreamCatchupScheme;
|
||||
|
||||
if (this.isAcceptedCatchupProbeStatus(restStatus)) {
|
||||
detectedScheme = 'rest';
|
||||
} else {
|
||||
const legacyStatus = await this.probeCatchupUrl(legacyUrl);
|
||||
detectedScheme = this.isAcceptedCatchupProbeStatus(legacyStatus)
|
||||
? 'legacy'
|
||||
: restStatus === 404
|
||||
? 'legacy'
|
||||
: 'rest';
|
||||
}
|
||||
|
||||
this.catchupSchemeCache.set(cacheKey, detectedScheme);
|
||||
await this.databaseService.setAppState(cacheKey, detectedScheme);
|
||||
return detectedScheme;
|
||||
}
|
||||
|
||||
private async probeCatchupUrl(url: string): Promise<number> {
|
||||
const probeUrl = (window.electron as XtreamProbeApi | undefined)
|
||||
?.xtreamProbeUrl;
|
||||
|
||||
if (typeof probeUrl !== 'function') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await probeUrl(url, 'HEAD');
|
||||
return Number(result?.status ?? 0);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private isAcceptedCatchupProbeStatus(status: number): boolean {
|
||||
return (
|
||||
(status >= 200 && status < 400) ||
|
||||
status === 401 ||
|
||||
status === 403 ||
|
||||
status === 405
|
||||
);
|
||||
}
|
||||
|
||||
private formatCatchupStartTime(timestamp: number): string {
|
||||
const date = new Date(timestamp * 1000);
|
||||
const pad = (value: number) => String(value).padStart(2, '0');
|
||||
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}:${pad(date.getHours())}-${pad(date.getMinutes())}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './with-content.feature';
|
||||
export * from './with-epg.feature';
|
||||
export * from './with-playback-positions.feature';
|
||||
export * from './with-player.feature';
|
||||
export * from './with-portal.feature';
|
||||
export * from './with-search.feature';
|
||||
export * from './with-selection.feature';
|
||||
@@ -0,0 +1,772 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
|
||||
import { DatabaseService } from 'services';
|
||||
import {
|
||||
XTREAM_DATA_SOURCE,
|
||||
XtreamPlaylistData,
|
||||
} from '../../data-sources/xtream-data-source.interface';
|
||||
import { XtreamApiService } from '../../services/xtream-api.service';
|
||||
import { PortalStatusType } from '../../xtream-state';
|
||||
import { withContent } from './with-content.feature';
|
||||
|
||||
jest.mock('@iptvnator/portal/shared/util', () => ({
|
||||
createLogger: () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
type ContentType = 'live' | 'movie' | 'series';
|
||||
|
||||
const PLAYLIST: XtreamPlaylistData = {
|
||||
id: 'playlist-1',
|
||||
name: 'Test Xtream',
|
||||
serverUrl: 'http://localhost:8080',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
type: 'xtream',
|
||||
};
|
||||
|
||||
let checkPortalStatusMock: jest.Mock<Promise<PortalStatusType>, []>;
|
||||
|
||||
const TestContentStore = signalStore(
|
||||
withState({
|
||||
playlistId: PLAYLIST.id,
|
||||
currentPlaylist: PLAYLIST,
|
||||
portalStatus: 'active' as PortalStatusType,
|
||||
}),
|
||||
withMethods((store) => ({
|
||||
async checkPortalStatus(): Promise<PortalStatusType> {
|
||||
const status = await checkPortalStatusMock();
|
||||
patchState(store, { portalStatus: status });
|
||||
return status;
|
||||
},
|
||||
})),
|
||||
withContent()
|
||||
);
|
||||
|
||||
function createDeferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function createAbortError(): Error {
|
||||
const error = new Error('Import cancelled');
|
||||
error.name = 'AbortError';
|
||||
return error;
|
||||
}
|
||||
|
||||
async function waitForCondition(
|
||||
predicate: () => boolean,
|
||||
attempts = 20
|
||||
): Promise<void> {
|
||||
for (let index = 0; index < attempts; index += 1) {
|
||||
if (predicate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
throw new Error('Timed out waiting for test condition');
|
||||
}
|
||||
|
||||
describe('withContent import state', () => {
|
||||
let store: InstanceType<typeof TestContentStore>;
|
||||
let dataSource: {
|
||||
getCategories: jest.Mock;
|
||||
getContent: jest.Mock;
|
||||
hasCategories: jest.Mock;
|
||||
hasContent: jest.Mock;
|
||||
restoreUserData: jest.Mock;
|
||||
};
|
||||
let databaseService: {
|
||||
clearXtreamImportCache: jest.Mock;
|
||||
cancelOperation: jest.Mock;
|
||||
createOperationId: jest.Mock;
|
||||
getXtreamImportStatus: jest.Mock;
|
||||
setXtreamImportStatus: jest.Mock;
|
||||
supportsDbOperationCancellation: jest.Mock;
|
||||
};
|
||||
let xtreamApiService: {
|
||||
cancelSession: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
|
||||
let operationCounter = 0;
|
||||
dataSource = {
|
||||
getCategories: jest.fn().mockResolvedValue([]),
|
||||
getContent: jest.fn(),
|
||||
hasCategories: jest.fn().mockResolvedValue(true),
|
||||
hasContent: jest.fn().mockResolvedValue(true),
|
||||
restoreUserData: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
databaseService = {
|
||||
clearXtreamImportCache: jest.fn().mockResolvedValue(true),
|
||||
cancelOperation: jest.fn().mockResolvedValue(true),
|
||||
createOperationId: jest.fn().mockImplementation((prefix?: string) => {
|
||||
if (prefix === 'xtream-import-session') {
|
||||
return 'xtream-import-session';
|
||||
}
|
||||
|
||||
operationCounter += 1;
|
||||
return `${prefix ?? 'db-op'}-${operationCounter}`;
|
||||
}),
|
||||
getXtreamImportStatus: jest.fn().mockResolvedValue('completed'),
|
||||
setXtreamImportStatus: jest.fn().mockResolvedValue(true),
|
||||
supportsDbOperationCancellation: jest.fn().mockReturnValue(true),
|
||||
};
|
||||
xtreamApiService = {
|
||||
cancelSession: jest.fn().mockResolvedValue(true),
|
||||
};
|
||||
checkPortalStatusMock = jest.fn().mockResolvedValue('active');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TestContentStore,
|
||||
{
|
||||
provide: XTREAM_DATA_SOURCE,
|
||||
useValue: dataSource,
|
||||
},
|
||||
{
|
||||
provide: DatabaseService,
|
||||
useValue: databaseService,
|
||||
},
|
||||
{
|
||||
provide: XtreamApiService,
|
||||
useValue: xtreamApiService,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
store = TestBed.inject(TestContentStore);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('tracks aggregated import progress while content is loading', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
const pending = {
|
||||
live: createDeferred<any[]>(),
|
||||
movie: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
const optionsByType = new Map<
|
||||
ContentType,
|
||||
{ onEvent?: (event: any) => void; operationId?: string } | undefined
|
||||
>();
|
||||
const totals: Record<ContentType, number> = {
|
||||
live: 2,
|
||||
movie: 3,
|
||||
series: 4,
|
||||
};
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: ContentType,
|
||||
onProgress?: (count: number) => void,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: { onEvent?: (event: any) => void }
|
||||
) => {
|
||||
optionsByType.set(type, options);
|
||||
onTotal?.(totals[type]);
|
||||
const operationId = options?.operationId ?? `${type}-op`;
|
||||
options?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId,
|
||||
status: 'started',
|
||||
phase: 'saving-content',
|
||||
});
|
||||
onProgress?.(1);
|
||||
options?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId,
|
||||
status: 'progress',
|
||||
phase: 'saving-content',
|
||||
current: 1,
|
||||
total: totals[type],
|
||||
});
|
||||
|
||||
return pending[type].promise;
|
||||
}
|
||||
);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
await waitForCondition(() => store.importCount() === 1);
|
||||
|
||||
const liveOperationId =
|
||||
optionsByType.get('live')?.operationId ?? 'live-op';
|
||||
expect(store.isImporting()).toBe(true);
|
||||
expect(store.activeImportContentType()).toBe('live');
|
||||
expect(store.activeImportCurrentCount()).toBe(1);
|
||||
expect(store.activeImportTotalCount()).toBe(2);
|
||||
expect(store.importCount()).toBe(1);
|
||||
expect(store.itemsToImport()).toBe(2);
|
||||
expect(store.activeImportOperationIds()).toEqual([liveOperationId]);
|
||||
expect(store.importPhase()).toBe('saving-content');
|
||||
|
||||
optionsByType.get('live')?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId: liveOperationId,
|
||||
status: 'completed',
|
||||
phase: 'saving-content',
|
||||
current: totals.live,
|
||||
total: totals.live,
|
||||
});
|
||||
pending.live.resolve([]);
|
||||
|
||||
await waitForCondition(() => store.importCount() === 2);
|
||||
const movieOperationId =
|
||||
optionsByType.get('movie')?.operationId ?? 'movie-op';
|
||||
expect(store.activeImportContentType()).toBe('vod');
|
||||
expect(store.activeImportCurrentCount()).toBe(1);
|
||||
expect(store.activeImportTotalCount()).toBe(3);
|
||||
expect(store.itemsToImport()).toBe(5);
|
||||
expect(store.activeImportOperationIds()).toEqual([movieOperationId]);
|
||||
|
||||
optionsByType.get('movie')?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId: movieOperationId,
|
||||
status: 'completed',
|
||||
phase: 'saving-content',
|
||||
current: totals.movie,
|
||||
total: totals.movie,
|
||||
});
|
||||
pending.movie.resolve([]);
|
||||
|
||||
await waitForCondition(() => store.importCount() === 3);
|
||||
const seriesOperationId =
|
||||
optionsByType.get('series')?.operationId ?? 'series-op';
|
||||
expect(store.activeImportContentType()).toBe('series');
|
||||
expect(store.activeImportCurrentCount()).toBe(1);
|
||||
expect(store.activeImportTotalCount()).toBe(4);
|
||||
expect(store.itemsToImport()).toBe(9);
|
||||
expect(store.activeImportOperationIds()).toEqual([seriesOperationId]);
|
||||
|
||||
optionsByType.get('series')?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId: seriesOperationId,
|
||||
status: 'completed',
|
||||
phase: 'saving-content',
|
||||
current: totals.series,
|
||||
total: totals.series,
|
||||
});
|
||||
pending.series.resolve([]);
|
||||
|
||||
await initialization;
|
||||
|
||||
expect(store.isImporting()).toBe(false);
|
||||
expect(store.isContentInitialized()).toBe(true);
|
||||
expect(store.contentInitBlockReason()).toBeNull();
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'ready',
|
||||
vod: 'ready',
|
||||
series: 'ready',
|
||||
});
|
||||
expect(store.activeImportOperationIds()).toEqual([]);
|
||||
expect(store.importPhase()).toBeNull();
|
||||
expect(store.activeImportContentType()).toBeNull();
|
||||
expect(store.activeImportCurrentCount()).toBe(0);
|
||||
expect(store.activeImportTotalCount()).toBe(0);
|
||||
expect(store.importCount()).toBe(0);
|
||||
expect(store.itemsToImport()).toBe(0);
|
||||
});
|
||||
|
||||
it('marks content types ready and patches their streams as each import completes', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
const pending = {
|
||||
live: createDeferred<any[]>(),
|
||||
movie: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
|
||||
const liveItems = [
|
||||
{
|
||||
xtream_id: 101,
|
||||
category_id: 11,
|
||||
title: 'Live One',
|
||||
},
|
||||
];
|
||||
const vodItems = [
|
||||
{
|
||||
xtream_id: 202,
|
||||
category_id: 22,
|
||||
title: 'Movie One',
|
||||
},
|
||||
];
|
||||
const seriesItems = [
|
||||
{
|
||||
xtream_id: 303,
|
||||
category_id: 33,
|
||||
title: 'Series One',
|
||||
},
|
||||
];
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: ContentType
|
||||
) => pending[type].promise
|
||||
);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'loading',
|
||||
vod: 'loading',
|
||||
series: 'loading',
|
||||
});
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
|
||||
pending.live.resolve(liveItems);
|
||||
await waitForCondition(
|
||||
() => store.contentLoadStateByType().live === 'ready'
|
||||
);
|
||||
|
||||
expect(store.liveStreams()).toEqual(liveItems);
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'ready',
|
||||
vod: 'loading',
|
||||
series: 'loading',
|
||||
});
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
|
||||
pending.movie.resolve(vodItems);
|
||||
await waitForCondition(
|
||||
() => store.contentLoadStateByType().vod === 'ready'
|
||||
);
|
||||
|
||||
expect(store.vodStreams()).toEqual(vodItems);
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'ready',
|
||||
vod: 'ready',
|
||||
series: 'loading',
|
||||
});
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
|
||||
pending.series.resolve(seriesItems);
|
||||
await initialization;
|
||||
|
||||
expect(store.serialStreams()).toEqual(seriesItems);
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'ready',
|
||||
vod: 'ready',
|
||||
series: 'ready',
|
||||
});
|
||||
expect(store.isContentInitialized()).toBe(true);
|
||||
});
|
||||
|
||||
it('loads categories before starting content import', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(dataSource.getCategories).toHaveBeenCalledTimes(3);
|
||||
expect(dataSource.getContent).not.toHaveBeenCalled();
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
|
||||
await initialization;
|
||||
|
||||
expect(dataSource.getContent).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('reuses cached content without clearing the playlist import cache', async () => {
|
||||
dataSource.getCategories.mockResolvedValue([]);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(store.isImporting()).toBe(false);
|
||||
|
||||
await initialization;
|
||||
|
||||
expect(store.isImporting()).toBe(false);
|
||||
expect(store.isContentInitialized()).toBe(true);
|
||||
expect(store.contentInitBlockReason()).toBeNull();
|
||||
expect(databaseService.clearXtreamImportCache).not.toHaveBeenCalled();
|
||||
expect(databaseService.setXtreamImportStatus).not.toHaveBeenCalledWith(
|
||||
PLAYLIST.id,
|
||||
expect.anything(),
|
||||
'importing'
|
||||
);
|
||||
});
|
||||
|
||||
it('reports offline cache availability only when every import type is completed and cached', async () => {
|
||||
databaseService.getXtreamImportStatus
|
||||
.mockResolvedValueOnce('completed')
|
||||
.mockResolvedValueOnce('completed')
|
||||
.mockResolvedValueOnce('completed');
|
||||
dataSource.hasCategories
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true);
|
||||
dataSource.hasContent
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true);
|
||||
|
||||
await expect(store.hasUsableOfflineCache()).resolves.toBe(true);
|
||||
|
||||
expect(databaseService.getXtreamImportStatus).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
PLAYLIST.id,
|
||||
'live'
|
||||
);
|
||||
expect(databaseService.getXtreamImportStatus).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
PLAYLIST.id,
|
||||
'movie'
|
||||
);
|
||||
expect(databaseService.getXtreamImportStatus).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
PLAYLIST.id,
|
||||
'series'
|
||||
);
|
||||
});
|
||||
|
||||
it('treats partial cache as unusable for offline initialization', async () => {
|
||||
databaseService.getXtreamImportStatus
|
||||
.mockResolvedValueOnce('completed')
|
||||
.mockResolvedValueOnce('completed')
|
||||
.mockResolvedValueOnce('completed');
|
||||
dataSource.hasCategories
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true);
|
||||
dataSource.hasContent
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true);
|
||||
|
||||
await expect(store.hasUsableOfflineCache()).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('ignores concurrent initializeContent calls while an import is already running', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
const firstInitialization = store.initializeContent();
|
||||
const secondInitialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(store.activeImportSessionId()).toBe('xtream-import-session');
|
||||
expect(dataSource.getCategories).toHaveBeenCalledTimes(3);
|
||||
expect(dataSource.getContent).not.toHaveBeenCalled();
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
|
||||
await Promise.all([firstInitialization, secondInitialization]);
|
||||
|
||||
expect(dataSource.getCategories).toHaveBeenCalledTimes(3);
|
||||
expect(dataSource.getContent).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('blocks auto restart after cancelling during category loading until retry is explicit', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await waitForCondition(() => Boolean(store.activeImportSessionId()));
|
||||
|
||||
await store.cancelImport();
|
||||
|
||||
expect(store.isCancellingImport()).toBe(true);
|
||||
expect(store.contentInitBlockReason()).toBe('cancelled');
|
||||
expect(databaseService.cancelOperation).not.toHaveBeenCalled();
|
||||
expect(xtreamApiService.cancelSession).toHaveBeenCalledWith(
|
||||
'xtream-import-session'
|
||||
);
|
||||
|
||||
pendingCategories.live.reject(createAbortError());
|
||||
pendingCategories.vod.reject(createAbortError());
|
||||
pendingCategories.series.reject(createAbortError());
|
||||
|
||||
await expect(initialization).resolves.toBeUndefined();
|
||||
|
||||
expect(store.isImporting()).toBe(false);
|
||||
expect(store.isCancellingImport()).toBe(false);
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
expect(store.contentInitBlockReason()).toBe('cancelled');
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'idle',
|
||||
vod: 'idle',
|
||||
series: 'idle',
|
||||
});
|
||||
|
||||
await store.initializeContent();
|
||||
|
||||
expect(dataSource.getCategories).toHaveBeenCalledTimes(3);
|
||||
expect(dataSource.getContent).not.toHaveBeenCalled();
|
||||
|
||||
dataSource.getCategories.mockResolvedValue([]);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
await store.retryContentInitialization();
|
||||
|
||||
expect(checkPortalStatusMock).toHaveBeenCalledTimes(1);
|
||||
expect(store.contentInitBlockReason()).toBeNull();
|
||||
expect(store.isContentInitialized()).toBe(true);
|
||||
expect(dataSource.getCategories).toHaveBeenCalledTimes(6);
|
||||
expect(dataSource.getContent).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('stops before content fetch if cancel lands between categories and content phases', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await waitForCondition(() => Boolean(store.activeImportSessionId()));
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
|
||||
await store.cancelImport();
|
||||
await expect(initialization).resolves.toBeUndefined();
|
||||
|
||||
expect(store.contentInitBlockReason()).toBe('cancelled');
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
expect(dataSource.getContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the blocked state when retry finds a non-active portal status', async () => {
|
||||
checkPortalStatusMock.mockResolvedValue('expired');
|
||||
store.setContentInitBlockReason('cancelled');
|
||||
|
||||
await store.retryContentInitialization();
|
||||
|
||||
expect(checkPortalStatusMock).toHaveBeenCalledTimes(1);
|
||||
expect(store.contentInitBlockReason()).toBe('expired');
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
expect(dataSource.getCategories).not.toHaveBeenCalled();
|
||||
expect(dataSource.getContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps a cancelled block sticky until retry or reset clears it', async () => {
|
||||
store.setContentInitBlockReason('cancelled');
|
||||
|
||||
store.setContentInitBlockReason(null);
|
||||
|
||||
expect(store.contentInitBlockReason()).toBe('cancelled');
|
||||
|
||||
dataSource.getCategories.mockResolvedValue([]);
|
||||
dataSource.getContent.mockResolvedValue([]);
|
||||
|
||||
await store.retryContentInitialization();
|
||||
|
||||
expect(store.contentInitBlockReason()).toBeNull();
|
||||
expect(store.isContentInitialized()).toBe(true);
|
||||
});
|
||||
|
||||
it('cancels active imports and clears stale progress after worker aborts', async () => {
|
||||
const pendingCategories = {
|
||||
live: createDeferred<any[]>(),
|
||||
vod: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
const pending = {
|
||||
live: createDeferred<any[]>(),
|
||||
movie: createDeferred<any[]>(),
|
||||
series: createDeferred<any[]>(),
|
||||
};
|
||||
const optionsByType = new Map<
|
||||
ContentType,
|
||||
{ onEvent?: (event: any) => void; operationId?: string } | undefined
|
||||
>();
|
||||
|
||||
dataSource.getCategories.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: 'live' | 'vod' | 'series'
|
||||
) => pendingCategories[type].promise
|
||||
);
|
||||
dataSource.getContent.mockImplementation(
|
||||
(
|
||||
_playlistId: string,
|
||||
_credentials: unknown,
|
||||
type: ContentType,
|
||||
onProgress?: (count: number) => void,
|
||||
onTotal?: (total: number) => void,
|
||||
options?: { onEvent?: (event: any) => void }
|
||||
) => {
|
||||
optionsByType.set(type, options);
|
||||
onTotal?.(5);
|
||||
const operationId = options?.operationId ?? `${type}-op`;
|
||||
options?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId,
|
||||
status: 'started',
|
||||
phase: 'saving-content',
|
||||
});
|
||||
onProgress?.(2);
|
||||
options?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId,
|
||||
status: 'progress',
|
||||
phase: 'saving-content',
|
||||
current: 2,
|
||||
total: 5,
|
||||
});
|
||||
|
||||
return pending[type].promise;
|
||||
}
|
||||
);
|
||||
|
||||
const initialization = store.initializeContent();
|
||||
await Promise.resolve();
|
||||
|
||||
pendingCategories.live.resolve([]);
|
||||
pendingCategories.vod.resolve([]);
|
||||
pendingCategories.series.resolve([]);
|
||||
await waitForCondition(
|
||||
() => store.activeImportOperationIds().length === 1
|
||||
);
|
||||
const liveOperationId =
|
||||
optionsByType.get('live')?.operationId ?? 'live-op';
|
||||
expect(store.activeImportContentType()).toBe('live');
|
||||
expect(store.activeImportCurrentCount()).toBe(2);
|
||||
expect(store.activeImportTotalCount()).toBe(5);
|
||||
|
||||
await store.cancelImport();
|
||||
|
||||
expect(store.isCancellingImport()).toBe(true);
|
||||
expect(databaseService.cancelOperation).toHaveBeenCalledTimes(1);
|
||||
expect(databaseService.cancelOperation).toHaveBeenCalledWith(
|
||||
liveOperationId
|
||||
);
|
||||
expect(xtreamApiService.cancelSession).toHaveBeenCalledWith(
|
||||
'xtream-import-session'
|
||||
);
|
||||
|
||||
optionsByType.get('live')?.onEvent?.({
|
||||
operation: 'save-content',
|
||||
operationId: liveOperationId,
|
||||
status: 'cancelled',
|
||||
phase: 'saving-content',
|
||||
});
|
||||
pending.live.reject(createAbortError());
|
||||
|
||||
await expect(initialization).resolves.toBeUndefined();
|
||||
|
||||
expect(store.isImporting()).toBe(false);
|
||||
expect(store.isCancellingImport()).toBe(false);
|
||||
expect(store.isContentInitialized()).toBe(false);
|
||||
expect(store.contentInitBlockReason()).toBe('cancelled');
|
||||
expect(store.contentLoadStateByType()).toEqual({
|
||||
live: 'idle',
|
||||
vod: 'idle',
|
||||
series: 'idle',
|
||||
});
|
||||
expect(store.activeImportOperationIds()).toEqual([]);
|
||||
expect(store.importPhase()).toBeNull();
|
||||
expect(store.activeImportContentType()).toBeNull();
|
||||
expect(store.activeImportCurrentCount()).toBe(0);
|
||||
expect(store.activeImportTotalCount()).toBe(0);
|
||||
expect(store.importCount()).toBe(0);
|
||||
expect(store.itemsToImport()).toBe(0);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,109 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { signalStore, withState } from '@ngrx/signals';
|
||||
import { DataService } from 'services';
|
||||
import { EpgItem } from 'shared-interfaces';
|
||||
import { XtreamApiService } from '../../services/xtream-api.service';
|
||||
import { withEpg } from './with-epg.feature';
|
||||
|
||||
jest.mock('@iptvnator/portal/shared/util', () => ({
|
||||
createLogger: () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const PLAYLIST = {
|
||||
id: 'playlist-1',
|
||||
serverUrl: 'http://demo.example',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
};
|
||||
|
||||
const TestEpgStore = signalStore(
|
||||
withState({
|
||||
currentPlaylist: PLAYLIST,
|
||||
selectedItem: { xtream_id: 101 },
|
||||
}),
|
||||
withEpg()
|
||||
);
|
||||
|
||||
function buildProgram(
|
||||
title: string,
|
||||
startTimestamp: number,
|
||||
stopTimestamp: number
|
||||
): EpgItem {
|
||||
return {
|
||||
id: title,
|
||||
epg_id: title,
|
||||
title,
|
||||
description: `${title} description`,
|
||||
lang: 'en',
|
||||
start: new Date(startTimestamp * 1000).toISOString(),
|
||||
stop: new Date(stopTimestamp * 1000).toISOString(),
|
||||
end: new Date(stopTimestamp * 1000).toISOString(),
|
||||
channel_id: 'channel-101',
|
||||
start_timestamp: String(startTimestamp),
|
||||
stop_timestamp: String(stopTimestamp),
|
||||
};
|
||||
}
|
||||
|
||||
describe('withEpg', () => {
|
||||
let store: InstanceType<typeof TestEpgStore>;
|
||||
let xtreamApiService: {
|
||||
getFullEpg: jest.Mock<Promise<EpgItem[]>, unknown[]>;
|
||||
getShortEpg: jest.Mock<Promise<EpgItem[]>, unknown[]>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
xtreamApiService = {
|
||||
getFullEpg: jest.fn(),
|
||||
getShortEpg: jest.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TestEpgStore,
|
||||
{
|
||||
provide: DataService,
|
||||
useValue: { isElectron: true },
|
||||
},
|
||||
{
|
||||
provide: XtreamApiService,
|
||||
useValue: xtreamApiService,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
store = TestBed.inject(TestEpgStore);
|
||||
});
|
||||
|
||||
it('loads the full electron epg and derives the current program from timestamps', async () => {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const programs = [
|
||||
buildProgram('Past Show', now - 7200, now - 3600),
|
||||
buildProgram('Current Show', now - 300, now + 1800),
|
||||
buildProgram('Next Show', now + 1800, now + 3600),
|
||||
];
|
||||
xtreamApiService.getFullEpg.mockResolvedValue(programs);
|
||||
|
||||
const result = await store.loadEpg();
|
||||
|
||||
expect(xtreamApiService.getFullEpg).toHaveBeenCalledWith(
|
||||
{
|
||||
serverUrl: 'http://demo.example',
|
||||
username: 'demo',
|
||||
password: 'secret',
|
||||
},
|
||||
101,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
);
|
||||
expect(result).toEqual(programs);
|
||||
expect(store.epgItems()).toEqual(programs);
|
||||
expect(store.currentEpgItem()).toEqual(programs[1]);
|
||||
expect(store.isLoadingEpg()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withComputed,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { EpgItem } from 'shared-interfaces';
|
||||
import { DataService } from 'services';
|
||||
import {
|
||||
XtreamApiService,
|
||||
XtreamCredentials,
|
||||
} from '../../services/xtream-api.service';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
/**
|
||||
* EPG state for managing Electronic Program Guide data
|
||||
*/
|
||||
export interface EpgState {
|
||||
epgItems: EpgItem[];
|
||||
isLoadingEpg: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial EPG state
|
||||
*/
|
||||
const initialEpgState: EpgState = {
|
||||
epgItems: [],
|
||||
isLoadingEpg: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* EPG feature store for managing Electronic Program Guide data.
|
||||
* Handles:
|
||||
* - Loading EPG for selected stream
|
||||
* - Loading channel EPG for preview
|
||||
*/
|
||||
export function withEpg() {
|
||||
const logger = createLogger('withEpg');
|
||||
type ParentSelectionStoreLike = {
|
||||
currentPlaylist?: () => {
|
||||
password: string;
|
||||
serverUrl: string;
|
||||
username: string;
|
||||
} | null;
|
||||
selectedItem?: () => {
|
||||
xtream_id?: number | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
return signalStoreFeature(
|
||||
withState<EpgState>(initialEpgState),
|
||||
withComputed((store) => ({
|
||||
currentEpgItem: computed(() => {
|
||||
const now = Date.now();
|
||||
const items = [...store.epgItems()].sort(
|
||||
(left, right) =>
|
||||
getEpgTimestampMs(
|
||||
left.start,
|
||||
left.start_timestamp
|
||||
) -
|
||||
getEpgTimestampMs(
|
||||
right.start,
|
||||
right.start_timestamp
|
||||
)
|
||||
);
|
||||
|
||||
return (
|
||||
items.find((item) => {
|
||||
const start = getEpgTimestampMs(
|
||||
item.start,
|
||||
item.start_timestamp
|
||||
);
|
||||
const stop = getEpgTimestampMs(
|
||||
item.stop ?? item.end,
|
||||
item.stop_timestamp
|
||||
);
|
||||
return now >= start && now < stop;
|
||||
}) ?? null
|
||||
);
|
||||
}),
|
||||
})),
|
||||
|
||||
withMethods((store) => {
|
||||
const apiService = inject(XtreamApiService);
|
||||
const dataService = inject(DataService);
|
||||
|
||||
/**
|
||||
* Helper to get credentials from parent store
|
||||
*/
|
||||
const getCredentialsFromStore = (): XtreamCredentials | null => {
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const playlist = storeAny.currentPlaylist?.();
|
||||
|
||||
if (!playlist) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
* Load EPG for the currently selected item
|
||||
*/
|
||||
async loadEpg(): Promise<EpgItem[]> {
|
||||
const credentials = getCredentialsFromStore();
|
||||
if (!credentials) {
|
||||
patchState(store, { epgItems: [] });
|
||||
return [];
|
||||
}
|
||||
|
||||
// Access selected item from parent store (from withSelection)
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const selectedItem = storeAny.selectedItem?.();
|
||||
|
||||
if (!selectedItem?.xtream_id) {
|
||||
patchState(store, { epgItems: [] });
|
||||
return [];
|
||||
}
|
||||
|
||||
patchState(store, { epgItems: [], isLoadingEpg: true });
|
||||
|
||||
try {
|
||||
const epgItems = dataService.isElectron
|
||||
? await apiService.getFullEpg(
|
||||
credentials,
|
||||
selectedItem.xtream_id,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
)
|
||||
: await apiService.getShortEpg(
|
||||
credentials,
|
||||
selectedItem.xtream_id,
|
||||
10,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
);
|
||||
|
||||
patchState(store, {
|
||||
epgItems,
|
||||
isLoadingEpg: false,
|
||||
});
|
||||
|
||||
return epgItems;
|
||||
} catch (error) {
|
||||
logger.error('Error loading EPG', error);
|
||||
patchState(store, {
|
||||
epgItems: [],
|
||||
isLoadingEpg: false,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load EPG for a specific channel (for preview)
|
||||
*/
|
||||
async loadChannelEpg(streamId: number): Promise<EpgItem[]> {
|
||||
const credentials = getCredentialsFromStore();
|
||||
if (!credentials) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return await apiService.getShortEpg(
|
||||
credentials,
|
||||
streamId,
|
||||
1,
|
||||
{
|
||||
suppressErrorLog: true,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Error loading channel EPG', error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear EPG data
|
||||
*/
|
||||
clearEpg(): void {
|
||||
patchState(store, initialEpgState);
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getEpgTimestampMs(
|
||||
dateValue: string | undefined,
|
||||
unixTimestampValue: string | undefined
|
||||
): number {
|
||||
const unixTimestamp = Number.parseInt(String(unixTimestampValue ?? ''), 10);
|
||||
if (Number.isFinite(unixTimestamp) && unixTimestamp > 0) {
|
||||
return unixTimestamp * 1000;
|
||||
}
|
||||
|
||||
return Date.parse(String(dateValue ?? ''));
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
import { inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withHooks,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { XtreamSerieEpisode } from 'shared-interfaces';
|
||||
import {
|
||||
PlaybackPositionData,
|
||||
XTREAM_DATA_SOURCE,
|
||||
} from '../../data-sources/xtream-data-source.interface';
|
||||
|
||||
export interface PlaybackPositionsState {
|
||||
playbackPositions: Map<string, PlaybackPositionData>; // key: `${contentType}_${xtreamId}`
|
||||
seriesPositions: Map<number, PlaybackPositionData[]>; // key: seriesXtreamId
|
||||
}
|
||||
|
||||
const initialState: PlaybackPositionsState = {
|
||||
playbackPositions: new Map(),
|
||||
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),
|
||||
|
||||
withMethods((store) => {
|
||||
const dataSource = inject(XTREAM_DATA_SOURCE);
|
||||
|
||||
const getPositionKey = (type: string, id: number) =>
|
||||
`${type}_${id}`;
|
||||
|
||||
return {
|
||||
/**
|
||||
* Get progress percentage for display (0-100)
|
||||
*/
|
||||
getProgressPercent(
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): number {
|
||||
const key = getPositionKey(contentType, contentXtreamId);
|
||||
const position = store.playbackPositions().get(key);
|
||||
|
||||
if (!position || !position.durationSeconds) return 0;
|
||||
|
||||
const percent =
|
||||
(position.positionSeconds / position.durationSeconds) *
|
||||
100;
|
||||
|
||||
// If watched > 10s but percent < 1, return 1 to show visual progress
|
||||
if (position.positionSeconds > 10 && percent < 1) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return Math.min(100, Math.round(percent));
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if content is considered "watched" (>90% complete)
|
||||
*/
|
||||
isWatched(
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): boolean {
|
||||
return (
|
||||
this.getProgressPercent(
|
||||
contentXtreamId,
|
||||
contentType
|
||||
) >= 90
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if content is "in progress" (started but not finished)
|
||||
*/
|
||||
isInProgress(
|
||||
contentXtreamId: number,
|
||||
contentType: 'vod' | 'episode'
|
||||
): boolean {
|
||||
const key = getPositionKey(contentType, contentXtreamId);
|
||||
const position = store.playbackPositions().get(key);
|
||||
if (!position) return false;
|
||||
|
||||
const percent = this.getProgressPercent(
|
||||
contentXtreamId,
|
||||
contentType
|
||||
);
|
||||
const inProgress =
|
||||
position.positionSeconds > 10 && percent < 90;
|
||||
return inProgress;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all playback positions for the playlist (for grid view)
|
||||
*/
|
||||
async loadAllPositions(playlistId: string): Promise<void> {
|
||||
const positions = await dataSource.getAllPlaybackPositions(
|
||||
playlistId
|
||||
);
|
||||
|
||||
const positionsMap = new Map<string, PlaybackPositionData>();
|
||||
const seriesMap = new Map<number, PlaybackPositionData[]>();
|
||||
|
||||
positions.forEach((pos) => {
|
||||
const key = getPositionKey(
|
||||
pos.contentType,
|
||||
pos.contentXtreamId
|
||||
);
|
||||
positionsMap.set(key, pos);
|
||||
|
||||
if (
|
||||
pos.contentType === 'episode' &&
|
||||
pos.seriesXtreamId
|
||||
) {
|
||||
const existing =
|
||||
seriesMap.get(pos.seriesXtreamId) || [];
|
||||
existing.push(pos);
|
||||
seriesMap.set(pos.seriesXtreamId, existing);
|
||||
}
|
||||
});
|
||||
|
||||
patchState(store, {
|
||||
playbackPositions: positionsMap,
|
||||
seriesPositions: seriesMap,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if a series has any started or watched episodes
|
||||
*/
|
||||
hasSeriesProgress(seriesXtreamId: number): boolean {
|
||||
const positions = store
|
||||
.seriesPositions()
|
||||
.get(seriesXtreamId);
|
||||
return positions !== undefined && positions.length > 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load positions for a VOD item
|
||||
*/
|
||||
async loadVodPosition(
|
||||
playlistId: string,
|
||||
vodXtreamId: number
|
||||
): Promise<void> {
|
||||
const position = await dataSource.getPlaybackPosition(
|
||||
playlistId,
|
||||
vodXtreamId,
|
||||
'vod'
|
||||
);
|
||||
|
||||
if (position) {
|
||||
const key = getPositionKey('vod', vodXtreamId);
|
||||
const updated = new Map(store.playbackPositions());
|
||||
updated.set(key, position);
|
||||
patchState(store, { playbackPositions: updated });
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all episode positions for a series
|
||||
*/
|
||||
async loadSeriesPositions(
|
||||
playlistId: string,
|
||||
seriesXtreamId: number
|
||||
): Promise<void> {
|
||||
const positions = await dataSource.getSeriesPlaybackPositions(
|
||||
playlistId,
|
||||
seriesXtreamId
|
||||
);
|
||||
|
||||
const updated = new Map(store.seriesPositions());
|
||||
updated.set(seriesXtreamId, positions);
|
||||
patchState(store, { seriesPositions: updated });
|
||||
|
||||
// Also populate individual positions map
|
||||
const positionsMap = new Map(store.playbackPositions());
|
||||
positions.forEach((pos) => {
|
||||
const key = getPositionKey(
|
||||
'episode',
|
||||
pos.contentXtreamId
|
||||
);
|
||||
positionsMap.set(key, pos);
|
||||
});
|
||||
patchState(store, { playbackPositions: positionsMap });
|
||||
},
|
||||
|
||||
/**
|
||||
* Save playback position (called from MPV updates)
|
||||
*/
|
||||
async savePosition(
|
||||
playlistId: string,
|
||||
data: PlaybackPositionData
|
||||
): Promise<void> {
|
||||
await dataSource.savePlaybackPosition(playlistId, data);
|
||||
|
||||
const key = getPositionKey(
|
||||
data.contentType,
|
||||
data.contentXtreamId
|
||||
);
|
||||
const updated = new Map(store.playbackPositions());
|
||||
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,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
withHooks((store) => {
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
|
||||
return {
|
||||
onInit() {
|
||||
if (window.electron?.onPlaybackPositionUpdate) {
|
||||
unsubscribe = window.electron.onPlaybackPositionUpdate(
|
||||
(data: PlaybackPositionData) => {
|
||||
if (data.playlistId) {
|
||||
store.savePosition(data.playlistId, data);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
onDestroy() {
|
||||
unsubscribe?.();
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { PORTAL_PLAYER } from '@iptvnator/portal/shared/util';
|
||||
import { XtreamSerieEpisode, XtreamVodDetails } from 'shared-interfaces';
|
||||
import { XtreamCredentials } from '../../services/xtream-api.service';
|
||||
import { XtreamUrlService } from '../../services/xtream-url.service';
|
||||
|
||||
/**
|
||||
* Player state for managing stream URLs and player settings
|
||||
*/
|
||||
export interface PlayerState {
|
||||
streamUrl: string | null;
|
||||
hideExternalInfoDialog: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial player state
|
||||
*/
|
||||
const initialPlayerState: PlayerState = {
|
||||
streamUrl: null,
|
||||
hideExternalInfoDialog:
|
||||
localStorage.getItem('hideExternalInfoDialog') === 'true',
|
||||
};
|
||||
|
||||
interface XtreamPlayableItem {
|
||||
readonly xtream_id: number;
|
||||
}
|
||||
|
||||
type XtreamPlaylistHeadersLike = XtreamCredentials & {
|
||||
readonly origin?: string;
|
||||
readonly referrer?: string;
|
||||
readonly userAgent?: string;
|
||||
};
|
||||
|
||||
type ParentPlayerStoreLike = {
|
||||
currentPlaylist?: () => XtreamPlaylistHeadersLike | null;
|
||||
loadEpg?: () => void;
|
||||
selectedContentType?: () => 'live' | 'vod' | 'series' | undefined;
|
||||
setSelectedItem?: (item: XtreamPlayableItem) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Player feature store for managing stream playback.
|
||||
* Handles:
|
||||
* - Stream URL construction
|
||||
* - External player integration
|
||||
* - Player settings
|
||||
*/
|
||||
export function withPlayer() {
|
||||
return signalStoreFeature(
|
||||
withState<PlayerState>(initialPlayerState),
|
||||
|
||||
withMethods((store) => {
|
||||
const urlService = inject(XtreamUrlService);
|
||||
const playerService = inject(PORTAL_PLAYER);
|
||||
|
||||
/**
|
||||
* Helper to get credentials from parent store
|
||||
*/
|
||||
const getCredentialsFromStore = (): XtreamCredentials | null => {
|
||||
const storeAny = store as ParentPlayerStoreLike;
|
||||
const playlist = storeAny.currentPlaylist?.();
|
||||
|
||||
if (!playlist) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper to get playlist with headers from parent store
|
||||
*/
|
||||
const getPlaylistFromStore = (): XtreamPlaylistHeadersLike | null => {
|
||||
const storeAny = store as ParentPlayerStoreLike;
|
||||
return storeAny.currentPlaylist?.();
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
* Construct and return live stream URL
|
||||
*/
|
||||
constructStreamUrl(item: XtreamPlayableItem): string {
|
||||
const credentials = getCredentialsFromStore();
|
||||
if (!credentials) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const streamUrl = urlService.constructLiveUrl(
|
||||
credentials,
|
||||
item.xtream_id
|
||||
);
|
||||
|
||||
// Set selected item in parent store and load EPG
|
||||
const storeAny = store as ParentPlayerStoreLike;
|
||||
if (storeAny.setSelectedItem) {
|
||||
storeAny.setSelectedItem(item);
|
||||
}
|
||||
if (storeAny.loadEpg) {
|
||||
storeAny.loadEpg();
|
||||
}
|
||||
|
||||
patchState(store, { streamUrl });
|
||||
return streamUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* Construct and return VOD stream URL
|
||||
*/
|
||||
constructVodStreamUrl(vodItem: XtreamVodDetails): string {
|
||||
const credentials = getCredentialsFromStore();
|
||||
if (!credentials) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const streamUrl = urlService.constructVodUrl(
|
||||
credentials,
|
||||
vodItem
|
||||
);
|
||||
patchState(store, { streamUrl });
|
||||
return streamUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* Construct and return series episode stream URL
|
||||
*/
|
||||
constructEpisodeStreamUrl(episode: XtreamSerieEpisode): string {
|
||||
const credentials = getCredentialsFromStore();
|
||||
if (!credentials) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const streamUrl = urlService.constructEpisodeUrl(
|
||||
credentials,
|
||||
episode
|
||||
);
|
||||
patchState(store, { streamUrl });
|
||||
return streamUrl;
|
||||
},
|
||||
|
||||
/**
|
||||
* Open external player with stream
|
||||
*/
|
||||
openPlayer(
|
||||
streamUrl: string,
|
||||
title: string,
|
||||
thumbnail: string | null = null,
|
||||
startTime?: number,
|
||||
contentInfo?: unknown
|
||||
): void {
|
||||
const playlist = getPlaylistFromStore();
|
||||
const storeAny = store as ParentPlayerStoreLike;
|
||||
const contentType =
|
||||
storeAny.selectedContentType?.() || 'vod';
|
||||
|
||||
void playerService.openPlayer(
|
||||
streamUrl,
|
||||
title,
|
||||
thumbnail,
|
||||
localStorage.getItem('hideExternalInfoDialog') ===
|
||||
'true',
|
||||
contentType === 'live',
|
||||
playlist?.userAgent,
|
||||
playlist?.referrer,
|
||||
playlist?.origin,
|
||||
contentInfo,
|
||||
startTime
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Set hide external info dialog preference
|
||||
*/
|
||||
setHideExternalInfoDialog(hide: boolean): void {
|
||||
localStorage.setItem(
|
||||
'hideExternalInfoDialog',
|
||||
String(hide)
|
||||
);
|
||||
patchState(store, { hideExternalInfoDialog: hide });
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset player state
|
||||
*/
|
||||
resetPlayer(): void {
|
||||
patchState(store, {
|
||||
streamUrl: null,
|
||||
hideExternalInfoDialog:
|
||||
localStorage.getItem('hideExternalInfoDialog') ===
|
||||
'true',
|
||||
});
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import {
|
||||
XTREAM_DATA_SOURCE,
|
||||
XtreamPlaylistData,
|
||||
} from '../../data-sources/xtream-data-source.interface';
|
||||
import {
|
||||
XtreamApiService,
|
||||
XtreamCredentials,
|
||||
} from '../../services/xtream-api.service';
|
||||
import { PortalStatusType } from '../../xtream-state';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
/**
|
||||
* Portal state for managing playlist and portal status
|
||||
*/
|
||||
export interface PortalState {
|
||||
playlistId: string | null;
|
||||
currentPlaylist: XtreamPlaylistData | null;
|
||||
portalStatus: PortalStatusType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial portal state
|
||||
*/
|
||||
const initialPortalState: PortalState = {
|
||||
playlistId: null,
|
||||
currentPlaylist: null,
|
||||
portalStatus: 'unavailable',
|
||||
};
|
||||
|
||||
/**
|
||||
* Portal feature store for managing the current Xtream playlist and status.
|
||||
* Handles:
|
||||
* - Setting/clearing playlist ID
|
||||
* - Fetching playlist details
|
||||
* - Checking portal status (active, inactive, expired, unavailable)
|
||||
*/
|
||||
export function withPortal() {
|
||||
const logger = createLogger('withPortal');
|
||||
|
||||
const resolvePortalStatus = (response: {
|
||||
user_info?: {
|
||||
exp_date?: string;
|
||||
status?: string;
|
||||
};
|
||||
} | null): PortalStatusType => {
|
||||
if (!response?.user_info?.status) {
|
||||
return 'unavailable';
|
||||
}
|
||||
|
||||
if (response.user_info.status === 'Active') {
|
||||
if (!response.user_info.exp_date) {
|
||||
return 'active';
|
||||
}
|
||||
|
||||
const expDate = new Date(
|
||||
parseInt(response.user_info.exp_date, 10) * 1000
|
||||
);
|
||||
return expDate < new Date() ? 'expired' : 'active';
|
||||
}
|
||||
|
||||
return 'inactive';
|
||||
};
|
||||
|
||||
return signalStoreFeature(
|
||||
withState<PortalState>(initialPortalState),
|
||||
|
||||
withMethods((store) => {
|
||||
const apiService = inject(XtreamApiService);
|
||||
const dataSource = inject(XTREAM_DATA_SOURCE);
|
||||
|
||||
return {
|
||||
/**
|
||||
* Set the current playlist ID
|
||||
*/
|
||||
setPlaylistId(playlistId: string): void {
|
||||
patchState(store, { playlistId });
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch playlist details from data source
|
||||
*/
|
||||
async fetchPlaylist(): Promise<void> {
|
||||
const playlistId = store.playlistId();
|
||||
if (!playlistId) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const playlist =
|
||||
await dataSource.getPlaylist(playlistId);
|
||||
|
||||
if (playlist) {
|
||||
patchState(store, { currentPlaylist: playlist });
|
||||
return;
|
||||
}
|
||||
|
||||
const currentPlaylist = store.currentPlaylist();
|
||||
if (
|
||||
!currentPlaylist ||
|
||||
currentPlaylist.id !== playlistId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
await dataSource.createPlaylist(currentPlaylist);
|
||||
patchState(store, { currentPlaylist });
|
||||
} catch (error) {
|
||||
logger.error('Error fetching playlist', error);
|
||||
}
|
||||
},
|
||||
|
||||
setCurrentPlaylist(playlist: XtreamPlaylistData | null): void {
|
||||
patchState(store, { currentPlaylist: playlist });
|
||||
},
|
||||
|
||||
/**
|
||||
* Check portal status via API
|
||||
*/
|
||||
async checkPortalStatus(): Promise<PortalStatusType> {
|
||||
const playlist = store.currentPlaylist();
|
||||
if (!playlist) {
|
||||
patchState(store, { portalStatus: 'unavailable' });
|
||||
return 'unavailable';
|
||||
}
|
||||
|
||||
const credentials: XtreamCredentials = {
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
};
|
||||
|
||||
try {
|
||||
const response =
|
||||
await apiService.getAccountInfo(credentials);
|
||||
const portalStatus = resolvePortalStatus(response);
|
||||
patchState(store, { portalStatus });
|
||||
return portalStatus;
|
||||
} catch (error) {
|
||||
logger.error('Error checking portal status', error);
|
||||
patchState(store, { portalStatus: 'unavailable' });
|
||||
return 'unavailable';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Update playlist details
|
||||
*/
|
||||
updatePlaylist(updates: Partial<XtreamPlaylistData>): void {
|
||||
const current = store.currentPlaylist();
|
||||
if (current) {
|
||||
patchState(store, {
|
||||
currentPlaylist: { ...current, ...updates },
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset portal state
|
||||
*/
|
||||
resetPortal(): void {
|
||||
patchState(store, initialPortalState);
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { GlobalSearchResult } from 'services';
|
||||
import {
|
||||
XTREAM_DATA_SOURCE,
|
||||
XtreamContentItem,
|
||||
} from '../../data-sources/xtream-data-source.interface';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
/**
|
||||
* Search filters configuration
|
||||
*/
|
||||
export interface SearchFilters {
|
||||
live: boolean;
|
||||
movie: boolean;
|
||||
series: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search state for managing search results
|
||||
*/
|
||||
export interface SearchState {
|
||||
searchTerm: string;
|
||||
searchFilters: SearchFilters;
|
||||
searchResults: XtreamContentItem[];
|
||||
globalSearchResults: GlobalSearchResult[];
|
||||
isSearching: boolean;
|
||||
}
|
||||
|
||||
type SearchContentParams = {
|
||||
term: string;
|
||||
types: string[];
|
||||
excludeHidden?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initial search filters
|
||||
*/
|
||||
const initialSearchFilters: SearchFilters = {
|
||||
live: true,
|
||||
movie: true,
|
||||
series: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Initial search state
|
||||
*/
|
||||
const initialSearchState: SearchState = {
|
||||
searchTerm: '',
|
||||
searchFilters: initialSearchFilters,
|
||||
searchResults: [],
|
||||
globalSearchResults: [],
|
||||
isSearching: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Search feature store for managing content search.
|
||||
* Handles:
|
||||
* - Local playlist search
|
||||
* - Global search results from external sources
|
||||
*/
|
||||
export function withSearch() {
|
||||
const logger = createLogger('withSearch');
|
||||
type ParentSearchStoreLike = {
|
||||
playlistId?: () => string | null;
|
||||
};
|
||||
|
||||
return signalStoreFeature(
|
||||
withState<SearchState>(initialSearchState),
|
||||
|
||||
withMethods((store) => {
|
||||
const dataSource = inject(XTREAM_DATA_SOURCE);
|
||||
let searchRequestVersion = 0;
|
||||
|
||||
return {
|
||||
/**
|
||||
* Search content within the current playlist
|
||||
*/
|
||||
async searchContent(
|
||||
searchTermOrParams: string | SearchContentParams,
|
||||
typesArg?: string[],
|
||||
excludeHiddenArg?: boolean
|
||||
): Promise<XtreamContentItem[]> {
|
||||
const searchTerm =
|
||||
typeof searchTermOrParams === 'string'
|
||||
? searchTermOrParams
|
||||
: searchTermOrParams.term;
|
||||
const types =
|
||||
typeof searchTermOrParams === 'string'
|
||||
? (typesArg ?? [])
|
||||
: searchTermOrParams.types;
|
||||
const excludeHidden =
|
||||
typeof searchTermOrParams === 'string'
|
||||
? excludeHiddenArg
|
||||
: searchTermOrParams.excludeHidden;
|
||||
|
||||
// Access parent store's playlistId (from withPortal)
|
||||
const storeAny = store as ParentSearchStoreLike;
|
||||
const playlistId = storeAny.playlistId?.();
|
||||
const requestVersion = ++searchRequestVersion;
|
||||
|
||||
if (!playlistId || !searchTerm.trim()) {
|
||||
patchState(store, {
|
||||
searchResults: [],
|
||||
isSearching: false,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
patchState(store, { isSearching: true });
|
||||
|
||||
try {
|
||||
const results = await dataSource.searchContent(
|
||||
playlistId,
|
||||
searchTerm,
|
||||
types,
|
||||
excludeHidden
|
||||
);
|
||||
|
||||
if (requestVersion !== searchRequestVersion) {
|
||||
return results;
|
||||
}
|
||||
|
||||
patchState(store, {
|
||||
searchResults: results,
|
||||
isSearching: false,
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
logger.error('Error searching content', error);
|
||||
|
||||
if (requestVersion !== searchRequestVersion) {
|
||||
return [];
|
||||
}
|
||||
|
||||
patchState(store, {
|
||||
searchResults: [],
|
||||
isSearching: false,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Set global search results (from external search)
|
||||
*/
|
||||
setGlobalSearchResults(results: GlobalSearchResult[]): void {
|
||||
patchState(store, {
|
||||
searchResults: results,
|
||||
globalSearchResults: results,
|
||||
isSearching: false,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the searching state
|
||||
*/
|
||||
setIsSearching(value: boolean): void {
|
||||
patchState(store, { isSearching: value });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the search term
|
||||
*/
|
||||
setSearchTerm(term: string): void {
|
||||
patchState(store, { searchTerm: term });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set search filters
|
||||
*/
|
||||
setSearchFilters(filters: SearchFilters): void {
|
||||
patchState(store, { searchFilters: filters });
|
||||
},
|
||||
|
||||
/**
|
||||
* Update a single filter
|
||||
*/
|
||||
updateSearchFilter(
|
||||
key: keyof SearchFilters,
|
||||
value: boolean
|
||||
): void {
|
||||
patchState(store, {
|
||||
searchFilters: {
|
||||
...store.searchFilters(),
|
||||
[key]: value,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear search results
|
||||
*/
|
||||
resetSearchResults(): void {
|
||||
searchRequestVersion++;
|
||||
patchState(store, initialSearchState);
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { signalStore, withState } from '@ngrx/signals';
|
||||
import { withSelection } from './with-selection.feature';
|
||||
|
||||
const TestSelectionStore = signalStore(
|
||||
withState({
|
||||
contentLoadStateByType: {
|
||||
live: 'ready',
|
||||
vod: 'ready',
|
||||
series: 'ready',
|
||||
},
|
||||
liveCategories: [],
|
||||
liveStreams: [],
|
||||
vodCategories: [
|
||||
{
|
||||
id: 10,
|
||||
category_id: '10',
|
||||
category_name: 'Movies',
|
||||
type: 'vod',
|
||||
},
|
||||
],
|
||||
vodStreams: [
|
||||
{
|
||||
xtream_id: 1,
|
||||
category_id: '10',
|
||||
title: 'First',
|
||||
added: '4',
|
||||
},
|
||||
{
|
||||
xtream_id: 2,
|
||||
category_id: '10',
|
||||
title: 'Second',
|
||||
added: '3',
|
||||
},
|
||||
{
|
||||
xtream_id: 3,
|
||||
category_id: '10',
|
||||
title: 'Third',
|
||||
added: '2',
|
||||
},
|
||||
{
|
||||
xtream_id: 4,
|
||||
category_id: '10',
|
||||
title: 'Fourth',
|
||||
added: '1',
|
||||
},
|
||||
],
|
||||
serialCategories: [],
|
||||
serialStreams: [],
|
||||
}),
|
||||
withSelection()
|
||||
);
|
||||
|
||||
describe('withSelection', () => {
|
||||
let store: InstanceType<typeof TestSelectionStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [TestSelectionStore],
|
||||
});
|
||||
|
||||
store = TestBed.inject(TestSelectionStore);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('keeps the current page when the category search term is unchanged', () => {
|
||||
store.setSelectedContentType('vod');
|
||||
store.setSelectedCategory(10);
|
||||
store.setLimit(2);
|
||||
store.setPage(1);
|
||||
|
||||
store.setCategorySearchTerm('');
|
||||
|
||||
expect(store.page()).toBe(1);
|
||||
expect(store.getPaginatedContent().map((item) => item.title)).toEqual([
|
||||
'Third',
|
||||
'Fourth',
|
||||
]);
|
||||
});
|
||||
|
||||
it('resets the current page when the category search term changes', () => {
|
||||
store.setSelectedContentType('vod');
|
||||
store.setSelectedCategory(10);
|
||||
store.setLimit(2);
|
||||
store.setPage(1);
|
||||
|
||||
store.setCategorySearchTerm('first');
|
||||
|
||||
expect(store.page()).toBe(0);
|
||||
expect(store.getPaginatedContent().map((item) => item.title)).toEqual([
|
||||
'First',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,528 @@
|
||||
import { computed } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withComputed,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { ContentType, XtreamContentLoadState } from '../../xtream-state';
|
||||
|
||||
/**
|
||||
* Module-level collator — allocating Intl.Collator is expensive;
|
||||
* one shared instance avoids repeated allocation on every sort call.
|
||||
*/
|
||||
const COLLATOR = new Intl.Collator(undefined, {
|
||||
numeric: true,
|
||||
sensitivity: 'base',
|
||||
});
|
||||
|
||||
export type XtreamCategorySortMode =
|
||||
| 'date-desc'
|
||||
| 'date-asc'
|
||||
| 'name-asc'
|
||||
| 'name-desc';
|
||||
|
||||
/**
|
||||
* Selection state for managing UI selection and pagination
|
||||
*/
|
||||
export interface SelectionState {
|
||||
selectedContentType: ContentType;
|
||||
selectedCategoryId: number | null;
|
||||
selectedItem: XtreamSelectionItem | null;
|
||||
page: number;
|
||||
limit: number;
|
||||
contentSortMode: XtreamCategorySortMode;
|
||||
categorySearchTerm: string;
|
||||
isLoadingDetails: boolean;
|
||||
detailsError: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial selection state
|
||||
*/
|
||||
const initialSelectionState: SelectionState = {
|
||||
selectedContentType: 'vod',
|
||||
selectedCategoryId: null,
|
||||
selectedItem: null,
|
||||
page: 0,
|
||||
limit: Number(localStorage.getItem('xtream-page-size') ?? 25),
|
||||
contentSortMode: 'date-desc',
|
||||
categorySearchTerm: '',
|
||||
isLoadingDetails: false,
|
||||
detailsError: null,
|
||||
};
|
||||
|
||||
interface XtreamSelectionCategory {
|
||||
readonly [key: string]: unknown;
|
||||
readonly category_name?: string;
|
||||
readonly category_id?: string | number;
|
||||
readonly id?: string | number;
|
||||
readonly name?: string;
|
||||
readonly type?: ContentType;
|
||||
}
|
||||
|
||||
interface XtreamSelectionItem {
|
||||
readonly [key: string]: unknown;
|
||||
readonly added?: string;
|
||||
readonly category_id?: string | number;
|
||||
readonly episodes?: unknown;
|
||||
readonly id?: string | number;
|
||||
readonly info?:
|
||||
| {
|
||||
readonly actors?: string;
|
||||
readonly backdrop_path?: string[];
|
||||
readonly cast?: string;
|
||||
readonly country?: string;
|
||||
readonly cover?: string;
|
||||
readonly description?: string;
|
||||
readonly director?: string;
|
||||
readonly duration?: string;
|
||||
readonly episode_run_time?: number | string;
|
||||
readonly genre?: string;
|
||||
readonly movie_image?: string;
|
||||
readonly name?: string;
|
||||
readonly plot?: string;
|
||||
readonly rating?: number | string;
|
||||
readonly rating_imdb?: string;
|
||||
readonly rating_kinopoisk?: string;
|
||||
readonly releaseDate?: string;
|
||||
readonly releasedate?: string;
|
||||
readonly youtube_trailer?: string;
|
||||
}
|
||||
| []
|
||||
| null;
|
||||
readonly last_modified?: string;
|
||||
readonly movie_data?: {
|
||||
readonly name?: string;
|
||||
};
|
||||
readonly name?: string;
|
||||
readonly series_id?: string | number;
|
||||
readonly stream_id?: string | number;
|
||||
readonly title?: string;
|
||||
readonly xtream_id?: number;
|
||||
}
|
||||
|
||||
type ParentSelectionStoreLike = {
|
||||
contentLoadStateByType?: () => Record<ContentType, XtreamContentLoadState>;
|
||||
isLoadingContent?: () => boolean;
|
||||
liveCategories?: () => XtreamSelectionCategory[];
|
||||
liveStreams?: () => XtreamSelectionItem[];
|
||||
serialCategories?: () => XtreamSelectionCategory[];
|
||||
serialStreams?: () => XtreamSelectionItem[];
|
||||
vodCategories?: () => XtreamSelectionCategory[];
|
||||
vodStreams?: () => XtreamSelectionItem[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Selection feature store for managing UI selection and pagination.
|
||||
* Handles:
|
||||
* - Content type selection (live, vod, series)
|
||||
* - Category selection
|
||||
* - Item selection
|
||||
* - Pagination (page, limit)
|
||||
*/
|
||||
export function withSelection() {
|
||||
return signalStoreFeature(
|
||||
withState<SelectionState>(initialSelectionState),
|
||||
|
||||
withComputed((store) => {
|
||||
const getItemDate = (
|
||||
item: XtreamSelectionItem,
|
||||
categoryType: ContentType
|
||||
): number => {
|
||||
const value =
|
||||
categoryType === 'series'
|
||||
? (item.last_modified ?? item.added)
|
||||
: item.added;
|
||||
return parseInt(value ?? '', 10) || 0;
|
||||
};
|
||||
|
||||
const sortByMode = (
|
||||
items: XtreamSelectionItem[],
|
||||
sortMode: XtreamCategorySortMode,
|
||||
categoryType: ContentType
|
||||
): XtreamSelectionItem[] => {
|
||||
return [...items].sort((a, b) => {
|
||||
if (sortMode === 'date-desc') {
|
||||
return (
|
||||
getItemDate(b, categoryType) -
|
||||
getItemDate(a, categoryType)
|
||||
);
|
||||
}
|
||||
if (sortMode === 'date-asc') {
|
||||
return (
|
||||
getItemDate(a, categoryType) -
|
||||
getItemDate(b, categoryType)
|
||||
);
|
||||
}
|
||||
|
||||
const titleA = a.title ?? a.name ?? '';
|
||||
const titleB = b.title ?? b.name ?? '';
|
||||
const byName = COLLATOR.compare(titleA, titleB);
|
||||
return sortMode === 'name-asc' ? byName : -byName;
|
||||
});
|
||||
};
|
||||
|
||||
const filterBySearchTerm = (
|
||||
items: XtreamSelectionItem[],
|
||||
searchTerm: string
|
||||
): XtreamSelectionItem[] => {
|
||||
const normalized = searchTerm.trim().toLocaleLowerCase();
|
||||
if (!normalized) {
|
||||
return items;
|
||||
}
|
||||
|
||||
return items.filter((item) => {
|
||||
const title = (item.title ?? item.name ?? '').toString();
|
||||
return title.toLocaleLowerCase().includes(normalized);
|
||||
});
|
||||
};
|
||||
|
||||
// Memoized sorted content - only recalculates when content/type changes
|
||||
const sortedContent = computed(() => {
|
||||
const categoryType = store.selectedContentType();
|
||||
const sortMode = store.contentSortMode();
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const content =
|
||||
categoryType === 'live'
|
||||
? storeAny.liveStreams?.() || []
|
||||
: categoryType === 'vod'
|
||||
? storeAny.vodStreams?.() || []
|
||||
: storeAny.serialStreams?.() || [];
|
||||
|
||||
if (categoryType === 'vod' || categoryType === 'series') {
|
||||
return sortByMode(content, sortMode, categoryType);
|
||||
}
|
||||
|
||||
return sortByMode(content, 'date-desc', categoryType);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-type category item-count maps.
|
||||
// Each computed only recomputes when ITS streams array changes —
|
||||
// switching content tabs no longer triggers an O(n) full scan.
|
||||
// ---------------------------------------------------------------------------
|
||||
const buildCountMap = (
|
||||
streams: XtreamSelectionItem[]
|
||||
): Map<number, number> => {
|
||||
const countMap = new Map<number, number>();
|
||||
for (const item of streams) {
|
||||
const catId = Number(item.category_id);
|
||||
if (!isNaN(catId)) {
|
||||
countMap.set(catId, (countMap.get(catId) || 0) + 1);
|
||||
}
|
||||
}
|
||||
return countMap;
|
||||
};
|
||||
|
||||
const liveItemCounts = computed(() =>
|
||||
buildCountMap(
|
||||
(store as ParentSelectionStoreLike).liveStreams?.() || []
|
||||
)
|
||||
);
|
||||
const vodItemCounts = computed(() =>
|
||||
buildCountMap(
|
||||
(store as ParentSelectionStoreLike).vodStreams?.() || []
|
||||
)
|
||||
);
|
||||
const seriesItemCounts = computed(() =>
|
||||
buildCountMap(
|
||||
(store as ParentSelectionStoreLike).serialStreams?.() || []
|
||||
)
|
||||
);
|
||||
const selectedTypeContentState = computed(() => {
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const selectedType = store.selectedContentType();
|
||||
return (
|
||||
storeAny.contentLoadStateByType?.()?.[selectedType] ??
|
||||
'idle'
|
||||
);
|
||||
});
|
||||
const selectedTypeContentLoading = computed(
|
||||
() => selectedTypeContentState() === 'loading'
|
||||
);
|
||||
const selectedTypeContentReady = computed(
|
||||
() => selectedTypeContentState() === 'ready'
|
||||
);
|
||||
const selectedTypeCountsReady = computed(() =>
|
||||
selectedTypeContentReady()
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stable filter + sort intermediate.
|
||||
// Depends on category / search / sort — but NOT on page or limit.
|
||||
// This prevents re-sorting the full array on every page-navigation.
|
||||
// ---------------------------------------------------------------------------
|
||||
const filteredAndSortedContent = computed(() => {
|
||||
const categoryId = store.selectedCategoryId();
|
||||
const categoryType = store.selectedContentType();
|
||||
const sortMode = store.contentSortMode();
|
||||
const searchTerm = store.categorySearchTerm();
|
||||
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const content =
|
||||
categoryType === 'live'
|
||||
? storeAny.liveStreams?.() || []
|
||||
: categoryType === 'vod'
|
||||
? storeAny.vodStreams?.() || []
|
||||
: storeAny.serialStreams?.() || [];
|
||||
|
||||
if (!categoryId) {
|
||||
return sortedContent();
|
||||
}
|
||||
|
||||
let filtered = content.filter(
|
||||
(item) => Number(item.category_id) === categoryId
|
||||
);
|
||||
if (categoryType === 'vod' || categoryType === 'series') {
|
||||
filtered = filterBySearchTerm(filtered, searchTerm);
|
||||
filtered = sortByMode(filtered, sortMode, categoryType);
|
||||
}
|
||||
return filtered;
|
||||
});
|
||||
|
||||
return {
|
||||
/**
|
||||
* Get the selected category from the parent store's categories
|
||||
*/
|
||||
getSelectedCategory: computed(() => {
|
||||
const categoryId = store.selectedCategoryId();
|
||||
if (!categoryId) {
|
||||
return {
|
||||
id: 0,
|
||||
name: 'All Items',
|
||||
type: store.selectedContentType(),
|
||||
};
|
||||
}
|
||||
|
||||
// Access parent store categories (from withContent)
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const allCategories: XtreamSelectionCategory[] = [
|
||||
...(storeAny.vodCategories?.() || []),
|
||||
...(storeAny.liveCategories?.() || []),
|
||||
...(storeAny.serialCategories?.() || []),
|
||||
];
|
||||
|
||||
return allCategories.find(
|
||||
(c) =>
|
||||
c.id === categoryId ||
|
||||
c.category_id === String(categoryId)
|
||||
);
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get the selected item by ID from content
|
||||
*/
|
||||
getSelectedItemById: computed(() => {
|
||||
const categoryType = store.selectedContentType();
|
||||
const selectedItem = store.selectedItem();
|
||||
|
||||
if (!selectedItem) return null;
|
||||
|
||||
// Access parent store content (from withContent)
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
const content =
|
||||
categoryType === 'live'
|
||||
? storeAny.liveStreams?.() || []
|
||||
: categoryType === 'vod'
|
||||
? storeAny.vodStreams?.() || []
|
||||
: storeAny.serialStreams?.() || [];
|
||||
|
||||
return content.find(
|
||||
(item) =>
|
||||
item.stream_id === selectedItem.stream_id ||
|
||||
item.id === selectedItem.id ||
|
||||
item.series_id === selectedItem.series_id
|
||||
);
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get paginated content for the selected category.
|
||||
* Slices from the stable `filteredAndSortedContent` intermediate so
|
||||
* page navigation never triggers a full re-sort of the array.
|
||||
*/
|
||||
getPaginatedContent: computed(() => {
|
||||
const start = store.page() * store.limit();
|
||||
return filteredAndSortedContent().slice(
|
||||
start,
|
||||
start + store.limit()
|
||||
);
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get all items from the selected category (without pagination).
|
||||
* Reuses the `filteredAndSortedContent` intermediate to avoid
|
||||
* duplicating the filter+sort work already done for pagination.
|
||||
*/
|
||||
selectItemsFromSelectedCategory: computed(() =>
|
||||
filteredAndSortedContent()
|
||||
),
|
||||
|
||||
/**
|
||||
* Get total pages for the selected category.
|
||||
* Derives length from the shared `filteredAndSortedContent` intermediate.
|
||||
*/
|
||||
getTotalPages: computed(() =>
|
||||
Math.ceil(filteredAndSortedContent().length / store.limit())
|
||||
),
|
||||
|
||||
/**
|
||||
* Check if paginated content is loading
|
||||
*/
|
||||
isPaginatedContentLoading: computed(() =>
|
||||
selectedTypeContentLoading()
|
||||
),
|
||||
|
||||
selectedTypeContentState,
|
||||
|
||||
selectedTypeContentLoading,
|
||||
|
||||
selectedTypeContentReady,
|
||||
|
||||
selectedTypeCountsReady,
|
||||
|
||||
/**
|
||||
* Memoized category item counts map.
|
||||
* Selects from per-type pre-computed maps so switching content tabs
|
||||
* is O(1) — no full array scan on every tab switch.
|
||||
*/
|
||||
getCategoryItemCounts: computed(() => {
|
||||
const type = store.selectedContentType();
|
||||
return type === 'live'
|
||||
? liveItemCounts()
|
||||
: type === 'vod'
|
||||
? vodItemCounts()
|
||||
: seriesItemCounts();
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get categories for the currently selected content type
|
||||
*/
|
||||
getCategoriesBySelectedType: computed(() => {
|
||||
const type = store.selectedContentType();
|
||||
|
||||
// Access parent store categories (from withContent)
|
||||
const storeAny = store as ParentSelectionStoreLike;
|
||||
return type === 'live'
|
||||
? storeAny.liveCategories?.() || []
|
||||
: type === 'vod'
|
||||
? storeAny.vodCategories?.() || []
|
||||
: storeAny.serialCategories?.() || [];
|
||||
}),
|
||||
};
|
||||
}),
|
||||
|
||||
withMethods((store) => ({
|
||||
/**
|
||||
* Set the content type (live, vod, series)
|
||||
*/
|
||||
setSelectedContentType(type: ContentType): void {
|
||||
if (store.selectedContentType() === type) {
|
||||
return;
|
||||
}
|
||||
|
||||
patchState(store, {
|
||||
selectedContentType: type,
|
||||
selectedCategoryId: null,
|
||||
page: 0,
|
||||
categorySearchTerm: '',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the selected category
|
||||
* Only resets page to 0 when category actually changes
|
||||
*/
|
||||
setSelectedCategory(categoryId: number | null): void {
|
||||
const newCategoryId =
|
||||
categoryId !== null ? Number(categoryId) : null;
|
||||
const currentCategoryId = store.selectedCategoryId();
|
||||
|
||||
// Only reset page if category actually changed
|
||||
if (currentCategoryId !== newCategoryId) {
|
||||
patchState(store, {
|
||||
selectedCategoryId: newCategoryId,
|
||||
page: 0,
|
||||
categorySearchTerm: '',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the selected item
|
||||
*/
|
||||
setSelectedItem(item: XtreamSelectionItem | null): void {
|
||||
patchState(store, { selectedItem: item });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the loading details state
|
||||
*/
|
||||
setIsLoadingDetails(isLoading: boolean): void {
|
||||
patchState(store, { isLoadingDetails: isLoading });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the details error state
|
||||
*/
|
||||
setDetailsError(error: string | null): void {
|
||||
patchState(store, { detailsError: error });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the current page
|
||||
*/
|
||||
setPage(page: number): void {
|
||||
patchState(store, { page });
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the page limit (items per page)
|
||||
*/
|
||||
setLimit(limit: number): void {
|
||||
patchState(store, { limit });
|
||||
localStorage.setItem('xtream-page-size', String(limit));
|
||||
},
|
||||
|
||||
/**
|
||||
* Set category content sort mode
|
||||
*/
|
||||
setContentSortMode(mode: XtreamCategorySortMode): void {
|
||||
if (store.contentSortMode() === mode) {
|
||||
return;
|
||||
}
|
||||
patchState(store, {
|
||||
contentSortMode: mode,
|
||||
page: 0,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Set selected category search term
|
||||
*/
|
||||
setCategorySearchTerm(term: string): void {
|
||||
if (store.categorySearchTerm() === term) {
|
||||
return;
|
||||
}
|
||||
|
||||
patchState(store, {
|
||||
categorySearchTerm: term,
|
||||
page: 0,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset selection state
|
||||
*/
|
||||
resetSelection(): void {
|
||||
patchState(store, {
|
||||
...initialSelectionState,
|
||||
limit: Number(
|
||||
localStorage.getItem('xtream-page-size') ?? 25
|
||||
),
|
||||
});
|
||||
},
|
||||
}))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './features';
|
||||
export * from './xtream.store';
|
||||
@@ -0,0 +1,227 @@
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { signalStore, withComputed, withMethods } from '@ngrx/signals';
|
||||
import { XtreamSerieDetails, XtreamVodDetails } from 'shared-interfaces';
|
||||
|
||||
// Import existing features that are already separate
|
||||
import { withFavorites } from '../with-favorites.feature';
|
||||
import { withRecentItems } from '../with-recent-items';
|
||||
|
||||
// Import service
|
||||
import { XTREAM_DATA_SOURCE } from '../data-sources/xtream-data-source.interface';
|
||||
import { XtreamApiService } from '../services/xtream-api.service';
|
||||
|
||||
// Import new feature stores
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
import {
|
||||
withContent,
|
||||
withEpg,
|
||||
withPlaybackPositions,
|
||||
withPlayer,
|
||||
withPortal,
|
||||
withSearch,
|
||||
withSelection,
|
||||
} from './features';
|
||||
|
||||
/**
|
||||
* XtreamStore - Facade composing all feature stores.
|
||||
*
|
||||
* This store provides a unified API for components while delegating
|
||||
* to specialized feature stores for different concerns:
|
||||
*
|
||||
* - withPortal: Playlist and portal status management
|
||||
* - withContent: Categories and streams management
|
||||
* - withSelection: UI selection and pagination
|
||||
* - withSearch: Search functionality
|
||||
* - withEpg: EPG (Electronic Program Guide) data
|
||||
* - withPlayer: Stream URL construction and player integration
|
||||
* - withFavorites: Favorites management
|
||||
* - withRecentItems: Recently viewed items
|
||||
* - withPlaybackPositions: Playback position tracking
|
||||
*
|
||||
* @see docs/XTREAM_STORE_REFACTORING_PLAN.md
|
||||
*/
|
||||
export const XtreamStore = signalStore(
|
||||
{ providedIn: 'root' },
|
||||
|
||||
// Compose all features
|
||||
withPortal(),
|
||||
withContent(),
|
||||
withSelection(),
|
||||
withSearch(),
|
||||
withEpg(),
|
||||
withPlayer(),
|
||||
withFavorites(),
|
||||
withRecentItems(),
|
||||
withPlaybackPositions(),
|
||||
|
||||
// Cross-feature computed properties
|
||||
withComputed((store) => ({
|
||||
/**
|
||||
* Get global recent items (from withRecentItems)
|
||||
*/
|
||||
globalRecentItems: computed(() => {
|
||||
return store.recentItems();
|
||||
}),
|
||||
})),
|
||||
|
||||
// Cross-feature methods & orchestration
|
||||
withMethods((store) => {
|
||||
const xtreamApiService = inject(XtreamApiService);
|
||||
const dataSource = inject(XTREAM_DATA_SOURCE);
|
||||
const logger = createLogger('XtreamStore');
|
||||
const findVodCatalogItem = (vodId: string | number) =>
|
||||
store.vodStreams().find((item) => {
|
||||
const candidateId =
|
||||
item.xtream_id ??
|
||||
item.stream_id ??
|
||||
(item as { id?: string | number }).id;
|
||||
|
||||
return Number(candidateId) === Number(vodId);
|
||||
});
|
||||
|
||||
return {
|
||||
/**
|
||||
* Full store reset for switching between playlists
|
||||
*/
|
||||
resetStore(newPlaylistId?: string): void {
|
||||
// Clear the session cache for the playlist we're leaving so
|
||||
// stale data cannot bleed into the new playlist (PWA path).
|
||||
const leavingPlaylistId = store.playlistId();
|
||||
const preserveCancelledBlock =
|
||||
Boolean(newPlaylistId) &&
|
||||
leavingPlaylistId === newPlaylistId &&
|
||||
store.contentInitBlockReason() === 'cancelled';
|
||||
if (leavingPlaylistId) {
|
||||
dataSource.clearSessionCache(leavingPlaylistId);
|
||||
}
|
||||
|
||||
store.resetPortal();
|
||||
store.resetContent();
|
||||
store.resetSelection();
|
||||
store.resetSearchResults();
|
||||
store.clearEpg();
|
||||
store.resetPlayer();
|
||||
|
||||
if (newPlaylistId) {
|
||||
store.setPlaylistId(newPlaylistId);
|
||||
}
|
||||
|
||||
if (preserveCancelledBlock) {
|
||||
store.setContentInitBlockReason('cancelled');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize the store for a playlist
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
await store.fetchPlaylist();
|
||||
await store.checkPortalStatus();
|
||||
await store.initializeContent();
|
||||
const playlist = store.currentPlaylist();
|
||||
if (playlist) {
|
||||
store.loadAllPositions(playlist.id);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch Xtream playlist (convenience alias)
|
||||
*/
|
||||
async fetchXtreamPlaylist(): Promise<void> {
|
||||
await store.fetchPlaylist();
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch VOD details with metadata
|
||||
* Accepts object format for backward compatibility with rxMethod callers
|
||||
*/
|
||||
fetchVodDetailsWithMetadata(params: {
|
||||
vodId: string;
|
||||
categoryId: number;
|
||||
}): void {
|
||||
const playlist = store.currentPlaylist();
|
||||
if (!playlist) return;
|
||||
|
||||
store.setIsLoadingDetails(true);
|
||||
store.setDetailsError(null);
|
||||
xtreamApiService
|
||||
.getVodInfo(
|
||||
{
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
},
|
||||
params.vodId
|
||||
)
|
||||
.then((vodDetails: XtreamVodDetails) => {
|
||||
const catalogItem = findVodCatalogItem(params.vodId);
|
||||
|
||||
store.setSelectedCategory(params.categoryId);
|
||||
store.setSelectedItem({
|
||||
...catalogItem,
|
||||
...vodDetails,
|
||||
stream_id: params.vodId,
|
||||
xtream_id:
|
||||
catalogItem?.xtream_id ?? Number(params.vodId),
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
logger.error('Error fetching VOD details', error);
|
||||
store.setDetailsError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Unknown error'
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
store.setIsLoadingDetails(false);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch series details with metadata
|
||||
* Accepts object format for backward compatibility with rxMethod callers
|
||||
*/
|
||||
fetchSerialDetailsWithMetadata(params: {
|
||||
serialId: string;
|
||||
categoryId: number;
|
||||
}): void {
|
||||
const playlist = store.currentPlaylist();
|
||||
if (!playlist) return;
|
||||
|
||||
store.setIsLoadingDetails(true);
|
||||
store.setDetailsError(null);
|
||||
xtreamApiService
|
||||
.getSeriesInfo(
|
||||
{
|
||||
serverUrl: playlist.serverUrl,
|
||||
username: playlist.username,
|
||||
password: playlist.password,
|
||||
},
|
||||
params.serialId
|
||||
)
|
||||
.then((serialDetails: XtreamSerieDetails) => {
|
||||
store.setSelectedCategory(params.categoryId);
|
||||
store.setSelectedItem({
|
||||
...serialDetails,
|
||||
series_id: params.serialId,
|
||||
});
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
logger.error('Error fetching series details', error);
|
||||
store.setDetailsError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Unknown error'
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
store.setIsLoadingDetails(false);
|
||||
});
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Type alias for the store
|
||||
export type XtreamStoreType = InstanceType<typeof XtreamStore>;
|
||||
@@ -0,0 +1,125 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { patchState, signalStore } from '@ngrx/signals';
|
||||
import { DatabaseService } from 'services';
|
||||
import { FavoritesService } from './services/favorites.service';
|
||||
import { withFavorites } from './with-favorites.feature';
|
||||
|
||||
jest.mock('@iptvnator/portal/shared/util', () => ({
|
||||
createLogger: () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const TestFavoritesStore = signalStore(withFavorites());
|
||||
|
||||
describe('withFavorites', () => {
|
||||
let store: InstanceType<typeof TestFavoritesStore>;
|
||||
let databaseService: {
|
||||
getContentByXtreamId: jest.Mock;
|
||||
};
|
||||
let favoritesService: {
|
||||
addToFavorites: jest.Mock;
|
||||
isFavorite: jest.Mock;
|
||||
removeFromFavorites: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
databaseService = {
|
||||
getContentByXtreamId: jest.fn(),
|
||||
};
|
||||
favoritesService = {
|
||||
addToFavorites: jest.fn().mockResolvedValue(undefined),
|
||||
isFavorite: jest.fn().mockResolvedValue(false),
|
||||
removeFromFavorites: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TestFavoritesStore,
|
||||
{
|
||||
provide: DatabaseService,
|
||||
useValue: databaseService,
|
||||
},
|
||||
{
|
||||
provide: FavoritesService,
|
||||
useValue: favoritesService,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
store = TestBed.inject(TestFavoritesStore);
|
||||
});
|
||||
|
||||
it('looks favorites up with the requested content type before adding one', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
xtream_id: 290,
|
||||
});
|
||||
|
||||
const result = await store.toggleFavorite(290, 'playlist-1', 'series');
|
||||
|
||||
expect(databaseService.getContentByXtreamId).toHaveBeenCalledWith(
|
||||
290,
|
||||
'playlist-1',
|
||||
'series'
|
||||
);
|
||||
expect(favoritesService.addToFavorites).toHaveBeenCalledWith({
|
||||
content_id: 3941697,
|
||||
playlist_id: 'playlist-1',
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
expect(store.isFavorite()).toBe(true);
|
||||
});
|
||||
|
||||
it('looks favorites up with the requested content type before removing one', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3867578,
|
||||
title: 'SE: V Film Premiere FHD',
|
||||
type: 'live',
|
||||
xtream_id: 290,
|
||||
});
|
||||
patchState(store, { isFavorite: true });
|
||||
|
||||
const result = await store.toggleFavorite(290, 'playlist-1', 'live');
|
||||
|
||||
expect(databaseService.getContentByXtreamId).toHaveBeenCalledWith(
|
||||
290,
|
||||
'playlist-1',
|
||||
'live'
|
||||
);
|
||||
expect(favoritesService.removeFromFavorites).toHaveBeenCalledWith(
|
||||
3867578,
|
||||
'playlist-1'
|
||||
);
|
||||
expect(result).toBe(false);
|
||||
expect(store.isFavorite()).toBe(false);
|
||||
});
|
||||
|
||||
it('checks favorite state against the matching content type', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3829429,
|
||||
title: 'Dragon Ball Heroes',
|
||||
type: 'series',
|
||||
xtream_id: 31,
|
||||
});
|
||||
favoritesService.isFavorite.mockResolvedValue(true);
|
||||
|
||||
await store.checkFavoriteStatus(31, 'playlist-1', 'series');
|
||||
|
||||
expect(databaseService.getContentByXtreamId).toHaveBeenCalledWith(
|
||||
31,
|
||||
'playlist-1',
|
||||
'series'
|
||||
);
|
||||
expect(favoritesService.isFavorite).toHaveBeenCalledWith(
|
||||
3829429,
|
||||
'playlist-1'
|
||||
);
|
||||
expect(store.isFavorite()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { inject } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { DatabaseService } from 'services';
|
||||
import { FavoritesService } from './services/favorites.service';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
export const withFavorites = function () {
|
||||
const logger = createLogger('withFavorites');
|
||||
return signalStoreFeature(
|
||||
withState({
|
||||
isFavorite: false,
|
||||
}),
|
||||
withMethods(
|
||||
(
|
||||
store,
|
||||
dbService = inject(DatabaseService),
|
||||
favoritesService = inject(FavoritesService)
|
||||
) => ({
|
||||
async toggleFavorite(
|
||||
xtreamId: number,
|
||||
playlistId: string,
|
||||
contentType: 'live' | 'movie' | 'series',
|
||||
backdropUrl?: string
|
||||
) {
|
||||
if (!xtreamId || !playlistId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const content = await dbService.getContentByXtreamId(
|
||||
xtreamId,
|
||||
playlistId,
|
||||
contentType
|
||||
);
|
||||
if (!content) {
|
||||
logger.error(
|
||||
'Content not found for xtream ID',
|
||||
xtreamId
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const currentStatus = store.isFavorite();
|
||||
|
||||
if (currentStatus) {
|
||||
// Remove from favorites
|
||||
await favoritesService.removeFromFavorites(
|
||||
content.id,
|
||||
playlistId
|
||||
);
|
||||
patchState(store, { isFavorite: false });
|
||||
return false;
|
||||
} else {
|
||||
// Add to favorites
|
||||
await favoritesService.addToFavorites({
|
||||
content_id: content.id,
|
||||
playlist_id: playlistId,
|
||||
backdrop_url: backdropUrl,
|
||||
});
|
||||
patchState(store, { isFavorite: true });
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
async checkFavoriteStatus(
|
||||
xtreamId: number,
|
||||
playlistId: string,
|
||||
contentType: 'live' | 'movie' | 'series'
|
||||
) {
|
||||
if (!xtreamId || !playlistId) {
|
||||
patchState(store, { isFavorite: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const content = await dbService.getContentByXtreamId(
|
||||
xtreamId,
|
||||
playlistId,
|
||||
contentType
|
||||
);
|
||||
if (!content) {
|
||||
patchState(store, { isFavorite: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const isFavorite = await favoritesService.isFavorite(
|
||||
content.id,
|
||||
playlistId
|
||||
);
|
||||
|
||||
patchState(store, { isFavorite });
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { signalStore } from '@ngrx/signals';
|
||||
import { of } from 'rxjs';
|
||||
import { DatabaseService, PlaylistsService } from 'services';
|
||||
import { withRecentItems } from './with-recent-items';
|
||||
|
||||
jest.mock('@iptvnator/portal/shared/util', () => ({
|
||||
createLogger: () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const TestRecentItemsStore = signalStore(withRecentItems());
|
||||
|
||||
describe('withRecentItems', () => {
|
||||
let store: InstanceType<typeof TestRecentItemsStore>;
|
||||
let databaseService: {
|
||||
addRecentItem: jest.Mock;
|
||||
getContentByXtreamId: jest.Mock;
|
||||
getRecentItems: jest.Mock;
|
||||
setContentBackdropIfMissing: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'electron', {
|
||||
value: {} as Window['electron'],
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
databaseService = {
|
||||
addRecentItem: jest.fn().mockResolvedValue(undefined),
|
||||
getContentByXtreamId: jest.fn(),
|
||||
getRecentItems: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
poster_url: 'https://example.com/krypton.png',
|
||||
backdrop_url: 'https://example.com/krypton-backdrop.png',
|
||||
viewed_at: '2026-04-21T20:42:27.000Z',
|
||||
xtream_id: 290,
|
||||
category_id: 17,
|
||||
},
|
||||
]),
|
||||
setContentBackdropIfMissing: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TestRecentItemsStore,
|
||||
{
|
||||
provide: DatabaseService,
|
||||
useValue: databaseService,
|
||||
},
|
||||
{
|
||||
provide: PlaylistsService,
|
||||
useValue: {
|
||||
clearPlaylistRecentlyViewed: jest.fn().mockReturnValue(
|
||||
of(undefined)
|
||||
),
|
||||
getAllPlaylists: jest.fn().mockReturnValue(of([])),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
store = TestBed.inject(TestRecentItemsStore);
|
||||
});
|
||||
|
||||
it('looks recent items up with the requested content type before saving one', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
xtream_id: 290,
|
||||
});
|
||||
|
||||
store.addRecentItem({
|
||||
xtreamId: 290,
|
||||
contentType: 'series',
|
||||
playlist: signal({ id: 'playlist-1' }),
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(databaseService.getContentByXtreamId).toHaveBeenCalledWith(
|
||||
290,
|
||||
'playlist-1',
|
||||
'series'
|
||||
);
|
||||
expect(databaseService.addRecentItem).toHaveBeenCalledWith(
|
||||
3941697,
|
||||
'playlist-1',
|
||||
undefined
|
||||
);
|
||||
expect(store.recentItems()).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
xtream_id: 290,
|
||||
backdrop_url: 'https://example.com/krypton-backdrop.png',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('forwards backdrop urls on recent-item saves', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
xtream_id: 290,
|
||||
});
|
||||
|
||||
store.addRecentItem({
|
||||
xtreamId: 290,
|
||||
contentType: 'series',
|
||||
playlist: signal({ id: 'playlist-1' }),
|
||||
backdropUrl: 'https://example.com/krypton-backdrop.png',
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(databaseService.addRecentItem).toHaveBeenCalledWith(
|
||||
3941697,
|
||||
'playlist-1',
|
||||
'https://example.com/krypton-backdrop.png'
|
||||
);
|
||||
});
|
||||
|
||||
it('backfills a backdrop without rewriting recent ordering', async () => {
|
||||
databaseService.getContentByXtreamId.mockResolvedValue({
|
||||
id: 3941697,
|
||||
title: 'Krypton',
|
||||
type: 'series',
|
||||
xtream_id: 290,
|
||||
});
|
||||
|
||||
await store.backfillContentBackdrop({
|
||||
xtreamId: 290,
|
||||
contentType: 'series',
|
||||
playlist: signal({ id: 'playlist-1' }),
|
||||
backdropUrl: ' https://example.com/krypton-backdrop.png ',
|
||||
});
|
||||
|
||||
expect(databaseService.getContentByXtreamId).toHaveBeenCalledWith(
|
||||
290,
|
||||
'playlist-1',
|
||||
'series'
|
||||
);
|
||||
expect(
|
||||
databaseService.setContentBackdropIfMissing
|
||||
).toHaveBeenCalledWith(
|
||||
3941697,
|
||||
'https://example.com/krypton-backdrop.png'
|
||||
);
|
||||
expect(databaseService.addRecentItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { inject, Signal } from '@angular/core';
|
||||
import {
|
||||
patchState,
|
||||
signalStoreFeature,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import { rxMethod } from '@ngrx/signals/rxjs-interop';
|
||||
import { firstValueFrom, pipe, switchMap, tap } from 'rxjs';
|
||||
import { DatabaseService, PlaylistsService } from 'services';
|
||||
import {
|
||||
buildPlaylistRecentItems,
|
||||
Playlist,
|
||||
PortalRecentItem,
|
||||
} from 'shared-interfaces';
|
||||
import { createLogger } from '@iptvnator/portal/shared/util';
|
||||
|
||||
export interface RecentlyViewedItem extends PortalRecentItem {
|
||||
/** @deprecated Redundant — always equals `id`. Retained for compat. */
|
||||
content_id: number | string;
|
||||
}
|
||||
|
||||
function mapDbRecentItem(
|
||||
item: {
|
||||
id: number;
|
||||
title: string;
|
||||
type: string;
|
||||
poster_url: string;
|
||||
backdrop_url?: string | null;
|
||||
viewed_at?: string;
|
||||
xtream_id: number;
|
||||
category_id: number;
|
||||
},
|
||||
playlistId: string
|
||||
): RecentlyViewedItem {
|
||||
return {
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
type: item.type as 'live' | 'movie' | 'series',
|
||||
poster_url: item.poster_url,
|
||||
backdrop_url: item.backdrop_url ?? undefined,
|
||||
content_id: item.id,
|
||||
playlist_id: playlistId,
|
||||
viewed_at: item.viewed_at || '',
|
||||
xtream_id: item.xtream_id,
|
||||
category_id: item.category_id,
|
||||
};
|
||||
}
|
||||
|
||||
export const withRecentItems = function () {
|
||||
const logger = createLogger('withRecentItems');
|
||||
return signalStoreFeature(
|
||||
withState({
|
||||
recentItems: [],
|
||||
}),
|
||||
withMethods((store, dbService = inject(DatabaseService)) => ({
|
||||
loadRecentItems: rxMethod<{ id: string }>(
|
||||
pipe(
|
||||
switchMap(async (playlist) => {
|
||||
const items = await dbService.getRecentItems(
|
||||
playlist.id
|
||||
);
|
||||
return items.map((item) =>
|
||||
mapDbRecentItem(item, playlist.id)
|
||||
);
|
||||
}),
|
||||
tap((items: RecentlyViewedItem[]) =>
|
||||
patchState(store, { recentItems: items })
|
||||
)
|
||||
)
|
||||
),
|
||||
})),
|
||||
withMethods(
|
||||
(
|
||||
store,
|
||||
dbService = inject(DatabaseService),
|
||||
playlistsService = inject(PlaylistsService)
|
||||
) => ({
|
||||
addRecentItem: rxMethod<{
|
||||
xtreamId: number;
|
||||
contentType: 'live' | 'movie' | 'series';
|
||||
playlist: Signal<{ id: string }>;
|
||||
backdropUrl?: string;
|
||||
}>(
|
||||
pipe(
|
||||
switchMap(
|
||||
async ({
|
||||
xtreamId,
|
||||
contentType,
|
||||
playlist,
|
||||
backdropUrl,
|
||||
}) => {
|
||||
const playlistId = playlist().id;
|
||||
const content = await dbService.getContentByXtreamId(
|
||||
xtreamId,
|
||||
playlistId,
|
||||
contentType
|
||||
);
|
||||
if (content) {
|
||||
await dbService.addRecentItem(
|
||||
content.id,
|
||||
playlistId,
|
||||
backdropUrl
|
||||
);
|
||||
|
||||
// Reload after add/update so re-watched items
|
||||
// immediately move to the top in recently-viewed.
|
||||
const items =
|
||||
await dbService.getRecentItems(playlistId);
|
||||
patchState(store, {
|
||||
recentItems: items.map((item) =>
|
||||
mapDbRecentItem(item, playlistId)
|
||||
),
|
||||
});
|
||||
}
|
||||
})
|
||||
)
|
||||
),
|
||||
async backfillContentBackdrop({
|
||||
xtreamId,
|
||||
contentType,
|
||||
playlist,
|
||||
backdropUrl,
|
||||
}: {
|
||||
xtreamId: number;
|
||||
contentType: 'live' | 'movie' | 'series';
|
||||
playlist: Signal<{ id: string }>;
|
||||
backdropUrl?: string;
|
||||
}): Promise<void> {
|
||||
if (!window.electron) {
|
||||
return;
|
||||
}
|
||||
|
||||
const playlistId = playlist().id;
|
||||
const normalizedBackdropUrl = backdropUrl?.trim();
|
||||
if (!playlistId || !normalizedBackdropUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const content = await dbService.getContentByXtreamId(
|
||||
xtreamId,
|
||||
playlistId,
|
||||
contentType
|
||||
);
|
||||
if (!content) {
|
||||
return;
|
||||
}
|
||||
|
||||
await dbService.setContentBackdropIfMissing(
|
||||
content.id,
|
||||
normalizedBackdropUrl
|
||||
);
|
||||
},
|
||||
clearRecentItems: rxMethod<{ id: string }>(
|
||||
pipe(
|
||||
switchMap(async (playlist) => {
|
||||
await dbService.clearPlaylistRecentItems(
|
||||
playlist.id
|
||||
);
|
||||
patchState(store, { recentItems: [] });
|
||||
})
|
||||
)
|
||||
),
|
||||
removeRecentItem: rxMethod<{
|
||||
itemId: number;
|
||||
playlistId: string;
|
||||
}>(
|
||||
pipe(
|
||||
switchMap(async ({ itemId, playlistId }) => {
|
||||
await dbService.removeRecentItem(
|
||||
itemId,
|
||||
playlistId
|
||||
);
|
||||
// Reload recent items to update UI
|
||||
const items =
|
||||
await dbService.getRecentItems(playlistId);
|
||||
patchState(store, {
|
||||
recentItems: items.map((item) =>
|
||||
mapDbRecentItem(item, playlistId)
|
||||
),
|
||||
});
|
||||
})
|
||||
)
|
||||
),
|
||||
async loadGlobalRecentItems() {
|
||||
try {
|
||||
const xtreamItems =
|
||||
await dbService.getGlobalRecentlyViewed();
|
||||
const playlists = (await firstValueFrom(
|
||||
playlistsService.getAllPlaylists()
|
||||
)) as Playlist[];
|
||||
const playlistBackedItems =
|
||||
buildPlaylistRecentItems(playlists, {
|
||||
stalker: 'Stalker Portal',
|
||||
m3u: 'M3U',
|
||||
}).map((item) => ({
|
||||
...item,
|
||||
content_id: item.id,
|
||||
})) as RecentlyViewedItem[];
|
||||
|
||||
const normalizedXtream: RecentlyViewedItem[] = (
|
||||
xtreamItems || []
|
||||
).map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
type: item.type as 'live' | 'movie' | 'series',
|
||||
poster_url: item.poster_url,
|
||||
backdrop_url: item.backdrop_url ?? undefined,
|
||||
content_id: item.id,
|
||||
playlist_id: item.playlist_id,
|
||||
playlist_name: item.playlist_name,
|
||||
viewed_at: item.viewed_at,
|
||||
xtream_id: item.xtream_id,
|
||||
category_id: item.category_id,
|
||||
source: 'xtream',
|
||||
}));
|
||||
|
||||
const items = [
|
||||
...normalizedXtream,
|
||||
...playlistBackedItems,
|
||||
].sort(
|
||||
(a, b) =>
|
||||
new Date(b.viewed_at).getTime() -
|
||||
new Date(a.viewed_at).getTime()
|
||||
);
|
||||
patchState(store, {
|
||||
recentItems: items,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'Error loading global recent items',
|
||||
error
|
||||
);
|
||||
patchState(store, { recentItems: [] });
|
||||
}
|
||||
},
|
||||
async clearGlobalRecentlyViewed() {
|
||||
try {
|
||||
await dbService.clearGlobalRecentlyViewed();
|
||||
const playlists = (await firstValueFrom(
|
||||
playlistsService.getAllPlaylists()
|
||||
)) as Playlist[];
|
||||
await Promise.all(
|
||||
playlists
|
||||
.filter(
|
||||
(playlist) =>
|
||||
Boolean(playlist.macAddress) ||
|
||||
!playlist.serverUrl
|
||||
)
|
||||
.map((playlist) =>
|
||||
firstValueFrom(
|
||||
playlistsService.clearPlaylistRecentlyViewed(
|
||||
playlist._id
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
patchState(store, { recentItems: [] });
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'Error clearing global recently viewed',
|
||||
error
|
||||
);
|
||||
}
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import { GlobalSearchResult } from 'services';
|
||||
import {
|
||||
EpgItem,
|
||||
XtreamCategory,
|
||||
XtreamLiveStream,
|
||||
XtreamSerieItem,
|
||||
XtreamVodStream,
|
||||
} from 'shared-interfaces';
|
||||
import {
|
||||
XtreamContentItem,
|
||||
XtreamPlaylistData,
|
||||
} from './data-sources/xtream-data-source.interface';
|
||||
|
||||
export type ContentType = 'live' | 'vod' | 'series';
|
||||
export type XtreamContentLoadState = 'idle' | 'loading' | 'ready' | 'error';
|
||||
export type XtreamContentLoadStateByType = Record<
|
||||
ContentType,
|
||||
XtreamContentLoadState
|
||||
>;
|
||||
|
||||
export type PortalStatusType =
|
||||
| 'active'
|
||||
| 'inactive'
|
||||
| 'expired'
|
||||
| 'unavailable';
|
||||
|
||||
export type XtreamContentInitBlockReason =
|
||||
| 'cancelled'
|
||||
| 'expired'
|
||||
| 'inactive'
|
||||
| 'unavailable'
|
||||
| 'error';
|
||||
|
||||
export interface XtreamPortalStatus {
|
||||
status: 'active' | 'inactive' | 'expired' | 'unavailable';
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface XtreamState {
|
||||
isLoadingCategories: boolean;
|
||||
isLoadingContent: boolean;
|
||||
isImporting: boolean;
|
||||
contentLoadStateByType: XtreamContentLoadStateByType;
|
||||
liveCategories: XtreamCategory[];
|
||||
vodCategories: XtreamCategory[];
|
||||
serialCategories: XtreamCategory[];
|
||||
liveStreams: XtreamLiveStream[];
|
||||
vodStreams: XtreamVodStream[];
|
||||
serialStreams: XtreamSerieItem[];
|
||||
page: number;
|
||||
limit: number;
|
||||
selectedCategoryId: number | null;
|
||||
searchResults: XtreamContentItem[];
|
||||
selectedContentType: ContentType;
|
||||
selectedItem: unknown | null;
|
||||
importCount: number;
|
||||
itemsToImport: number;
|
||||
currentPlaylist: XtreamPlaylistData | null;
|
||||
epgItems: EpgItem[];
|
||||
hideExternalInfoDialog: boolean;
|
||||
portalStatus: PortalStatusType;
|
||||
contentInitBlockReason: XtreamContentInitBlockReason | null;
|
||||
globalSearchResults: GlobalSearchResult[];
|
||||
streamUrl: string;
|
||||
playlistId: string | null;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
|
||||
|
||||
setupZoneTestEnv({
|
||||
errorOnUnknownElements: true,
|
||||
errorOnUnknownProperties: true,
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"target": "es2016",
|
||||
"types": ["jest", "node"],
|
||||
"moduleResolution": "node10"
|
||||
},
|
||||
"files": ["src/test-setup.ts"],
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user