Proyecto App Windows

This commit is contained in:
2026-05-03 23:36:48 +02:00
commit 96793b2e1e
1248 changed files with 189750 additions and 0 deletions
+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"
]
}