Proyecto App Linux

This commit is contained in:
2026-05-03 23:43:09 +02:00
commit 7482733843
1248 changed files with 189750 additions and 0 deletions
@@ -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 ?? ''));
}
@@ -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"
]
}
+21
View File
@@ -0,0 +1,21 @@
export default {
displayName: 'portal-xtream-feature',
preset: '../../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../../../coverage/libs/portal/xtream/feature',
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',
],
};
+21
View File
@@ -0,0 +1,21 @@
{
"name": "portal-xtream-feature",
"$schema": "../../../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/portal/xtream/feature/src",
"prefix": "lib",
"projectType": "library",
"tags": ["scope:portal", "domain:xtream", "type:feature"],
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/portal/xtream/feature/jest.config.ts",
"tsConfig": "libs/portal/xtream/feature/tsconfig.spec.json"
}
},
"lint": {
"executor": "@nx/eslint:lint"
}
}
}
+16
View File
@@ -0,0 +1,16 @@
export * from './lib/account-info/account-info.component';
export * from './lib/category-management-dialog/category-management-dialog.component';
export * from './lib/global-search-results/global-search-results.component';
export * from './lib/live-stream-layout/live-stream-layout.component';
export * from './lib/loading-overlay.component';
export * from './lib/player-dialog/player-dialog.component';
export * from './lib/portal-channels-list/portal-channels-list.component';
export * from './lib/recently-added/recently-added.component';
export * from './lib/search-results/search-results.component';
export * from './lib/serial-details/serial-details.component';
export * from './lib/xtream-collection-detail.component';
export * from './lib/vod-details/vod-details-route.component';
export * from './lib/xtream-content-gate.component';
export * from './lib/xtream-catalog-facade.service';
export * from './lib/xtream-feature.routes';
export * from './lib/xtream-workspace-route-session.service';
@@ -0,0 +1,218 @@
<section mat-dialog-title class="account-dialog__hero">
<div class="account-dialog__hero-copy">
<div class="account-dialog__eyebrow">
<span class="account-dialog__eyebrow-mark"></span>
@if (accountInfo(); as info) {
{{ info.server_info?.server_protocol || 'Xtream' }}
@if (info.server_info?.timezone) {
<span class="account-dialog__eyebrow-divider"></span>
{{ info.server_info?.timezone }}
}
} @else {
Xtream
}
</div>
<div class="account-dialog__headline-row">
<div>
<h2 class="account-dialog__title">
{{ 'XTREAM.ACCOUNT_INFO.TITLE' | translate }}
</h2>
<p class="account-dialog__subtitle">
{{ playlistLabel() }}
</p>
</div>
@if (accountInfo(); as info) {
<div class="account-dialog__status-cluster">
<span
class="account-dialog__status-pill"
[class.account-dialog__status-pill--active]="isActive()"
>
{{ info.user_info?.status || '-' }}
</span>
@if (isTrial()) {
<span
class="account-dialog__status-pill account-dialog__status-pill--trial"
>
{{
'XTREAM.ACCOUNT_INFO.TRIAL_ACCOUNT' | translate
}}
</span>
}
</div>
}
</div>
@if (accountInfo()?.user_info?.message) {
<div class="account-dialog__message">
{{ accountInfo()?.user_info?.message }}
</div>
} @else if (loadState() === 'loading') {
<p class="account-dialog__loading-copy">
{{ 'LOADING' | translate }}...
</p>
}
</div>
<div class="account-dialog__hero-stats">
@if (loadState() === 'ready') {
@for (stat of heroStats(); track stat.labelKey) {
<article class="account-stat">
<div class="account-stat__icon">
<mat-icon>{{ stat.icon }}</mat-icon>
</div>
<div class="account-stat__label">
{{ stat.labelKey | translate }}
</div>
<div class="account-stat__value">
{{ stat.value }}
</div>
@if (stat.meter !== null) {
<div class="account-stat__meter">
<span [style.width.%]="stat.meter"></span>
</div>
}
</article>
}
} @else {
@for (item of skeletonStats; track item) {
<div class="account-skeleton account-skeleton--stat"></div>
}
}
</div>
</section>
<mat-dialog-content class="account-dialog__content">
@if (loadState() === 'error') {
<section class="account-dialog__error-state">
<div class="account-dialog__error-icon">
<mat-icon>signal_wifi_connected_no_internet_4</mat-icon>
</div>
<h3>
{{ 'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.TITLE' | translate }}
</h3>
<p>
{{
'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.DESCRIPTION'
| translate
}}
</p>
<button mat-flat-button color="primary" (click)="reload()">
{{ 'RETRY' | translate }}
</button>
</section>
} @else if (loadState() === 'loading') {
<div class="account-dialog__grid">
@for (panel of skeletonPanels; track panel) {
<section class="account-panel account-panel--loading">
<div class="account-skeleton account-skeleton--heading"></div>
<div class="account-skeleton account-skeleton--row"></div>
<div class="account-skeleton account-skeleton--row"></div>
<div class="account-skeleton account-skeleton--row"></div>
<div class="account-skeleton account-skeleton--row short"></div>
</section>
}
</div>
} @else if (accountInfo(); as info) {
<div class="account-dialog__grid">
<section class="account-panel">
<div class="account-panel__header">
<p class="account-panel__eyebrow">
{{ 'XTREAM.ACCOUNT_INFO.USER_INFO' | translate }}
</p>
<h3>{{ info.user_info?.username || '-' }}</h3>
</div>
<dl class="account-detail-list">
@for (row of userDetails(); track row.labelKey) {
<div class="account-detail-row">
<dt>{{ row.labelKey | translate }}</dt>
<dd
[class.account-detail-row__value--mono]="
row.mono
"
[class.account-detail-row__value--accent]="
row.tone === 'accent'
"
[class.account-detail-row__value--positive]="
row.tone === 'positive'
"
[class.account-detail-row__value--warning]="
row.tone === 'warning'
"
>
@if (row.translateValue) {
{{ row.value | translate }}
} @else {
{{ row.value }}
}
</dd>
</div>
}
</dl>
<div class="account-chip-section">
<p class="account-chip-section__label">
{{ 'XTREAM.ACCOUNT_INFO.ALLOWED_FORMATS' | translate }}
</p>
<div class="account-chip-group">
@for (format of allowedFormats(); track format) {
<span class="account-chip">
{{ format }}
</span>
} @empty {
<span class="account-chip account-chip--muted">
-
</span>
}
</div>
</div>
</section>
<section class="account-panel">
<div class="account-panel__header">
<p class="account-panel__eyebrow">
{{ 'XTREAM.ACCOUNT_INFO.SERVER_INFO' | translate }}
</p>
<h3>{{ serverHost() }}</h3>
</div>
<dl class="account-detail-list">
@for (row of serverDetails(); track row.labelKey) {
<div class="account-detail-row">
<dt>{{ row.labelKey | translate }}</dt>
<dd
[class.account-detail-row__value--mono]="
row.mono
"
>
{{ row.value }}
</dd>
</div>
}
</dl>
<div class="account-chip-section">
<p class="account-chip-section__label">
{{ 'XTREAM.ACCOUNT_INFO.PORTS' | translate }}
</p>
<div class="account-chip-group">
@for (port of ports(); track port.labelKey) {
<span class="account-chip account-chip--mono">
{{ port.labelKey | translate }} {{ port.value }}
</span>
}
</div>
</div>
</section>
</div>
}
</mat-dialog-content>
<mat-dialog-actions class="account-dialog__actions">
<button mat-stroked-button mat-dialog-close class="account-dialog__close">
{{ 'CLOSE' | translate }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,477 @@
:host {
display: block;
color: var(--app-body-color, var(--mat-sys-on-surface));
}
// ─── Hero header ────────────────────────────────────────────────────────────
.account-dialog__hero {
margin: 0;
padding: 20px 20px 18px;
display: grid;
gap: 18px;
background:
var(--app-accent-gradient),
var(--app-widget-header-bg, var(--mat-sys-surface-container-high));
border-bottom: 1px solid var(--app-widget-header-border, rgba(255, 255, 255, 0.05));
}
.account-dialog__hero-copy {
display: grid;
gap: 10px;
}
.account-dialog__eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin: 0;
color: var(--app-eyebrow-color, var(--mat-sys-on-surface-variant));
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.account-dialog__eyebrow-mark {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--app-provider-xtream, var(--mat-sys-primary));
box-shadow: 0 0 0 4px color-mix(in srgb, var(--app-provider-xtream, var(--mat-sys-primary)) 14%, transparent);
}
.account-dialog__eyebrow-divider {
width: 3px;
height: 3px;
border-radius: 999px;
background: currentColor;
opacity: 0.5;
}
.account-dialog__headline-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
.account-dialog__title {
margin: 0;
font-size: 1.3rem;
line-height: 1.2;
font-weight: 650;
letter-spacing: -0.02em;
color: var(--app-heading-color, var(--mat-sys-on-surface));
}
.account-dialog__subtitle {
margin: 4px 0 0;
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
font-size: 0.88rem;
}
// ─── Status pills ───────────────────────────────────────────────────────────
.account-dialog__status-cluster {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 6px;
}
.account-dialog__status-pill {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
border: 1px solid var(--app-separator);
background: var(--mat-sys-surface-container);
color: var(--app-body-color, var(--mat-sys-on-surface));
font-size: 0.76rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.account-dialog__status-pill--active {
border-color: color-mix(in srgb, #34d399 30%, transparent);
background: color-mix(in srgb, #34d399 12%, transparent);
color: #2db36f;
}
.account-dialog__status-pill--trial {
border-color: color-mix(in srgb, #fbbf24 28%, transparent);
background: color-mix(in srgb, #f59e0b 12%, transparent);
color: #d18b09;
}
// ─── Messages ───────────────────────────────────────────────────────────────
.account-dialog__message,
.account-dialog__loading-copy {
margin: 0;
max-width: 60ch;
color: var(--app-body-color, var(--mat-sys-on-surface));
}
.account-dialog__message {
padding: 10px 14px;
border-radius: 10px;
border: 1px solid var(--app-separator);
background: var(--mat-sys-surface-container);
line-height: 1.5;
font-size: 0.88rem;
}
// ─── Hero stat cards ────────────────────────────────────────────────────────
.account-dialog__hero-stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
}
.account-stat {
display: grid;
gap: 6px;
padding: 12px 14px;
border-radius: 12px;
border: 1px solid var(--app-widget-border, transparent);
background: var(--app-widget-bg, var(--mat-sys-surface-container));
box-shadow: var(--app-widget-shadow, none);
// Subtle inset highlight matching widget-shell pattern
outline: 1px solid rgba(255, 255, 255, 0.04);
outline-offset: -1px;
}
.account-stat__icon {
width: 32px;
height: 32px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: color-mix(in srgb, var(--app-provider-xtream, var(--mat-sys-primary)) 12%, transparent);
color: var(--app-provider-xtream, var(--mat-sys-primary));
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.account-stat__label {
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.account-stat__value {
font-size: 1.3rem;
font-weight: 650;
letter-spacing: -0.03em;
color: var(--app-heading-color, var(--mat-sys-on-surface));
}
.account-stat__meter {
position: relative;
overflow: hidden;
height: 4px;
border-radius: 999px;
background: var(--app-separator);
}
.account-stat__meter span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--app-provider-xtream, var(--mat-sys-primary));
}
// ─── Content area ───────────────────────────────────────────────────────────
.account-dialog__content {
margin: 0;
padding: 20px;
background: var(--app-widget-bg, var(--mat-sys-surface));
}
.account-dialog__grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
// ─── Detail panels ──────────────────────────────────────────────────────────
.account-panel {
display: grid;
gap: 14px;
padding: 16px;
border-radius: 16px;
border: 1px solid var(--app-widget-border, transparent);
background: var(--app-widget-bg, var(--mat-sys-surface-container-low));
box-shadow: var(--app-widget-shadow, none);
outline: 1px solid rgba(255, 255, 255, 0.04);
outline-offset: -1px;
}
.account-panel__header {
display: grid;
gap: 4px;
}
.account-panel__header h3 {
margin: 0;
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--app-heading-color, var(--mat-sys-on-surface));
}
.account-panel__eyebrow {
margin: 0;
color: var(--app-eyebrow-color, var(--mat-sys-on-surface-variant));
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
// ─── Detail rows ────────────────────────────────────────────────────────────
.account-detail-list {
display: grid;
gap: 0;
margin: 0;
}
.account-detail-row {
display: grid;
grid-template-columns: minmax(120px, 140px) minmax(0, 1fr);
gap: 12px;
align-items: baseline;
padding: 10px 0;
border-bottom: 1px solid var(--app-separator);
}
.account-detail-row:last-child {
border-bottom: 0;
padding-bottom: 0;
}
.account-detail-row dt {
margin: 0;
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.account-detail-row dd {
margin: 0;
color: var(--app-body-color, var(--mat-sys-on-surface));
font-size: 0.9rem;
font-weight: 500;
word-break: break-word;
}
.account-detail-row__value--mono {
font-family: 'JetBrains Mono', 'Roboto Mono', monospace;
font-size: 0.84rem;
}
.account-detail-row__value--accent {
color: var(--app-provider-xtream, var(--mat-sys-primary));
}
.account-detail-row__value--positive {
color: #2db36f;
}
.account-detail-row__value--warning {
color: #d18b09;
}
// ─── Chip sections ──────────────────────────────────────────────────────────
.account-chip-section {
display: grid;
gap: 10px;
}
.account-chip-section__label {
margin: 0;
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.account-chip-group {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.account-chip {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--app-provider-xtream, var(--mat-sys-primary)) 16%, transparent);
background: color-mix(in srgb, var(--app-provider-xtream, var(--mat-sys-primary)) 8%, transparent);
color: var(--app-body-color, var(--mat-sys-on-surface));
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
}
.account-chip--mono {
font-family: 'JetBrains Mono', 'Roboto Mono', monospace;
text-transform: none;
}
.account-chip--muted {
border-color: var(--app-separator);
background: var(--mat-sys-surface-container);
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
}
// ─── Error state ────────────────────────────────────────────────────────────
.account-dialog__error-state {
display: grid;
justify-items: center;
gap: 12px;
padding: 36px 20px;
border-radius: 16px;
border: 1px dashed var(--app-separator);
background: var(--app-widget-bg, var(--mat-sys-surface-container-low));
text-align: center;
}
.account-dialog__error-state h3,
.account-dialog__error-state p {
margin: 0;
}
.account-dialog__error-state p {
max-width: 52ch;
color: var(--app-muted-color, var(--mat-sys-on-surface-variant));
line-height: 1.5;
font-size: 0.88rem;
}
.account-dialog__error-icon {
width: 48px;
height: 48px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 14px;
background: color-mix(in srgb, var(--mat-sys-error) 12%, transparent);
color: var(--mat-sys-error);
}
// ─── Skeleton loading ───────────────────────────────────────────────────────
.account-panel--loading {
gap: 12px;
}
.account-skeleton {
position: relative;
overflow: hidden;
border-radius: 999px;
background: var(--app-separator);
}
.account-skeleton::after {
content: '';
position: absolute;
inset: 0;
transform: translateX(-100%);
background: linear-gradient(
90deg,
transparent,
color-mix(in srgb, var(--app-heading-color, var(--mat-sys-on-surface)) 10%, transparent),
transparent
);
animation: account-dialog-shimmer 1.4s infinite;
}
.account-skeleton--stat {
min-height: 110px;
border-radius: 12px;
}
.account-skeleton--heading {
width: 54%;
height: 20px;
}
.account-skeleton--row {
width: 100%;
height: 16px;
}
.account-skeleton--row.short {
width: 62%;
}
// ─── Footer actions ─────────────────────────────────────────────────────────
.account-dialog__actions {
padding: 0 20px 20px;
display: flex;
justify-content: flex-end;
gap: 10px;
border-top: 1px solid var(--app-widget-header-border, rgba(255, 255, 255, 0.05));
background: var(--app-widget-bg, var(--mat-sys-surface));
}
.account-dialog__close {
min-width: 100px;
border-radius: 999px;
}
@keyframes account-dialog-shimmer {
100% {
transform: translateX(100%);
}
}
// ─── Responsive breakpoints ─────────────────────────────────────────────────
@media (max-width: 980px) {
.account-dialog__hero-stats,
.account-dialog__grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 720px) {
.account-dialog__hero,
.account-dialog__content,
.account-dialog__actions {
padding-left: 16px;
padding-right: 16px;
}
.account-dialog__headline-row {
flex-direction: column;
align-items: flex-start;
}
.account-dialog__status-cluster {
justify-content: flex-start;
}
.account-dialog__hero-stats,
.account-dialog__grid {
grid-template-columns: 1fr;
}
.account-detail-row {
grid-template-columns: 1fr;
gap: 4px;
}
}
@@ -0,0 +1,95 @@
import { signal } from '@angular/core';
import type { WritableSignal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
import {
XtreamApiService,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { AccountInfoComponent } from './account-info.component';
describe('AccountInfoComponent', () => {
let fixture: ComponentFixture<AccountInfoComponent>;
let component: AccountInfoComponent;
let xtreamApiService: {
getAccountInfo: jest.Mock;
};
let currentPlaylist: WritableSignal<null>;
beforeEach(async () => {
xtreamApiService = {
getAccountInfo: jest.fn().mockResolvedValue({
user_info: {
active_cons: '0',
allowed_output_formats: [],
max_connections: '0',
status: 'Active',
username: 'dialog-user',
},
server_info: {
server_protocol: 'http',
url: 'dialog.example.test',
},
}),
};
currentPlaylist = signal(null);
await TestBed.configureTestingModule({
imports: [
AccountInfoComponent,
NoopAnimationsModule,
TranslateModule.forRoot(),
],
providers: [
{
provide: MAT_DIALOG_DATA,
useValue: {
playlist: {
id: 'dialog-playlist',
title: 'Dialog Xtream',
serverUrl: 'https://dialog.example.test',
username: 'dialog-user',
password: 'dialog-secret',
},
},
},
{
provide: XtreamApiService,
useValue: xtreamApiService,
},
{
provide: XtreamStore,
useValue: {
currentPlaylist,
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(AccountInfoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
await fixture.whenStable();
});
it('loads account info from dialog-supplied playlist credentials', () => {
expect(xtreamApiService.getAccountInfo).toHaveBeenCalledWith({
serverUrl: 'https://dialog.example.test',
username: 'dialog-user',
password: 'dialog-secret',
});
expect(component.loadState()).toBe('ready');
expect(component.playlistLabel()).toBe('Dialog Xtream');
});
it('shows unknown content counts when dashboard does not supply them', () => {
expect(component.heroStats().map((stat) => stat.value)).toEqual([
'0/0',
'-',
'-',
'-',
]);
});
});
@@ -0,0 +1,265 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { TranslatePipe } from '@ngx-translate/core';
import {
XtreamAccountInfo,
XtreamApiService,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { createLogger } from '@iptvnator/portal/shared/util';
import type { XtreamAccountInfoDialogData } from 'shared-interfaces';
type AccountLoadState = 'loading' | 'ready' | 'error';
interface AccountStat {
icon: string;
labelKey: string;
value: string;
meter: number | null;
}
interface AccountDetailRow {
labelKey: string;
value: string;
mono?: boolean;
tone?: 'accent' | 'positive' | 'warning';
translateValue?: boolean;
}
interface AccountPort {
labelKey: string;
value: string;
}
@Component({
selector: 'app-account-info',
imports: [MatButtonModule, MatDialogModule, MatIconModule, TranslatePipe],
templateUrl: './account-info.component.html',
styleUrl: './account-info.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AccountInfoComponent {
readonly data =
inject<XtreamAccountInfoDialogData | null>(MAT_DIALOG_DATA, {
optional: true,
}) ?? {};
private readonly xtreamApiService = inject(XtreamApiService);
private readonly xtreamStore = inject(XtreamStore);
private readonly logger = createLogger('XtreamAccountInfo');
readonly currentPlaylist = computed(
() => this.data.playlist ?? this.xtreamStore.currentPlaylist()
);
readonly loadState = signal<AccountLoadState>('loading');
readonly accountInfo = signal<XtreamAccountInfo | null>(null);
readonly skeletonStats = [1, 2, 3, 4];
readonly skeletonPanels = [1, 2];
readonly isActive = computed(
() => this.accountInfo()?.user_info?.status === 'Active'
);
readonly isTrial = computed(
() => this.accountInfo()?.user_info?.is_trial === '1'
);
readonly playlistLabel = computed(() => {
const playlist = this.currentPlaylist();
const info = this.accountInfo();
return (
playlist?.title ||
playlist?.name ||
info?.server_info?.url ||
info?.user_info?.username ||
'-'
);
});
readonly serverHost = computed(
() => this.accountInfo()?.server_info?.url || '-'
);
readonly activeConnections = computed(() =>
this.parseNumber(this.accountInfo()?.user_info?.active_cons)
);
readonly maxConnections = computed(() =>
this.parseNumber(this.accountInfo()?.user_info?.max_connections)
);
readonly connectionUsagePercent = computed(() => {
const maxConnections = this.maxConnections();
if (maxConnections <= 0) {
return 0;
}
return Math.min(
100,
Math.round((this.activeConnections() / maxConnections) * 100)
);
});
readonly activeConnectionsLabel = computed(
() =>
`${this.activeConnections()}/${Math.max(this.maxConnections(), 0)}`
);
readonly formattedExpDate = computed(() =>
this.formatUnixDate(this.accountInfo()?.user_info?.exp_date)
);
readonly formattedCreatedDate = computed(() =>
this.formatUnixDate(this.accountInfo()?.user_info?.created_at)
);
readonly allowedFormats = computed(
() => this.accountInfo()?.user_info?.allowed_output_formats ?? []
);
readonly ports = computed<AccountPort[]>(() => {
const serverInfo = this.accountInfo()?.server_info;
return [
{
labelKey: 'XTREAM.ACCOUNT_INFO.HTTP_PORT',
value: serverInfo?.port || '-',
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.HTTPS_PORT',
value: serverInfo?.https_port || '-',
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.RTMP_PORT',
value: serverInfo?.rtmp_port || '-',
},
];
});
readonly heroStats = computed<AccountStat[]>(() => [
{
icon: 'bolt',
labelKey: 'XTREAM.ACCOUNT_INFO.ACTIVE_CONNECTIONS',
value: this.activeConnectionsLabel(),
meter: this.connectionUsagePercent(),
},
{
icon: 'live_tv',
labelKey: 'XTREAM.ACCOUNT_INFO.LIVE_TV',
value: this.formatOptionalCount(this.data.liveStreamsCount),
meter: null,
},
{
icon: 'movie',
labelKey: 'XTREAM.ACCOUNT_INFO.MOVIES',
value: this.formatOptionalCount(this.data.vodStreamsCount),
meter: null,
},
{
icon: 'tv',
labelKey: 'XTREAM.ACCOUNT_INFO.TV_SERIES',
value: this.formatOptionalCount(this.data.seriesCount),
meter: null,
},
]);
readonly userDetails = computed<AccountDetailRow[]>(() => [
{
labelKey: 'XTREAM.ACCOUNT_INFO.STATUS',
value: this.accountInfo()?.user_info?.status || '-',
tone: this.isActive() ? 'positive' : undefined,
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.USERNAME',
value: this.accountInfo()?.user_info?.username || '-',
mono: true,
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.ACTIVE_CONNECTIONS',
value: this.activeConnectionsLabel(),
tone: 'accent',
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.CREATED',
value: this.formattedCreatedDate(),
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.EXPIRES',
value: this.formattedExpDate(),
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.TRIAL_ACCOUNT',
value: this.isTrial()
? 'XTREAM.ACCOUNT_INFO.YES'
: 'XTREAM.ACCOUNT_INFO.NO',
translateValue: true,
tone: this.isTrial() ? 'warning' : undefined,
},
]);
readonly serverDetails = computed<AccountDetailRow[]>(() => [
{
labelKey: 'XTREAM.ACCOUNT_INFO.URL',
value: this.accountInfo()?.server_info?.url || '-',
mono: true,
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.PROTOCOL',
value: this.accountInfo()?.server_info?.server_protocol || '-',
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.TIMEZONE',
value: this.accountInfo()?.server_info?.timezone || '-',
},
{
labelKey: 'XTREAM.ACCOUNT_INFO.SERVER_TIME',
value: this.accountInfo()?.server_info?.time_now || '-',
mono: true,
},
]);
constructor() {
void this.reload();
}
async reload(): Promise<void> {
const playlist = this.currentPlaylist();
if (!playlist?.serverUrl || !playlist.username || !playlist.password) {
this.loadState.set('error');
this.accountInfo.set(null);
return;
}
this.loadState.set('loading');
try {
const accountInfo = await this.xtreamApiService.getAccountInfo({
serverUrl: playlist.serverUrl,
username: playlist.username,
password: playlist.password,
});
this.accountInfo.set(accountInfo);
this.loadState.set('ready');
} catch (error) {
this.logger.error('Failed to fetch account info', error);
this.accountInfo.set(null);
this.loadState.set('error');
}
}
private formatUnixDate(timestamp?: string): string {
const value = Number.parseInt(timestamp ?? '', 10);
if (!Number.isFinite(value) || value <= 0) {
return '-';
}
return new Date(value * 1000).toLocaleDateString();
}
private parseNumber(value?: string): number {
const parsed = Number.parseInt(value ?? '', 10);
return Number.isFinite(parsed) ? parsed : 0;
}
private formatOptionalCount(value?: number): string {
return Number.isFinite(value) ? String(value) : '-';
}
}
@@ -0,0 +1,111 @@
<h2 mat-dialog-title>{{ 'XTREAM.CATEGORY_MANAGEMENT.TITLE' | translate }}</h2>
<mat-dialog-content>
@if (isLoading()) {
<div class="loading-container">
<mat-spinner diameter="40" />
<p>{{ 'XTREAM.CATEGORY_MANAGEMENT.LOADING' | translate }}</p>
</div>
} @else {
<div class="header-actions">
<div class="selection-info">
{{ 'XTREAM.CATEGORY_MANAGEMENT.SELECTED' | translate }}:
<strong>{{ selectedCount() }}</strong> / {{ totalCount() }}
</div>
<div class="bulk-actions">
<button
mat-stroked-button
(click)="selectAll()"
[disabled]="allSelected()"
>
<mat-icon>check_box</mat-icon>
{{ 'XTREAM.CATEGORY_MANAGEMENT.SELECT_ALL' | translate }}
</button>
<button
mat-stroked-button
(click)="deselectAll()"
[disabled]="selectedCount() === 0"
>
<mat-icon>check_box_outline_blank</mat-icon>
{{ 'XTREAM.CATEGORY_MANAGEMENT.DESELECT_ALL' | translate }}
</button>
</div>
</div>
<label class="search-inline">
<mat-icon class="search-inline__icon">search</mat-icon>
<input
type="search"
spellcheck="false"
[value]="searchTerm()"
(input)="searchTerm.set($any($event.target).value)"
[placeholder]="
'XTREAM.CATEGORY_MANAGEMENT.SEARCH_PLACEHOLDER'
| translate
"
/>
@if (searchTerm()) {
<button
type="button"
mat-icon-button
class="search-inline__clear"
(click)="clearSearch()"
>
<mat-icon>close</mat-icon>
</button>
}
</label>
<div class="categories-list">
@for (category of filteredCategories(); track category.id) {
<div
class="category-item"
[attr.data-category-id]="category.xtream_id"
(click)="toggleCategory(category)"
>
<mat-checkbox
[checked]="category.selected"
(click)="$event.stopPropagation()"
(change)="toggleCategory(category)"
>
</mat-checkbox>
<span class="category-name">{{ category.name }}</span>
<span class="item-count"
>({{ getItemCount(category) }})</span
>
</div>
} @empty {
<div class="empty-message">
@if (searchTerm()) {
{{
'XTREAM.CATEGORY_MANAGEMENT.NO_RESULTS' | translate
}}
} @else {
{{
'XTREAM.CATEGORY_MANAGEMENT.NO_CATEGORIES'
| translate
}}
}
</div>
}
</div>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="cancel()" [disabled]="isSaving()">
{{ 'CLOSE' | translate }}
</button>
<button
mat-flat-button
color="primary"
(click)="save()"
[disabled]="isLoading() || isSaving()"
>
@if (isSaving()) {
<mat-spinner diameter="20" />
} @else {
{{ 'XTREAM.CATEGORY_MANAGEMENT.SAVE' | translate }}
}
</button>
</mat-dialog-actions>
@@ -0,0 +1,170 @@
::ng-deep .mat-mdc-dialog-content {
overflow: hidden !important;
}
.mat-mdc-dialog-content {
display: flex;
gap: 10px;
flex-direction: column;
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px;
gap: 16px;
}
.header-actions {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
.selection-info {
font-size: 0.8125rem;
color: var(--mat-sys-on-surface-variant);
strong {
color: var(--mat-sys-primary);
}
}
.bulk-actions {
display: flex;
gap: 8px;
button {
font-size: 12px;
}
}
.search-inline {
display: flex;
align-items: center;
gap: 8px;
padding: 0 10px;
min-height: 36px;
border-radius: 10px;
border: 1px solid var(--app-search-border, var(--mat-sys-outline-variant));
background: var(--app-search-bg, var(--mat-sys-surface-container));
cursor: text;
transition:
border-color 0.15s ease,
box-shadow 0.15s ease;
&:focus-within {
border-color: var(--mat-sys-primary);
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--mat-sys-primary) 12%, transparent);
}
}
.search-inline__icon {
font-size: 18px;
width: 18px;
height: 18px;
color: var(--mat-sys-on-surface-variant);
flex-shrink: 0;
}
.search-inline input {
flex: 1;
border: none;
outline: none;
background: transparent;
color: var(--mat-sys-on-surface);
font: inherit;
font-size: 0.84rem;
width: 100%;
min-width: 0;
&::placeholder {
color: var(--mat-sys-on-surface-variant);
opacity: 0.6;
}
&::-webkit-search-cancel-button {
display: none;
}
}
.search-inline__clear {
width: 24px;
height: 24px;
min-width: 24px;
line-height: 24px;
flex-shrink: 0;
padding: 0;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
}
.categories-list {
flex: 1;
min-height: 200px;
overflow-y: auto;
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
}
.category-item {
display: flex;
align-items: center;
padding: 0 10px;
min-height: 30px;
cursor: pointer;
gap: 6px;
transition: background-color 0.12s ease;
&:hover {
background-color: var(--mat-sys-surface-container);
}
&:not(:last-child) {
border-bottom: 1px solid var(--mat-sys-surface-container);
}
mat-checkbox {
--mdc-checkbox-state-layer-size: 28px;
}
}
.category-name {
flex: 1;
font-size: 0.8125rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.empty-message {
padding: 24px;
text-align: center;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8125rem;
}
:host ::ng-deep {
.mat-mdc-dialog-content {
min-width: 480px;
max-width: 600px;
max-height: 85vh !important;
}
}
mat-dialog-actions {
button {
mat-spinner {
display: inline-block;
}
}
}
@@ -0,0 +1,199 @@
import { Component, computed, inject, OnInit, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TranslatePipe } from '@ngx-translate/core';
import { DatabaseService, XCategoryFromDb } from 'services';
import { createLogger } from '@iptvnator/portal/shared/util';
export interface CategoryManagementDialogData {
playlistId: string;
contentType: 'live' | 'vod' | 'series';
itemCounts: Map<number, number>;
}
interface CategoryWithSelection extends XCategoryFromDb {
selected: boolean;
}
@Component({
selector: 'app-category-management-dialog',
imports: [
MatDialogModule,
MatButtonModule,
MatCheckboxModule,
MatIconModule,
MatProgressSpinnerModule,
TranslatePipe,
],
templateUrl: './category-management-dialog.component.html',
styleUrl: './category-management-dialog.component.scss',
})
export class CategoryManagementDialogComponent implements OnInit {
private readonly dbService = inject(DatabaseService);
private readonly dialogRef = inject(
MatDialogRef<CategoryManagementDialogComponent>
);
readonly data = inject<CategoryManagementDialogData>(MAT_DIALOG_DATA);
private readonly logger = createLogger('CategoryManagementDialog');
readonly isLoading = signal(true);
readonly isSaving = signal(false);
readonly categories = signal<CategoryWithSelection[]>([]);
readonly searchTerm = signal('');
readonly filteredCategories = computed(() => {
const term = this.searchTerm().toLowerCase();
if (!term) return this.categories();
return this.categories().filter((c) =>
c.name.toLowerCase().includes(term)
);
});
readonly selectedCount = computed(
() => this.categories().filter((c) => c.selected).length
);
readonly totalCount = computed(() => this.categories().length);
readonly allSelected = computed(
() =>
this.categories().length > 0 &&
this.categories().every((c) => c.selected)
);
readonly someSelected = computed(
() => this.categories().some((c) => c.selected) && !this.allSelected()
);
async ngOnInit(): Promise<void> {
await this.loadCategories();
}
private async loadCategories(): Promise<void> {
try {
const type = this.getDbType();
const allCategories = await this.waitForCategories(type);
this.categories.set(
allCategories.map((c) => ({
...c,
selected: !c.hidden,
}))
);
} catch (error) {
this.logger.error('Error loading categories', error);
} finally {
this.isLoading.set(false);
}
}
private async waitForCategories(
type: 'live' | 'movies' | 'series'
): Promise<XCategoryFromDb[]> {
const retryDeadlineMs = Date.now() + 10000;
const expectedCategoryCount = this.data.itemCounts.size;
while (true) {
const categories = await this.dbService.getAllXtreamCategories(
this.data.playlistId,
type
);
if (
categories.length > 0 ||
expectedCategoryCount === 0 ||
Date.now() >= retryDeadlineMs
) {
return categories;
}
await new Promise((resolve) => setTimeout(resolve, 250));
}
}
clearSearch(): void {
this.searchTerm.set('');
}
getItemCount(category: CategoryWithSelection): number {
const categoryId = Number(category.id);
return this.data.itemCounts.get(categoryId) ?? 0;
}
private getDbType(): 'live' | 'movies' | 'series' {
switch (this.data.contentType) {
case 'live':
return 'live';
case 'vod':
return 'movies';
case 'series':
return 'series';
}
}
toggleCategory(category: CategoryWithSelection): void {
this.categories.update((cats) =>
cats.map((c) =>
c.id === category.id ? { ...c, selected: !c.selected } : c
)
);
}
selectAll(): void {
this.categories.update((cats) =>
cats.map((c) => ({ ...c, selected: true }))
);
}
deselectAll(): void {
this.categories.update((cats) =>
cats.map((c) => ({ ...c, selected: false }))
);
}
toggleAll(): void {
if (this.allSelected()) {
this.deselectAll();
} else {
this.selectAll();
}
}
async save(): Promise<void> {
this.isSaving.set(true);
try {
const categories = this.categories();
const toHide = categories.filter((c) => !c.selected).map((c) => c.id);
const toShow = categories.filter((c) => c.selected).map((c) => c.id);
if (toHide.length > 0) {
await this.dbService.updateCategoryVisibility(toHide, true);
}
if (toShow.length > 0) {
await this.dbService.updateCategoryVisibility(toShow, false);
}
this.dialogRef.close(true);
} catch (error) {
this.logger.error('Error saving category visibility', error);
inject(MatSnackBar).open(
'Failed to save category visibility',
'Close',
{ duration: 3000 }
);
} finally {
this.isSaving.set(false);
}
}
cancel(): void {
this.dialogRef.close(false);
}
}
@@ -0,0 +1,11 @@
import { Component } from '@angular/core';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { SearchResultsComponent } from '../search-results/search-results.component';
@Component({
selector: 'app-global-search-results',
imports: [SearchResultsComponent],
providers: [XtreamStore],
template: '<app-search-results/>',
})
export class GlobalSearchResultsComponent {}
@@ -0,0 +1,131 @@
@let isEmbeddedPlayer = usesEmbeddedPlayer();
@let streamUrl = activeStreamUrl();
@let epgPrograms = controlledEpgPrograms();
@if (selectedCategoryId()) {
<div
class="sidebar"
appResizable
[minWidth]="250"
[maxWidth]="600"
[defaultWidth]="400"
storageKey="sidebar-width"
>
<div class="sidebar-header">
<div class="category-heading">
<h2 class="category-title">
{{ selectedCategoryInfo()?.name }}
</h2>
@if (selectedCategoryInfo()?.count) {
<span class="category-count">{{
selectedCategoryInfo()?.count
}}</span>
}
</div>
<button
mat-icon-button
[matMenuTriggerFor]="channelSortMenu"
[matTooltip]="'Sort: ' + liveChannelSortLabel()"
aria-label="Sort channels"
>
<mat-icon>sort_by_alpha</mat-icon>
</button>
<mat-menu #channelSortMenu="matMenu">
<button
mat-menu-item
(click)="setLiveChannelSortMode('server')"
>
<span>Server Order</span>
@if (liveChannelSortMode() === 'server') {
<mat-icon>check</mat-icon>
}
</button>
<button
mat-menu-item
(click)="setLiveChannelSortMode('name-asc')"
>
<span>Name A-Z</span>
@if (liveChannelSortMode() === 'name-asc') {
<mat-icon>check</mat-icon>
}
</button>
<button
mat-menu-item
(click)="setLiveChannelSortMode('name-desc')"
>
<span>Name Z-A</span>
@if (liveChannelSortMode() === 'name-desc') {
<mat-icon>check</mat-icon>
}
</button>
</mat-menu>
</div>
<app-portal-channels-list
[sortMode]="liveChannelSortMode()"
[searchTermInput]="workspaceSearchTerm()"
(playClicked)="playLive($event)"
/>
</div>
}
<div class="content-container">
@if (!selectedCategoryId()) {
<app-portal-empty-state
icon="live_tv"
[message]="'PORTALS.SELECT_CATEGORY' | translate"
/>
} @else if (streamUrl) {
@if (isEmbeddedPlayer) {
<div class="video-player">
<app-web-player-view [streamUrl]="streamUrl" />
</div>
}
<div class="epg">
<div class="epg-content">
@if (isLoadingEpg()) {
<div class="loading-indicator">
<mat-spinner diameter="24" />
</div>
} @else if (isElectron && epgPrograms.length > 0) {
@if (showArchiveUnavailableNotice()) {
<div class="archive-unavailable-banner" role="status">
<div class="archive-unavailable-banner__title">
{{
'EPG.ARCHIVE_PLAYBACK_UNAVAILABLE_TITLE'
| translate
}}
</div>
<div
class="archive-unavailable-banner__description"
>
{{
'EPG.ARCHIVE_PLAYBACK_UNAVAILABLE_DESCRIPTION'
| translate
}}
</div>
</div>
}
<app-epg-list
[controlledPrograms]="epgPrograms"
[controlledArchiveDays]="controlledArchiveDays()"
[archivePlaybackAvailable]="
archivePlaybackAvailable()
"
(programActivated)="onProgramActivated($event)"
/>
} @else if (!isElectron && epgItems().length > 0) {
<app-epg-view [epgItems]="epgItems()" />
} @else {
<app-portal-empty-state
icon="event_busy"
[message]="'EPG.EPG_NOT_AVAILABLE_CHANNEL_TITLE' | translate"
/>
}
</div>
</div>
} @else {
<app-portal-empty-state
icon="live_tv"
[message]="'CHANNELS.SELECT_CHANNEL_PLAYBACK' | translate"
/>
}
</div>
@@ -0,0 +1,52 @@
@use '@angular/material' as mat;
@use '../../../../../../ui/styles/portal-layout' as portal;
@use '../../../../../../ui/styles/portal-sidebar';
@include portal.live-layout;
// ─── Sidebar-header overrides ──────────────────────────────────────────────
// Base .sidebar-header styles come from portal-sidebar
.sidebar-header button {
@include mat.form-field-density(-5);
}
// ─── Side-panel channel list ───────────────────────────────────────────────
.sidebar {
app-portal-channels-list {
flex: 1;
overflow: hidden;
width: 100%;
}
}
.loading-indicator {
display: flex;
justify-content: center;
padding: 16px;
}
.archive-unavailable-banner {
margin: 12px 12px 0;
padding: 12px 14px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.08);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0)),
rgba(127, 127, 127, 0.05);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.04),
0 10px 20px -20px rgba(0, 0, 0, 0.35);
}
.archive-unavailable-banner__title {
font-size: 0.85rem;
font-weight: 600;
letter-spacing: 0.01em;
}
.archive-unavailable-banner__description {
margin-top: 4px;
font-size: 0.78rem;
line-height: 1.45;
opacity: 0.74;
}
@@ -0,0 +1,405 @@
import { Directive, Component, input, output, signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { MockPipe } from 'ng-mocks';
import { TranslatePipe } from '@ngx-translate/core';
import { of } from 'rxjs';
import {
PORTAL_PLAYER,
ResizableDirective,
} from '@iptvnator/portal/shared/util';
import {
FavoritesService,
XtreamStore,
XtreamUrlService,
} from '@iptvnator/portal/xtream/data-access';
import { EpgListComponent, EpgProgramActivationEvent } from '@iptvnator/ui/epg';
import { EpgViewComponent, WebPlayerViewComponent } from 'shared-portals';
import { EpgItem, EpgProgram } from 'shared-interfaces';
import { PortalChannelsListComponent } from '../portal-channels-list/portal-channels-list.component';
import { LiveStreamLayoutComponent } from './live-stream-layout.component';
const LIVE_CHANNEL_SORT_STORAGE_KEY = 'xtream-live-channel-sort-mode';
@Component({
selector: 'app-portal-channels-list',
standalone: true,
template: '',
})
class StubPortalChannelsListComponent {
readonly sortMode = input<'server' | 'name-asc' | 'name-desc'>('server');
readonly searchTermInput = input('');
readonly playClicked = output<unknown>();
}
@Component({
selector: 'app-web-player-view',
standalone: true,
template: '',
})
class StubWebPlayerViewComponent {
readonly streamUrl = input('');
}
@Component({
selector: 'app-epg-view',
standalone: true,
template: '',
})
class StubEpgViewComponent {
readonly epgItems = input<EpgItem[]>([]);
}
@Component({
selector: 'app-epg-list',
standalone: true,
template: '',
})
class StubEpgListComponent {
readonly controlledPrograms = input<EpgProgram[] | null>(null);
readonly controlledArchiveDays = input<number | null>(null);
readonly archivePlaybackAvailable = input<boolean | null>(null);
readonly programActivated = output<EpgProgramActivationEvent>();
}
@Directive({
selector: '[appResizable]',
standalone: true,
})
class StubResizableDirective {}
describe('LiveStreamLayoutComponent', () => {
let fixture: ComponentFixture<LiveStreamLayoutComponent>;
let component: LiveStreamLayoutComponent;
const fixedNow = new Date('2026-04-05T12:00:00.000Z');
const sampleChannel = {
xtream_id: 101,
name: 'Channel 101',
stream_icon: 'channel-101.png',
tv_archive: 1,
tv_archive_duration: 3,
};
const playlist = {
id: 'playlist-1',
serverUrl: 'http://demo.example',
username: 'demo',
password: 'secret',
};
const categories = signal([{ category_id: 1, category_name: 'News' }]);
const categoryItemCounts = signal(new Map<number, number>([[1, 1]]));
const epgItems = signal<EpgItem[]>([]);
const currentEpgItem = signal<EpgItem | null>(null);
const isLoadingEpg = signal(false);
const selectedCategoryId = signal<number | null>(1);
const selectedContentType = signal<'live' | 'vod' | 'series'>('live');
const selectedItem = signal<unknown>(sampleChannel);
const currentPlaylist = signal(playlist);
const xtreamStore = {
getCategoriesBySelectedType: categories,
getCategoryItemCounts: categoryItemCounts,
epgItems,
currentEpgItem,
isLoadingEpg,
selectedCategoryId,
selectedContentType,
selectedItem,
currentPlaylist,
selectItemsFromSelectedCategory: jest.fn(() => [sampleChannel]),
constructStreamUrl: jest.fn(() => 'https://example.com/live.ts'),
openPlayer: jest.fn(),
};
const favoritesService = {
getFavorites: jest.fn().mockReturnValue(of([])),
};
const xtreamUrlService = {
resolveCatchupUrl: jest
.fn()
.mockResolvedValue('https://example.com/timeshift.ts'),
};
const portalPlayer = {
isEmbeddedPlayer: jest.fn().mockReturnValue(true),
};
const originalElectron = window.electron;
beforeEach(async () => {
jest.useFakeTimers();
jest.setSystemTime(fixedNow);
localStorage.removeItem(LIVE_CHANNEL_SORT_STORAGE_KEY);
window.electron = {
updateRemoteControlStatus: jest.fn(),
} as typeof window.electron;
xtreamStore.constructStreamUrl.mockClear();
xtreamStore.openPlayer.mockClear();
xtreamStore.selectItemsFromSelectedCategory.mockReturnValue([
sampleChannel,
]);
favoritesService.getFavorites.mockClear();
xtreamUrlService.resolveCatchupUrl.mockClear();
portalPlayer.isEmbeddedPlayer.mockReset();
portalPlayer.isEmbeddedPlayer.mockReturnValue(true);
epgItems.set([]);
currentEpgItem.set(null);
isLoadingEpg.set(false);
selectedCategoryId.set(1);
selectedContentType.set('live');
selectedItem.set(sampleChannel);
currentPlaylist.set(playlist);
await TestBed.configureTestingModule({
imports: [LiveStreamLayoutComponent, NoopAnimationsModule],
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
data: {},
queryParamMap: convertToParamMap({}),
},
queryParamMap: of(convertToParamMap({})),
pathFromRoot: [
{
snapshot: {
data: {},
},
},
],
},
},
{ provide: XtreamStore, useValue: xtreamStore },
{ provide: FavoritesService, useValue: favoritesService },
{ provide: XtreamUrlService, useValue: xtreamUrlService },
{ provide: PORTAL_PLAYER, useValue: portalPlayer },
],
})
.overrideComponent(LiveStreamLayoutComponent, {
remove: {
imports: [
EpgListComponent,
EpgViewComponent,
PortalChannelsListComponent,
ResizableDirective,
TranslatePipe,
WebPlayerViewComponent,
],
},
add: {
imports: [
StubEpgListComponent,
StubEpgViewComponent,
StubPortalChannelsListComponent,
StubResizableDirective,
MockPipe(
TranslatePipe,
(value: string | null | undefined) => value ?? ''
),
StubWebPlayerViewComponent,
],
},
})
.compileComponents();
fixture = TestBed.createComponent(LiveStreamLayoutComponent);
component = fixture.componentInstance;
});
afterEach(() => {
fixture.destroy();
jest.useRealTimers();
localStorage.removeItem(LIVE_CHANNEL_SORT_STORAGE_KEY);
window.electron = originalElectron;
});
it('renders the controlled epg list for electron playback', () => {
epgItems.set([
buildEpgItem(
'1',
'Current Show',
'2026-04-05T11:30:00.000Z',
'2026-04-05T12:30:00.000Z'
),
]);
component.playLive(sampleChannel);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('app-epg-list')
).not.toBeNull();
expect(fixture.nativeElement.querySelector('app-epg-view')).toBeNull();
});
it('uses currentEpgItem instead of assuming the first schedule item is current', () => {
epgItems.set([
buildEpgItem(
'past',
'Past Show',
'2026-04-05T08:00:00.000Z',
'2026-04-05T09:00:00.000Z'
),
buildEpgItem(
'current',
'Current Show',
'2026-04-05T11:30:00.000Z',
'2026-04-05T12:30:00.000Z'
),
]);
currentEpgItem.set(epgItems()[1]);
fixture.detectChanges();
expect(window.electron?.updateRemoteControlStatus).toHaveBeenCalledWith(
expect.objectContaining({
epgTitle: 'Current Show',
})
);
});
it('resolves a catchup url for archived program activation', async () => {
portalPlayer.isEmbeddedPlayer.mockReturnValue(false);
await component.onProgramActivated({
type: 'timeshift',
program: {
start: '2026-04-04T10:00:00.000Z',
stop: '2026-04-04T11:00:00.000Z',
channel: 'channel-101',
title: 'Archived Show',
desc: null,
category: null,
startTimestamp: 1775296800,
stopTimestamp: 1775300400,
},
});
expect(xtreamUrlService.resolveCatchupUrl).toHaveBeenCalledWith(
'playlist-1',
{
serverUrl: 'http://demo.example',
username: 'demo',
password: 'secret',
},
101,
1775296800,
1775300400
);
expect(xtreamStore.openPlayer).toHaveBeenCalledWith(
'https://example.com/timeshift.ts',
'Channel 101 - Archived Show',
'channel-101.png'
);
});
it('shows an archive-unavailable notice when past programs exist but archive playback is unavailable', () => {
const nonArchiveChannel = {
...sampleChannel,
tv_archive: 0,
tv_archive_duration: null,
};
selectedItem.set(nonArchiveChannel);
epgItems.set([
buildEpgItem(
'past',
'Past Show',
'2026-04-05T09:00:00.000Z',
'2026-04-05T10:00:00.000Z'
),
buildEpgItem(
'current',
'Current Show',
'2026-04-05T11:30:00.000Z',
'2026-04-05T12:30:00.000Z'
),
]);
component.playLive(nonArchiveChannel);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.archive-unavailable-banner')
).not.toBeNull();
});
it('hides the archive-unavailable notice when archive playback is available', () => {
selectedItem.set(sampleChannel);
epgItems.set([
buildEpgItem(
'past',
'Past Show',
'2026-04-05T09:00:00.000Z',
'2026-04-05T10:00:00.000Z'
),
buildEpgItem(
'current',
'Current Show',
'2026-04-05T11:30:00.000Z',
'2026-04-05T12:30:00.000Z'
),
]);
component.playLive(sampleChannel);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.archive-unavailable-banner')
).toBeNull();
});
it('hides the archive-unavailable notice when there are no past programs yet', () => {
const nonArchiveChannel = {
...sampleChannel,
tv_archive: 0,
tv_archive_duration: null,
};
selectedItem.set(nonArchiveChannel);
epgItems.set([
buildEpgItem(
'current',
'Current Show',
'2026-04-05T11:30:00.000Z',
'2026-04-05T12:30:00.000Z'
),
buildEpgItem(
'future',
'Future Show',
'2026-04-05T12:30:00.000Z',
'2026-04-05T13:30:00.000Z'
),
]);
component.playLive(nonArchiveChannel);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.archive-unavailable-banner')
).toBeNull();
});
});
function buildEpgItem(
id: string,
title: string,
start: string,
stop: string
): EpgItem {
return {
id,
epg_id: `epg-${id}`,
title,
description: '',
lang: 'en',
start,
stop,
end: stop,
channel_id: 'channel-101',
start_timestamp: String(Math.floor(Date.parse(start) / 1000)),
stop_timestamp: String(Math.floor(Date.parse(stop) / 1000)),
};
}
@@ -0,0 +1,502 @@
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
OnDestroy,
OnInit,
signal,
} from '@angular/core';
import { MatIconButton } from '@angular/material/button';
import { MatIcon } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatTooltipModule } from '@angular/material/tooltip';
import { TranslatePipe } from '@ngx-translate/core';
import { ResizableDirective } from 'components';
import { PortalEmptyStateComponent } from '@iptvnator/portal/shared/ui';
import {
PORTAL_PLAYER,
PortalChannelSortMode,
getPortalChannelSortModeLabel,
getAdjacentChannelItem,
getChannelItemByNumber,
isWorkspaceLayoutRoute,
persistPortalChannelSortMode,
queryParamSignal,
restorePortalChannelSortMode,
} from '@iptvnator/portal/shared/util';
import {
FavoriteItem,
FavoritesService,
XtreamUrlService,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { EpgListComponent, EpgProgramActivationEvent } from '@iptvnator/ui/epg';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { EpgViewComponent, WebPlayerViewComponent } from 'shared-portals';
import { EpgItem, EpgProgram } from 'shared-interfaces';
import { PortalChannelsListComponent } from '../portal-channels-list/portal-channels-list.component';
import { ActivatedRoute } from '@angular/router';
const LIVE_CHANNEL_SORT_STORAGE_KEY = 'xtream-live-channel-sort-mode';
interface XtreamLiveChannelItem {
readonly name?: string;
readonly poster_url?: string;
readonly stream_icon?: string;
readonly title?: string;
readonly tv_archive?: number | null;
readonly tv_archive_duration?: number | string | null;
readonly xtream_id: number;
}
@Component({
selector: 'app-live-stream-layout',
templateUrl: './live-stream-layout.component.html',
styleUrls: ['./live-stream-layout.component.scss'],
imports: [
EpgListComponent,
EpgViewComponent,
MatIcon,
MatIconButton,
MatMenuModule,
MatProgressSpinnerModule,
MatTooltipModule,
PortalChannelsListComponent,
PortalEmptyStateComponent,
ResizableDirective,
TranslatePipe,
WebPlayerViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LiveStreamLayoutComponent implements OnInit, OnDestroy {
private readonly route = inject(ActivatedRoute);
private readonly favoritesService = inject(FavoritesService);
private readonly xtreamStore = inject(XtreamStore);
private readonly xtreamUrlService = inject(XtreamUrlService);
private readonly portalPlayer = inject(PORTAL_PLAYER);
readonly categories = this.xtreamStore.getCategoriesBySelectedType;
readonly categoryItemCounts = this.xtreamStore.getCategoryItemCounts;
readonly epgItems = this.xtreamStore.epgItems;
readonly currentEpgItem = this.xtreamStore.currentEpgItem;
readonly isLoadingEpg = this.xtreamStore.isLoadingEpg;
readonly selectedCategoryId = this.xtreamStore.selectedCategoryId;
readonly liveChannelSortMode = signal<PortalChannelSortMode>('server');
readonly isElectron = Boolean(window.electron);
readonly isWorkspaceLayout = isWorkspaceLayoutRoute(this.route);
private readonly routeSearchTerm = queryParamSignal(
this.route,
'q',
(value) => (value ?? '').trim()
);
readonly workspaceSearchTerm = computed(() =>
this.isWorkspaceLayout ? this.routeSearchTerm() : ''
);
private readonly pendingAutoOpenLiveItemId = signal<number | null>(null);
readonly selectedLiveItem = computed<XtreamLiveChannelItem | null>(() => {
if (this.xtreamStore.selectedContentType() !== 'live') {
return null;
}
const selectedItem = this.xtreamStore.selectedItem();
if (!selectedItem || typeof selectedItem !== 'object') {
return null;
}
const item = selectedItem as XtreamLiveChannelItem;
return item.xtream_id ? item : null;
});
readonly controlledEpgPrograms = computed<EpgProgram[]>(() =>
this.epgItems().map((program) => this.toControlledEpgProgram(program))
);
private readonly currentTimeMs = signal(Date.now());
readonly controlledArchiveDays = computed(() =>
Math.max(
0,
Number(this.selectedLiveItem()?.tv_archive_duration ?? 0) || 0
)
);
readonly archivePlaybackAvailable = computed(() => {
const selectedItem = this.selectedLiveItem();
return (
Number(selectedItem?.tv_archive ?? 0) === 1 &&
this.controlledArchiveDays() > 0
);
});
readonly hasPastPrograms = computed(() => {
const now = this.currentTimeMs();
return this.controlledEpgPrograms().some((program) => {
const stop = this.getProgramTimestampMilliseconds(
program.stop,
program.stopTimestamp
);
return stop !== null && stop < now;
});
});
readonly showArchiveUnavailableNotice = computed(
() =>
this.controlledEpgPrograms().length > 0 &&
this.hasPastPrograms() &&
!this.archivePlaybackAvailable()
);
readonly liveChannelSortLabel = computed(() =>
getPortalChannelSortModeLabel(this.liveChannelSortMode())
);
readonly selectedCategoryInfo = computed(() => {
const categoryId = this.selectedCategoryId();
if (!categoryId) return null;
const categories = this.categories();
const category = categories?.find(
(c) => (c.category_id ?? c.id) === categoryId
);
const count = this.categoryItemCounts()?.get(categoryId) ?? 0;
return {
name: category?.category_name ?? category?.name ?? 'Channels',
count,
};
});
private unsubscribeRemoteChannelChange?: () => void;
private unsubscribeRemoteCommand?: () => void;
readonly usesEmbeddedPlayer = computed(() =>
this.portalPlayer.isEmbeddedPlayer()
);
readonly activeStreamUrl = signal('');
favorites = new Map<number, boolean>();
constructor() {
effect((onCleanup) => {
const intervalId = window.setInterval(() => {
this.currentTimeMs.set(Date.now());
}, 30_000);
onCleanup(() => clearInterval(intervalId));
});
const requestedItemId = Number(
(window.history.state as Record<string, unknown> | null)?.[
'openXtreamLiveItemId'
]
);
if (Number.isFinite(requestedItemId) && requestedItemId > 0) {
this.pendingAutoOpenLiveItemId.set(requestedItemId);
}
effect(() => {
const pendingId = this.pendingAutoOpenLiveItemId();
if (!pendingId) {
return;
}
const channels = this.getVisibleChannels();
if (!Array.isArray(channels) || channels.length === 0) {
return;
}
const item = channels.find(
(channel) => Number(channel?.xtream_id) === pendingId
);
if (!item) {
this.pendingAutoOpenLiveItemId.set(null);
return;
}
this.playLive(item);
this.pendingAutoOpenLiveItemId.set(null);
this.clearAutoOpenHistoryState();
});
effect(() => {
if (!window.electron?.updateRemoteControlStatus) {
return;
}
const selectedContentType = this.xtreamStore.selectedContentType();
const selectedItem = this.xtreamStore.selectedItem();
const channels = this.getVisibleChannels();
const currentProgram = this.currentEpgItem();
if (selectedContentType !== 'live' || !selectedItem?.xtream_id) {
window.electron.updateRemoteControlStatus({
portal: 'xtream',
isLiveView: false,
supportsVolume: false,
});
return;
}
const currentIndex = channels.findIndex(
(item) =>
Number(item.xtream_id) === Number(selectedItem.xtream_id)
);
window.electron.updateRemoteControlStatus({
portal: 'xtream',
isLiveView: true,
channelName: selectedItem.title ?? selectedItem.name,
channelNumber: currentIndex >= 0 ? currentIndex + 1 : undefined,
epgTitle: currentProgram?.title,
epgStart: currentProgram?.start,
epgEnd: currentProgram?.stop ?? currentProgram?.end,
supportsVolume: false,
});
});
}
ngOnInit() {
if (window.electron?.onChannelChange) {
const unsubscribe = window.electron.onChannelChange(
(data: { direction: 'up' | 'down' }) => {
this.handleRemoteChannelChange(data.direction);
}
);
if (typeof unsubscribe === 'function') {
this.unsubscribeRemoteChannelChange = unsubscribe;
}
}
if (window.electron?.onRemoteControlCommand) {
const unsubscribe = window.electron.onRemoteControlCommand(
(command) => {
this.handleRemoteControlCommand(command);
}
);
if (typeof unsubscribe === 'function') {
this.unsubscribeRemoteCommand = unsubscribe;
}
}
this.liveChannelSortMode.set(
restorePortalChannelSortMode(LIVE_CHANNEL_SORT_STORAGE_KEY)
);
const playlist = this.xtreamStore.currentPlaylist();
if (playlist) {
this.favoritesService
.getFavorites(playlist.id)
.subscribe((favorites) => {
// Map using content.id instead of xtream_id
favorites.forEach((fav: FavoriteItem) => {
this.favorites.set(fav.xtream_id, true);
});
});
}
}
playLive(item: XtreamLiveChannelItem) {
const streamUrl = this.xtreamStore.constructStreamUrl(item);
this.activeStreamUrl.set(streamUrl);
if (this.usesEmbeddedPlayer()) {
return;
}
this.xtreamStore.openPlayer(
streamUrl,
item.title ?? item.name ?? '',
item.poster_url ?? item.stream_icon ?? null
);
}
async onProgramActivated(event: EpgProgramActivationEvent): Promise<void> {
const selectedItem = this.selectedLiveItem();
if (!selectedItem?.xtream_id) {
return;
}
if (event.type === 'live') {
this.playLive(selectedItem);
return;
}
await this.playCatchup(event.program, selectedItem);
}
setLiveChannelSortMode(mode: PortalChannelSortMode): void {
this.liveChannelSortMode.set(mode);
persistPortalChannelSortMode(LIVE_CHANNEL_SORT_STORAGE_KEY, mode);
}
ngOnDestroy(): void {
this.unsubscribeRemoteChannelChange?.();
this.unsubscribeRemoteCommand?.();
}
private handleRemoteChannelChange(direction: 'up' | 'down'): void {
const activeItem = this.xtreamStore.selectedItem();
if (!activeItem?.xtream_id) {
return;
}
const channels = this.getVisibleChannels();
const nextItem = getAdjacentChannelItem(
channels,
activeItem.xtream_id,
direction,
(item) => item.xtream_id
);
if (!nextItem) {
return;
}
this.playLive(nextItem);
}
private handleRemoteControlCommand(command: {
type:
| 'channel-select-number'
| 'volume-up'
| 'volume-down'
| 'volume-toggle-mute';
number?: number;
}): void {
if (command.type !== 'channel-select-number' || !command.number) {
return;
}
const channels = this.getVisibleChannels();
const channel = getChannelItemByNumber(channels, command.number);
if (!channel) {
return;
}
this.playLive(channel);
}
private getVisibleChannels(): XtreamLiveChannelItem[] {
return this.xtreamStore.selectItemsFromSelectedCategory() as XtreamLiveChannelItem[];
}
private async playCatchup(
program: EpgProgram,
item: XtreamLiveChannelItem
): Promise<void> {
const playlist = this.xtreamStore.currentPlaylist();
if (!playlist) {
return;
}
const startTimestamp = this.getProgramTimestampSeconds(
program.start,
program.startTimestamp
);
const stopTimestamp = this.getProgramTimestampSeconds(
program.stop,
program.stopTimestamp
);
if (!startTimestamp || !stopTimestamp) {
return;
}
const catchupUrl = await this.xtreamUrlService.resolveCatchupUrl(
playlist.id,
{
serverUrl: playlist.serverUrl,
username: playlist.username,
password: playlist.password,
},
item.xtream_id,
startTimestamp,
stopTimestamp
);
this.activeStreamUrl.set(catchupUrl);
if (this.usesEmbeddedPlayer()) {
return;
}
this.xtreamStore.openPlayer(
catchupUrl,
this.getCatchupPlaybackTitle(item, program),
item.poster_url ?? item.stream_icon ?? null
);
}
private toControlledEpgProgram(program: EpgItem): EpgProgram {
return {
start: program.start,
stop: program.stop ?? program.end,
channel: program.channel_id ?? program.id,
title: program.title,
desc: program.description ?? null,
category: null,
startTimestamp: this.getProgramTimestampSeconds(
program.start,
program.start_timestamp
),
stopTimestamp: this.getProgramTimestampSeconds(
program.stop ?? program.end,
program.stop_timestamp
),
};
}
private getProgramTimestampSeconds(
dateValue: string,
unixTimestampValue?: number | string | null
): number | null {
const unixTimestamp = Number.parseInt(
String(unixTimestampValue ?? ''),
10
);
if (Number.isFinite(unixTimestamp) && unixTimestamp > 0) {
return unixTimestamp;
}
const parsedDate = Date.parse(dateValue);
return Number.isFinite(parsedDate)
? Math.floor(parsedDate / 1000)
: null;
}
private getProgramTimestampMilliseconds(
dateValue: string,
unixTimestampValue?: number | string | null
): number | null {
const unixTimestamp = this.getProgramTimestampSeconds(
dateValue,
unixTimestampValue
);
return unixTimestamp !== null ? unixTimestamp * 1000 : null;
}
private getCatchupPlaybackTitle(
item: XtreamLiveChannelItem,
program: EpgProgram
): string {
const channelTitle = item.title ?? item.name ?? '';
if (!program.title) {
return channelTitle;
}
return channelTitle
? `${channelTitle} - ${program.title}`
: program.title;
}
private clearAutoOpenHistoryState(): void {
try {
const state = (window.history.state ?? {}) as Record<
string,
unknown
>;
if (!('openXtreamLiveItemId' in state)) {
return;
}
const nextState = { ...state };
delete nextState['openXtreamLiveItemId'];
delete nextState['openXtreamLiveTitle'];
delete nextState['openXtreamLivePoster'];
window.history.replaceState(nextState, document.title);
} catch {
// no-op
}
}
}
@@ -0,0 +1,54 @@
import { Component, input } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
@Component({
selector: 'app-loading-overlay',
imports: [MatProgressBarModule],
template: `
<div class="overlay">
<div class="progress-container">
<h3>Loading playlist...</h3>
@if (current() !== 0 && total() !== 0) {
<mat-progress-bar
mode="determinate"
[value]="(current() / total()) * 100"
/>
<p>{{ current() }} / {{ total() }}</p>
} @else {
<mat-progress-bar mode="indeterminate" />
}
</div>
</div>
`,
styles: [
`
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.progress-container {
padding: 2rem;
border-radius: 8px;
min-width: 300px;
text-align: center;
h3 {
margin-top: 0;
}
}
`,
],
})
export class LoadingOverlayComponent {
current = input(0);
total = input(0);
}
@@ -0,0 +1,22 @@
<h2 mat-dialog-title>{{ title }}</h2>
<mat-dialog-content class="content">
<app-web-player-view
[streamUrl]="streamUrl"
[startTime]="data.startTime || 0"
(timeUpdate)="handleTimeUpdate($event)"
/>
</mat-dialog-content>
<mat-dialog-actions class="align-actions">
<button
mat-button
[cdkCopyToClipboard]="streamUrl"
(click)="showCopyNotification()"
[matTooltip]="streamUrl"
>
<mat-icon>content_copy</mat-icon>
{{ 'PORTALS.COPY_STREAM_URL' | translate }}
</button>
<button mat-button mat-dialog-close color="accent">
{{ 'CLOSE' | translate }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,16 @@
@use '@angular/material' as mat;
.content {
overflow: hidden;
padding: 10px !important;
}
.align-actions {
justify-content: space-between;
}
mat-dialog-content {
.video-js {
height: 500px !important;
}
}
@@ -0,0 +1,77 @@
import { ClipboardModule } from '@angular/cdk/clipboard';
import { Component, inject, ViewEncapsulation } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatTooltip } from '@angular/material/tooltip';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { PORTAL_PLAYBACK_POSITIONS } from '@iptvnator/portal/shared/util';
import { PlayerContentInfo } from 'shared-interfaces';
import { WebPlayerViewComponent } from 'shared-portals';
export interface PlayerDialogData {
streamUrl: string;
title: string;
contentInfo?: PlayerContentInfo;
startTime?: number;
}
@Component({
templateUrl: './player-dialog.component.html',
imports: [
ClipboardModule,
MatButton,
MatDialogModule,
MatIcon,
MatTooltip,
TranslatePipe,
WebPlayerViewComponent,
],
styleUrl: './player-dialog.component.scss',
encapsulation: ViewEncapsulation.None,
})
export class PlayerDialogComponent {
readonly data = inject<PlayerDialogData>(MAT_DIALOG_DATA);
private snackBar = inject(MatSnackBar);
private translateService = inject(TranslateService);
private readonly playbackPositions = inject(PORTAL_PLAYBACK_POSITIONS);
readonly title: string;
readonly streamUrl: string;
private lastSaveTime = 0;
constructor() {
this.streamUrl = this.data.streamUrl;
this.title = this.data.title;
}
handleTimeUpdate(event: { currentTime: number; duration: number }) {
if (!this.data.contentInfo) return;
const now = Date.now();
// Save every 15 seconds
if (now - this.lastSaveTime > 15000) {
this.lastSaveTime = now;
void this.playbackPositions.savePlaybackPosition(
this.data.contentInfo.playlistId,
{
...this.data.contentInfo,
positionSeconds: Math.floor(event.currentTime),
durationSeconds: Math.floor(event.duration),
}
);
}
}
showCopyNotification() {
this.snackBar.open(
this.translateService.instant('PORTALS.STREAM_URL_COPIED'),
null,
{
duration: 2000,
}
);
}
}
@@ -0,0 +1,60 @@
<div class="channels-list">
@if (isSelectedTypeContentLoading()) {
<div class="channels-loading-state" aria-live="polite">
<div class="channels-loading-state__copy">
<div class="channels-loading-state__title">
{{ 'CHANNELS.LOADING' | translate }}
</div>
</div>
<div class="channels-loading-state__list" aria-hidden="true">
@for (row of loadingRows; track row) {
<div class="channel-skeleton">
<span class="channel-skeleton__logo"></span>
<span class="channel-skeleton__title"></span>
<span class="channel-skeleton__meta"></span>
</div>
}
</div>
</div>
} @else if (filteredChannels().length > 0) {
<cdk-virtual-scroll-viewport
[itemSize]="68"
class="scroll-viewport-portals"
>
<app-channel-list-item
*cdkVirtualFor="
let item of filteredChannels();
trackBy: trackBy;
templateCacheSize: 0
"
[name]="item.title || item.name"
[logo]="item.stream_icon ?? item.poster_url"
[selected]="
xtreamStore.selectedItem()?.xtream_id === item.xtream_id
"
[epgProgram]="epgPrograms.get(item.xtream_id) ?? null"
[progressPercentage]="
currentProgramsProgress.get(item.xtream_id) ?? 0
"
[showFavoriteButton]="true"
[showProgramInfoButton]="false"
[isFavorite]="favorites.get(favoriteKeyFor(item)) ?? false"
(clicked)="playClicked.emit(item)"
(favoriteToggled)="toggleFavorite($event, item)"
/>
</cdk-virtual-scroll-viewport>
} @else {
<div class="empty-search-state">
<div class="empty-icon-wrapper">
<mat-icon>search_off</mat-icon>
</div>
<h3>{{ 'CHANNELS.NO_CHANNELS_FOUND' | translate }}</h3>
@if (searchTermInput()) {
<p>
{{ 'CHANNELS.TRY_DIFFERENT_SEARCH' | translate }}
</p>
}
</div>
}
</div>
@@ -0,0 +1,263 @@
:host {
display: block;
height: 100%;
width: 100%;
overflow: hidden;
container-type: inline-size;
border-right: 1px solid var(--app-separator);
}
.channels-list {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
width: 100%;
}
.scroll-viewport-portals {
height: 100%;
width: 100%;
padding: 4px 8px 12px;
box-sizing: border-box;
::ng-deep .cdk-virtual-scroll-content-wrapper {
width: 100% !important;
max-width: 100% !important;
contain: layout style;
}
}
.search-panel {
padding: 10px 12px;
flex-shrink: 0;
height: 56px;
box-sizing: border-box;
display: flex;
align-items: center;
background: var(--app-widget-header-bg, var(--mat-sys-surface-container-high));
border-bottom: 1px solid var(--app-separator);
app-region: drag;
}
.search-field {
flex: 1;
width: 100%;
height: 36px;
border-radius: 10px;
border: 1px solid rgba(127, 127, 127, 0.22);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0)),
rgba(127, 127, 127, 0.08);
display: flex;
align-items: center;
gap: 8px;
padding: 0 12px;
box-sizing: border-box;
cursor: text;
transition:
border-color 0.15s ease,
background-color 0.15s ease,
box-shadow 0.15s ease;
&:focus-within {
border-color: var(--app-selection-border);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--app-selection-color) 16%, transparent);
}
mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
opacity: 0.68;
flex-shrink: 0;
}
input {
flex: 1;
border: none;
outline: none;
background: transparent;
color: inherit;
font: inherit;
font-size: 0.875rem;
&:disabled {
cursor: not-allowed;
opacity: 0.5;
}
&::placeholder {
opacity: 0.62;
}
}
}
.empty-search-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
padding: 32px 24px;
text-align: center;
animation: fade-in 0.3s ease-out;
.empty-icon-wrapper {
width: 64px;
height: 64px;
border-radius: 20px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0)),
rgba(127, 127, 127, 0.1);
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
box-shadow:
0 8px 24px -8px rgba(0, 0, 0, 0.1),
inset 0 1px 1px rgba(255, 255, 255, 0.05);
mat-icon {
width: 32px;
height: 32px;
font-size: 32px;
opacity: 0.8;
}
}
h3 {
font-size: 1.05rem;
font-weight: 520;
margin: 0 0 8px;
letter-spacing: -0.01em;
}
p {
font-size: 0.85rem;
margin: 0;
opacity: 0.65;
line-height: 1.4;
max-width: 260px;
}
}
.channels-loading-state {
display: grid;
gap: 14px;
height: 100%;
padding: 16px 12px 18px;
}
.channels-loading-state__copy {
padding: 0 4px;
}
.channels-loading-state__title {
font-size: 0.86rem;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--mat-sys-on-surface);
}
.channels-loading-state__list {
display: grid;
gap: 8px;
overflow: hidden;
}
.channel-skeleton {
display: grid;
grid-template-columns: 44px minmax(0, 1fr);
grid-template-rows: 14px 10px;
align-items: center;
gap: 8px 12px;
min-height: 68px;
padding: 10px 12px;
border-radius: 14px;
background: color-mix(
in srgb,
var(--app-widget-header-bg, var(--mat-sys-surface-container-high)) 88%,
var(--app-widget-bg, var(--mat-sys-surface-container)) 12%
);
border: 1px solid
color-mix(
in srgb,
var(--app-widget-header-border, var(--mat-sys-outline-variant)) 96%,
transparent
);
}
.channel-skeleton__logo,
.channel-skeleton__title,
.channel-skeleton__meta {
position: relative;
overflow: hidden;
background: color-mix(
in srgb,
var(--app-widget-header-bg, var(--mat-sys-surface-container-high)) 52%,
var(--app-body-color, var(--mat-sys-on-surface-variant)) 48%
);
&::after {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
100deg,
transparent 8%,
color-mix(
in srgb,
var(--app-heading-color, var(--mat-sys-on-surface)) 18%,
transparent
)
44%,
transparent 74%
);
transform: translateX(-120%);
animation: channel-skeleton-shimmer 1.15s ease-in-out infinite;
}
}
.channel-skeleton__logo {
grid-row: 1 / span 2;
width: 44px;
height: 44px;
border-radius: 12px;
}
.channel-skeleton__title {
height: 11px;
width: min(68%, 180px);
border-radius: 999px;
}
.channel-skeleton__meta {
height: 9px;
width: min(42%, 120px);
border-radius: 999px;
}
@container (max-width: 350px) {
.scroll-viewport-portals {
padding-inline: 6px;
}
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes channel-skeleton-shimmer {
100% {
transform: translateX(120%);
}
}
@@ -0,0 +1,299 @@
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { of, Subject } from 'rxjs';
import {
FavoriteItem,
EpgQueueService,
FavoritesService,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { PortalChannelsListComponent } from './portal-channels-list.component';
function buildEpgItem(params: {
id: string;
title: string;
start: string;
stop: string;
startTimestamp: number;
stopTimestamp: number;
}) {
return {
id: params.id,
epg_id: `epg-${params.id}`,
title: params.title,
description: `${params.title} description`,
lang: 'en',
start: params.start,
end: params.stop,
stop: params.stop,
channel_id: 'channel-1',
start_timestamp: String(params.startTimestamp),
stop_timestamp: String(params.stopTimestamp),
};
}
describe('PortalChannelsListComponent', () => {
let fixture: ComponentFixture<PortalChannelsListComponent>;
const selectedChannels = signal<unknown[]>([]);
const selectedItem = signal<unknown>(null);
const epgItems = signal<unknown[]>([]);
const selectedTypeContentLoading = signal(true);
const selectedContentType = signal('live');
const currentPlaylist = signal<unknown>(null);
const selectedCategoryId = signal<number | null>(1);
const storeSignals = {
selectItemsFromSelectedCategory: selectedChannels,
selectedItem,
epgItems,
selectedTypeContentLoading,
selectedContentType,
currentPlaylist,
selectedCategoryId,
setSelectedCategory: jest.fn(),
toggleFavorite: jest.fn().mockResolvedValue(true),
};
const epgResults$ = new Subject<{ streamId: number; items: unknown[] }>();
const favoritesService = {
getFavorites: jest.fn().mockReturnValue(of([] as FavoriteItem[])),
};
beforeEach(async () => {
storeSignals.setSelectedCategory.mockClear();
storeSignals.toggleFavorite.mockClear();
selectedChannels.set([]);
selectedItem.set(null);
epgItems.set([]);
selectedTypeContentLoading.set(true);
selectedContentType.set('live');
currentPlaylist.set(null);
selectedCategoryId.set(1);
favoritesService.getFavorites.mockReturnValue(of([] as FavoriteItem[]));
await TestBed.configureTestingModule({
imports: [PortalChannelsListComponent, NoopAnimationsModule],
providers: [
{
provide: TranslateService,
useValue: {
instant: (key: string) =>
key === 'CHANNELS.LOADING'
? 'Loading channels...'
: key,
get: (key: string) =>
of(
key === 'CHANNELS.LOADING'
? 'Loading channels...'
: key
),
stream: (key: string) =>
of(
key === 'CHANNELS.LOADING'
? 'Loading channels...'
: key
),
onLangChange: of(null),
onTranslationChange: of(null),
onDefaultLangChange: of(null),
currentLang: 'en',
defaultLang: 'en',
},
},
{
provide: XtreamStore,
useValue: storeSignals,
},
{
provide: FavoritesService,
useValue: favoritesService,
},
{
provide: EpgQueueService,
useValue: {
epgResult$: epgResults$,
getCached: jest.fn().mockReturnValue(null),
enqueue: jest.fn(),
},
},
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: {},
},
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(PortalChannelsListComponent);
});
afterEach(() => {
jest.useRealTimers();
});
it('renders a loading placeholder instead of the empty state while xtream live content is still loading', () => {
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.channels-loading-state')
).not.toBeNull();
expect(
fixture.nativeElement.querySelector('.empty-search-state')
).toBeNull();
});
it('renders the empty state once loading has finished and the selected category has no channels', () => {
selectedTypeContentLoading.set(false);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.channels-loading-state')
).toBeNull();
expect(
fixture.nativeElement.querySelector('.empty-search-state')
).not.toBeNull();
});
it('selects the current preview program by timestamps, preserves them, and updates progress from them', () => {
jest.useFakeTimers();
const currentStartTimestamp = Math.floor(
Date.parse('2026-04-05T05:30:00.000Z') / 1000
);
const currentStopTimestamp = Math.floor(
Date.parse('2026-04-05T06:00:00.000Z') / 1000
);
const previousStartTimestamp = Math.floor(
Date.parse('2026-04-05T05:00:00.000Z') / 1000
);
const previousStopTimestamp = Math.floor(
Date.parse('2026-04-05T05:30:00.000Z') / 1000
);
jest.setSystemTime(new Date('2026-04-05T05:45:00.000Z'));
selectedTypeContentLoading.set(false);
selectedChannels.set([
{
title: 'Cartoon Network',
xtream_id: 50,
},
]);
currentPlaylist.set({
id: 'playlist-1',
password: 'secret',
serverUrl: 'http://demo.example',
username: 'demo',
});
fixture.detectChanges();
epgResults$.next({
streamId: 50,
items: [
buildEpgItem({
id: 'previous',
title: 'Previous Show',
start: '2026-04-05T03:00:00.000Z',
stop: '2026-04-05T03:30:00.000Z',
startTimestamp: previousStartTimestamp,
stopTimestamp: previousStopTimestamp,
}),
buildEpgItem({
id: 'current',
title: 'Current Show',
start: '2026-04-05T03:00:00.000Z',
stop: '2026-04-05T03:30:00.000Z',
startTimestamp: currentStartTimestamp,
stopTimestamp: currentStopTimestamp,
}),
],
});
fixture.detectChanges();
const component = fixture.componentInstance;
expect(component.epgPrograms.get(50)).toEqual(
expect.objectContaining({
title: 'Current Show',
startTimestamp: currentStartTimestamp,
stopTimestamp: currentStopTimestamp,
})
);
expect(component.currentProgramsProgress.get(50)).toBeCloseTo(50, 1);
});
it('does not mark a live item as favorite when only a colliding movie ID is favorited', () => {
favoritesService.getFavorites.mockReturnValue(
of([
{
content_id: 42,
playlist_id: 'playlist-1',
type: 'movie',
title: 'Krypton',
category_id: 7,
xtream_id: 290,
},
] satisfies FavoriteItem[])
);
selectedTypeContentLoading.set(false);
selectedChannels.set([
{
title: 'SE: V Film Premiere FHD',
type: 'live',
xtream_id: 290,
},
]);
currentPlaylist.set({
id: 'playlist-1',
password: 'secret',
serverUrl: 'http://demo.example',
username: 'demo',
});
fixture.detectChanges();
const component = fixture.componentInstance;
expect(component.favorites.get('movie:290')).toBe(true);
expect(component.favorites.get('live:290')).toBeUndefined();
expect(
component.favoriteKeyFor({
title: 'SE: V Film Premiere FHD',
type: 'live',
xtream_id: 290,
})
).toBe('live:290');
});
it('passes the live content type when toggling a channel favorite', async () => {
selectedTypeContentLoading.set(false);
currentPlaylist.set({
id: 'playlist-1',
password: 'secret',
serverUrl: 'http://demo.example',
username: 'demo',
});
fixture.detectChanges();
fixture.componentInstance.toggleFavorite(
new MouseEvent('click'),
{
title: 'Cartoon Network',
xtream_id: 253,
}
);
await Promise.resolve();
expect(storeSignals.toggleFavorite).toHaveBeenCalledWith(
253,
'playlist-1',
'live'
);
expect(fixture.componentInstance.favorites.get('live:253')).toBe(true);
});
});
@@ -0,0 +1,404 @@
import {
CdkVirtualScrollViewport,
ScrollingModule,
} from '@angular/cdk/scrolling';
import {
AfterViewInit,
ChangeDetectorRef,
Component,
computed,
effect,
inject,
input,
OnDestroy,
output,
viewChild,
} from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { ActivatedRoute } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import {
EpgItem,
EpgProgram,
XtreamCategory,
XtreamItem,
} from 'shared-interfaces';
import { ChannelListItemComponent } from 'components';
import {
PortalChannelSortMode,
sortPortalChannelItems,
} from '@iptvnator/portal/shared/util';
import { EpgQueueService } from '@iptvnator/portal/xtream/data-access';
import { XtreamCredentials } from '@iptvnator/portal/xtream/data-access';
import { FavoritesService } from '@iptvnator/portal/xtream/data-access';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
export interface XtreamChannelListItem {
readonly category_id?: string | number;
readonly id?: string | number;
readonly name?: string;
readonly poster_url?: string;
readonly stream_icon?: string;
readonly title?: string;
readonly type?: 'live' | 'movie' | 'series' | 'vod';
readonly xtream_id: number;
}
interface XtreamCategoryLike {
readonly category_id?: string | number;
readonly id?: string | number;
}
@Component({
selector: 'app-portal-channels-list',
templateUrl: './portal-channels-list.component.html',
styleUrls: ['./portal-channels-list.component.scss'],
imports: [
ChannelListItemComponent,
MatIcon,
ScrollingModule,
TranslatePipe,
],
})
export class PortalChannelsListComponent implements AfterViewInit, OnDestroy {
readonly playClicked = output<XtreamChannelListItem>();
readonly sortMode = input<PortalChannelSortMode>('server');
readonly channelsOverride = input<XtreamChannelListItem[] | null>(null);
readonly searchTermInput = input('');
readonly xtreamStore = inject(XtreamStore);
private readonly favoritesService = inject(FavoritesService);
private readonly epgQueueService = inject(EpgQueueService);
private readonly route = inject(ActivatedRoute);
readonly isSelectedTypeContentLoading =
this.xtreamStore.selectedTypeContentLoading;
readonly loadingRows = Array.from({ length: 9 }, (_, index) => index);
readonly channels = computed(() => {
const override = this.channelsOverride();
if (Array.isArray(override)) {
return override;
}
return this.xtreamStore.selectItemsFromSelectedCategory() as XtreamChannelListItem[];
});
readonly sortedChannels = computed(() => {
const mode = this.sortMode();
const channels = this.channels();
return sortPortalChannelItems(
channels,
mode,
(item) => item.title ?? item.name
);
});
readonly filteredChannels = computed(() => {
const term = this.searchTermInput().trim().toLowerCase();
const channels = this.sortedChannels();
if (!term) {
return channels;
}
return channels.filter((item) =>
`${item.title ?? ''} ${item.name ?? ''}`
.toLowerCase()
.includes(term)
);
});
favorites = new Map<string, boolean>();
epgPrograms = new Map<number, EpgProgram>();
currentProgramsProgress = new Map<number, number>();
readonly viewport = viewChild(CdkVirtualScrollViewport);
private subscriptions = new Subscription();
constructor(private cdr: ChangeDetectorRef) {
effect(() => {
const selectedItem = this.xtreamStore.selectedItem();
const epgItems = this.xtreamStore.epgItems();
if (!selectedItem?.xtream_id || epgItems.length === 0) {
return;
}
const previewProgram = this.pickPreviewProgram(epgItems);
if (!previewProgram) {
return;
}
this.applyProgram(selectedItem.xtream_id, previewProgram);
});
}
trackBy(_index: number, item: XtreamChannelListItem | XtreamItem) {
return item.xtream_id;
}
ngOnInit(): void {
const { categoryId } = this.route.snapshot.params;
if (categoryId && !this.channelsOverride())
this.xtreamStore.setSelectedCategory(Number(categoryId));
const playlist = this.xtreamStore.currentPlaylist();
if (playlist) {
this.favoritesService
.getFavorites(playlist.id)
.subscribe((favorites) => {
favorites.forEach((fav) => {
this.favorites.set(
this.getFavoriteKey(fav.xtream_id, fav.type),
true
);
});
});
}
// Subscribe to EPG results from the queue service
this.subscriptions.add(
this.epgQueueService.epgResult$.subscribe(({ streamId, items }) => {
const previewProgram = this.pickPreviewProgram(items);
if (previewProgram) {
this.applyProgram(streamId, previewProgram);
}
})
);
}
ngAfterViewInit() {
const vp = this.viewport();
if (vp && this.xtreamStore.selectedContentType() === 'live') {
this.subscriptions.add(
vp.renderedRangeStream
.pipe(debounceTime(300))
.subscribe((range) => {
const visibleChannels = this.filteredChannels().slice(
range.start,
range.end
);
this.loadEpgForVisibleChannels(visibleChannels);
})
);
}
}
private loadEpgForVisibleChannels(channels: XtreamChannelListItem[]): void {
const playlist = this.xtreamStore.currentPlaylist();
if (!playlist) return;
const credentials: XtreamCredentials = {
serverUrl: playlist.serverUrl,
username: playlist.username,
password: playlist.password,
};
const visibleIds = new Set<number>(channels.map((ch) => ch.xtream_id));
const uncachedIds: number[] = [];
// Apply cached results immediately
for (const channel of channels) {
const cached = this.epgQueueService.getCached(channel.xtream_id);
if (cached !== null) {
const previewProgram = this.pickPreviewProgram(cached);
if (previewProgram) {
if (!this.epgPrograms.has(channel.xtream_id)) {
this.applyProgram(channel.xtream_id, previewProgram);
}
}
continue;
}
if (!this.epgPrograms.has(channel.xtream_id)) {
uncachedIds.push(channel.xtream_id);
}
}
if (uncachedIds.length > 0) {
this.epgQueueService.enqueue(uncachedIds, visibleIds, credentials);
}
}
private updateProgramProgress(streamId: number, program: EpgItem) {
const now = Date.now();
const start = this.getProgramTimestampMs(
program.start,
program.start_timestamp
);
const end = this.getProgramTimestampMs(
program.stop ?? program.end,
program.stop_timestamp
);
if (now >= start && now <= end) {
const duration = end - start;
const elapsed = now - start;
const progress = (elapsed / duration) * 100;
this.currentProgramsProgress.set(streamId, progress);
return;
}
this.currentProgramsProgress.delete(streamId);
}
isSelected(item: XtreamCategory | XtreamCategoryLike): boolean {
const selectedCategory = this.xtreamStore.selectedCategoryId();
const itemId = Number(item.category_id ?? item.id);
return selectedCategory !== null && selectedCategory === itemId;
}
toggleFavorite(event: Event, item: XtreamChannelListItem) {
event.stopPropagation();
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (!playlistId) {
return;
}
const favoriteKey = this.favoriteKeyFor(item);
const contentType = this.getContentTypeForItem(item);
this.xtreamStore
.toggleFavorite(item.xtream_id, playlistId, contentType)
.then((result: boolean) => {
if (result) {
this.favorites.set(favoriteKey, true);
} else {
this.favorites.delete(favoriteKey);
}
this.cdr.detectChanges();
});
}
favoriteKeyFor(item: XtreamChannelListItem): string {
return this.getFavoriteKey(
item.xtream_id,
item.type ?? this.xtreamStore.selectedContentType()
);
}
private getFavoriteKey(
xtreamId: number,
type?: 'live' | 'movie' | 'series' | 'vod'
): string {
return `${this.normalizeContentType(type)}:${xtreamId}`;
}
private getContentTypeForItem(
item: XtreamChannelListItem
): 'live' | 'movie' | 'series' {
return this.normalizeContentType(
item.type ?? this.xtreamStore.selectedContentType()
);
}
private normalizeContentType(
type?: 'live' | 'movie' | 'series' | 'vod'
): 'live' | 'movie' | 'series' {
if (type === 'movie' || type === 'vod') {
return 'movie';
}
if (type === 'series') {
return 'series';
}
return 'live';
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
private applyProgram(streamId: number, program: EpgItem): void {
this.epgPrograms.set(streamId, this.toSharedEpgProgram(program));
this.updateProgramProgress(streamId, program);
this.cdr.detectChanges();
}
private pickPreviewProgram(items: EpgItem[]): EpgItem | null {
if (!items.length) {
return null;
}
const now = Date.now();
const normalizedItems = [...items].sort(
(a, b) =>
this.getProgramTimestampMs(a.start, a.start_timestamp) -
this.getProgramTimestampMs(b.start, b.start_timestamp)
);
const currentProgram = normalizedItems.find((item) => {
const start = this.getProgramTimestampMs(
item.start,
item.start_timestamp
);
const end = this.getProgramTimestampMs(
item.stop ?? item.end,
item.stop_timestamp
);
return now >= start && now <= end;
});
if (currentProgram) {
return currentProgram;
}
const nextProgram = normalizedItems.find((item) => {
return (
this.getProgramTimestampMs(item.start, item.start_timestamp) >
now
);
});
return nextProgram ?? normalizedItems[0];
}
private getProgramTimestampMs(
dateValue: string | undefined,
unixTimestampValue: string | undefined
): number {
const unixTimestamp = Number(unixTimestampValue);
if (Number.isFinite(unixTimestamp) && unixTimestamp > 0) {
return unixTimestamp * 1000;
}
return new Date(dateValue ?? '').getTime();
}
private toSharedEpgProgram(program: EpgItem): EpgProgram {
return {
start: program.start,
stop: program.stop ?? program.end,
channel: program.channel_id ?? program.id,
title: program.title,
desc: program.description ?? null,
category: null,
startTimestamp: this.getProgramTimestampSeconds(
program.start,
program.start_timestamp
),
stopTimestamp: this.getProgramTimestampSeconds(
program.stop ?? program.end,
program.stop_timestamp
),
};
}
private getProgramTimestampSeconds(
dateValue: string | undefined,
unixTimestampValue: string | undefined
): number | null {
const unixTimestamp = Number(unixTimestampValue);
if (Number.isFinite(unixTimestamp) && unixTimestamp > 0) {
return unixTimestamp;
}
const parsedDate = new Date(dateValue ?? '').getTime();
return Number.isFinite(parsedDate)
? Math.floor(parsedDate / 1000)
: null;
}
}
@@ -0,0 +1,85 @@
<div class="recently-added-page">
<h2 class="recently-added-page__title">
{{ 'PORTALS.SIDEBAR.RECENTLY_ADDED' | translate }}
</h2>
@if (isLoading()) {
<!-- Three skeleton rails cover the typical shape of this view. -->
@for (_ of [1, 2, 3]; track $index) {
<section class="recently-added-page__skeleton-rail">
<div
class="recently-added-page__skeleton-header"
aria-hidden="true"
></div>
<div
class="recently-added-page__skeleton-track"
aria-hidden="true"
>
@for (slot of skeletonSlots; track slot) {
<div class="recently-added-page__skeleton-card"></div>
}
</div>
</section>
}
} @else {
@if (recentlyAddedVod().length > 0) {
<app-content-rail-shell
class="recently-added-page__rail"
[label]="'PORTALS.SIDEBAR.MOVIES' | translate"
[totalCount]="recentlyAddedVod().length"
[seeAllLink]="vodSeeAllLink()"
[seeAllLabel]="vodSeeAllLabel()"
>
@for (item of recentlyAddedVod(); track item.xtream_id) {
<app-content-card
[title]="item.title || item.name"
[posterUrl]="item.poster_url || item.stream_icon"
[type]="'movie'"
[date]="getDate(item)"
(cardClick)="openItem(item, 'vod')"
/>
}
</app-content-rail-shell>
}
@if (recentlyAddedSeries().length > 0) {
<app-content-rail-shell
class="recently-added-page__rail"
[label]="'PORTALS.SIDEBAR.SERIES' | translate"
[totalCount]="recentlyAddedSeries().length"
[seeAllLink]="seriesSeeAllLink()"
[seeAllLabel]="seriesSeeAllLabel()"
>
@for (item of recentlyAddedSeries(); track item.xtream_id) {
<app-content-card
[title]="item.title || item.name"
[posterUrl]="item.poster_url || item.cover"
[type]="'series'"
[date]="getDate(item)"
(cardClick)="openItem(item, 'series')"
/>
}
</app-content-rail-shell>
}
@if (recentlyAddedLive().length > 0) {
<app-content-rail-shell
class="recently-added-page__rail"
[label]="'PORTALS.SIDEBAR.LIVE_TV' | translate"
[totalCount]="recentlyAddedLive().length"
[seeAllLink]="liveSeeAllLink()"
[seeAllLabel]="liveSeeAllLabel()"
>
@for (item of recentlyAddedLive(); track item.xtream_id) {
<app-content-card
[title]="item.title || item.name"
[posterUrl]="item.poster_url || item.stream_icon"
[type]="'live'"
[date]="getDate(item)"
(cardClick)="openItem(item, 'live')"
/>
}
</app-content-rail-shell>
}
}
</div>
@@ -0,0 +1,106 @@
:host {
display: block;
height: 100%;
overflow-y: auto;
}
.recently-added-page {
padding: 24px 28px 40px;
max-width: 1440px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 28px;
min-width: 0;
box-sizing: border-box;
}
.recently-added-page__title {
margin: 0;
font-size: 1.5rem;
font-weight: 650;
line-height: 1.2;
letter-spacing: -0.02em;
color: var(--app-heading-color, #d8dce8);
}
// Projected card sizing lives on the caller — the rail shell can't reach
// projected children through emulated encapsulation.
.recently-added-page__rail app-content-card {
flex: 0 0 160px;
width: 160px;
scroll-snap-align: start;
}
// ── Skeleton rails ─────────────────────────────────────────────────────────
// Shown while the xtream store is still fetching categories/content and
// before any section has resolved data. Matches the rail shell's header +
// track geometry so the layout doesn't shift when real content arrives.
.recently-added-page__skeleton-rail {
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px 0 0;
}
.recently-added-page__skeleton-header {
width: 180px;
height: 22px;
border-radius: 6px;
}
.recently-added-page__skeleton-track {
display: flex;
gap: 16px;
padding: 4px 0 16px;
overflow: hidden;
}
.recently-added-page__skeleton-card {
flex: 0 0 160px;
width: 160px;
aspect-ratio: 2 / 3;
border-radius: 12px;
}
.recently-added-page__skeleton-header,
.recently-added-page__skeleton-card {
background: linear-gradient(
90deg,
var(--app-widget-bg, #1e2330) 0%,
var(--app-widget-header-bg, #232840) 50%,
var(--app-widget-bg, #1e2330) 100%
);
background-size: 200% 100%;
animation: recently-added-shimmer 1.6s linear infinite;
border: 1px solid var(--app-widget-header-border, rgba(255, 255, 255, 0.05));
}
@keyframes recently-added-shimmer {
from {
background-position: 200% 0;
}
to {
background-position: -200% 0;
}
}
@media (prefers-reduced-motion: reduce) {
.recently-added-page__skeleton-header,
.recently-added-page__skeleton-card {
animation: none;
background-position: 0 0;
}
}
@media (max-width: 720px) {
.recently-added-page {
padding: 16px 16px 32px;
gap: 20px;
}
.recently-added-page__skeleton-card {
flex: 0 0 136px;
width: 136px;
}
}
@@ -0,0 +1,162 @@
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { startWith } from 'rxjs';
import {
ContentCardComponent,
ContentRailShellComponent,
} from '@iptvnator/portal/shared/ui';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { ContentType } from '@iptvnator/portal/xtream/data-access';
interface RecentlyAddedItem {
readonly added?: string;
readonly category_id: string | number;
readonly cover?: string;
readonly id?: number;
readonly last_modified?: string;
readonly name?: string;
readonly poster_url?: string;
readonly series_id?: number;
readonly stream_id?: number;
readonly stream_icon?: string;
readonly title?: string;
readonly xtream_id?: number;
}
// Three placeholder slots per skeleton rail — enough to suggest a horizontal
// scroll without taking the whole viewport.
const SKELETON_CARDS_PER_RAIL = [1, 2, 3, 4, 5, 6] as const;
@Component({
selector: 'app-recently-added',
templateUrl: './recently-added.component.html',
styleUrls: ['./recently-added.component.scss'],
imports: [ContentCardComponent, ContentRailShellComponent, TranslatePipe],
})
export class RecentlyAddedComponent {
private readonly xtreamStore = inject(XtreamStore);
private readonly router = inject(Router);
private readonly activatedRoute = inject(ActivatedRoute);
private readonly translate = inject(TranslateService);
// Re-compute translated labels when the active language changes.
private readonly languageTick = toSignal(
this.translate.onLangChange.pipe(startWith(null)),
{ initialValue: null }
);
readonly recentlyAddedLive = computed(() =>
this.getRecentlyAdded(
this.xtreamStore.liveStreams() as RecentlyAddedItem[]
)
);
readonly recentlyAddedVod = computed(() =>
this.getRecentlyAdded(
this.xtreamStore.vodStreams() as RecentlyAddedItem[]
)
);
readonly recentlyAddedSeries = computed(() =>
this.getRecentlyAdded(
this.xtreamStore.serialStreams() as RecentlyAddedItem[],
true
)
);
readonly skeletonSlots = SKELETON_CARDS_PER_RAIL;
readonly totalItems = computed(
() =>
this.recentlyAddedVod().length +
this.recentlyAddedSeries().length +
this.recentlyAddedLive().length
);
/**
* Show skeleton rails when the store is still fetching AND we have
* nothing resolved yet. Once a single section has data we drop the
* skeletons so partial-load states aren't obscured.
*/
readonly isLoading = computed(() => {
const store = this.xtreamStore;
const hasAnyData = this.totalItems() > 0;
if (hasAnyData) return false;
return (
store.isLoadingContent() ||
store.isLoadingCategories() ||
store.isImporting()
);
});
// Absolute rail "browse all" routes reuse the active playlist id. The
// store owns the current playlist, so navigation stays correct even if
// the user switches playlists before the rails finish loading.
private readonly playlistId = computed(
() => this.xtreamStore.currentPlaylist()?.id ?? null
);
readonly vodSeeAllLink = computed(() => this.buildSectionLink('vod'));
readonly seriesSeeAllLink = computed(() =>
this.buildSectionLink('series')
);
readonly liveSeeAllLink = computed(() => this.buildSectionLink('live'));
readonly vodSeeAllLabel = computed(() =>
this.translateWithTick('PORTALS.BROWSE_ALL_MOVIES')
);
readonly seriesSeeAllLabel = computed(() =>
this.translateWithTick('PORTALS.BROWSE_ALL_SERIES')
);
readonly liveSeeAllLabel = computed(() =>
this.translateWithTick('PORTALS.BROWSE_ALL_LIVE')
);
private buildSectionLink(section: 'vod' | 'series' | 'live'): string[] | null {
const id = this.playlistId();
if (!id) return null;
return ['/workspace', 'xtreams', id, section];
}
private translateWithTick(key: string): string {
this.languageTick();
return this.translate.instant(key);
}
private getRecentlyAdded<T extends RecentlyAddedItem>(
items: T[],
isSeries = false
): T[] {
return [...items]
.sort((a, b) => {
const dateA =
parseInt(isSeries ? a.last_modified : a.added) || 0;
const dateB =
parseInt(isSeries ? b.last_modified : b.added) || 0;
return dateB - dateA;
})
.slice(0, 20);
}
getDate(item: RecentlyAddedItem): number {
const timestamp = item.added || item.last_modified;
return parseInt(timestamp) * 1000;
}
openItem(item: RecentlyAddedItem, type: ContentType) {
this.xtreamStore.setSelectedContentType(type);
if (type === 'live') {
this.router.navigate(['..', type, item.category_id], {
relativeTo: this.activatedRoute,
});
} else {
const itemId =
item.xtream_id ||
item.id ||
(type === 'series' ? item.series_id : item.stream_id);
this.router.navigate(['..', type, item.category_id, itemId], {
relativeTo: this.activatedRoute,
});
}
}
}
@@ -0,0 +1,134 @@
<app-search-layout
[searchTerm]="searchTerm()"
[resultsCount]="xtreamStore.searchResults().length"
[isLoading]="xtreamStore.isSearching()"
[showCloseButton]="false"
[showResultsCount]="!isGlobalSearch || !groupByPlaylist()"
[showSearchInput]="showInlineSearchInput"
(searchTermChange)="updateSearchTerm($event)"
(closeClick)="onCloseDialog()"
>
<!-- Type filters -->
<ng-container filters>
@if (!isGlobalSearch) {
@for (filter of filterConfig; track filter.key) {
<mat-checkbox
[ngModel]="filters()[filter.key]"
(ngModelChange)="updateFilter(filter.key, $event)"
>
{{ filter.translationKey | translate }}
</mat-checkbox>
}
}
</ng-container>
<ng-container header-actions>
<mat-checkbox
[ngModel]="excludeHidden()"
(ngModelChange)="toggleExcludeHidden($event)"
>
{{ 'PORTALS.SEARCH_VIEW.VISIBLE_CATEGORIES_ONLY' | translate }}
</mat-checkbox>
@if (isGlobalSearch) {
<button mat-icon-button (click)="onCloseDialog()">
<mat-icon>close</mat-icon>
</button>
}
</ng-container>
<ng-container subheader>
@if (isGlobalSearch) {
<div class="global-search-subheader">
<div class="global-search-subheader-left">
<div class="global-search-note">
<mat-icon>info_outline</mat-icon>
<span>{{ 'PORTALS.SEARCH_VIEW.XTREAM_ONLY_NOTE' | translate }}</span>
</div>
<div class="global-search-filters">
@for (filter of filterConfig; track filter.key) {
<mat-checkbox
[ngModel]="filters()[filter.key]"
(ngModelChange)="updateFilter(filter.key, $event)"
>
{{ filter.translationKey | translate }}
</mat-checkbox>
}
</div>
</div>
<mat-checkbox
[ngModel]="groupByPlaylist()"
(ngModelChange)="toggleGroupByPlaylist($event)"
>
{{ 'PORTALS.SEARCH_VIEW.GROUP_BY_PLAYLIST' | translate }}
</mat-checkbox>
</div>
}
</ng-container>
<!-- Results -->
<ng-container results>
@if (isGlobalSearch) {
<!-- Global Search Results -->
@if (groupByPlaylist()) {
<!-- Grouped by playlist -->
<div class="playlist-section">
<h2 class="section-title">
Found {{ xtreamStore.searchResults().length }} items across
{{ (groupedResults() | keyvalue).length }} playlists
</h2>
@for (
group of groupedResults() | keyvalue;
track group.key
) {
<div class="playlist-group">
<h3 class="playlist-title">
<mat-icon>playlist_play</mat-icon>
{{ group.key }}
<span class="item-count"
>({{ $any(group).value.length }} items)</span
>
</h3>
<div class="results-grid">
@for (item of $any(group).value; track item.id) {
<app-content-card
[posterUrl]="item.poster_url"
[title]="item.title"
[type]="item.type"
[showPlaceholder]="true"
(cardClick)="selectItem(item)"
/>
}
</div>
</div>
}
</div>
} @else {
<!-- Flat list -->
<div class="results-grid">
@for (item of xtreamStore.searchResults(); track item.id) {
<app-content-card
[posterUrl]="item.poster_url"
[title]="item.title"
[type]="item.type"
[showPlaceholder]="true"
(cardClick)="selectItem(item)"
/>
}
</div>
}
} @else {
<!-- Playlist-level Search Results -->
<div class="results-grid">
@for (item of xtreamStore.searchResults(); track item.id) {
<app-content-card
[posterUrl]="item.poster_url"
[title]="item.title"
[type]="item.type"
[showPlaceholder]="true"
(cardClick)="selectItem(item)"
/>
}
</div>
}
</ng-container>
</app-search-layout>
@@ -0,0 +1,160 @@
@use '../../../../../shared/ui/src/lib/styles/content-grid' as grid;
:host {
display: flex;
flex-direction: column;
overflow-y: auto;
height: 100%;
width: 100%;
}
// Results grid styling
.results-grid {
@include grid.content-grid(140px, 20px);
padding-bottom: 1rem;
}
// Global search overlay styles
:host-context(.global-search-overlay) {
.results-grid {
mat-card {
position: relative;
.poster,
.poster-placeholder {
margin-top: 24px;
}
.playlist-badge {
position: absolute;
top: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.85);
padding: 6px 8px;
font-size: 12px;
color: white;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border-top-left-radius: inherit;
border-top-right-radius: inherit;
display: flex;
align-items: center;
gap: 4px;
mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
flex-shrink: 0;
}
}
}
}
}
// Subheader row for global search (note + grouping toggle)
.global-search-subheader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
.global-search-subheader-left {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.global-search-note {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.8rem;
opacity: 0.55;
mat-icon {
font-size: 15px;
width: 15px;
height: 15px;
flex-shrink: 0;
}
}
.global-search-filters {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
::ng-deep mat-checkbox {
flex-shrink: 0;
}
}
// Playlist grouping styles for global search
.playlist-group {
margin-bottom: 2rem;
.playlist-title {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 1rem 0;
padding: 8px;
background: rgba(0, 0, 0, 0.05);
border-radius: 4px;
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.01em;
mat-icon {
opacity: 0.7;
}
.item-count {
margin-left: auto;
font-size: 0.85rem;
opacity: 0.7;
}
}
.results-grid {
margin-bottom: 0;
}
}
:host-context(.global-search-overlay) {
.playlist-group {
.playlist-title {
background: var(--surface);
}
}
.results-grid {
mat-card {
.playlist-badge {
display: none;
}
.poster,
.poster-placeholder {
margin-top: 0;
}
}
}
}
.playlist-section {
.section-title {
margin: 0 0 1.5rem;
font-size: 1rem;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--mat-sys-on-surface);
padding: 0 8px;
}
}
@@ -0,0 +1,203 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, Router, convertToParamMap } from '@angular/router';
import { of } from 'rxjs';
import { DatabaseService } from 'services';
import { SearchResultsComponent } from './search-results.component';
import {
SearchFilters,
XtreamContentItem,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
jest.mock('@iptvnator/portal/shared/ui', () => ({
ContentCardComponent: class {},
SearchLayoutComponent: class {},
}));
const DEFAULT_SEARCH_FILTERS: SearchFilters = {
live: true,
movie: true,
series: true,
};
function createSearchItem(
overrides: Partial<XtreamContentItem> = {}
): XtreamContentItem {
return {
id: 1,
category_id: 123,
title: 'Matrix',
rating: '0',
added: '0',
poster_url: '',
xtream_id: 456,
type: 'movie',
...overrides,
};
}
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 };
}
class MockXtreamStore {
readonly searchTerm = signal('');
readonly searchFilters = signal(DEFAULT_SEARCH_FILTERS);
readonly searchResults = signal<XtreamContentItem[]>([]);
readonly isSearching = signal(false);
setSearchTerm = jest.fn((term: string) => {
this.searchTerm.set(term);
});
setSearchFilters = jest.fn((filters: SearchFilters) => {
this.searchFilters.set(filters);
});
updateSearchFilter = jest.fn();
setGlobalSearchResults = jest.fn((items: XtreamContentItem[]) => {
this.searchResults.set(items);
});
setIsSearching = jest.fn((state: boolean) => {
this.isSearching.set(state);
});
resetSearchResults = jest.fn();
searchContent = jest.fn();
setSelectedContentType = jest.fn();
}
describe('SearchResultsComponent initialQuery contract', () => {
let routerNavigateMock: jest.Mock;
beforeEach(() => {
routerNavigateMock = jest.fn();
TestBed.configureTestingModule({
providers: [
{
provide: XtreamStore,
useClass: MockXtreamStore,
},
{
provide: Router,
useValue: {
navigate: routerNavigateMock,
},
},
{
provide: ActivatedRoute,
useValue: {
snapshot: {
data: {},
queryParamMap: convertToParamMap({ q: '' }),
},
queryParamMap: of(convertToParamMap({ q: '' })),
},
},
{
provide: DatabaseService,
useValue: {
globalSearchContent: jest.fn().mockResolvedValue([]),
},
},
],
});
});
it('applies initialQuery when opened as global search', () => {
const component = TestBed.runInInjectionContext(
() =>
new SearchResultsComponent(
{
isGlobalSearch: true,
initialQuery: 'matrix',
},
undefined
)
);
const store = TestBed.inject(XtreamStore) as unknown as MockXtreamStore;
expect(store.setSearchTerm).toHaveBeenCalledWith('matrix');
expect(component.searchTerm()).toBe('matrix');
});
it('does not force search term when initialQuery is not provided', () => {
TestBed.runInInjectionContext(
() =>
new SearchResultsComponent(
{
isGlobalSearch: true,
},
undefined
)
);
const store = TestBed.inject(XtreamStore) as unknown as MockXtreamStore;
expect(store.setSearchTerm).not.toHaveBeenCalled();
});
it('navigates global search selection to workspace xtream route', () => {
const component = TestBed.runInInjectionContext(
() =>
new SearchResultsComponent(
{
isGlobalSearch: true,
},
undefined
)
);
component.selectItem(
createSearchItem({
playlist_id: 'playlist-1',
})
);
expect(routerNavigateMock).toHaveBeenCalledWith(
['/workspace', 'xtreams', 'playlist-1', 'vod', '123', '456'],
{
state: undefined,
}
);
});
it('ignores stale global search responses once a newer search has completed', async () => {
const staleSearch = createDeferred<XtreamContentItem[]>();
const freshResults = [
createSearchItem({ xtream_id: 777, title: 'Fresh result' }),
];
const databaseService = TestBed.inject(DatabaseService) as {
globalSearchContent: jest.Mock;
};
databaseService.globalSearchContent
.mockReturnValueOnce(staleSearch.promise)
.mockResolvedValueOnce(freshResults);
const component = TestBed.runInInjectionContext(
() =>
new SearchResultsComponent({
isGlobalSearch: true,
}, undefined)
);
const store = TestBed.inject(XtreamStore) as unknown as MockXtreamStore;
const stalePromise = component.searchGlobal('mat', ['movie']);
const freshPromise = component.searchGlobal('matrix', ['movie']);
await freshPromise;
expect(store.searchResults()).toEqual(freshResults);
staleSearch.resolve([
createSearchItem({ xtream_id: 1, title: 'Stale result' }),
]);
await stalePromise;
expect(store.searchResults()).toEqual(freshResults);
});
});
@@ -0,0 +1,350 @@
import { KeyValuePipe } from '@angular/common';
import {
AfterViewInit,
Component,
computed,
effect,
inject,
Inject,
Optional,
signal,
viewChild,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatIconButton } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { DatabaseService } from 'services';
import { ContentCardComponent } from '@iptvnator/portal/shared/ui';
import { SearchLayoutComponent } from '@iptvnator/portal/shared/ui';
import {
buildXtreamNavigationTarget,
isWorkspaceLayoutRoute,
queryParamSignal,
} from '@iptvnator/portal/shared/util';
import { createLogger } from '@iptvnator/portal/shared/util';
import { XtreamContentItem } from '@iptvnator/portal/xtream/data-access';
import { SearchFilters } from '@iptvnator/portal/xtream/data-access';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { ContentType } from '@iptvnator/portal/xtream/data-access';
interface SearchResultsData {
isGlobalSearch: boolean;
initialQuery?: string;
}
function groupResultsByPlaylistName(
items: XtreamContentItem[]
): Record<string, XtreamContentItem[]> {
return items.reduce<Record<string, XtreamContentItem[]>>(
(groups, item) => {
const key = String(item.playlist_name);
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
},
{}
);
}
@Component({
selector: 'app-search-results',
imports: [
ContentCardComponent,
FormsModule,
KeyValuePipe,
MatCheckboxModule,
MatDialogModule,
MatIcon,
MatIconButton,
SearchLayoutComponent,
TranslatePipe,
],
providers: [],
templateUrl: './search-results.component.html',
styleUrls: ['./search-results.component.scss'],
})
export class SearchResultsComponent implements AfterViewInit {
readonly searchLayoutComponent = viewChild(SearchLayoutComponent);
readonly xtreamStore = inject(XtreamStore);
readonly router = inject(Router);
readonly activatedRoute = inject(ActivatedRoute);
readonly databaseService = inject(DatabaseService);
private readonly logger = createLogger('XtreamSearchResults');
readonly isWorkspaceLayout = isWorkspaceLayoutRoute(this.activatedRoute);
readonly routeSearchTerm = queryParamSignal(
this.activatedRoute,
'q',
(value) => (value ?? '').trim()
);
/** Search term from store */
readonly searchTerm = this.xtreamStore.searchTerm;
/** Search filters from store */
readonly filters = this.xtreamStore.searchFilters;
private globalSearchRequestVersion = 0;
private static readonly GROUP_BY_STORAGE_KEY =
'global-search-group-by-playlist';
private static readonly EXCLUDE_HIDDEN_STORAGE_KEY =
'xtream-search-exclude-hidden';
private static readonly TYPE_FILTERS_STORAGE_KEY =
'global-search-type-filters';
isGlobalSearch = false;
/** Whether to group global search results by playlist */
readonly groupByPlaylist = signal(
localStorage.getItem(SearchResultsComponent.GROUP_BY_STORAGE_KEY) !==
'false'
);
/** Whether to exclude content from hidden categories */
readonly excludeHidden = signal(
localStorage.getItem(
SearchResultsComponent.EXCLUDE_HIDDEN_STORAGE_KEY
) === 'true'
);
readonly filterConfig = [
{
key: 'live' as keyof SearchFilters,
label: 'Live TV',
translationKey: 'PORTALS.SIDEBAR.LIVE_TV',
},
{
key: 'movie' as keyof SearchFilters,
label: 'Movies',
translationKey: 'PORTALS.SIDEBAR.MOVIES',
},
{
key: 'series' as keyof SearchFilters,
label: 'Series',
translationKey: 'PORTALS.SIDEBAR.SERIES',
},
];
/** Grouped results computed once per result change (avoids recalculating on every CD cycle) */
readonly groupedResults = computed(() => {
const results = this.xtreamStore.searchResults();
if (!this.isGlobalSearch) return { default: results };
return groupResultsByPlaylistName(results);
});
constructor(
@Optional() @Inject(MAT_DIALOG_DATA) data: SearchResultsData,
@Optional() public dialogRef: MatDialogRef<SearchResultsComponent>
) {
this.isGlobalSearch = data?.isGlobalSearch || false;
const initialQuery = (data?.initialQuery ?? '').trim();
if (this.isGlobalSearch) {
const savedFilters = localStorage.getItem(
SearchResultsComponent.TYPE_FILTERS_STORAGE_KEY
);
if (savedFilters) {
try {
const parsed = JSON.parse(
savedFilters
) as Partial<SearchFilters>;
this.xtreamStore.setSearchFilters({
live: parsed.live !== false,
movie: parsed.movie !== false,
series: parsed.series !== false,
});
} catch {
// Ignore malformed storage value and keep defaults.
}
}
if (initialQuery) {
this.xtreamStore.setSearchTerm(initialQuery);
}
}
effect((onCleanup) => {
const term = this.searchTerm();
if (term.length >= 3) {
const timeout = setTimeout(() => this.executeSearch(), 300);
onCleanup(() => clearTimeout(timeout));
} else if (term.length === 0) {
this.clearResultsOnly();
}
});
effect(() => {
if (this.isGlobalSearch || !this.isWorkspaceLayout) {
return;
}
const queryTerm = this.routeSearchTerm();
if (!queryTerm || queryTerm === this.searchTerm()) {
return;
}
this.xtreamStore.setSearchTerm(queryTerm);
});
}
ngAfterViewInit() {
this.xtreamStore.setSelectedContentType(undefined);
setTimeout(() => {
this.searchLayoutComponent()?.focusSearchInput();
});
}
executeSearch() {
const filters = this.filters();
const types = Object.entries(filters)
.filter(([, enabled]) => enabled)
.map(([type]) => type);
const excludeHidden = this.excludeHidden();
if (this.isGlobalSearch) {
this.searchGlobal(this.searchTerm(), types, excludeHidden);
} else {
this.xtreamStore.searchContent({
term: this.searchTerm(),
types,
excludeHidden,
});
}
}
/**
* Update search term in the store
*/
updateSearchTerm(term: string) {
this.xtreamStore.setSearchTerm(term);
}
/**
* Update a single filter in the store
*/
updateFilter(key: keyof SearchFilters, value: boolean) {
this.xtreamStore.updateSearchFilter(key, value);
if (this.isGlobalSearch) {
localStorage.setItem(
SearchResultsComponent.TYPE_FILTERS_STORAGE_KEY,
JSON.stringify(this.xtreamStore.searchFilters())
);
}
if (this.searchTerm().length >= 3) {
this.executeSearch();
}
}
/**
* Clear only the results, not the search term/filters
*/
private clearResultsOnly() {
this.globalSearchRequestVersion++;
this.xtreamStore.setIsSearching(false);
this.xtreamStore.setGlobalSearchResults([]);
}
async searchGlobal(term: string, types: string[], excludeHidden?: boolean) {
const requestVersion = ++this.globalSearchRequestVersion;
this.xtreamStore.setIsSearching(true);
try {
const results = await this.databaseService.globalSearchContent(
term,
types,
excludeHidden
);
if (requestVersion !== this.globalSearchRequestVersion) {
return;
}
if (results && Array.isArray(results)) {
this.xtreamStore.setGlobalSearchResults(results);
} else {
this.xtreamStore.setIsSearching(false);
}
} catch (error) {
if (requestVersion !== this.globalSearchRequestVersion) {
return;
}
this.logger.error('Error in global search', error);
this.xtreamStore.resetSearchResults();
}
}
selectItem(item: XtreamContentItem) {
const playlistId = item.playlist_id ?? this.xtreamStore.playlistId();
if (!playlistId) {
return;
}
const type = (item.type === 'movie' ? 'vod' : item.type) as ContentType;
const navigationType =
item.type === 'movie'
? 'movie'
: item.type === 'series'
? 'series'
: 'live';
this.xtreamStore.setSelectedContentType(type);
const navigation = buildXtreamNavigationTarget({
playlistId,
type: navigationType,
categoryId: item.category_id,
itemId: item.xtream_id,
title: item.title,
imageUrl: item.poster_url,
});
if (this.isGlobalSearch) {
this.dialogRef?.close();
}
void this.router.navigate(navigation.link, {
state: navigation.state,
});
}
onCloseDialog() {
this.dialogRef?.close();
}
toggleGroupByPlaylist(value: boolean) {
this.groupByPlaylist.set(value);
localStorage.setItem(
SearchResultsComponent.GROUP_BY_STORAGE_KEY,
String(value)
);
}
toggleExcludeHidden(value: boolean) {
this.excludeHidden.set(value);
localStorage.setItem(
SearchResultsComponent.EXCLUDE_HIDDEN_STORAGE_KEY,
String(value)
);
if (this.searchTerm().length >= 3) {
this.executeSearch();
}
}
getGroupedResults() {
return this.groupedResults();
}
get showInlineSearchInput(): boolean {
return !this.isWorkspaceLayout || this.isGlobalSearch;
}
}
@@ -0,0 +1,94 @@
@let item = selectedItem();
@if (item?.info) {
<app-content-hero
[title]="item.info?.name"
[description]="item.info?.plot"
[posterUrl]="item.info?.cover"
[backdropUrl]="item.info?.backdrop_path?.[0]"
(backClicked)="goBack()"
>
<ng-container hero-tags>
@if (item.info?.releaseDate) {
<span class="details__tag">{{
item.info.releaseDate | slice: 0 : 4
}}</span>
}
@if (item.info?.genre) {
<span class="details__tag">{{ item.info.genre }}</span>
}
@if (item.info?.episode_run_time) {
<span class="details__tag"
>{{ item.info.episode_run_time }} min/ep</span
>
}
@if (item.info?.rating) {
<span class="details__tag details__tag--rating">
⭐ {{ item.info.rating }}
</span>
}
</ng-container>
<ng-container hero-meta>
@if (item.info?.cast) {
<div class="details__meta-item">
<span class="label">{{ 'XTREAM.CAST' | translate }}</span>
<span class="value">{{ item.info.cast }}</span>
</div>
}
@if (item.info?.director) {
<div class="details__meta-item">
<span class="label">{{
'XTREAM.DIRECTOR' | translate
}}</span>
<span class="value">{{ item.info.director }}</span>
</div>
}
</ng-container>
<ng-container hero-actions>
@if (!isFavorite()) {
<button class="favorite-btn" (click)="toggleFavorite()">
<mat-icon>add</mat-icon>
{{ 'PORTALS.ADD_TO_FAVORITES' | translate }}
</button>
} @else {
<button
class="favorite-btn favorite-btn--active"
(click)="toggleFavorite()"
>
<mat-icon>check</mat-icon>
{{ 'PORTALS.REMOVE_FROM_FAVORITES' | translate }}
</button>
}
</ng-container>
@if (inlinePlayback(); as playback) {
<app-portal-inline-player
[playback]="playback"
(timeUpdate)="handleInlineTimeUpdate($event)"
(closed)="closeInlinePlayer()"
(streamUrlCopied)="showCopyNotification()"
/>
}
<app-season-container
[seasons]="item.episodes"
[seriesId]="item.series_id"
[playlistId]="currentPlaylistId()"
[seriesTitle]="item.info?.name"
[playbackPositions]="episodePlaybackPositions()"
[xtreamDownloadContext]="xtreamDownloadContext()"
[openingEpisodeId]="openingEpisodeId()"
[activeEpisodeId]="activeEpisodeId()"
(episodeClicked)="playEpisode($event)"
(playbackToggleRequested)="handlePlaybackToggleRequested($event)"
/>
</app-content-hero>
} @else if (detailsError()) {
<app-content-hero
[errorMessage]="detailsError()"
(backClicked)="goBack()"
/>
} @else {
<app-content-hero [isLoading]="true" (backClicked)="goBack()" />
}
@@ -0,0 +1,269 @@
import { Component, input, output, signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Location } from '@angular/common';
import { MatIcon } from '@angular/material/icon';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { MockPipe } from 'ng-mocks';
import {
ContentHeroComponent,
SeasonContainerComponent,
} from 'components';
import {
PORTAL_EXTERNAL_PLAYBACK,
PORTAL_PLAYBACK_POSITIONS,
PORTAL_PLAYER,
} from '@iptvnator/portal/shared/util';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { PortalInlinePlayerComponent } from '@iptvnator/ui/playback';
import { of } from 'rxjs';
import { SerialDetailsComponent } from './serial-details.component';
@Component({
selector: 'app-content-hero',
standalone: true,
template: '<ng-content />',
})
class StubContentHeroComponent {
readonly title = input<string | undefined>(undefined);
readonly description = input<string | undefined>(undefined);
readonly posterUrl = input<string | undefined>(undefined);
readonly backdropUrl = input<string | undefined>(undefined);
readonly isLoading = input(false);
readonly errorMessage = input<string | null>(null);
readonly backClicked = output<void>();
}
@Component({
selector: 'app-season-container',
standalone: true,
template: '<div data-testid="season-container"></div>',
})
class StubSeasonContainerComponent {
readonly seasons = input<unknown>(null);
readonly seriesId = input<number | string | null>(null);
readonly playlistId = input('');
readonly seriesTitle = input<string | undefined>(undefined);
readonly playbackPositions = input<unknown>(null);
readonly xtreamDownloadContext = input<unknown>(null);
readonly openingEpisodeId = input<number | null>(null);
readonly activeEpisodeId = input<number | null>(null);
readonly episodeClicked = output<unknown>();
readonly playbackToggleRequested = output<unknown>();
}
@Component({
selector: 'app-portal-inline-player',
standalone: true,
template: '',
})
class StubPortalInlinePlayerComponent {
readonly playback = input<unknown>(null);
readonly timeUpdate = output<unknown>();
readonly closed = output<void>();
readonly streamUrlCopied = output<void>();
}
@Component({
selector: 'mat-icon',
standalone: true,
template: '<ng-content />',
})
class StubMatIconComponent {}
describe('SerialDetailsComponent', () => {
let fixture: ComponentFixture<SerialDetailsComponent>;
const selectedItem = signal<unknown>(null);
const selectedContentType = signal<'series'>('series');
const isFavorite = signal(false);
const isLoadingDetails = signal(false);
const detailsError = signal<string | null>(null);
const currentPlaylist = signal({
id: 'xtream-1',
serverUrl: 'http://xtream.example',
username: 'user',
password: 'pass',
});
const fetchSerialDetailsWithMetadata = jest.fn();
const checkFavoriteStatus = jest.fn();
const getSeriesPlaybackPositions = jest.fn().mockResolvedValue([]);
beforeEach(async () => {
selectedItem.set({
series_id: 103,
info: {
name: 'Series One',
plot: 'Series plot',
cover: 'cover.jpg',
backdrop_path: [],
genre: 'Drama',
},
episodes: {
'1': [
{
id: '1001',
episode_num: 1,
title: 'Episode 1',
season: 1,
},
],
},
});
isFavorite.set(false);
isLoadingDetails.set(false);
detailsError.set(null);
fetchSerialDetailsWithMetadata.mockClear();
checkFavoriteStatus.mockClear();
getSeriesPlaybackPositions.mockClear();
await TestBed.configureTestingModule({
imports: [SerialDetailsComponent],
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: {
categoryId: '3',
serialId: '103',
},
},
},
},
{
provide: XtreamStore,
useValue: {
selectedItem,
selectedContentType,
isFavorite,
isLoadingDetails,
detailsError,
currentPlaylist,
fetchSerialDetailsWithMetadata,
checkFavoriteStatus,
setSelectedItem: jest.fn((value: unknown) =>
selectedItem.set(value)
),
toggleFavorite: jest.fn(),
constructEpisodeStreamUrl: jest.fn(),
addRecentItem: jest.fn(),
backfillContentBackdrop: jest.fn(),
},
},
{
provide: PORTAL_EXTERNAL_PLAYBACK,
useValue: {
activeSession: signal(null),
},
},
{
provide: PORTAL_PLAYBACK_POSITIONS,
useValue: {
getSeriesPlaybackPositions,
savePlaybackPosition: jest.fn(),
clearPlaybackPosition: jest.fn(),
},
},
{
provide: PORTAL_PLAYER,
useValue: {
isEmbeddedPlayer: jest.fn().mockReturnValue(false),
openResolvedPlayback: jest.fn(),
},
},
{
provide: MatSnackBar,
useValue: {
open: jest.fn(),
},
},
{
provide: TranslateService,
useValue: {
instant: (key: string) => key,
get: (key: string) => of(key),
stream: (key: string) => of(key),
onLangChange: of(null),
onTranslationChange: of(null),
onDefaultLangChange: of(null),
},
},
{
provide: Location,
useValue: {
back: jest.fn(),
},
},
],
})
.overrideComponent(SerialDetailsComponent, {
remove: {
imports: [
ContentHeroComponent,
MatIcon,
PortalInlinePlayerComponent,
SeasonContainerComponent,
TranslatePipe,
],
},
add: {
imports: [
StubContentHeroComponent,
StubMatIconComponent,
StubPortalInlinePlayerComponent,
StubSeasonContainerComponent,
MockPipe(
TranslatePipe,
(value: string | null | undefined) => value ?? ''
),
],
},
})
.compileComponents();
fixture = TestBed.createComponent(SerialDetailsComponent);
});
afterEach(() => {
fixture?.destroy();
});
it('initializes series metadata and renders the season container', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(fetchSerialDetailsWithMetadata).toHaveBeenCalledWith({
serialId: '103',
categoryId: 3,
});
expect(checkFavoriteStatus).toHaveBeenCalledWith(
103,
'xtream-1',
'series'
);
expect(getSeriesPlaybackPositions).toHaveBeenCalledWith(
'xtream-1',
103
);
const seasonContainer = fixture.debugElement.query(
By.directive(StubSeasonContainerComponent)
)?.componentInstance as StubSeasonContainerComponent | undefined;
expect(seasonContainer).toBeDefined();
expect(seasonContainer?.seriesId()).toBe(103);
expect(seasonContainer?.playlistId()).toBe('xtream-1');
expect(seasonContainer?.seasons()).toEqual({
'1': [
{
id: '1001',
episode_num: 1,
title: 'Episode 1',
season: 1,
},
],
});
});
});
@@ -0,0 +1,404 @@
import { Location, SlicePipe } from '@angular/common';
import {
Component,
effect,
inject,
OnDestroy,
OnInit,
signal,
} from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import {
ContentHeroComponent,
SeasonContainerComponent,
SeasonContainerPlaybackToggleRequest,
SeasonContainerXtreamDownloadContext,
} from 'components';
import {
PORTAL_EXTERNAL_PLAYBACK,
PORTAL_PLAYBACK_POSITIONS,
PORTAL_PLAYER,
} from '@iptvnator/portal/shared/util';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { PortalInlinePlayerComponent } from '@iptvnator/ui/playback';
import {
PlaybackPositionData,
PlayerContentInfo,
ResolvedPortalPlayback,
XtreamSerieEpisode,
XtreamSerieDetails,
} from 'shared-interfaces';
type XtreamSerieDetailsView = XtreamSerieDetails & {
readonly series_id: number;
};
@Component({
selector: 'app-serial-details',
templateUrl: './serial-details.component.html',
styleUrls: [
'../../../../../../ui/components/src/lib/styles/detail-view.scss',
],
styles: [
`
:host {
display: block;
width: 100%;
height: 100%;
min-height: 0;
}
`,
],
imports: [
ContentHeroComponent,
MatIcon,
PortalInlinePlayerComponent,
SeasonContainerComponent,
SlicePipe,
TranslatePipe,
],
})
export class SerialDetailsComponent implements OnInit, OnDestroy {
private readonly location = inject(Location);
private readonly route = inject(ActivatedRoute);
private readonly xtreamStore = inject(XtreamStore);
private readonly playbackPositions = inject(PORTAL_PLAYBACK_POSITIONS);
private readonly portalPlayer = inject(PORTAL_PLAYER);
private readonly externalPlayback = inject(PORTAL_EXTERNAL_PLAYBACK);
private readonly snackBar = inject(MatSnackBar);
private readonly translateService = inject(TranslateService);
readonly selectedItem = signal<XtreamSerieDetailsView | null>(null);
readonly selectedContentType = this.xtreamStore.selectedContentType;
readonly isFavorite = this.xtreamStore.isFavorite;
readonly isLoadingDetails = this.xtreamStore.isLoadingDetails;
readonly detailsError = this.xtreamStore.detailsError;
readonly inlinePlayback = signal<ResolvedPortalPlayback | null>(null);
readonly episodePlaybackPositions = signal<
Map<number, PlaybackPositionData>
>(new Map());
readonly currentPlaylistId = signal('');
readonly xtreamDownloadContext =
signal<SeasonContainerXtreamDownloadContext | null>(null);
private readonly detailsInitDone = signal(false);
private readonly backdropBackfillKey = signal<string | null>(null);
private lastSaveTime = 0;
private unsubscribePositionUpdates: (() => void) | null = null;
readonly openingEpisodeId = signal<number | null>(null);
readonly activeEpisodeId = signal<number | null>(null);
constructor() {
effect(() => {
const item = this.xtreamStore.selectedItem() as unknown as
| (XtreamSerieDetails & {
readonly series_id?: string | number;
})
| null;
this.selectedItem.set(
item
? {
...item,
series_id: Number(item.series_id),
}
: null
);
});
effect(() => {
const playlist = this.xtreamStore.currentPlaylist();
this.currentPlaylistId.set(playlist?.id ?? '');
this.xtreamDownloadContext.set(
playlist
? {
serverUrl: playlist.serverUrl,
username: playlist.username,
password: playlist.password,
}
: null
);
});
effect(() => {
const playlistId = this.xtreamStore.currentPlaylist()?.id;
const { categoryId, serialId } = this.route.snapshot.params;
if (!playlistId || this.detailsInitDone()) {
return;
}
this.initializeSerialDetails(playlistId, categoryId, serialId);
this.detailsInitDone.set(true);
});
effect(() => {
const playlistId = this.currentPlaylistId();
const selectedItem = this.selectedItem();
const xtreamId = Number(selectedItem?.series_id ?? 0);
const backdropUrl = selectedItem?.info?.backdrop_path?.[0]?.trim();
if (!playlistId || !Number.isFinite(xtreamId) || xtreamId <= 0 || !backdropUrl) {
return;
}
const backfillKey = `${playlistId}:${xtreamId}:${backdropUrl}`;
if (this.backdropBackfillKey() === backfillKey) {
return;
}
this.backdropBackfillKey.set(backfillKey);
void this.xtreamStore.backfillContentBackdrop({
xtreamId,
contentType: 'series',
playlist: this.xtreamStore.currentPlaylist,
backdropUrl,
});
});
effect(() => {
const session = this.externalPlayback.activeSession();
const selectedItem = this.selectedItem();
const playlistId = this.currentPlaylistId();
if (
!session?.contentInfo ||
!selectedItem?.series_id ||
!playlistId ||
session.contentInfo.contentType !== 'episode' ||
session.contentInfo.playlistId !== playlistId ||
session.contentInfo.seriesXtreamId !==
Number(selectedItem.series_id)
) {
this.openingEpisodeId.set(null);
this.activeEpisodeId.set(null);
return;
}
if (session.status === 'launching') {
this.openingEpisodeId.set(session.contentInfo.contentXtreamId);
this.activeEpisodeId.set(null);
return;
}
if (session.status === 'opened' || session.status === 'playing') {
this.openingEpisodeId.set(null);
this.activeEpisodeId.set(session.contentInfo.contentXtreamId);
return;
}
this.openingEpisodeId.set(null);
this.activeEpisodeId.set(null);
});
if (window.electron?.onPlaybackPositionUpdate) {
this.unsubscribePositionUpdates =
window.electron.onPlaybackPositionUpdate(
(data: PlaybackPositionData) => {
const selectedItem = this.selectedItem();
if (
data.contentType !== 'episode' ||
data.playlistId !== this.currentPlaylistId() ||
data.seriesXtreamId !==
Number(selectedItem?.series_id ?? 0)
) {
return;
}
this.updateEpisodePlaybackPosition(data);
}
);
}
}
ngOnInit(): void {
const currentPlaylist = this.xtreamStore.currentPlaylist();
if (!currentPlaylist?.id) {
return;
}
const { categoryId, serialId } = this.route.snapshot.params;
this.initializeSerialDetails(currentPlaylist.id, categoryId, serialId);
this.detailsInitDone.set(true);
}
ngOnDestroy(): void {
this.closeInlinePlayer();
this.xtreamStore.setSelectedItem(null);
this.unsubscribePositionUpdates?.();
}
playEpisode(episode: XtreamSerieEpisode): void {
this.addToRecentlyViewed(this.route.snapshot.params.serialId);
const streamUrl = this.xtreamStore.constructEpisodeStreamUrl(episode);
const contentInfo: PlayerContentInfo = {
playlistId: this.xtreamStore.currentPlaylist().id,
contentXtreamId: Number(episode.id),
contentType: 'episode',
seriesXtreamId: Number(this.selectedItem().series_id),
seasonNumber: Number(episode.season),
episodeNumber: Number(episode.episode_num),
};
const position = this.episodePlaybackPositions().get(
Number(episode.id)
);
const playback: ResolvedPortalPlayback = {
streamUrl,
title: episode.title,
thumbnail: this.selectedItem().info.cover,
startTime: position?.positionSeconds,
contentInfo,
};
this.startPlayback(playback);
}
toggleFavorite(): void {
this.xtreamStore.toggleFavorite(
this.route.snapshot.params.serialId,
this.xtreamStore.currentPlaylist().id,
'series',
this.selectedItem()?.info?.backdrop_path?.[0]
);
}
goBack(): void {
this.closeInlinePlayer();
this.location.back();
}
closeInlinePlayer(): void {
this.inlinePlayback.set(null);
this.lastSaveTime = 0;
}
handleInlineTimeUpdate(event: {
currentTime: number;
duration: number;
}): void {
const playback = this.inlinePlayback();
if (!playback?.contentInfo) return;
const now = Date.now();
if (now - this.lastSaveTime <= 15000) return;
this.lastSaveTime = now;
const position: PlaybackPositionData = {
...playback.contentInfo,
positionSeconds: Math.floor(event.currentTime),
durationSeconds: Math.floor(event.duration),
};
void this.playbackPositions.savePlaybackPosition(
playback.contentInfo.playlistId,
position
);
this.updateEpisodePlaybackPosition(position);
}
showCopyNotification(): void {
this.snackBar.open(
this.translateService.instant('PORTALS.STREAM_URL_COPIED'),
null,
{
duration: 2000,
}
);
}
private addToRecentlyViewed(xtreamId: number): void {
this.xtreamStore.addRecentItem({
xtreamId,
contentType: 'series',
playlist: this.xtreamStore.currentPlaylist,
backdropUrl: this.selectedItem()?.info?.backdrop_path?.[0],
});
}
private startPlayback(playback: ResolvedPortalPlayback): void {
this.lastSaveTime = 0;
if (this.portalPlayer.isEmbeddedPlayer()) {
this.inlinePlayback.set(playback);
return;
}
this.closeInlinePlayer();
void this.portalPlayer.openResolvedPlayback(playback, true);
}
async handlePlaybackToggleRequested(
request: SeasonContainerPlaybackToggleRequest
): Promise<void> {
const playlistId = this.currentPlaylistId();
if (!playlistId) {
return;
}
if (request.nextPosition) {
await this.playbackPositions.savePlaybackPosition(
playlistId,
request.nextPosition
);
this.updateEpisodePlaybackPosition(request.nextPosition);
return;
}
await this.playbackPositions.clearPlaybackPosition(
playlistId,
request.contentXtreamId,
'episode'
);
this.removeEpisodePlaybackPosition(request.contentXtreamId);
}
private async loadSeriesPlaybackPositions(
playlistId: string,
seriesXtreamId: number
): Promise<void> {
const positions =
await this.playbackPositions.getSeriesPlaybackPositions(
playlistId,
seriesXtreamId
);
const positionsMap = new Map<number, PlaybackPositionData>();
positions.forEach((position) => {
positionsMap.set(position.contentXtreamId, position);
});
this.episodePlaybackPositions.set(positionsMap);
}
private updateEpisodePlaybackPosition(
position: PlaybackPositionData
): void {
const updated = new Map(this.episodePlaybackPositions());
updated.set(position.contentXtreamId, position);
this.episodePlaybackPositions.set(updated);
}
private removeEpisodePlaybackPosition(contentXtreamId: number): void {
const updated = new Map(this.episodePlaybackPositions());
updated.delete(contentXtreamId);
this.episodePlaybackPositions.set(updated);
}
private initializeSerialDetails(
playlistId: string,
categoryId: string | number,
serialId: string
): void {
this.xtreamStore.fetchSerialDetailsWithMetadata({
serialId,
categoryId: Number(categoryId),
});
const serialXtreamId = Number(serialId);
this.xtreamStore.checkFavoriteStatus(
serialXtreamId,
playlistId,
'series'
);
void this.loadSeriesPlaybackPositions(playlistId, serialXtreamId);
}
}
@@ -0,0 +1,177 @@
import { XtreamVodDetails, XtreamVodStream } from 'shared-interfaces';
import {
buildXtreamVodFallbackViewModel,
hasUsableXtreamVodMetadata,
} from './vod-details-fallback.util';
describe('vod-details-fallback.util', () => {
it('treats populated Xtream info as usable metadata', () => {
const vodDetails: XtreamVodDetails = {
info: {
kinopoisk_url: '',
tmdb_id: 1,
name: 'City of McFarland',
o_name: 'City of McFarland',
cover_big: 'https://example.com/poster.jpg',
movie_image: 'https://example.com/poster.jpg',
releasedate: '2015-02-20',
episode_run_time: 120,
youtube_trailer: '',
director: 'Niki Caro',
actors: 'Kevin Costner',
cast: 'Kevin Costner',
description: 'A real description',
plot: 'A real plot',
age: '',
mpaa_rating: '',
rating_count_kinopoisk: 0,
country: 'US',
genre: 'Drama',
backdrop_path: ['https://example.com/backdrop.jpg'],
duration_secs: 7200,
duration: '02:00:00',
video: ['H.264'],
audio: ['AAC'],
bitrate: 5000,
rating: 7.4,
rating_imdb: '7.4',
rating_kinopoisk: '7.4',
},
movie_data: {
stream_id: 678140,
name: 'City of McFarland (2015) DE',
added: '1750671180',
category_id: '235',
container_extension: 'mkv',
custom_sid: null,
direct_source: '',
},
};
expect(hasUsableXtreamVodMetadata(vodDetails)).toBe(true);
});
it('builds a curated fallback model when Xtream returns info as an empty array', () => {
const catalogItem = {
name: 'Die Kühe sind Los! (2004) DE',
stream_id: 650020,
stream_icon: 'https://example.com/cows.jpg',
added: '1720000000',
category_id: '235',
container_extension: 'mp4',
rating: 6.1,
rating_imdb: '6.1',
} satisfies Partial<XtreamVodStream>;
const fallback = buildXtreamVodFallbackViewModel({
vodDetails: { info: [] },
catalogItem,
category: {
category_id: '235',
category_name: 'DE | DISNEY',
},
vodId: 650020,
});
expect(hasUsableXtreamVodMetadata({ info: [] })).toBe(false);
expect(fallback).toEqual({
added: '2024-07-03',
facts: [
{
labelKey: 'XTREAM.DETAIL_FALLBACK.STREAM_ID',
monospace: true,
value: '650020',
},
{
labelKey: 'XTREAM.DETAIL_FALLBACK.CATEGORY',
value: 'DE | DISNEY',
},
{
labelKey: 'XTREAM.DETAIL_FALLBACK.CONTAINER',
monospace: true,
value: 'MP4',
},
],
format: 'MP4',
posterUrl: 'https://example.com/cows.jpg',
rating: '6.1',
title: 'Die Kühe sind Los! (2004) DE',
year: '2004',
});
});
it('falls back to the route id when movie_data and catalog context are missing', () => {
const fallback = buildXtreamVodFallbackViewModel({
vodDetails: {
info: [],
} as XtreamVodDetails,
vodId: 650021,
});
expect(fallback).toEqual({
added: undefined,
facts: [
{
labelKey: 'XTREAM.DETAIL_FALLBACK.STREAM_ID',
monospace: true,
value: '650021',
},
],
format: undefined,
posterUrl: undefined,
rating: undefined,
title: 'VOD 650021',
year: undefined,
});
});
it('uses preserved catalog fields from the selected item when the details payload is sparse', () => {
const fallback = buildXtreamVodFallbackViewModel({
vodDetails: {
info: [],
xtream_id: 20000,
title: "Ain't No Sunshine: venia turbo",
poster_url: 'https://example.com/sunshine.jpg',
rating_imdb: '7.7',
added: '1743984000',
container_extension: 'avi',
} as XtreamVodDetails & {
added?: string;
container_extension?: string;
poster_url?: string;
rating_imdb?: string;
title?: string;
xtream_id?: number;
},
category: {
category_name: 'Action',
},
vodId: 20000,
});
expect(fallback).toEqual({
added: '2025-04-07',
facts: [
{
labelKey: 'XTREAM.DETAIL_FALLBACK.STREAM_ID',
monospace: true,
value: '20000',
},
{
labelKey: 'XTREAM.DETAIL_FALLBACK.CATEGORY',
value: 'Action',
},
{
labelKey: 'XTREAM.DETAIL_FALLBACK.CONTAINER',
monospace: true,
value: 'AVI',
},
],
format: 'AVI',
posterUrl: 'https://example.com/sunshine.jpg',
rating: '7.7',
title: "Ain't No Sunshine: venia turbo",
year: undefined,
});
});
});
@@ -0,0 +1,235 @@
import {
XtreamVodDetails,
XtreamVodInfo,
XtreamVodStream,
getXtreamVodInfo,
} from 'shared-interfaces';
type XtreamCategoryContext = {
readonly id?: string | number;
readonly name?: string;
readonly category_id?: string | number;
readonly category_name?: string;
};
type XtreamVodCatalogContext = Partial<XtreamVodStream> & {
readonly added_at?: string | number;
readonly id?: string | number;
readonly poster_url?: string;
readonly title?: string;
readonly xtream_id?: string | number;
};
type XtreamVodDetailsContext = XtreamVodDetails &
Partial<XtreamVodStream> & {
readonly added_at?: string | number;
readonly id?: string | number;
readonly poster_url?: string;
readonly title?: string;
readonly xtream_id?: string | number;
};
export interface XtreamVodFallbackFact {
readonly labelKey: string;
readonly monospace?: boolean;
readonly value: string;
}
export interface XtreamVodFallbackViewModel {
readonly added?: string;
readonly facts: XtreamVodFallbackFact[];
readonly format?: string;
readonly posterUrl?: string;
readonly rating?: string;
readonly title: string;
readonly year?: string;
}
export interface XtreamVodFallbackOptions {
readonly category?: XtreamCategoryContext | null;
readonly catalogItem?: XtreamVodCatalogContext | null;
readonly vodDetails?: XtreamVodDetails | null;
readonly vodId: number;
}
export function hasUsableXtreamVodMetadata(
vodDetails: XtreamVodDetails | null | undefined
): vodDetails is XtreamVodDetails & { info: XtreamVodInfo } {
const info = getXtreamVodInfo(vodDetails);
if (!info) {
return false;
}
return Boolean(
info.description ||
info.plot ||
info.movie_image ||
info.cover_big ||
info.genre ||
info.releasedate ||
info.duration ||
info.duration_secs ||
info.country ||
info.director ||
info.actors ||
info.cast ||
info.youtube_trailer ||
info.rating_imdb ||
info.rating_kinopoisk ||
info.backdrop_path?.length
);
}
export function buildXtreamVodFallbackViewModel(
options: XtreamVodFallbackOptions
): XtreamVodFallbackViewModel | null {
const detailItem = options.vodDetails as XtreamVodDetailsContext | null;
const info = getXtreamVodInfo(detailItem);
const movieData = detailItem?.movie_data;
const catalogItem = options.catalogItem;
const categoryName =
options.category?.name ?? options.category?.category_name;
const streamId =
movieData?.stream_id ??
numericValue(detailItem?.xtream_id) ??
numericValue(detailItem?.stream_id) ??
numericValue(detailItem?.id) ??
numericValue(catalogItem?.xtream_id) ??
numericValue(catalogItem?.stream_id) ??
numericValue(catalogItem?.id) ??
options.vodId;
const sourceTitle =
sanitizeText(detailItem?.title) ??
sanitizeText(detailItem?.name) ??
sanitizeText(catalogItem?.title) ??
sanitizeText(catalogItem?.name);
const title =
sanitizeText(movieData?.name) ??
sourceTitle ??
sanitizeText(info?.name) ??
`VOD ${streamId}`;
const posterUrl =
sanitizeText(detailItem?.poster_url) ??
sanitizeText(detailItem?.stream_icon) ??
sanitizeText(catalogItem?.poster_url) ??
sanitizeText(catalogItem?.stream_icon) ??
sanitizeText(info?.movie_image) ??
sanitizeText(info?.cover_big) ??
undefined;
const rating =
sanitizeText(detailItem?.rating_imdb) ??
formatRating(detailItem?.rating) ??
sanitizeText(catalogItem?.rating_imdb) ??
formatRating(catalogItem?.rating);
const added = formatUnixDate(
movieData?.added ??
detailItem?.added_at ??
detailItem?.added ??
catalogItem?.added_at ??
catalogItem?.added
);
const format = sanitizeText(
movieData?.container_extension ??
detailItem?.container_extension ??
catalogItem?.container_extension
)?.toUpperCase();
const year = extractYear(info?.releasedate) ?? extractYear(title);
const facts: XtreamVodFallbackFact[] = [
{
labelKey: 'XTREAM.DETAIL_FALLBACK.STREAM_ID',
monospace: true,
value: String(streamId),
},
];
if (categoryName) {
facts.push({
labelKey: 'XTREAM.DETAIL_FALLBACK.CATEGORY',
value: categoryName,
});
}
if (format) {
facts.push({
labelKey: 'XTREAM.DETAIL_FALLBACK.CONTAINER',
monospace: true,
value: format,
});
}
if (sourceTitle && sourceTitle !== title) {
facts.push({
labelKey: 'XTREAM.DETAIL_FALLBACK.SOURCE_TITLE',
value: sourceTitle,
});
}
return {
added,
facts,
format,
posterUrl,
rating,
title,
year,
};
}
function sanitizeText(value: unknown): string | undefined {
if (typeof value !== 'string') {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function numericValue(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string' && value.trim().length > 0) {
const parsed = Number.parseInt(value, 10);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return undefined;
}
function formatRating(value: unknown): string | undefined {
if (typeof value === 'number' && Number.isFinite(value)) {
return value.toFixed(1);
}
if (typeof value === 'string' && value.trim().length > 0) {
return value.trim();
}
return undefined;
}
function extractYear(value: string | undefined): string | undefined {
if (!value) {
return undefined;
}
const yearMatch = value.match(/\b(19|20)\d{2}\b/);
return yearMatch?.[0];
}
function formatUnixDate(value: unknown): string | undefined {
const seconds = numericValue(value);
if (!seconds) {
return undefined;
}
try {
return new Date(seconds * 1000).toISOString().slice(0, 10);
} catch {
return undefined;
}
}
@@ -0,0 +1,235 @@
@let item = selectedItem();
@if (selectedVodInfo(); as info) {
<app-content-hero
[title]="info.name || item?.movie_data?.name"
[description]="info.description || info.plot"
[posterUrl]="info.movie_image || info.cover_big"
[backdropUrl]="info.backdrop_path?.[0]"
(backClicked)="goBack()"
>
<ng-container hero-tags>
@if (info.releasedate) {
<span class="details__tag">{{
info.releasedate | slice: 0 : 4
}}</span>
}
@if (info.genre) {
<span class="details__tag">{{ info.genre }}</span>
}
@if (info.duration) {
<span class="details__tag">{{ info.duration }}</span>
}
@if (info.rating_imdb) {
<span class="details__tag details__tag--rating">
⭐ {{ info.rating_imdb }}
</span>
}
@if (info.country) {
<span class="details__tag">{{ info.country }}</span>
}
</ng-container>
<ng-container hero-meta>
@if (info.actors || info.cast) {
<div class="details__meta-item">
<span class="label">{{ 'XTREAM.ACTORS' | translate }}</span>
<span class="value">{{ info.actors || info.cast }}</span>
</div>
}
@if (info.director) {
<div class="details__meta-item">
<span class="label">{{
'XTREAM.DIRECTOR' | translate
}}</span>
<span class="value">{{ info.director }}</span>
</div>
}
@if (info.rating_kinopoisk) {
<div class="details__meta-item">
<span class="label">{{
'XTREAM.KINOPOISK_RATING' | translate
}}</span>
<span class="value">{{ info.rating_kinopoisk }}</span>
</div>
}
</ng-container>
<ng-container hero-actions>
@if (hasPlaybackPosition()) {
<button
class="play-btn play-btn--resume"
(click)="onPrimaryAction(item)"
[disabled]="isExternalLaunchPending()"
[class.play-btn--state-launching]="externalPrimaryButtonState() === 'launching'"
[class.play-btn--state-stop]="externalPrimaryButtonState() === 'stop'"
>
<span class="play-btn__icon-shell" aria-hidden="true">
<mat-icon class="play-btn__icon">{{
externalPrimaryIcon()
}}</mat-icon>
</span>
<span class="play-btn__label">
@if (externalPrimaryLabel(); as label) {
{{ label }}
} @else {
{{ 'XTREAM.RESUME' | translate }}
{{ formatPosition() }}
}
</span>
</button>
@if (!isExternalStopAction()) {
<button
class="play-btn play-btn--restart"
(click)="playVod(item)"
>
<mat-icon>replay</mat-icon>
{{ 'XTREAM.RESTART' | translate }}
</button>
}
} @else {
<button
class="play-btn"
(click)="onPrimaryAction(item)"
[disabled]="isExternalLaunchPending()"
[class.play-btn--state-launching]="externalPrimaryButtonState() === 'launching'"
[class.play-btn--state-stop]="externalPrimaryButtonState() === 'stop'"
>
<span class="play-btn__icon-shell" aria-hidden="true">
<mat-icon class="play-btn__icon">{{
externalPrimaryIcon()
}}</mat-icon>
</span>
<span class="play-btn__label">
@if (externalPrimaryLabel(); as label) {
{{ label }}
} @else {
{{ 'XTREAM.PLAY' | translate }}
}
</span>
</button>
}
@if (!isFavorite()) {
<button class="favorite-btn" (click)="toggleFavorite()">
<mat-icon>add</mat-icon>
{{ 'PORTALS.ADD_TO_FAVORITES' | translate }}
</button>
} @else {
<button
class="favorite-btn favorite-btn--active"
(click)="toggleFavorite()"
>
<mat-icon>check</mat-icon>
{{ 'PORTALS.REMOVE_FROM_FAVORITES' | translate }}
</button>
}
@if (isElectron()) {
@if (isDownloaded()) {
<button
class="download-btn download-btn--completed"
(click)="playFromLocal()"
>
<mat-icon>play_circle</mat-icon>
{{ 'DOWNLOADS.PLAY_LOCAL' | translate }}
</button>
} @else if (isDownloading()) {
<button
class="download-btn download-btn--downloading"
disabled
>
<mat-icon>downloading</mat-icon>
{{ 'DOWNLOADS.STATUS.DOWNLOADING' | translate }}
</button>
} @else {
<button class="download-btn" (click)="downloadVod(item)">
<mat-icon>download</mat-icon>
{{ 'DOWNLOADS.DOWNLOAD' | translate }}
</button>
}
}
</ng-container>
@if (inlinePlayback(); as playback) {
<app-portal-inline-player
[playback]="playback"
(timeUpdate)="handleInlineTimeUpdate($event)"
(closed)="closeInlinePlayer()"
(streamUrlCopied)="showCopyNotification()"
/>
}
@if (info.youtube_trailer) {
<div class="youtube-trailer">
<h3>{{ 'XTREAM.YOUTUBE_TRAILER' | translate }}</h3>
<div class="trailer-wrapper">
<iframe
[src]="
'https://www.youtube.com/embed/' +
info.youtube_trailer | safe
"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
</div>
</div>
}
</app-content-hero>
} @else if (fallbackView(); as fallback) {
<app-content-hero
[title]="fallback.title"
[posterUrl]="fallback.posterUrl"
(backClicked)="goBack()"
>
<ng-container hero-tags>
<span
class="details__tag details__tag--status"
data-testid="xtream-vod-fallback-status"
>
{{ 'XTREAM.DETAIL_FALLBACK.STATUS' | translate }}
</span>
@if (fallback.year) {
<span class="details__tag">{{ fallback.year }}</span>
}
@if (fallback.rating) {
<span class="details__tag details__tag--rating">
⭐ {{ fallback.rating }}
</span>
}
@if (fallback.added) {
<span class="details__tag">{{ fallback.added }}</span>
}
@if (fallback.format) {
<span class="details__tag">{{ fallback.format }}</span>
}
</ng-container>
<ng-container hero-meta>
<div
class="details__fallback-note"
data-testid="xtream-vod-fallback"
>
{{ 'XTREAM.DETAIL_FALLBACK.NOTE' | translate }}
</div>
@for (fact of fallback.facts; track fact.labelKey) {
<div class="details__meta-item details__meta-item--fallback">
<span class="label">{{ fact.labelKey | translate }}</span>
<span
class="value"
[class.value--mono]="fact.monospace"
>
{{ fact.value }}
</span>
</div>
}
</ng-container>
</app-content-hero>
} @else if (detailsError()) {
<app-content-hero
[errorMessage]="detailsError()"
(backClicked)="goBack()"
/>
} @else {
<app-content-hero [isLoading]="true" (backClicked)="goBack()" />
}
@@ -0,0 +1,45 @@
:host {
display: block;
width: 100%;
height: 100%;
min-height: 0;
::ng-deep .details__tag--status {
color: var(--text-primary);
border-color: color-mix(in srgb, var(--accent-color) 28%, transparent);
background: linear-gradient(
135deg,
color-mix(in srgb, var(--accent-color) 12%, transparent) 0%,
var(--tag-bg) 100%
);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);
}
::ng-deep .details__fallback-note {
flex: 1 0 100%;
margin-bottom: 4px;
padding: 14px 16px;
border: 1px solid color-mix(in srgb, var(--tag-border) 85%, transparent);
border-radius: 14px;
background: linear-gradient(
180deg,
color-mix(in srgb, var(--surface-bg) 86%, transparent) 0%,
color-mix(in srgb, var(--tag-bg) 86%, transparent) 100%
);
color: var(--text-secondary);
line-height: 1.5;
backdrop-filter: blur(14px);
}
::ng-deep .details__meta-item--fallback {
min-width: min(220px, 100%);
.value--mono {
font-family:
ui-monospace, 'SFMono-Regular', 'SF Mono', Menlo, Consolas,
monospace;
font-size: 0.8125rem;
letter-spacing: 0.03em;
}
}
}
@@ -0,0 +1,254 @@
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import { Location } from '@angular/common';
import {
PORTAL_EXTERNAL_PLAYBACK,
PORTAL_PLAYBACK_POSITIONS,
PORTAL_PLAYER,
} from '@iptvnator/portal/shared/util';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import {
XtreamCategory,
XtreamVodDetails,
XtreamVodStream,
} from 'shared-interfaces';
import { DownloadsService, SettingsStore } from 'services';
import { MatSnackBar } from '@angular/material/snack-bar';
import { VodDetailsRouteComponent } from './vod-details-route.component';
describe('VodDetailsRouteComponent', () => {
let fixture: ComponentFixture<VodDetailsRouteComponent>;
const selectedItem = signal<XtreamVodDetails | null>(null);
const isLoadingDetails = signal(false);
const detailsError = signal<string | null>(null);
const isFavorite = signal(false);
const currentPlaylist = signal<{
id: string;
userAgent?: string;
referrer?: string;
origin?: string;
} | null>(null);
const vodStreams = signal<Partial<XtreamVodStream>[]>([]);
const vodCategories = signal<Partial<XtreamCategory>[]>([]);
const fetchVodDetailsWithMetadata = jest.fn();
const checkFavoriteStatus = jest.fn();
const setSelectedItem = jest.fn();
const toggleFavorite = jest.fn();
const constructVodStreamUrl = jest.fn().mockReturnValue(
'http://example.com/movie/650020.mp4'
);
const addRecentItem = jest.fn();
const downloads = signal([]);
const getPlaybackPosition = jest.fn().mockResolvedValue(null);
beforeEach(async () => {
selectedItem.set(null);
isLoadingDetails.set(false);
detailsError.set(null);
isFavorite.set(false);
currentPlaylist.set(null);
vodStreams.set([]);
vodCategories.set([]);
fetchVodDetailsWithMetadata.mockClear();
checkFavoriteStatus.mockClear();
setSelectedItem.mockClear();
toggleFavorite.mockClear();
constructVodStreamUrl.mockClear();
addRecentItem.mockClear();
getPlaybackPosition.mockClear();
await TestBed.configureTestingModule({
imports: [VodDetailsRouteComponent],
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: {
vodId: '650020',
categoryId: '235',
},
},
},
},
{
provide: TranslateService,
useValue: {
instant: (key: string) => key,
get: (key: string) => of(key),
stream: (key: string) => of(key),
onLangChange: of(null),
onTranslationChange: of(null),
onDefaultLangChange: of(null),
currentLang: 'en',
defaultLang: 'en',
},
},
{
provide: XtreamStore,
useValue: {
selectedItem,
isLoadingDetails,
detailsError,
isFavorite,
currentPlaylist,
vodStreams,
vodCategories,
fetchVodDetailsWithMetadata,
checkFavoriteStatus,
setSelectedItem,
toggleFavorite,
constructVodStreamUrl,
addRecentItem,
},
},
{
provide: SettingsStore,
useValue: {
theme: signal('dark'),
},
},
{
provide: DownloadsService,
useValue: {
isAvailable: signal(false),
downloads,
isDownloaded: jest.fn().mockReturnValue(false),
isDownloading: jest.fn().mockReturnValue(false),
startDownload: jest.fn(),
getDownloadedFilePath: jest.fn(),
playDownload: jest.fn(),
},
},
{
provide: PORTAL_EXTERNAL_PLAYBACK,
useValue: {
activeSession: signal(null),
closeSession: jest.fn(),
},
},
{
provide: PORTAL_PLAYBACK_POSITIONS,
useValue: {
getPlaybackPosition,
savePlaybackPosition: jest.fn().mockResolvedValue(undefined),
},
},
{
provide: PORTAL_PLAYER,
useValue: {
isEmbeddedPlayer: jest.fn().mockReturnValue(false),
openResolvedPlayback: jest.fn(),
},
},
{
provide: MatSnackBar,
useValue: {
open: jest.fn(),
},
},
{
provide: Location,
useValue: {
back: jest.fn(),
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(VodDetailsRouteComponent);
});
it('renders an informational fallback without playback controls when Xtream returns empty metadata', () => {
selectedItem.set({
info: [],
} as XtreamVodDetails);
vodStreams.set([
{
name: 'Die Kühe sind Los! (2004) DE',
stream_id: 650020,
stream_icon: 'https://example.com/cows.jpg',
added: '1720000000',
category_id: '235',
container_extension: 'mp4',
rating: 6.1,
rating_imdb: '6.1',
},
]);
vodCategories.set([
{
category_id: '235',
category_name: 'DE | DISNEY',
},
]);
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
expect(host.textContent).toContain('Die Kühe sind Los! (2004) DE');
expect(
host.querySelector('[data-testid="xtream-vod-fallback"]')?.textContent
).toContain('XTREAM.DETAIL_FALLBACK.NOTE');
expect(
host.querySelector('[data-testid="xtream-vod-fallback-status"]')
?.textContent
).toContain('XTREAM.DETAIL_FALLBACK.STATUS');
expect(host.querySelector('button.play-btn')).toBeNull();
expect(host.querySelector('button.favorite-btn')).toBeNull();
expect(host.querySelector('button.download-btn')).toBeNull();
});
it('keeps the full Xtream detail view when usable metadata exists', () => {
selectedItem.set({
info: {
kinopoisk_url: '',
tmdb_id: 228203,
name: 'City of McFarland (2015)',
o_name: 'City of McFarland (2015)',
cover_big: 'https://example.com/poster-big.jpg',
movie_image: 'https://example.com/poster.jpg',
releasedate: '2015-02-20',
episode_run_time: 129,
youtube_trailer: '',
director: 'Niki Caro',
actors: 'Kevin Costner',
cast: 'Kevin Costner',
description: 'A populated description',
plot: 'A populated plot',
age: '',
mpaa_rating: '',
rating_count_kinopoisk: 0,
country: 'English',
genre: 'Drama',
backdrop_path: ['https://example.com/backdrop.jpg'],
duration_secs: 7744,
duration: '02:09:04',
video: ['H.264'],
audio: ['AAC'],
bitrate: 6251,
rating: 7.455,
rating_imdb: '7.455',
rating_kinopoisk: '7.455',
},
movie_data: {
stream_id: 678140,
name: 'City of McFarland (2015) DE',
added: '1750671180',
category_id: '235',
container_extension: 'mkv',
custom_sid: null,
direct_source: '',
},
});
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
expect(host.textContent).toContain('City of McFarland (2015)');
expect(host.querySelector('[data-testid="xtream-vod-fallback"]')).toBeNull();
expect(host.querySelector('button.play-btn')).not.toBeNull();
});
});
@@ -0,0 +1,552 @@
import { Location, SlicePipe } from '@angular/common';
import {
Component,
OnDestroy,
OnInit,
computed,
effect,
inject,
signal,
} from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ContentHeroComponent } from 'components';
import { SafePipe } from '@iptvnator/pipes';
import {
PORTAL_EXTERNAL_PLAYBACK,
PORTAL_PLAYBACK_POSITIONS,
PORTAL_PLAYER,
createLogger,
getPortalPlaybackProgressPercent,
} from '@iptvnator/portal/shared/util';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
import { PortalInlinePlayerComponent } from '@iptvnator/ui/playback';
import { DownloadsService, SettingsStore } from 'services';
import {
PlaybackPositionData,
PlayerContentInfo,
ResolvedPortalPlayback,
XtreamCategory,
XtreamVodDetails,
XtreamVodStream,
getXtreamVodInfo,
} from 'shared-interfaces';
import {
buildXtreamVodFallbackViewModel,
hasUsableXtreamVodMetadata,
} from './vod-details-fallback.util';
@Component({
templateUrl: './vod-details-route.component.html',
styleUrls: [
'../../../../../../ui/components/src/lib/styles/detail-view.scss',
'./vod-details-route.component.scss',
],
imports: [
ContentHeroComponent,
MatIcon,
SafePipe,
SlicePipe,
TranslateModule,
PortalInlinePlayerComponent,
],
})
export class VodDetailsRouteComponent implements OnInit, OnDestroy {
private readonly location = inject(Location);
private readonly settingsStore = inject(SettingsStore);
private readonly route = inject(ActivatedRoute);
private readonly xtreamStore = inject(XtreamStore);
private readonly playbackPositions = inject(PORTAL_PLAYBACK_POSITIONS);
private readonly downloadsService = inject(DownloadsService);
private readonly externalPlayback = inject(PORTAL_EXTERNAL_PLAYBACK);
private readonly portalPlayer = inject(PORTAL_PLAYER);
private readonly snackBar = inject(MatSnackBar);
private readonly translateService = inject(TranslateService);
private readonly logger = createLogger('VodDetailsRoute');
private readonly detailsInitDone = signal(false);
private readonly backdropBackfillKey = signal<string | null>(null);
readonly inlinePlayback = signal<ResolvedPortalPlayback | null>(null);
readonly vodPlaybackPosition = signal<PlaybackPositionData | null>(null);
readonly theme = this.settingsStore.theme;
readonly isElectron = this.downloadsService.isAvailable;
readonly isFavorite = this.xtreamStore.isFavorite;
readonly selectedItem = computed(
() =>
this.xtreamStore.selectedItem() as unknown as XtreamVodDetails | null
);
readonly selectedVodId = computed(() =>
Number(this.route.snapshot.params.vodId)
);
readonly selectedCategory = computed<Partial<XtreamCategory> | null>(() => {
const categoryId = this.route.snapshot.params.categoryId;
if (!categoryId) {
return null;
}
return (
this.xtreamStore
.vodCategories()
.find(
(category) =>
String(
(category as XtreamCategory & { id?: string | number })
.category_id ??
(category as XtreamCategory & { id?: string | number })
.id
) === String(categoryId)
) ?? null
);
});
readonly selectedCatalogItem = computed<
(Partial<XtreamVodStream> & {
id?: string | number;
poster_url?: string;
title?: string;
xtream_id?: string | number;
}) | null
>(() => {
const vodId = this.selectedVodId();
if (!Number.isFinite(vodId) || vodId <= 0) {
return null;
}
return (
this.xtreamStore
.vodStreams()
.find(
(item) =>
Number(
(
item as XtreamVodStream & {
id?: string | number;
xtream_id?: string | number;
}
).xtream_id ??
(
item as XtreamVodStream & {
id?: string | number;
}
).stream_id ??
(
item as XtreamVodStream & {
id?: string | number;
}
).id
) === vodId
) ?? null
);
});
readonly selectedVodInfo = computed(() => {
const item = this.selectedItem();
return item && hasUsableXtreamVodMetadata(item)
? getXtreamVodInfo(item)
: null;
});
readonly fallbackView = computed(() => {
const item = this.selectedItem();
if (!item || this.selectedVodInfo()) {
return null;
}
return buildXtreamVodFallbackViewModel({
vodDetails: item,
catalogItem: this.selectedCatalogItem(),
category: this.selectedCategory(),
vodId: this.selectedVodId(),
});
});
readonly isLoadingDetails = this.xtreamStore.isLoadingDetails;
readonly detailsError = this.xtreamStore.detailsError;
private lastSaveTime = 0;
private unsubscribePositionUpdates: (() => void) | null = null;
readonly matchedExternalPlayback = computed(() => {
const session = this.externalPlayback.activeSession();
const vodId = Number(this.route.snapshot.params.vodId);
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (
!session?.contentInfo ||
!playlistId ||
session.status === 'error' ||
session.status === 'closed'
) {
return null;
}
const contentInfo = session.contentInfo;
if (
contentInfo.playlistId !== playlistId ||
contentInfo.contentType !== 'vod' ||
contentInfo.contentXtreamId !== vodId
) {
return null;
}
return session;
});
readonly externalPrimaryLabel = computed(() => {
const session = this.matchedExternalPlayback();
if (!session) {
return null;
}
const player = session.player.toUpperCase();
switch (session.status) {
case 'launching':
return `Opening in ${player}...`;
case 'opened':
case 'playing':
return `Stop ${player}`;
default:
return null;
}
});
readonly externalPrimaryIcon = computed(() => {
const session = this.matchedExternalPlayback();
switch (session?.status) {
case 'launching':
return 'hourglass_top';
case 'opened':
case 'playing':
return 'stop_circle';
default:
return 'play_arrow';
}
});
readonly isExternalLaunchPending = computed(
() => this.matchedExternalPlayback()?.status === 'launching'
);
readonly isExternalStopAction = computed(() => {
const status = this.matchedExternalPlayback()?.status;
return status === 'opened' || status === 'playing';
});
readonly externalPrimaryButtonState = computed(() => {
if (this.isExternalLaunchPending()) {
return 'launching';
}
return this.isExternalStopAction() ? 'stop' : 'idle';
});
readonly vodPlaybackProgress = computed(() =>
getPortalPlaybackProgressPercent(this.vodPlaybackPosition())
);
readonly hasPlaybackPosition = computed(() => {
const inProgress =
this.vodPlaybackProgress() > 0 && this.vodPlaybackProgress() < 90;
this.logger.debug('hasPlaybackPosition check', {
vodId: this.route.snapshot.params.vodId,
inProgress,
});
return inProgress;
});
readonly isDownloaded = computed(() => {
const vodId = Number(this.route.snapshot.params.vodId);
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (!playlistId) return false;
this.downloadsService.downloads();
return this.downloadsService.isDownloaded(vodId, playlistId, 'vod');
});
readonly isDownloading = computed(() => {
const vodId = Number(this.route.snapshot.params.vodId);
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (!playlistId) return false;
this.downloadsService.downloads();
return this.downloadsService.isDownloading(vodId, playlistId, 'vod');
});
constructor() {
effect(() => {
const playlistId = this.xtreamStore.currentPlaylist()?.id;
const vodId = Number(this.route.snapshot.params.vodId);
if (!playlistId || this.detailsInitDone()) return;
this.initializeVodDetails(playlistId, vodId);
this.detailsInitDone.set(true);
});
effect(() => {
const playlistId = this.xtreamStore.currentPlaylist()?.id;
const vodId = Number(this.route.snapshot.params.vodId);
const backdropUrl = this.selectedVodInfo()?.backdrop_path?.[0]?.trim();
if (!playlistId || !Number.isFinite(vodId) || vodId <= 0 || !backdropUrl) {
return;
}
const backfillKey = `${playlistId}:${vodId}:${backdropUrl}`;
if (this.backdropBackfillKey() === backfillKey) {
return;
}
this.backdropBackfillKey.set(backfillKey);
void this.xtreamStore.backfillContentBackdrop({
xtreamId: vodId,
contentType: 'movie',
playlist: this.xtreamStore.currentPlaylist,
backdropUrl,
});
});
if (window.electron?.onPlaybackPositionUpdate) {
this.unsubscribePositionUpdates =
window.electron.onPlaybackPositionUpdate(
(data: PlaybackPositionData) => {
const playlistId = this.xtreamStore.currentPlaylist()?.id;
const vodId = Number(this.route.snapshot.params.vodId);
if (
data.contentType !== 'vod' ||
data.playlistId !== playlistId ||
data.contentXtreamId !== vodId
) {
return;
}
this.vodPlaybackPosition.set(data);
}
);
}
}
ngOnInit(): void {
const currentPlaylist = this.xtreamStore.currentPlaylist();
if (!currentPlaylist?.id) {
this.logger.warn('Deferring VOD details init: playlist not ready');
return;
}
this.initializeVodDetails(currentPlaylist.id, Number(this.route.snapshot.params.vodId));
this.detailsInitDone.set(true);
}
ngOnDestroy(): void {
this.inlinePlayback.set(null);
this.unsubscribePositionUpdates?.();
this.xtreamStore.setSelectedItem(null);
}
playVod(vodItem: XtreamVodDetails): void {
const info = getXtreamVodInfo(vodItem);
this.addToRecentlyViewed();
const streamUrl = this.xtreamStore.constructVodStreamUrl(vodItem);
const routeVodId = this.route.snapshot.params.vodId;
const id = routeVodId
? Number(routeVodId)
: Number(
vodItem.movie_data?.stream_id ||
(vodItem as { stream_id?: number }).stream_id
);
this.logger.debug('playVod resolved ID', { id, vodItem });
const contentInfo: PlayerContentInfo = {
playlistId: this.xtreamStore.currentPlaylist().id,
contentXtreamId: id,
contentType: 'vod',
};
const playback: ResolvedPortalPlayback = {
streamUrl,
title: info?.name ?? vodItem.movie_data?.name,
thumbnail: info?.movie_image,
contentInfo,
};
this.startPlayback(playback);
}
resumeVod(vodItem: XtreamVodDetails): void {
const info = getXtreamVodInfo(vodItem);
this.addToRecentlyViewed();
const vodId = Number(this.route.snapshot.params.vodId);
const position = this.vodPlaybackPosition();
const streamUrl = this.xtreamStore.constructVodStreamUrl(vodItem);
const contentInfo: PlayerContentInfo = {
playlistId: this.xtreamStore.currentPlaylist().id,
contentXtreamId: vodId,
contentType: 'vod',
};
const playback: ResolvedPortalPlayback = {
streamUrl,
title: info?.name ?? vodItem.movie_data?.name,
thumbnail: info?.movie_image,
startTime: position?.positionSeconds,
contentInfo,
};
this.startPlayback(playback);
}
onPrimaryAction(vodItem: XtreamVodDetails): void {
if (this.isExternalStopAction()) {
void this.stopExternalPlayback();
return;
}
if (this.hasPlaybackPosition()) {
this.resumeVod(vodItem);
return;
}
this.playVod(vodItem);
}
async stopExternalPlayback(): Promise<void> {
await this.externalPlayback.closeSession(this.matchedExternalPlayback());
}
formatPosition(): string {
const position = this.vodPlaybackPosition();
if (!position) return '';
const date = new Date(0);
date.setSeconds(position.positionSeconds);
const timeString = date.toISOString().substr(11, 8);
return timeString.startsWith('00:')
? timeString.substr(3)
: timeString;
}
toggleFavorite(): void {
this.xtreamStore.toggleFavorite(
this.route.snapshot.params.vodId,
this.xtreamStore.currentPlaylist().id,
'movie',
this.selectedVodInfo()?.backdrop_path?.[0]
);
}
goBack(): void {
this.closeInlinePlayer();
this.location.back();
}
closeInlinePlayer(): void {
this.inlinePlayback.set(null);
this.lastSaveTime = 0;
}
handleInlineTimeUpdate(event: {
currentTime: number;
duration: number;
}): void {
const playback = this.inlinePlayback();
if (!playback?.contentInfo) return;
const now = Date.now();
if (now - this.lastSaveTime <= 15000) return;
this.lastSaveTime = now;
const position: PlaybackPositionData = {
...playback.contentInfo,
positionSeconds: Math.floor(event.currentTime),
durationSeconds: Math.floor(event.duration),
};
void this.playbackPositions.savePlaybackPosition(
playback.contentInfo.playlistId,
position
);
this.vodPlaybackPosition.set(position);
}
showCopyNotification(): void {
this.snackBar.open(
this.translateService.instant('PORTALS.STREAM_URL_COPIED'),
null,
{
duration: 2000,
}
);
}
async downloadVod(vodItem: XtreamVodDetails): Promise<void> {
const info = getXtreamVodInfo(vodItem);
const streamUrl = this.xtreamStore.constructVodStreamUrl(vodItem);
const routeVodId = this.route.snapshot.params.vodId;
const id = routeVodId
? Number(routeVodId)
: Number(
vodItem.movie_data?.stream_id ||
(vodItem as { stream_id?: number }).stream_id
);
const playlist = this.xtreamStore.currentPlaylist();
await this.downloadsService.startDownload({
playlistId: playlist.id,
xtreamId: id,
contentType: 'vod',
title: info?.name ?? vodItem.movie_data?.name ?? 'Unknown',
url: streamUrl,
posterUrl: info?.movie_image,
headers: {
userAgent: playlist.userAgent,
referer: playlist.referrer,
origin: playlist.origin,
},
});
}
async playFromLocal(): Promise<void> {
const vodId = Number(this.route.snapshot.params.vodId);
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (!playlistId) return;
const filePath = this.downloadsService.getDownloadedFilePath(
vodId,
playlistId,
'vod'
);
if (filePath) {
await this.downloadsService.playDownload(filePath);
}
}
private addToRecentlyViewed(): void {
this.xtreamStore.addRecentItem({
xtreamId: Number(this.route.snapshot.params.vodId),
contentType: 'movie',
playlist: this.xtreamStore.currentPlaylist,
backdropUrl: this.selectedVodInfo()?.backdrop_path?.[0],
});
}
private initializeVodDetails(playlistId: string, vodId: number): void {
const { categoryId } = this.route.snapshot.params;
this.xtreamStore.fetchVodDetailsWithMetadata({
vodId: String(vodId),
categoryId,
});
this.xtreamStore.checkFavoriteStatus(vodId, playlistId, 'movie');
void this.loadVodPlaybackPosition(playlistId, vodId);
}
private startPlayback(playback: ResolvedPortalPlayback): void {
this.lastSaveTime = 0;
if (this.portalPlayer.isEmbeddedPlayer()) {
this.inlinePlayback.set(playback);
return;
}
this.closeInlinePlayer();
void this.portalPlayer.openResolvedPlayback(playback, true);
}
private async loadVodPlaybackPosition(
playlistId: string,
vodId: number
): Promise<void> {
const position = await this.playbackPositions.getPlaybackPosition(
playlistId,
vodId,
'vod'
);
this.vodPlaybackPosition.set(position);
}
}
@@ -0,0 +1,81 @@
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { TranslatePipe } from '@ngx-translate/core';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
@Component({
selector: 'app-xtream-cached-offline-notice',
imports: [MatIconModule, TranslatePipe],
template: `
@if (showWarning()) {
<div
class="xtream-cached-offline-notice"
data-test-id="xtream-offline-warning"
data-testid="xtream-offline-warning"
>
<mat-icon>cloud_off</mat-icon>
<div class="xtream-cached-offline-notice__copy">
<strong>
{{
'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.TITLE'
| translate
}}
</strong>
<span>
{{
'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.DESCRIPTION'
| translate
}}
</span>
</div>
</div>
}
`,
styles: [
`
.xtream-cached-offline-notice {
display: flex;
align-items: flex-start;
gap: 12px;
margin: 0 0 12px;
padding: 12px 14px;
border-radius: 12px;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
}
.xtream-cached-offline-notice__copy {
display: grid;
gap: 4px;
}
.xtream-cached-offline-notice__copy strong {
font-size: 0.92rem;
font-weight: 700;
line-height: 1.2;
}
.xtream-cached-offline-notice__copy span {
font-size: 0.84rem;
line-height: 1.35;
}
.xtream-cached-offline-notice mat-icon {
margin-top: 1px;
flex-shrink: 0;
}
`,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class XtreamCachedOfflineNoticeComponent {
private readonly xtreamStore = inject(XtreamStore);
readonly showWarning = computed(
() =>
this.xtreamStore.portalStatus() === 'unavailable' &&
this.xtreamStore.isContentInitialized() &&
!this.xtreamStore.contentInitBlockReason()
);
}
@@ -0,0 +1,193 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
PortalCatalogSortMode,
} from '@iptvnator/portal/shared/util';
import {
XtreamPlaylistData,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { XtreamCatalogFacadeService } from './xtream-catalog-facade.service';
const PLAYLIST_ONE: XtreamPlaylistData = {
id: 'playlist-1',
name: 'Playlist One',
title: 'Playlist One',
serverUrl: 'http://localhost:3000',
username: 'user',
password: 'secret',
type: 'xtream',
};
const PLAYLIST_TWO: XtreamPlaylistData = {
...PLAYLIST_ONE,
id: 'playlist-2',
name: 'Playlist Two',
title: 'Playlist Two',
};
describe('XtreamCatalogFacadeService', () => {
let service: XtreamCatalogFacadeService;
const contentType = signal<'live' | 'vod' | 'series'>('vod');
const limit = signal(25);
const page = signal(0);
const selectedCategory = signal<Record<string, unknown> | null>({
id: 11,
name: 'Movies',
});
const selectedCategoryId = signal<number | null>(11);
const paginatedContent = signal<Record<string, unknown>[]>([
{ xtream_id: 1, title: 'A' },
]);
const selectedCategoryItems = signal<Record<string, unknown>[]>([
{ xtream_id: 1, title: 'A' },
{ xtream_id: 2, title: 'B' },
]);
const selectedItem = signal<Record<string, unknown> | null>(null);
const totalPages = signal(1);
const isPaginatedContentLoading = signal(false);
const contentSortMode = signal<PortalCatalogSortMode>('date-desc');
const currentPlaylist = signal<XtreamPlaylistData | null>(PLAYLIST_ONE);
const xtreamStore = {
selectedContentType: contentType,
limit,
page,
getSelectedCategory: selectedCategory,
selectedCategoryId,
getPaginatedContent: paginatedContent,
selectItemsFromSelectedCategory: selectedCategoryItems,
selectedItem,
getTotalPages: totalPages,
isPaginatedContentLoading,
contentSortMode,
currentPlaylist,
loadAllPositions: jest.fn(),
setCategorySearchTerm: jest.fn(),
setSelectedItem: jest.fn((item: Record<string, unknown> | null) => {
selectedItem.set(item);
}),
setSelectedCategory: jest.fn((categoryId: number | null) => {
selectedCategoryId.set(categoryId);
}),
setPage: jest.fn((nextPage: number) => {
page.set(nextPage);
}),
setLimit: jest.fn((nextLimit: number) => {
limit.set(nextLimit);
}),
setContentSortMode: jest.fn((mode: PortalCatalogSortMode) => {
contentSortMode.set(mode);
}),
hasSeriesProgress: jest.fn().mockReturnValue(false),
getProgressPercent: jest.fn().mockReturnValue(40),
isWatched: jest.fn().mockReturnValue(false),
};
beforeEach(() => {
localStorage.removeItem('xtream-category-sort-mode');
contentType.set('vod');
limit.set(25);
page.set(0);
selectedCategory.set({ id: 11, name: 'Movies' });
selectedCategoryId.set(11);
paginatedContent.set([{ xtream_id: 1, title: 'A' }]);
selectedCategoryItems.set([
{ xtream_id: 1, title: 'A' },
{ xtream_id: 2, title: 'B' },
]);
selectedItem.set(null);
totalPages.set(1);
isPaginatedContentLoading.set(false);
contentSortMode.set('date-desc');
currentPlaylist.set(PLAYLIST_ONE);
xtreamStore.loadAllPositions.mockClear();
xtreamStore.setCategorySearchTerm.mockClear();
xtreamStore.setSelectedItem.mockClear();
xtreamStore.setSelectedCategory.mockClear();
xtreamStore.setPage.mockClear();
xtreamStore.setLimit.mockClear();
xtreamStore.setContentSortMode.mockClear();
xtreamStore.hasSeriesProgress.mockClear();
xtreamStore.getProgressPercent.mockClear();
xtreamStore.isWatched.mockClear();
TestBed.configureTestingModule({
providers: [
XtreamCatalogFacadeService,
{
provide: XtreamStore,
useValue: xtreamStore,
},
],
});
service = TestBed.inject(XtreamCatalogFacadeService);
});
it('delegates category search to the Xtream store', () => {
service.setSearchQuery('matrix');
expect(xtreamStore.setCategorySearchTerm).toHaveBeenCalledWith(
'matrix'
);
});
it('exposes store-driven paginated content, total pages, and category counts', () => {
expect(service.paginatedContent()).toEqual([
{ xtream_id: 1, title: 'A' },
]);
expect(service.totalPages()).toBe(1);
expect(service.categoryItemCount()).toBe(2);
paginatedContent.set([
{ xtream_id: 3, title: 'C' },
{ xtream_id: 4, title: 'D' },
]);
selectedCategoryItems.set([
{ xtream_id: 3, title: 'C' },
{ xtream_id: 4, title: 'D' },
{ xtream_id: 5, title: 'E' },
]);
totalPages.set(4);
expect(service.paginatedContent()).toEqual([
{ xtream_id: 3, title: 'C' },
{ xtream_id: 4, title: 'D' },
]);
expect(service.totalPages()).toBe(4);
expect(service.categoryItemCount()).toBe(3);
});
it('restores saved sort mode, sets the selected category, and loads positions once per playlist', () => {
localStorage.setItem('xtream-category-sort-mode', 'name-asc');
service.initialize('42');
service.initialize('77');
expect(xtreamStore.setContentSortMode).toHaveBeenCalledWith('name-asc');
expect(xtreamStore.setSelectedCategory).toHaveBeenLastCalledWith(77);
expect(xtreamStore.loadAllPositions).toHaveBeenCalledTimes(1);
expect(xtreamStore.loadAllPositions).toHaveBeenCalledWith('playlist-1');
currentPlaylist.set(PLAYLIST_TWO);
service.initialize('88');
expect(xtreamStore.loadAllPositions).toHaveBeenCalledTimes(2);
expect(xtreamStore.loadAllPositions).toHaveBeenLastCalledWith(
'playlist-2'
);
});
it('persists sort mode changes and delegates them to the store', () => {
service.setContentSortMode('name-desc');
expect(xtreamStore.setContentSortMode).toHaveBeenCalledWith(
'name-desc'
);
expect(localStorage.getItem('xtream-category-sort-mode')).toBe(
'name-desc'
);
});
});
@@ -0,0 +1,149 @@
import { Provider, Injectable, computed, inject } from '@angular/core';
import {
PortalCatalogFacade,
PortalCatalogItemProgress,
PortalCatalogPlaylistMeta,
PortalCatalogSortMode,
PORTAL_CATALOG_FACADE,
} from '@iptvnator/portal/shared/util';
import { XtreamStore } from '@iptvnator/portal/xtream/data-access';
const SORT_STORAGE_KEY = 'xtream-category-sort-mode';
@Injectable()
export class XtreamCatalogFacadeService implements PortalCatalogFacade<
Record<string, unknown>,
Record<string, unknown>,
unknown
> {
private readonly xtreamStore = inject(XtreamStore);
private loadedPositionsPlaylistId: string | null = null;
readonly provider = 'xtream' as const;
readonly pageSizeOptions = [10, 25, 50, 100] as const;
readonly contentType = this.xtreamStore.selectedContentType;
readonly limit = this.xtreamStore.limit;
readonly pageIndex = this.xtreamStore.page;
readonly selectedCategory = this.xtreamStore.getSelectedCategory;
readonly paginatedContent = this.xtreamStore.getPaginatedContent;
readonly selectedItem = this.xtreamStore.selectedItem;
readonly totalPages = this.xtreamStore.getTotalPages;
readonly isPaginatedContentLoading =
this.xtreamStore.isPaginatedContentLoading;
readonly selectedCategoryTitle = computed(() => {
const category = this.selectedCategory();
return String(category?.['name'] ?? category?.['title'] ?? '');
});
readonly categoryItemCount = computed(
() => this.xtreamStore.selectItemsFromSelectedCategory().length
);
readonly contentSortMode = this.xtreamStore.contentSortMode;
readonly playlist = computed<PortalCatalogPlaylistMeta | null>(() => {
const playlist = this.xtreamStore.currentPlaylist();
if (!playlist) {
return null;
}
return {
id: String(playlist.id),
title: playlist.name ?? playlist.title ?? 'Xtream',
};
});
initialize(categoryId?: string | null): void {
const savedSortMode = localStorage.getItem(SORT_STORAGE_KEY);
if (
savedSortMode === 'date-desc' ||
savedSortMode === 'date-asc' ||
savedSortMode === 'name-asc' ||
savedSortMode === 'name-desc'
) {
this.xtreamStore.setContentSortMode(savedSortMode);
}
const playlistId = this.xtreamStore.currentPlaylist()?.id;
if (playlistId && this.loadedPositionsPlaylistId !== playlistId) {
this.loadedPositionsPlaylistId = playlistId;
this.xtreamStore.loadAllPositions(playlistId);
}
this.clearSelectedItem();
if (categoryId) {
this.xtreamStore.setSelectedCategory(Number(categoryId));
} else {
this.xtreamStore.setSelectedCategory(null);
}
}
clearSelectedItem(): void {
this.xtreamStore.setSelectedItem(null);
}
setSearchQuery(query: string): void {
this.xtreamStore.setCategorySearchTerm(query);
}
setPage(page: number): void {
this.xtreamStore.setPage(page);
}
setLimit(limit: number): void {
this.xtreamStore.setLimit(limit);
}
setContentSortMode(mode: PortalCatalogSortMode): void {
this.xtreamStore.setContentSortMode(mode);
localStorage.setItem(SORT_STORAGE_KEY, mode);
}
selectItem(item: Record<string, unknown>): string[] | null {
const xtreamId = item['xtream_id'];
if (xtreamId === undefined || xtreamId === null) {
return null;
}
const selectedCategoryId = this.xtreamStore.selectedCategoryId();
if (selectedCategoryId !== null && selectedCategoryId !== undefined) {
return [String(xtreamId)];
}
const categoryId = item['category_id'];
if (categoryId === undefined || categoryId === null) {
return null;
}
return [String(categoryId), String(xtreamId)];
}
getItemProgress(item: Record<string, unknown>): PortalCatalogItemProgress {
const isSeries = this.contentType() === 'series';
const itemId = Number(
item['xtream_id'] ?? item['series_id'] ?? item['stream_id']
);
if (Number.isNaN(itemId)) {
return {};
}
if (isSeries) {
return {
hasSeriesProgress: this.xtreamStore.hasSeriesProgress(itemId),
};
}
return {
progress: this.xtreamStore.getProgressPercent(itemId, 'vod'),
isWatched: this.xtreamStore.isWatched(itemId, 'vod'),
};
}
}
export function provideXtreamCatalogFacade(): Provider[] {
return [
XtreamCatalogFacadeService,
{
provide: PORTAL_CATALOG_FACADE,
useExisting: XtreamCatalogFacadeService,
},
];
}
@@ -0,0 +1,142 @@
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { UnifiedCollectionItem } from '@iptvnator/portal/shared/util';
import {
XtreamPlaylistData,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { PlaylistsService } from 'services';
import { Playlist } from 'shared-interfaces';
import { of } from 'rxjs';
import { SerialDetailsComponent } from './serial-details/serial-details.component';
import { XtreamCollectionDetailComponent } from './xtream-collection-detail.component';
describe('XtreamCollectionDetailComponent', () => {
let fixture: ComponentFixture<XtreamCollectionDetailComponent>;
let playlistId: ReturnType<typeof signal<string>>;
let currentPlaylist: ReturnType<
typeof signal<XtreamPlaylistData | null>
>;
let selectedContentType: ReturnType<
typeof signal<'live' | 'vod' | 'series'>
>;
let selectedCategoryId: ReturnType<typeof signal<number | null>>;
let selectedItem: ReturnType<typeof signal<unknown>>;
let isLoadingDetails: ReturnType<typeof signal<boolean>>;
let detailsError: ReturnType<typeof signal<string | null>>;
beforeEach(async () => {
playlistId = signal('');
currentPlaylist = signal<XtreamPlaylistData | null>(null);
selectedContentType = signal<'live' | 'vod' | 'series'>('vod');
selectedCategoryId = signal<number | null>(null);
selectedItem = signal<unknown>(null);
isLoadingDetails = signal(false);
detailsError = signal<string | null>(null);
await TestBed.configureTestingModule({
imports: [XtreamCollectionDetailComponent],
providers: [
{
provide: XtreamStore,
useValue: {
playlistId,
currentPlaylist,
selectedContentType,
selectedCategoryId,
selectedItem,
isLoadingDetails,
detailsError,
setPlaylistId: jest.fn((value: string) =>
playlistId.set(value)
),
setCurrentPlaylist: jest.fn(
(value: XtreamPlaylistData | null) =>
currentPlaylist.set(value)
),
setSelectedContentType: jest.fn(
(value: 'live' | 'vod' | 'series') =>
selectedContentType.set(value)
),
setSelectedCategory: jest.fn(
(value: number | null) =>
selectedCategoryId.set(value)
),
setSelectedItem: jest.fn((value: unknown) =>
selectedItem.set(value)
),
setIsLoadingDetails: jest.fn((value: boolean) =>
isLoadingDetails.set(value)
),
setDetailsError: jest.fn((value: string | null) =>
detailsError.set(value)
),
},
},
{
provide: PlaylistsService,
useValue: {
getPlaylistById: jest.fn(() =>
of({
_id: 'xtream-1',
title: 'Xtream Portal',
serverUrl: 'http://xtream.example',
username: 'user',
password: 'pass',
} as Playlist)
),
},
},
],
})
.overrideComponent(XtreamCollectionDetailComponent, {
set: {
template: '',
},
})
.compileComponents();
fixture = TestBed.createComponent(XtreamCollectionDetailComponent);
});
afterEach(() => {
fixture?.destroy();
});
it('opens Xtream series favorites with the serial detail route context', async () => {
fixture.componentRef.setInput(
'item',
{
uid: 'xtream::xtream-1::series:103',
name: 'Series One',
contentType: 'series',
sourceType: 'xtream',
playlistId: 'xtream-1',
playlistName: 'Xtream Portal',
xtreamId: 103,
categoryId: 3,
} satisfies UnifiedCollectionItem
);
fixture.detectChanges();
await fixture.whenStable();
await Promise.resolve();
fixture.detectChanges();
expect(selectedContentType()).toBe('series');
expect(selectedCategoryId()).toBe(3);
expect(fixture.componentInstance.detailComponent()).toBe(
SerialDetailsComponent
);
expect(
fixture.componentInstance
.detailInjector()
?.get(ActivatedRoute)
.snapshot.params
).toEqual({
categoryId: '3',
serialId: '103',
});
});
});
@@ -0,0 +1,243 @@
import { NgComponentOutlet } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
Injector,
Type,
effect,
inject,
input,
signal,
untracked,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ContentHeroComponent } from 'components';
import { UnifiedCollectionItem } from '@iptvnator/portal/shared/util';
import {
XtreamPlaylistData,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { PlaylistsService } from 'services';
import { Playlist } from 'shared-interfaces';
import { firstValueFrom } from 'rxjs';
import { SerialDetailsComponent } from './serial-details/serial-details.component';
import { VodDetailsRouteComponent } from './vod-details/vod-details-route.component';
interface XtreamCollectionStateSnapshot {
playlistId: string | null;
currentPlaylist: XtreamPlaylistData | null;
selectedContentType: 'live' | 'vod' | 'series';
selectedCategoryId: number | null;
selectedItem: unknown;
isLoadingDetails: boolean;
detailsError: string | null;
}
@Component({
selector: 'app-xtream-collection-detail',
imports: [ContentHeroComponent, NgComponentOutlet],
template: `
@if (detailComponent() && detailInjector()) {
<ng-container
*ngComponentOutlet="
detailComponent();
injector: detailInjector()
"
/>
} @else {
<app-content-hero [isLoading]="true" />
}
`,
changeDetection: ChangeDetectionStrategy.OnPush,
styles: [
`
:host {
display: block;
width: 100%;
height: 100%;
min-height: 0;
}
`,
],
})
export class XtreamCollectionDetailComponent {
readonly item = input<UnifiedCollectionItem | null>(null);
private readonly parentInjector = inject(Injector);
private readonly playlistsService = inject(PlaylistsService);
private readonly xtreamStore = inject(XtreamStore);
private readonly originalState = this.captureStoreState();
readonly detailComponent = signal<Type<unknown> | null>(null);
readonly detailInjector = signal<Injector | null>(null);
private initRequestId = 0;
constructor() {
effect(() => {
const item = this.item();
untracked(() => {
void this.prepareDetail(item);
});
});
}
ngOnDestroy(): void {
this.restoreStoreState();
}
private async prepareDetail(
item: UnifiedCollectionItem | null
): Promise<void> {
const requestId = ++this.initRequestId;
if (!item) {
this.detailComponent.set(null);
this.detailInjector.set(null);
return;
}
const xtreamId = this.resolveXtreamId(item);
if (!xtreamId) {
this.detailComponent.set(null);
this.detailInjector.set(null);
return;
}
const playlist = await this.loadPlaylist(item.playlistId);
if (requestId !== this.initRequestId) {
return;
}
if (!playlist?.serverUrl || !playlist.username || !playlist.password) {
this.detailComponent.set(null);
this.detailInjector.set(null);
return;
}
const xtreamPlaylist = this.toXtreamPlaylist(playlist);
this.xtreamStore.setPlaylistId(xtreamPlaylist.id);
this.xtreamStore.setCurrentPlaylist(xtreamPlaylist);
this.xtreamStore.setSelectedContentType(
item.contentType === 'movie' ? 'vod' : 'series'
);
this.xtreamStore.setSelectedCategory(
this.toCategoryId(item.categoryId)
);
this.xtreamStore.setSelectedItem(null);
this.xtreamStore.setIsLoadingDetails(false);
this.xtreamStore.setDetailsError(null);
this.detailComponent.set(
item.contentType === 'movie'
? VodDetailsRouteComponent
: SerialDetailsComponent
);
this.detailInjector.set(
Injector.create({
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params:
item.contentType === 'movie'
? {
categoryId: this.toPathSegment(
item.categoryId
),
vodId: xtreamId,
}
: {
categoryId: this.toPathSegment(
item.categoryId
),
serialId: xtreamId,
},
},
},
},
],
parent: this.parentInjector,
})
);
}
private captureStoreState(): XtreamCollectionStateSnapshot {
return {
playlistId: this.xtreamStore.playlistId(),
currentPlaylist: this.xtreamStore.currentPlaylist(),
selectedContentType: this.xtreamStore.selectedContentType(),
selectedCategoryId: this.xtreamStore.selectedCategoryId(),
selectedItem: this.xtreamStore.selectedItem(),
isLoadingDetails: this.xtreamStore.isLoadingDetails(),
detailsError: this.xtreamStore.detailsError(),
};
}
private restoreStoreState(): void {
this.xtreamStore.setPlaylistId(this.originalState.playlistId ?? '');
this.xtreamStore.setCurrentPlaylist(this.originalState.currentPlaylist);
this.xtreamStore.setSelectedContentType(
this.originalState.selectedContentType
);
this.xtreamStore.setSelectedCategory(
this.originalState.selectedCategoryId
);
this.xtreamStore.setSelectedItem(
this.originalState.selectedItem as never
);
this.xtreamStore.setIsLoadingDetails(
this.originalState.isLoadingDetails
);
this.xtreamStore.setDetailsError(this.originalState.detailsError);
}
private async loadPlaylist(playlistId: string): Promise<Playlist | null> {
try {
return (
(await firstValueFrom(
this.playlistsService.getPlaylistById(playlistId)
)) ?? null
);
} catch {
return null;
}
}
private toXtreamPlaylist(playlist: Playlist): XtreamPlaylistData {
return {
id: playlist._id,
name: playlist.title || '',
title: playlist.title || '',
serverUrl: playlist.serverUrl || '',
username: playlist.username || '',
password: playlist.password || '',
type: 'xtream',
userAgent: playlist.userAgent,
referrer: playlist.referrer,
origin: playlist.origin,
};
}
private resolveXtreamId(item: UnifiedCollectionItem): string | null {
const directId = Number(item.xtreamId);
if (Number.isFinite(directId) && directId > 0) {
return String(directId);
}
const uidSegments = item.uid.split('::');
const fallbackId = Number(uidSegments[uidSegments.length - 1]);
return Number.isFinite(fallbackId) && fallbackId > 0
? String(fallbackId)
: null;
}
private toCategoryId(value: unknown): number | null {
const categoryId = Number(String(value ?? '').trim());
return Number.isFinite(categoryId) ? categoryId : null;
}
private toPathSegment(value: unknown): string {
return String(value ?? '').trim();
}
}
@@ -0,0 +1,48 @@
import {
inject,
ChangeDetectionStrategy,
Component,
input,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
UnifiedCollectionDetailDirective,
UnifiedCollectionPageComponent,
} from '@iptvnator/portal/shared/ui';
import { routeParamSignal } from '@iptvnator/portal/shared/util';
import { XtreamCachedOfflineNoticeComponent } from './xtream-cached-offline-notice.component';
import { XtreamCollectionDetailComponent } from './xtream-collection-detail.component';
@Component({
selector: 'app-xtream-collection-route',
imports: [
UnifiedCollectionDetailDirective,
UnifiedCollectionPageComponent,
XtreamCachedOfflineNoticeComponent,
XtreamCollectionDetailComponent,
],
template: `
<app-xtream-cached-offline-notice />
<app-unified-collection-page
[mode]="mode()"
[portalType]="portalType()"
[playlistId]="playlistId()"
>
<ng-template unifiedCollectionDetail let-item>
<app-xtream-collection-detail [item]="item" />
</ng-template>
</app-unified-collection-page>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class XtreamCollectionRouteComponent {
private readonly route = inject(ActivatedRoute);
readonly mode = input<'favorites' | 'recent'>('favorites');
readonly portalType = input('xtream');
readonly playlistId = routeParamSignal<string | undefined>(
this.route,
'id',
(value) => value ?? undefined
);
}
@@ -0,0 +1,145 @@
import { Component, input, signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { provideRouter, RouterOutlet } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import {
XtreamContentInitBlockReason,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { XtreamCachedOfflineNoticeComponent } from './xtream-cached-offline-notice.component';
import { XtreamContentGateComponent } from './xtream-content-gate.component';
@Component({
selector: 'app-playlist-error-view',
standalone: true,
template: `
<div class="mock-error">
<span class="mock-error__title">{{ title() }}</span>
<span class="mock-error__description">{{ description() }}</span>
</div>
`,
})
class MockPlaylistErrorViewComponent {
readonly title = input<string>('');
readonly description = input<string | undefined>(undefined);
}
describe('XtreamContentGateComponent', () => {
let fixture: ComponentFixture<XtreamContentGateComponent>;
const contentInitBlockReason =
signal<XtreamContentInitBlockReason | null>(null);
const isContentInitialized = signal(false);
const portalStatus = signal<'active' | 'inactive' | 'expired' | 'unavailable'>(
'active'
);
const retryContentInitialization = jest.fn().mockResolvedValue(undefined);
beforeEach(async () => {
contentInitBlockReason.set(null);
isContentInitialized.set(false);
portalStatus.set('active');
retryContentInitialization.mockClear();
await TestBed.configureTestingModule({
imports: [XtreamContentGateComponent],
providers: [
provideRouter([]),
{
provide: TranslateService,
useValue: {
instant: (key: string) => key,
get: (key: string) => of(key),
stream: (key: string) => of(key),
onLangChange: of(null),
onTranslationChange: of(null),
onDefaultLangChange: of(null),
currentLang: 'en',
defaultLang: 'en',
},
},
{
provide: XtreamStore,
useValue: {
contentInitBlockReason,
isContentInitialized,
portalStatus,
retryContentInitialization,
},
},
],
})
.overrideComponent(XtreamContentGateComponent, {
set: {
imports: [
MatButtonModule,
MatIconModule,
MockPlaylistErrorViewComponent,
RouterOutlet,
TranslatePipe,
XtreamCachedOfflineNoticeComponent,
],
},
})
.compileComponents();
fixture = TestBed.createComponent(XtreamContentGateComponent);
});
it.each([
['cancelled', 'PORTALS.ERROR_VIEW.IMPORT_CANCELLED.TITLE'],
['expired', 'PORTALS.ERROR_VIEW.ACCOUNT_EXPIRED.TITLE'],
['inactive', 'PORTALS.ERROR_VIEW.ACCOUNT_INACTIVE.TITLE'],
['unavailable', 'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.TITLE'],
['error', 'PORTALS.ERROR_VIEW.UNKNOWN_ERROR.TITLE'],
] as const)(
'renders the blocked error state for %s imports',
(reason, expectedTitleKey) => {
contentInitBlockReason.set(reason);
fixture.detectChanges();
const title = fixture.nativeElement.querySelector(
'.mock-error__title'
) as HTMLElement | null;
expect(title?.textContent?.trim()).toBe(expectedTitleKey);
}
);
it('keeps the child outlet available when there is no block reason', () => {
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.mock-error')
).toBeNull();
expect(fixture.nativeElement.querySelector('router-outlet')).not.toBeNull();
});
it('shows an inline warning when cached content remains available offline', () => {
isContentInitialized.set(true);
portalStatus.set('unavailable');
fixture.detectChanges();
const warning = fixture.nativeElement.querySelector(
'[data-testid="xtream-offline-warning"]'
) as HTMLElement | null;
expect(warning?.textContent).toContain(
'PORTALS.ERROR_VIEW.PORTAL_UNAVAILABLE.TITLE'
);
expect(fixture.nativeElement.querySelector('router-outlet')).not.toBeNull();
});
it('retries content initialization from the blocked state', () => {
contentInitBlockReason.set('cancelled');
fixture.detectChanges();
const retryButton = fixture.nativeElement.querySelector(
'button'
) as HTMLButtonElement | null;
retryButton?.click();
expect(retryContentInitialization).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,97 @@
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { RouterOutlet } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import {
PlaylistErrorViewComponent,
} from '@iptvnator/portal/shared/ui';
import {
XtreamContentInitBlockReason,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { XtreamCachedOfflineNoticeComponent } from './xtream-cached-offline-notice.component';
@Component({
selector: 'app-xtream-content-gate',
standalone: true,
imports: [
MatButtonModule,
MatIconModule,
PlaylistErrorViewComponent,
RouterOutlet,
TranslatePipe,
XtreamCachedOfflineNoticeComponent,
],
template: `
@if (contentInitBlockReason(); as blockReason) {
<div class="xtream-content-gate">
<app-playlist-error-view
[title]="titleKey() | translate"
[description]="descriptionKey() | translate"
/>
<div class="xtream-content-gate__actions">
<button
mat-flat-button
color="primary"
type="button"
(click)="retryContentInitialization()"
>
<mat-icon>refresh</mat-icon>
{{ 'DOWNLOADS.RETRY' | translate }}
</button>
</div>
</div>
} @else {
<app-xtream-cached-offline-notice />
<router-outlet />
}
`,
styles: [
`
.xtream-content-gate {
display: grid;
gap: 16px;
justify-items: center;
padding: 24px;
}
.xtream-content-gate__actions {
display: flex;
justify-content: center;
}
`,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class XtreamContentGateComponent {
private readonly xtreamStore = inject(XtreamStore);
readonly contentInitBlockReason = this.xtreamStore.contentInitBlockReason;
private readonly errorViewKey = computed(() => {
switch (this.contentInitBlockReason()) {
case 'cancelled':
return 'IMPORT_CANCELLED';
case 'expired':
return 'ACCOUNT_EXPIRED';
case 'inactive':
return 'ACCOUNT_INACTIVE';
case 'unavailable':
return 'PORTAL_UNAVAILABLE';
case 'error':
default:
return 'UNKNOWN_ERROR';
}
});
readonly titleKey = computed(
() => `PORTALS.ERROR_VIEW.${this.errorViewKey()}.TITLE`
);
readonly descriptionKey = computed(
() => `PORTALS.ERROR_VIEW.${this.errorViewKey()}.DESCRIPTION`
);
retryContentInitialization(): void {
void this.xtreamStore.retryContentInitialization();
}
}
@@ -0,0 +1,28 @@
import { createXtreamRoutes } from './xtream-feature.routes';
describe('createXtreamRoutes', () => {
it('keeps import-driven routes behind the content gate and leaves collections outside it', () => {
const [xtreamRoute] = createXtreamRoutes();
const gateRoute = xtreamRoute.children?.find(
(route) => route.path === '' && typeof route.loadComponent === 'function'
);
expect(gateRoute?.children?.map((route) => route.path)).toEqual(
expect.arrayContaining([
'live',
'live/:categoryId',
'vod',
'series',
'search',
'recently-added',
])
);
expect(xtreamRoute.children?.find((route) => route.path === 'favorites'))
.toMatchObject({ path: 'favorites' });
expect(xtreamRoute.children?.find((route) => route.path === 'recent'))
.toMatchObject({ path: 'recent' });
expect(xtreamRoute.children?.find((route) => route.path === 'downloads'))
.toMatchObject({ path: 'downloads' });
});
});
@@ -0,0 +1,138 @@
import { Route } from '@angular/router';
import { provideXtreamCatalogFacade } from './xtream-catalog-facade.service';
import { provideXtreamWorkspaceRouteSession } from './xtream-workspace-route-session.service';
type ComponentLoader = NonNullable<Route['loadComponent']>;
const loadDownloadsComponent: ComponentLoader = () =>
import('@iptvnator/portal/downloads/feature').then(
(c) => c.DownloadsComponent
);
const loadXtreamContentGateComponent: ComponentLoader = () =>
import('./xtream-content-gate.component').then(
(c) => c.XtreamContentGateComponent
);
const loadLiveStreamLayoutComponent: ComponentLoader = () =>
import('./live-stream-layout/live-stream-layout.component').then(
(c) => c.LiveStreamLayoutComponent
);
const loadCategoryContentViewComponent: ComponentLoader = () =>
import('@iptvnator/portal/catalog/feature').then(
(c) => c.CategoryContentViewComponent
);
const loadXtreamCollectionRouteComponent: ComponentLoader = () =>
import('./xtream-collection-route.component').then(
(c) => c.XtreamCollectionRouteComponent
);
const loadSearchResultsComponent: ComponentLoader = () =>
import('./search-results/search-results.component').then(
(c) => c.SearchResultsComponent
);
const loadRecentlyAddedComponent: ComponentLoader = () =>
import('./recently-added/recently-added.component').then(
(c) => c.RecentlyAddedComponent
);
const loadVodDetailsRouteComponent: ComponentLoader = () =>
import('./vod-details/vod-details-route.component').then(
(c) => c.VodDetailsRouteComponent
);
const loadSerialDetailsComponent: ComponentLoader = () =>
import('./serial-details/serial-details.component').then(
(c) => c.SerialDetailsComponent
);
export function createXtreamRoutes(): Route[] {
return [
{
path: 'xtreams/:id',
providers: provideXtreamWorkspaceRouteSession(),
children: [
{
path: '',
redirectTo: 'vod',
pathMatch: 'full',
},
{
path: '',
loadComponent: loadXtreamContentGateComponent,
children: [
{
path: 'live',
loadComponent: loadLiveStreamLayoutComponent,
},
{
path: 'live/:categoryId',
loadComponent: loadLiveStreamLayoutComponent,
},
{
path: 'vod',
providers: provideXtreamCatalogFacade(),
children: [
{
path: '',
loadComponent: loadCategoryContentViewComponent,
},
{
path: ':categoryId',
loadComponent: loadCategoryContentViewComponent,
},
{
path: ':categoryId/:vodId',
loadComponent: loadVodDetailsRouteComponent,
},
],
},
{
path: 'series',
providers: provideXtreamCatalogFacade(),
children: [
{
path: '',
loadComponent: loadCategoryContentViewComponent,
},
{
path: ':categoryId',
loadComponent: loadCategoryContentViewComponent,
},
{
path: ':categoryId/:serialId',
loadComponent: loadSerialDetailsComponent,
},
],
},
{
path: 'search',
loadComponent: loadSearchResultsComponent,
},
{
path: 'recently-added',
loadComponent: loadRecentlyAddedComponent,
},
],
},
{
path: 'favorites',
loadComponent: loadXtreamCollectionRouteComponent,
data: { mode: 'favorites', portalType: 'xtream' },
},
{
path: 'recent',
loadComponent: loadXtreamCollectionRouteComponent,
data: { mode: 'recent', portalType: 'xtream' },
},
{
path: 'downloads',
loadComponent: loadDownloadsComponent,
},
],
},
];
}
@@ -0,0 +1,357 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { NavigationEnd, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { PlaylistContextFacade } from '@iptvnator/playlist/shared/util';
import {
PortalStatusType,
XtreamContentInitBlockReason,
XtreamPlaylistData,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { PlaylistMeta } from 'shared-interfaces';
import { XtreamWorkspaceRouteSession } from './xtream-workspace-route-session.service';
const PLAYLIST_ID = 'playlist-1';
const ACTIVE_PLAYLIST: PlaylistMeta = {
_id: PLAYLIST_ID,
filename: 'xtream.m3u',
password: 'secret',
serverUrl: 'http://localhost:3211',
title: 'Test Xtream',
username: 'user1',
} as PlaylistMeta;
const UPDATED_ACTIVE_PLAYLIST: PlaylistMeta = {
...ACTIVE_PLAYLIST,
serverUrl: 'http://localhost:65530',
} as PlaylistMeta;
const XTREAM_PLAYLIST: XtreamPlaylistData = {
id: PLAYLIST_ID,
name: 'Test Xtream',
title: 'Test Xtream',
serverUrl: 'http://localhost:3211',
username: 'user1',
password: 'secret',
type: 'xtream',
};
const XTREAM_PLAYLIST_WITH_NULL_OPTIONALS = {
...XTREAM_PLAYLIST,
origin: null,
referrer: null,
userAgent: null,
} as XtreamPlaylistData;
async function flushEffects(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
}
function getXtreamSectionFromUrl(url: string): string | null {
const match = url.match(
/^\/workspace\/xtreams\/[^/]+\/([^/?]+)(?:\/|$)/
);
return match?.[1] ?? null;
}
describe('XtreamWorkspaceRouteSession', () => {
const routerEvents = new Subject<NavigationEnd>();
const routeProvider = signal<'xtreams' | null>('xtreams');
const routePlaylistId = signal<string | null>(PLAYLIST_ID);
const activePlaylist = signal<PlaylistMeta | null>(ACTIVE_PLAYLIST);
const currentPlaylist = signal<XtreamPlaylistData | null>(XTREAM_PLAYLIST);
const playlistId = signal<string | null>(PLAYLIST_ID);
const portalStatus = signal<PortalStatusType>('active');
const selectedContentType = signal<'live' | 'vod' | 'series'>('vod');
const selectedCategoryId = signal<number | null>(null);
const isContentInitialized = signal(false);
const contentInitBlockReason =
signal<XtreamContentInitBlockReason | null>(null);
let hasUsableOfflineCache = false;
const playlistContext = {
routeProvider,
routePlaylistId,
activePlaylist,
syncFromUrl: jest.fn(),
};
const xtreamStore = {
currentPlaylist,
playlistId,
portalStatus,
resetStore: jest.fn((nextPlaylistId?: string) => {
playlistId.set(nextPlaylistId ?? null);
currentPlaylist.set(null);
selectedContentType.set('vod');
isContentInitialized.set(false);
}),
setCurrentPlaylist: jest.fn((playlist: XtreamPlaylistData | null) => {
currentPlaylist.set(playlist);
}),
fetchXtreamPlaylist: jest.fn().mockResolvedValue(undefined),
checkPortalStatus: jest.fn(),
hasUsableOfflineCache: jest.fn().mockImplementation(async () => {
return hasUsableOfflineCache;
}),
isContentInitialized,
contentInitBlockReason,
initializeContent: jest.fn().mockImplementation(async () => {
isContentInitialized.set(true);
}),
setSelectedContentType: jest.fn(
(type: 'live' | 'vod' | 'series') => {
selectedContentType.set(type);
}
),
setSelectedCategory: jest.fn((categoryId: number | null) => {
selectedCategoryId.set(categoryId);
}),
setContentInitBlockReason: jest.fn(
(reason: XtreamContentInitBlockReason | null) => {
contentInitBlockReason.set(reason);
}
),
};
const router = {
url: `/workspace/xtreams/${PLAYLIST_ID}/vod`,
events: routerEvents.asObservable(),
};
beforeEach(async () => {
router.url = `/workspace/xtreams/${PLAYLIST_ID}/vod`;
routeProvider.set('xtreams');
routePlaylistId.set(PLAYLIST_ID);
activePlaylist.set(ACTIVE_PLAYLIST);
currentPlaylist.set(null);
playlistId.set(null);
portalStatus.set('active');
selectedContentType.set('vod');
selectedCategoryId.set(null);
isContentInitialized.set(false);
contentInitBlockReason.set(null);
hasUsableOfflineCache = false;
playlistContext.syncFromUrl.mockImplementation((url: string) => ({
inWorkspace: true,
provider: 'xtreams',
playlistId: PLAYLIST_ID,
section: getXtreamSectionFromUrl(url) as
| 'favorites'
| 'live'
| 'recently-added'
| 'search'
| 'series'
| 'vod'
| null,
}));
xtreamStore.resetStore.mockClear();
xtreamStore.setCurrentPlaylist.mockClear();
xtreamStore.fetchXtreamPlaylist.mockClear();
xtreamStore.checkPortalStatus.mockReset();
xtreamStore.hasUsableOfflineCache.mockClear();
xtreamStore.initializeContent.mockClear();
xtreamStore.setSelectedContentType.mockClear();
xtreamStore.setSelectedCategory.mockClear();
xtreamStore.setContentInitBlockReason.mockClear();
await TestBed.configureTestingModule({
providers: [
XtreamWorkspaceRouteSession,
{
provide: PlaylistContextFacade,
useValue: playlistContext,
},
{
provide: Router,
useValue: router,
},
{
provide: XtreamStore,
useValue: xtreamStore,
},
],
});
});
it('initializes content for active import-driven routes', async () => {
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('active');
return 'active';
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.checkPortalStatus).toHaveBeenCalled();
expect(xtreamStore.setContentInitBlockReason).toHaveBeenCalledWith(null);
expect(xtreamStore.setSelectedContentType).toHaveBeenCalledWith('vod');
expect(xtreamStore.initializeContent).toHaveBeenCalled();
});
it('reapplies a live route section after resetStore restores the default selection', async () => {
router.url = `/workspace/xtreams/${PLAYLIST_ID}/live`;
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('active');
return 'active';
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.resetStore).toHaveBeenCalledWith(PLAYLIST_ID);
expect(xtreamStore.setSelectedContentType).toHaveBeenCalledWith('live');
expect(selectedContentType()).toBe('live');
expect(
xtreamStore.setSelectedContentType.mock.invocationCallOrder[0]
).toBeGreaterThan(xtreamStore.resetStore.mock.invocationCallOrder[0]);
});
it('does not bootstrap again when the store already holds the active playlist', async () => {
router.url = `/workspace/xtreams/${PLAYLIST_ID}/vod/101`;
currentPlaylist.set(XTREAM_PLAYLIST);
playlistId.set(PLAYLIST_ID);
isContentInitialized.set(true);
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.setSelectedContentType).toHaveBeenCalledWith('vod');
expect(xtreamStore.setSelectedCategory).toHaveBeenCalledWith(101);
expect(xtreamStore.resetStore).not.toHaveBeenCalled();
expect(xtreamStore.fetchXtreamPlaylist).not.toHaveBeenCalled();
expect(xtreamStore.checkPortalStatus).not.toHaveBeenCalled();
expect(xtreamStore.initializeContent).not.toHaveBeenCalled();
});
it('does not treat null and undefined Xtream connection metadata as a playlist change', async () => {
router.url = `/workspace/xtreams/${PLAYLIST_ID}/vod/101`;
currentPlaylist.set(XTREAM_PLAYLIST_WITH_NULL_OPTIONALS);
playlistId.set(PLAYLIST_ID);
isContentInitialized.set(true);
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.resetStore).not.toHaveBeenCalled();
expect(xtreamStore.fetchXtreamPlaylist).not.toHaveBeenCalled();
expect(xtreamStore.checkPortalStatus).not.toHaveBeenCalled();
expect(xtreamStore.initializeContent).not.toHaveBeenCalled();
});
it('does not reinitialize content when switching categories in an initialized playlist', async () => {
router.url = `/workspace/xtreams/${PLAYLIST_ID}/vod/101`;
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('active');
return 'active';
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
await flushEffects();
expect(isContentInitialized()).toBe(true);
xtreamStore.resetStore.mockClear();
xtreamStore.fetchXtreamPlaylist.mockClear();
xtreamStore.checkPortalStatus.mockClear();
xtreamStore.initializeContent.mockClear();
xtreamStore.setSelectedContentType.mockClear();
xtreamStore.setSelectedCategory.mockClear();
router.url = `/workspace/xtreams/${PLAYLIST_ID}/vod/202`;
routerEvents.next(
new NavigationEnd(1, router.url, router.url)
);
await flushEffects();
expect(xtreamStore.setSelectedContentType).toHaveBeenCalledWith('vod');
expect(xtreamStore.setSelectedCategory).toHaveBeenCalledWith(202);
expect(selectedCategoryId()).toBe(202);
expect(xtreamStore.resetStore).not.toHaveBeenCalled();
expect(xtreamStore.fetchXtreamPlaylist).not.toHaveBeenCalled();
expect(xtreamStore.checkPortalStatus).not.toHaveBeenCalled();
expect(xtreamStore.initializeContent).not.toHaveBeenCalled();
});
it.each(['expired', 'inactive', 'unavailable'] as const)(
'blocks %s portals before import-driven initialization starts',
async (status) => {
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set(status);
return status;
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.checkPortalStatus).toHaveBeenCalled();
expect(xtreamStore.setContentInitBlockReason).toHaveBeenCalledWith(
status
);
expect(xtreamStore.initializeContent).not.toHaveBeenCalled();
}
);
it('allows unavailable portals to initialize cached content', async () => {
hasUsableOfflineCache = true;
activePlaylist.set(UPDATED_ACTIVE_PLAYLIST);
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('unavailable');
return 'unavailable';
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
await flushEffects();
expect(xtreamStore.checkPortalStatus).toHaveBeenCalled();
expect(xtreamStore.hasUsableOfflineCache).toHaveBeenCalled();
expect(xtreamStore.setContentInitBlockReason).toHaveBeenCalledWith(
null
);
expect(xtreamStore.initializeContent).toHaveBeenCalled();
});
it('rebootstraps the current Xtream playlist when its connection details change', async () => {
activePlaylist.set(UPDATED_ACTIVE_PLAYLIST);
currentPlaylist.set(XTREAM_PLAYLIST);
playlistId.set(PLAYLIST_ID);
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('active');
return 'active';
});
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
await flushEffects();
expect(xtreamStore.resetStore).toHaveBeenCalledWith(PLAYLIST_ID);
expect(xtreamStore.setCurrentPlaylist).toHaveBeenCalledWith(
expect.objectContaining({
id: PLAYLIST_ID,
serverUrl: UPDATED_ACTIVE_PLAYLIST.serverUrl,
})
);
expect(xtreamStore.checkPortalStatus).toHaveBeenCalled();
});
it('does not clear a cancelled block while an active portal bootstrap finishes', async () => {
xtreamStore.checkPortalStatus.mockImplementation(async () => {
portalStatus.set('active');
return 'active';
});
contentInitBlockReason.set('cancelled');
TestBed.inject(XtreamWorkspaceRouteSession);
await flushEffects();
expect(xtreamStore.checkPortalStatus).toHaveBeenCalled();
expect(xtreamStore.setContentInitBlockReason).not.toHaveBeenCalledWith(
null
);
});
});
@@ -0,0 +1,321 @@
import {
DestroyRef,
ENVIRONMENT_INITIALIZER,
effect,
inject,
Injectable,
Provider,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { PlaylistContextFacade } from '@iptvnator/playlist/shared/util';
import { PortalRailSection } from '@iptvnator/portal/shared/util';
import {
PortalStatusType,
XtreamPlaylistData,
XtreamStore,
} from '@iptvnator/portal/xtream/data-access';
import { PlaylistMeta } from 'shared-interfaces';
function toXtreamPlaylistData(
playlist: PlaylistMeta | null
): XtreamPlaylistData | null {
if (
!playlist?._id ||
!playlist.serverUrl ||
!playlist.username ||
!playlist.password
) {
return null;
}
return {
id: playlist._id,
name: playlist.title || playlist.filename || 'Untitled playlist',
title: playlist.title,
updateDate: playlist.updateDate,
serverUrl: playlist.serverUrl,
username: playlist.username,
password: playlist.password,
type: 'xtream',
userAgent: playlist.userAgent,
referrer: playlist.referrer,
origin: playlist.origin,
};
}
function isImportDrivenSection(section: PortalRailSection | null): boolean {
return (
section === 'vod' ||
section === 'live' ||
section === 'series' ||
section === 'search' ||
section === 'recently-added'
);
}
function toContentInitBlockReason(
portalStatus: PortalStatusType
): 'expired' | 'inactive' | 'unavailable' | null {
switch (portalStatus) {
case 'expired':
case 'inactive':
case 'unavailable':
return portalStatus;
default:
return null;
}
}
function hasPlaylistConnectionChanges(
currentPlaylist: XtreamPlaylistData | null,
nextPlaylist: XtreamPlaylistData | null
): boolean {
if (!currentPlaylist || !nextPlaylist) {
return false;
}
const currentUserAgent = currentPlaylist.userAgent ?? null;
const nextUserAgent = nextPlaylist.userAgent ?? null;
const currentReferrer = currentPlaylist.referrer ?? null;
const nextReferrer = nextPlaylist.referrer ?? null;
const currentOrigin = currentPlaylist.origin ?? null;
const nextOrigin = nextPlaylist.origin ?? null;
return (
currentPlaylist.serverUrl !== nextPlaylist.serverUrl ||
currentPlaylist.username !== nextPlaylist.username ||
currentPlaylist.password !== nextPlaylist.password ||
currentUserAgent !== nextUserAgent ||
currentReferrer !== nextReferrer ||
currentOrigin !== nextOrigin
);
}
function shouldBootstrapXtreamPlaylist(
playlistId: string | null,
routePlaylist: XtreamPlaylistData | null,
storePlaylistId: string | null,
currentPlaylist: XtreamPlaylistData | null
): boolean {
const currentPlaylistUpdateDate = currentPlaylist?.updateDate ?? null;
const routePlaylistUpdateDate = routePlaylist?.updateDate ?? null;
return Boolean(
playlistId &&
routePlaylist &&
(storePlaylistId !== playlistId ||
currentPlaylist?.id !== playlistId ||
currentPlaylistUpdateDate !== routePlaylistUpdateDate ||
hasPlaylistConnectionChanges(currentPlaylist, routePlaylist))
);
}
function getXtreamRouteCategoryId(
url: string,
section: PortalRailSection | null
): number | null {
if (
section !== 'live' &&
section !== 'vod' &&
section !== 'series'
) {
return null;
}
const path = url.split('?')[0] ?? '';
const segments = path.split('/').filter(Boolean);
const categorySegment = segments[4];
if (!categorySegment) {
return null;
}
const categoryId = Number(categorySegment);
return Number.isNaN(categoryId) ? null : categoryId;
}
@Injectable()
export class XtreamWorkspaceRouteSession {
private readonly destroyRef = inject(DestroyRef);
private readonly playlistContext = inject(PlaylistContextFacade);
private readonly router = inject(Router);
private readonly xtreamStore = inject(XtreamStore);
private syncInFlight = false;
private syncPending = false;
constructor() {
effect(() => {
const routeProvider = this.playlistContext.routeProvider();
const routePlaylistId = this.playlistContext.routePlaylistId();
const activePlaylist = this.playlistContext.activePlaylist();
if (
routeProvider !== 'xtreams' ||
!routePlaylistId ||
activePlaylist?._id !== routePlaylistId
) {
return;
}
this.scheduleSyncRouteContext();
});
this.router.events
.pipe(
filter(
(event): event is NavigationEnd =>
event instanceof NavigationEnd
),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(() => {
this.scheduleSyncRouteContext();
});
this.scheduleSyncRouteContext();
}
private scheduleSyncRouteContext(): void {
if (this.syncInFlight) {
this.syncPending = true;
return;
}
this.syncInFlight = true;
void (async () => {
try {
do {
this.syncPending = false;
await this.syncRouteContext();
} while (this.syncPending);
} finally {
this.syncInFlight = false;
}
})();
}
private async syncRouteContext(): Promise<void> {
const routeContext = this.playlistContext.syncFromUrl(this.router.url);
const playlistId =
routeContext.provider === 'xtreams'
? routeContext.playlistId
: null;
const routeSection =
routeContext.provider === 'xtreams' ? routeContext.section : null;
const routePlaylist =
routeContext.provider === 'xtreams'
? toXtreamPlaylistData(this.playlistContext.activePlaylist())
: null;
const storePlaylistId = this.xtreamStore.playlistId();
const currentPlaylist = this.xtreamStore.currentPlaylist();
const shouldBootstrapPlaylist = shouldBootstrapXtreamPlaylist(
playlistId,
routePlaylist,
storePlaylistId,
currentPlaylist
);
let portalStatus = this.xtreamStore.portalStatus();
let didBootstrapPlaylist = false;
if (playlistId && shouldBootstrapPlaylist) {
this.xtreamStore.resetStore(playlistId);
didBootstrapPlaylist = true;
this.xtreamStore.setCurrentPlaylist(routePlaylist);
await this.xtreamStore.fetchXtreamPlaylist();
portalStatus = await this.xtreamStore.checkPortalStatus();
const hasUsableOfflineCache =
portalStatus === 'unavailable'
? await this.xtreamStore.hasUsableOfflineCache()
: false;
const nextBlockReason =
portalStatus === 'unavailable' && hasUsableOfflineCache
? null
: toContentInitBlockReason(portalStatus);
const currentBlockReason =
this.xtreamStore.contentInitBlockReason();
if (
nextBlockReason !== null ||
currentBlockReason !== 'cancelled'
) {
this.xtreamStore.setContentInitBlockReason(nextBlockReason);
}
}
const section = this.syncRouteState(routeSection);
const canUseOfflineCache =
portalStatus === 'unavailable'
? await this.xtreamStore.hasUsableOfflineCache()
: false;
if (
isImportDrivenSection(section) &&
portalStatus !== 'active' &&
!canUseOfflineCache
) {
return;
}
await this.initializeCurrentSectionContent(
section,
didBootstrapPlaylist
);
}
private syncRouteState(
section: PortalRailSection | null
): PortalRailSection | null {
if (!section) {
return null;
}
if (section === 'vod' || section === 'live' || section === 'series') {
this.xtreamStore.setSelectedContentType(section);
}
this.xtreamStore.setSelectedCategory(
getXtreamRouteCategoryId(this.router.url, section)
);
return section;
}
private async initializeCurrentSectionContent(
section: PortalRailSection | null,
didBootstrapPlaylist: boolean
): Promise<void> {
const playlist = this.xtreamStore.currentPlaylist();
const playlistId = this.xtreamStore.playlistId();
if (!playlist || playlist.id !== playlistId) {
return;
}
if (
isImportDrivenSection(section) &&
(didBootstrapPlaylist || !this.xtreamStore.isContentInitialized())
) {
await this.xtreamStore.initializeContent();
}
}
}
export function provideXtreamWorkspaceRouteSession(): Provider[] {
return [
XtreamWorkspaceRouteSession,
{
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useValue: () => {
inject(XtreamWorkspaceRouteSession);
},
},
];
}
@@ -0,0 +1,6 @@
import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
setupZoneTestEnv({
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
});
+28
View File
@@ -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"
]
}