refactor(settings): split the settings page into per-section facades (#1274)

settings.component.ts had grown to 819 lines — past the CLAUDE.md target (<300)
and hard maximum, passing lint only because it sat in the max-lines baseline.

The behaviour moves into facades the template binds to directly, following the
precedent already in this folder: new app-update (218), form (197), epg (123),
embedded-mpv (74) and remote-control (37) facades, with playlist-reset extended
to 143 and settings-options to 200. The component is now a 259-line coordinator
holding capability flags, section nav, players() and the cross-facade flows.
settings.component.ts is removed from the max-lines baseline.

No behaviour change. One ordering detail: applyChangedSettings now applies
language/theme before kicking off the EPG re-fetch; changeTheme only touches DOM
theme sync and translate.use does not touch the form, so the two are
independent.
This commit is contained in:
4gray authored and GitHub committed 2026-07-26 22:57:16 +02:00
1 parent 08b868d6c1
commit f9ea3070ee
12 files changed
+931 -751

No files matched your search

@@ -0,0 +1,218 @@
import { inject, Injectable, signal } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DataService, RuntimeCapabilitiesService } from '@iptvnator/services';
import {
ELECTRON_BRIDGE_APP_UPDATE_STATUSES,
ElectronBridgeAppUpdateStatus,
} from '@iptvnator/shared/interfaces';
import { TranslateService } from '@ngx-translate/core';
import { take } from 'rxjs';
import { SettingsService } from '../services/settings.service';
import { AppUpdateReleaseNotesDialogComponent } from './app-update-release-notes-dialog.component';
const APP_UPDATE_STATUS_LOAD_ATTEMPTS = 60;
const APP_UPDATE_STATUS_LOAD_RETRY_DELAY_MS = 250;
/**
* Owns everything the About section needs to talk about versions: the
* electron-updater status stream and the "is my build outdated" message.
*/
@Injectable()
export class SettingsAppUpdateFacade {
private readonly dataService = inject(DataService);
private readonly matDialog = inject(MatDialog);
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly settingsService = inject(SettingsService);
private readonly translate = inject(TranslateService);
/** Latest updater status, polled once and then pushed by the backend */
readonly status = signal<ElectronBridgeAppUpdateStatus | null>(null);
/** Current version of the app */
readonly version = signal('');
/** Update message to show */
readonly updateMessage = signal('');
private unsubscribeStatus: (() => void) | null = null;
/** Subscribes to status pushes and kicks off the initial status load */
init(): void {
this.bindStatusEvents();
void this.loadStatus();
}
dispose(): void {
this.unsubscribeStatus?.();
this.unsubscribeStatus = null;
}
async checkForAppUpdate(): Promise<void> {
if (!this.runtime.isElectron || !window.electron?.checkForAppUpdate) {
return;
}
this.status.set(await window.electron.checkForAppUpdate());
}
async downloadAppUpdate(): Promise<void> {
if (!this.runtime.isElectron || !window.electron?.downloadAppUpdate) {
return;
}
this.status.set(await window.electron.downloadAppUpdate());
}
async installAppUpdate(): Promise<void> {
if (!this.runtime.isElectron || !window.electron?.installAppUpdate) {
return;
}
this.status.set(await window.electron.installAppUpdate());
}
openManualAppUpdate(): void {
const manualDownloadUrl = this.status()?.manualDownloadUrl;
if (!manualDownloadUrl) {
return;
}
window.open(manualDownloadUrl, '_blank', 'noreferrer');
}
openReleaseNotes(): void {
const status = this.status();
const isUpdateRelease =
status?.status === ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Available ||
status?.status ===
ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Downloading ||
status?.status === ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Downloaded;
const initialReleaseNotesVersion = isUpdateRelease
? (status?.latestVersion ??
status?.release?.version ??
status?.currentVersion)
: status?.currentVersion;
this.matDialog.open(AppUpdateReleaseNotesDialogComponent, {
autoFocus: false,
data: {
...(!isUpdateRelease ? { fallbackToLatest: true } : {}),
initialVersion: initialReleaseNotesVersion,
},
maxWidth: 'calc(100vw - 32px)',
restoreFocus: true,
width: '720px',
});
}
/**
* Checks whether the latest version of the application
* is used and updates the version message in the
* settings UI
*/
checkAppVersion(): void {
this.settingsService
.getAppVersion()
.pipe(take(1))
.subscribe((version) => this.showVersionInformation(version));
}
/**
* Updates the message in settings UI about the used
* version of the app
* @param currentVersion current version of the application
*/
showVersionInformation(currentVersion: string): void {
const isOutdated = this.isCurrentVersionOutdated(currentVersion);
if (isOutdated) {
this.updateMessage.set(
`${
this.translate.instant(
'SETTINGS.NEW_VERSION_AVAILABLE'
) as string
}: ${currentVersion}`
);
} else {
this.updateMessage.set(
this.translate.instant('SETTINGS.LATEST_VERSION')
);
}
}
/**
* Compares actual with latest version of the
* application
* @param latestVersion latest version
* @returns returns true if an update is available
*/
isCurrentVersionOutdated(latestVersion: string): boolean {
this.version.set(this.dataService.getAppVersion());
return this.settingsService.isVersionOutdated(
this.version(),
latestVersion
);
}
private bindStatusEvents(): void {
if (
!this.runtime.isElectron ||
!window.electron?.onAppUpdateStatusChange
) {
return;
}
this.unsubscribeStatus = window.electron.onAppUpdateStatusChange(
(status) => {
this.status.set(status);
}
);
}
/**
* The updater IPC handlers can still be registering while the settings
* page mounts, so the first load retries until the bridge answers.
*/
private async loadStatus(): Promise<void> {
if (!this.runtime.isElectron) {
return;
}
let lastError: unknown;
for (
let attempt = 1;
attempt <= APP_UPDATE_STATUS_LOAD_ATTEMPTS;
attempt += 1
) {
const electron = window.electron;
if (electron?.getAppUpdateStatus) {
try {
this.status.set(await electron.getAppUpdateStatus());
return;
} catch (error) {
lastError = error;
}
}
if (attempt === APP_UPDATE_STATUS_LOAD_ATTEMPTS) {
console.warn(
'Failed to load app update status:',
lastError ??
new Error('Desktop app update bridge is unavailable')
);
return;
}
await this.waitForRetry();
}
}
private async waitForRetry(): Promise<void> {
await new Promise<void>((resolve) => {
setTimeout(resolve, APP_UPDATE_STATUS_LOAD_RETRY_DELAY_MS);
});
}
}
@@ -0,0 +1,74 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { RuntimeCapabilitiesService } from '@iptvnator/services';
import { EmbeddedMpvSupport } from '@iptvnator/shared/interfaces';
/**
* Probes the desktop backend for embedded MPV support so the playback
* section can hide options the current build cannot deliver.
*/
@Injectable()
export class SettingsEmbeddedMpvFacade {
private readonly runtime = inject(RuntimeCapabilitiesService);
readonly support = signal<EmbeddedMpvSupport | null>(null);
readonly supported = computed(
() => this.runtime.isElectron && !!this.support()?.supported
);
readonly frameCopyAvailable = computed(
() => this.runtime.isElectron && !!this.support()?.frameCopyAvailable
);
readonly frameCopyActive = computed(
() => this.support()?.engine === 'frame-copy'
);
async load(): Promise<void> {
if (!this.runtime.isElectron) {
this.support.set({
supported: false,
platform: 'web',
reason: 'Embedded MPV requires the Electron desktop build.',
});
return;
}
if (!window.electron?.getEmbeddedMpvSupport) {
this.support.set({
supported: false,
platform: window.electron.platform,
reason: 'Embedded MPV support is not available in this build.',
});
return;
}
try {
this.support.set(await window.electron.getEmbeddedMpvSupport());
} catch (error) {
this.support.set({
supported: false,
platform: window.electron.platform,
reason: error instanceof Error ? error.message : String(error),
});
}
}
/**
* Opens the native folder picker for MPV recordings.
* @returns the selected folder, or null when the user cancelled or the
* desktop bridge cannot show the dialog
*/
async selectRecordingFolder(): Promise<string | null> {
if (
!this.runtime.isElectron ||
!window.electron?.selectEmbeddedMpvRecordingFolder
) {
return null;
}
return (
(await window.electron.selectEmbeddedMpvRecordingFolder()) ?? null
);
}
}
@@ -0,0 +1,123 @@
import { inject, Injectable, signal } from '@angular/core';
import {
EpgRuntimeBridgeService,
EpgService,
} from '@iptvnator/epg/data-access';
import { DialogService } from '@iptvnator/ui/components';
import { TranslateService } from '@ngx-translate/core';
import { SettingsStore } from '../services/settings-store.service';
import { SettingsFormFacade } from './settings-form.facade';
import { SettingsSnackbarService } from './settings-snackbar.service';
/**
* EPG maintenance actions offered by the settings page: force refreshes and
* the destructive "clear all EPG data" flow.
*/
@Injectable()
export class SettingsEpgFacade {
private readonly dialogService = inject(DialogService);
private readonly epgBridge = inject(EpgRuntimeBridgeService);
private readonly epgService = inject(EpgService);
private readonly formFacade = inject(SettingsFormFacade);
private readonly settingsSnackbar = inject(SettingsSnackbarService);
private readonly settingsStore = inject(SettingsStore);
private readonly translate = inject(TranslateService);
readonly isClearing = signal(false);
/**
* Force-fetch EPG for a single URL, bypassing the 12-hour freshness check.
* The plain fetchEpg would short-circuit on fresh data and click the
* refresh button would be a no-op — that's exactly not what the user
* intends when clicking "Refresh".
*/
refresh(url: string): void {
if (!this.epgBridge.supportsDataManagement || !url) {
return;
}
void this.epgBridge.forceFetchEpg(
url,
this.settingsStore.getTrustOptions()
);
}
/**
* Force-fetch every configured EPG URL sequentially. Empty fields are
* skipped. Each URL flows through the normal progress panel so the user
* gets visible per-URL feedback.
*/
refreshAll(): void {
if (!this.epgBridge.supportsDataManagement) return;
const options = this.settingsStore.getTrustOptions();
this.formFacade.epgUrls.forEach(
(url) => void this.epgBridge.forceFetchEpg(url, options)
);
}
/**
* Clears all EPG data from database and immediately re-fetches every
* configured URL so the user isn't left staring at an empty state.
* Tracks progress with `isClearing` so the UI can show a spinner
* and block double-clicks, and surfaces failures via a dedicated snackbar.
*/
clear(): void {
this.dialogService.openConfirmDialog({
title: this.translate.instant('SETTINGS.CLEAR_EPG_DIALOG.TITLE'),
message: this.translate.instant(
'SETTINGS.CLEAR_EPG_DIALOG.MESSAGE'
),
onConfirm: async (): Promise<void> => {
if (
!this.epgBridge.supportsDataManagement ||
this.isClearing()
) {
return;
}
this.isClearing.set(true);
try {
const result = await this.epgBridge.clearEpgData();
if (result && result.success === false) {
throw new Error('Clear EPG returned success=false');
}
this.settingsSnackbar.open(
this.translate.instant('SETTINGS.EPG_DATA_CLEARED')
);
this.refreshAll();
} catch (error) {
console.error('Failed to clear EPG data:', error);
this.settingsSnackbar.open(
this.translate.instant('SETTINGS.EPG_DATA_CLEAR_FAILED')
);
} finally {
this.isClearing.set(false);
}
},
});
}
/**
* Re-fetches the EPG sources that were just saved so the guide reflects
* the new configuration without a restart.
*/
fetchConfiguredEpg(): void {
if (!this.formFacade.supportsEpg) {
return;
}
const epgUrl = this.formFacade.form.value.epgUrl;
if (!epgUrl) {
return;
}
const validEpgUrls = (Array.isArray(epgUrl) ? epgUrl : [epgUrl]).filter(
(url): url is string => typeof url === 'string' && url !== ''
);
if (validEpgUrls.length > 0) {
// Fetch all EPG URLs at once
this.epgService.fetchEpg(validEpgUrls);
}
}
}
@@ -0,0 +1,197 @@
import { DestroyRef, inject, Injectable } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormArray, FormBuilder } from '@angular/forms';
import { EpgRuntimeBridgeService } from '@iptvnator/epg/data-access';
import { RuntimeCapabilitiesService } from '@iptvnator/services';
import {
CoverSize,
EpgViewMode,
Language,
Theme,
} from '@iptvnator/shared/interfaces';
import { TranslateService } from '@ngx-translate/core';
import { SettingsStore } from '../services/settings-store.service';
import { SettingsService } from '../services/settings.service';
import {
applyEpgUrlsToFormArray,
createEpgUrlControl,
createSettingsForm,
createSettingsFromFormValue,
SettingsForm,
} from './settings-form.utils';
type SettingsFormPatch = Parameters<SettingsForm['patchValue']>[0];
/**
* Owns the settings form: creation, hydration from the store, the small
* mutations the section components trigger, and persisting on submit.
*/
@Injectable()
export class SettingsFormFacade {
private readonly destroyRef = inject(DestroyRef);
private readonly epgBridge = inject(EpgRuntimeBridgeService);
private readonly formBuilder = inject(FormBuilder);
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly settingsService = inject(SettingsService);
private readonly settingsStore = inject(SettingsStore);
private readonly translate = inject(TranslateService);
readonly supportsEpg =
this.epgBridge.supportsImport && this.epgBridge.supportsDataManagement;
/** Settings form object */
readonly form = createSettingsForm(this.formBuilder, this.supportsEpg);
/** Form array with epg sources — absent when EPG is unsupported */
readonly epgUrl = this.form.get('epgUrl') as FormArray;
/** Trimmed, non-empty EPG source URLs currently in the form */
get epgUrls(): string[] {
return ((this.epgUrl?.value as string[] | undefined) ?? [])
.map((url) => url?.trim())
.filter((url): url is string => Boolean(url));
}
/** Waits for the persisted settings to be available */
loadSettings(): Promise<void> {
return this.settingsStore.loadSettings();
}
/**
* Sets saved settings from the indexed db store
*/
hydrateFromStore(): void {
const currentSettings = this.settingsStore.getSettings();
this.form.patchValue(currentSettings);
this.syncDashboardControlsEnabledState(
currentSettings.showDashboard ?? true
);
if (this.supportsEpg && currentSettings.epgUrl) {
this.epgUrl.clear();
this.setEpgUrls(currentSettings.epgUrl);
}
}
bindDashboardControlsEnabledState(): void {
this.form
.get('showDashboard')
?.valueChanges.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((showDashboard) =>
this.syncDashboardControlsEnabledState(showDashboard ?? true)
);
}
selectTheme(theme: Theme): void {
if (this.form.value.theme === theme) {
return;
}
this.patchAndMarkDirty({ theme }, 'theme');
this.settingsService.changeTheme(theme);
}
selectCoverSize(coverSize: CoverSize): void {
if (this.form.value.coverSize === coverSize) {
return;
}
this.patchAndMarkDirty({ coverSize }, 'coverSize');
void this.settingsStore.updateSettings({ coverSize });
}
selectEpgViewMode(epgViewMode: EpgViewMode): void {
if (this.form.value.epgViewMode === epgViewMode) {
return;
}
this.patchAndMarkDirty({ epgViewMode }, 'epgViewMode');
void this.settingsStore.updateSettings({ epgViewMode });
}
setRecordingFolder(recordingFolder: string): void {
this.patchAndMarkDirty({ recordingFolder }, 'recordingFolder');
}
/**
* Sets the epg urls to the form array
* @param epgUrls urls of the EPG sources
*/
setEpgUrls(epgUrls: string[] | string): void {
applyEpgUrlsToFormArray(this.epgUrl, epgUrls);
}
/**
* Initializes new entry in form array for EPG URL
*/
addEpgSource(): void {
this.epgUrl.insert(this.epgUrl.length, createEpgUrlControl());
}
/**
* Removes entry from form array for EPG URL
* @param index index of the item to remove
*/
removeEpgSource(index: number): void {
this.epgUrl.removeAt(index);
this.form.markAsDirty();
}
/**
* Persists the form to the settings store and mirrors the result to the
* desktop backend.
* @param onSaved runs after the store write, before the backend is
* notified, so the UI confirmation is not delayed by IPC
*/
async save(onSaved: () => void): Promise<void> {
const settings = createSettingsFromFormValue(
this.form,
this.settingsStore.getSettings()
);
await this.settingsStore.updateSettings(settings);
onSaved();
if (!window.electron) {
return;
}
window.electron.updateSettings(settings);
if (this.runtime.supportsExternalPlayerPathSettings) {
window.electron.setMpvPlayerPath(settings.mpvPlayerPath);
window.electron.setVlcPlayerPath(settings.vlcPlayerPath);
}
}
/** Applies the saved language/theme and resets the dirty state */
applySavedSettings(): void {
this.form.markAsPristine();
this.translate.use(this.form.value.language ?? Language.ENGLISH);
this.settingsService.changeTheme(
this.form.value.theme ?? Theme.SystemTheme
);
}
private patchAndMarkDirty(
value: SettingsFormPatch,
controlName: string
): void {
this.form.patchValue(value);
this.form.get(controlName)?.markAsDirty();
this.form.markAsDirty();
}
private syncDashboardControlsEnabledState(showDashboard: boolean): void {
const dashboardRails = this.form.get('dashboardRails');
if (!dashboardRails) {
return;
}
if (showDashboard) {
dashboardRails.enable({ emitEvent: false });
} else {
dashboardRails.disable({ emitEvent: false });
}
}
}
@@ -100,6 +100,33 @@ export const SETTINGS_EMBEDDED_PLAYER_OPTIONS: SettingsPlayerOption[] = [
},
];
export interface SettingsPlayerAvailability {
supportsEmbeddedMpv: boolean;
supportsManagedExternalPlayers: boolean;
}
/**
* Built-in web players are always offered; the OS-backed ones only show up
* when the current runtime can actually launch them.
*/
export function buildSettingsPlayerOptions({
supportsEmbeddedMpv,
supportsManagedExternalPlayers,
}: SettingsPlayerAvailability): SettingsPlayerOption[] {
return [
...SETTINGS_EMBEDDED_PLAYER_OPTIONS,
...(supportsEmbeddedMpv
? [
{
id: VideoPlayer.EmbeddedMpv,
labelKey: 'SETTINGS.PLAYER_EMBEDDED_MPV',
},
]
: []),
...(supportsManagedExternalPlayers ? SETTINGS_OS_PLAYER_OPTIONS : []),
];
}
export interface SettingsSectionVisibility {
supportsEpg: boolean;
supportsRemoteControl: boolean;
@@ -1,19 +1,30 @@
import { inject, Injectable, signal } from '@angular/core';
import { computed, inject, Injectable, signal } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { firstValueFrom } from 'rxjs';
import { PlaylistActions } from '@iptvnator/m3u-state';
import { firstValueFrom, take } from 'rxjs';
import { PlaylistActions, selectAllPlaylistsMeta } from '@iptvnator/m3u-state';
import {
DatabaseService,
DbOperationEvent,
PlaylistsService,
RuntimeCapabilitiesService,
} from '@iptvnator/services';
import {
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
} from './settings-delete-all-playlists-dialog.component';
import {
buildRemoveAllProgressLabel,
buildSettingsPlaylistDeleteSummary,
} from './settings-playlist-summary.utils';
import { SettingsPlaylistDeleteSummary } from './settings.models';
import { SettingsSnackbarService } from './settings-snackbar.service';
@Injectable()
export class SettingsPlaylistResetFacade {
private readonly databaseService = inject(DatabaseService);
private readonly matDialog = inject(MatDialog);
private readonly playlistsService = inject(PlaylistsService);
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly settingsSnackbar = inject(SettingsSnackbarService);
@@ -23,7 +34,59 @@ export class SettingsPlaylistResetFacade {
readonly isRemovingAllPlaylists = signal(false);
readonly removeAllProgress = signal<DbOperationEvent | null>(null);
async removeAllConfirmed(
private readonly playlists = this.store.selectSignal(
selectAllPlaylistsMeta
);
readonly deleteSummary = computed<SettingsPlaylistDeleteSummary>(() =>
buildSettingsPlaylistDeleteSummary(this.playlists())
);
readonly canRemoveAll = computed(
() => !this.isRemovingAllPlaylists() && this.deleteSummary().total > 0
);
readonly removeAllProgressLabel = computed(() =>
buildRemoveAllProgressLabel({
isRemovingAllPlaylists: this.isRemovingAllPlaylists(),
progress: this.removeAllProgress(),
translate: (key, params) => this.translate.instant(key, params),
})
);
/**
* Asks for confirmation in a dedicated dialog before wiping every
* playlist, so the summary of what is about to be lost is visible.
*/
confirmAndRemoveAll(waitForUiFeedbackFrame: () => Promise<void>): void {
if (!this.canRemoveAll()) {
return;
}
this.matDialog
.open<
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
boolean
>(SettingsDeleteAllPlaylistsDialogComponent, {
autoFocus: false,
data: {
summary: this.deleteSummary(),
},
maxWidth: 'calc(100vw - 32px)',
restoreFocus: true,
width: '460px',
})
.afterClosed()
.pipe(take(1))
.subscribe((confirmed) => {
if (confirmed) {
void this.removeAllConfirmed(waitForUiFeedbackFrame);
}
});
}
private async removeAllConfirmed(
waitForUiFeedbackFrame: () => Promise<void>
): Promise<void> {
if (this.isRemovingAllPlaylists()) {
@@ -0,0 +1,37 @@
import { inject, Injectable, signal } from '@angular/core';
import { RuntimeCapabilitiesService } from '@iptvnator/services';
/**
* Backs the remote-control section: the reachable LAN addresses and which of
* them currently shows its pairing QR code.
*/
@Injectable()
export class SettingsRemoteControlFacade {
private readonly runtime = inject(RuntimeCapabilitiesService);
/** Local IP addresses for remote control URL display */
readonly localIpAddresses = signal<string[]>([]);
/** Currently visible QR code IP (null = none visible) */
readonly visibleQrCodeIp = signal<string | null>(null);
/**
* Fetches local IP addresses for remote control URL display
*/
async fetchLocalIpAddresses(): Promise<void> {
if (
this.runtime.supportsRemoteControl &&
window.electron?.getLocalIpAddresses
) {
const addresses = await window.electron.getLocalIpAddresses();
this.localIpAddresses.set(addresses);
}
}
/**
* Toggle QR code visibility for a given IP address
*/
toggleQrCode(ip: string): void {
this.visibleQrCodeIp.update((visible) => (visible === ip ? null : ip));
}
}
@@ -38,8 +38,8 @@
[themeOptions]="themeOptions"
[coverSizeOptions]="coverSizeOptions"
[startupBehaviorOptions]="startupBehaviorOptions"
(selectTheme)="selectTheme($event)"
(selectCoverSize)="selectCoverSize($event)"
(selectTheme)="form.selectTheme($event)"
(selectCoverSize)="form.selectCoverSize($event)"
/>
<app-settings-playback-section
@@ -50,8 +50,8 @@
[isDesktop]="isDesktop"
[supportsManagedExternalPlayers]="supportsManagedExternalPlayers"
[supportsExternalPlayerPathSettings]="supportsExternalPlayerPathSettings"
[frameCopyAvailable]="frameCopyAvailable()"
[frameCopyActive]="frameCopyActive()"
[frameCopyAvailable]="embeddedMpv.frameCopyAvailable()"
[frameCopyActive]="embeddedMpv.frameCopyActive()"
(selectRecordingFolder)="selectRecordingFolder()"
/>
@@ -59,15 +59,15 @@
<app-settings-epg-section
[form]="settingsForm"
[activeSection]="activeSection()"
[epgUrl]="epgUrl"
[isClearingEpgData]="isClearingEpgData()"
[epgUrl]="form.epgUrl"
[isClearingEpgData]="epg.isClearing()"
[epgViewModeOptions]="epgViewModeOptions"
(refreshEpg)="refreshEpg($event)"
(removeEpgSource)="removeEpgSource($event)"
(addEpgSource)="addEpgSource()"
(refreshAllEpg)="refreshAllEpg()"
(clearEpgData)="clearEpgData()"
(selectEpgViewMode)="selectEpgViewMode($event)"
(refreshEpg)="epg.refresh($event)"
(removeEpgSource)="form.removeEpgSource($event)"
(addEpgSource)="form.addEpgSource()"
(refreshAllEpg)="epg.refreshAll()"
(clearEpgData)="epg.clear()"
(selectEpgViewMode)="form.selectEpgViewMode($event)"
/>
}
@@ -80,9 +80,9 @@
<app-settings-remote-control-section
[form]="settingsForm"
[activeSection]="activeSection()"
[localIpAddresses]="localIpAddresses()"
[visibleQrCodeIp]="visibleQrCodeIp()"
(toggleQrCode)="toggleQrCode($event)"
[localIpAddresses]="remoteControl.localIpAddresses()"
[visibleQrCodeIp]="remoteControl.visibleQrCodeIp()"
(toggleQrCode)="remoteControl.toggleQrCode($event)"
/>
}
@@ -94,33 +94,33 @@
<app-settings-backup-section
[activeSection]="activeSection()"
[isPwa]="isPwa"
[isRemovingAllPlaylists]="isRemovingAllPlaylists()"
[isExportingData]="isExportingData()"
[isRemovingAllPlaylists]="playlistReset.isRemovingAllPlaylists()"
[isExportingData]="backup.isExportingData()"
(importData)="importData()"
(exportData)="exportData()"
/>
<app-settings-reset-section
[activeSection]="activeSection()"
[isRemovingAllPlaylists]="isRemovingAllPlaylists()"
[canRemoveAllPlaylists]="canRemoveAllPlaylists()"
[playlistDeleteSummary]="playlistDeleteSummary()"
[removeAllProgressLabel]="removeAllProgressLabel()"
[isRemovingAllPlaylists]="playlistReset.isRemovingAllPlaylists()"
[canRemoveAllPlaylists]="playlistReset.canRemoveAll()"
[playlistDeleteSummary]="playlistReset.deleteSummary()"
[removeAllProgressLabel]="playlistReset.removeAllProgressLabel()"
(removeAll)="removeAll()"
/>
<app-settings-about-section
[activeSection]="activeSection()"
[isDesktop]="isDesktop"
[version]="version"
[version]="appUpdate.version()"
[buildCommit]="buildCommit"
[updateMessage]="updateMessage"
[appUpdateStatus]="appUpdateStatus()"
(checkForAppUpdate)="checkForAppUpdate()"
(downloadAppUpdate)="downloadAppUpdate()"
(installAppUpdate)="installAppUpdate()"
(openManualAppUpdate)="openManualAppUpdate()"
(openAppUpdateReleaseNotes)="openAppUpdateReleaseNotes()"
[updateMessage]="appUpdate.updateMessage()"
[appUpdateStatus]="appUpdate.status()"
(checkForAppUpdate)="appUpdate.checkForAppUpdate()"
(downloadAppUpdate)="appUpdate.downloadAppUpdate()"
(installAppUpdate)="appUpdate.installAppUpdate()"
(openManualAppUpdate)="appUpdate.openManualAppUpdate()"
(openAppUpdateReleaseNotes)="appUpdate.openReleaseNotes()"
/>
<footer class="action-bar" data-test-id="settings-action-bar">
@@ -46,6 +46,7 @@ import {
} from '@iptvnator/shared/interfaces';
import { SettingsComponent } from './settings.component';
import { AppUpdateReleaseNotesDialogComponent } from './app-update-release-notes-dialog.component';
import { SettingsAppUpdateFacade } from './settings-app-update.facade';
import { signal } from '@angular/core';
import { SettingsContextService } from '@iptvnator/workspace/shell/util';
@@ -171,10 +172,28 @@ interface SettingsSectionScrollDirectiveTestApi {
}
interface SettingsComponentPrivateTestApi {
loadAppUpdateStatus(): Promise<void>;
matDialog: MatDialog;
waitForUiFeedbackFrame(): Promise<void>;
waitForAppUpdateStatusRetry(): Promise<void>;
}
interface SettingsAppUpdateFacadePrivateTestApi {
loadStatus(): Promise<void>;
waitForRetry(): Promise<void>;
}
/**
* `ngOnInit` kicks off a version check and a LAN address lookup; both are
* stubbed on the owning facades so tests stay deterministic.
*/
function stubSettingsSideEffects(settingsComponent: SettingsComponent): void {
jest.spyOn(
settingsComponent.appUpdate,
'checkAppVersion'
).mockImplementation();
jest.spyOn(
settingsComponent.remoteControl,
'fetchLocalIpAddresses'
).mockResolvedValue(undefined);
}
describe('SettingsComponent', () => {
@@ -361,10 +380,7 @@ describe('SettingsComponent', () => {
snackBar = TestBed.inject(MatSnackBar) as unknown as MatSnackBarStub;
component = fixture.componentInstance;
component.checkAppVersion = jest.fn();
component.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(component);
fixture.detectChanges();
});
@@ -384,6 +400,13 @@ describe('SettingsComponent', () => {
return settingsComponent as unknown as SettingsComponentPrivateTestApi;
}
/** Exposes the app update facade's retry internals to the tests */
function appUpdateFacade(): SettingsAppUpdateFacade &
SettingsAppUpdateFacadePrivateTestApi {
return component.appUpdate as SettingsAppUpdateFacade &
SettingsAppUpdateFacadePrivateTestApi;
}
it('should create and init component', () => {
expect(component).toBeTruthy();
});
@@ -405,7 +428,7 @@ describe('SettingsComponent', () => {
expect(window.electron.onAppUpdateStatusChange).toHaveBeenCalledTimes(
1
);
expect(component.appUpdateStatus()).toEqual(pushedStatus);
expect(component.appUpdate.status()).toEqual(pushedStatus);
});
it('retries the initial app update status load when IPC handlers are still starting', async () => {
@@ -419,15 +442,14 @@ describe('SettingsComponent', () => {
.mockReset()
.mockRejectedValueOnce(new Error('No handler registered'))
.mockResolvedValueOnce(retriedStatus);
jest.spyOn(
privateApi(component),
'waitForAppUpdateStatusRetry'
).mockResolvedValue(undefined);
jest.spyOn(appUpdateFacade(), 'waitForRetry').mockResolvedValue(
undefined
);
await privateApi(component).loadAppUpdateStatus();
await appUpdateFacade().loadStatus();
expect(window.electron.getAppUpdateStatus).toHaveBeenCalledTimes(2);
expect(component.appUpdateStatus()).toEqual(retriedStatus);
expect(component.appUpdate.status()).toEqual(retriedStatus);
});
it('waits for the desktop app update bridge method before loading status', async () => {
@@ -441,28 +463,27 @@ describe('SettingsComponent', () => {
.getAppUpdateStatus;
let retryCount = 0;
const getStatus = jest.fn().mockResolvedValue(retriedStatus);
jest.spyOn(
privateApi(component),
'waitForAppUpdateStatusRetry'
).mockImplementation(async () => {
retryCount += 1;
jest.spyOn(appUpdateFacade(), 'waitForRetry').mockImplementation(
async () => {
retryCount += 1;
if (retryCount === 1) {
window.electron.getAppUpdateStatus = getStatus;
if (retryCount === 1) {
window.electron.getAppUpdateStatus = getStatus;
}
}
});
);
await privateApi(component).loadAppUpdateStatus();
await appUpdateFacade().loadStatus();
expect(retryCount).toBe(1);
expect(getStatus).toHaveBeenCalledTimes(1);
expect(component.appUpdateStatus()).toEqual(retriedStatus);
expect(component.appUpdate.status()).toEqual(retriedStatus);
});
it('forwards app update actions to the desktop bridge', async () => {
await component.checkForAppUpdate();
await component.downloadAppUpdate();
await component.installAppUpdate();
await component.appUpdate.checkForAppUpdate();
await component.appUpdate.downloadAppUpdate();
await component.appUpdate.installAppUpdate();
expect(window.electron.checkForAppUpdate).toHaveBeenCalledTimes(1);
expect(window.electron.downloadAppUpdate).toHaveBeenCalledTimes(1);
@@ -471,13 +492,13 @@ describe('SettingsComponent', () => {
it('opens the manual release URL from unsupported update status', () => {
const openSpy = jest.spyOn(window, 'open').mockReturnValue(null);
component.appUpdateStatus.set({
component.appUpdate.status.set({
...DEFAULT_APP_UPDATE_STATUS,
status: ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Unsupported,
supportedSelfUpdate: false,
});
component.openManualAppUpdate();
component.appUpdate.openManualAppUpdate();
expect(openSpy).toHaveBeenCalledWith(
DEFAULT_APP_UPDATE_STATUS.manualDownloadUrl,
@@ -490,13 +511,13 @@ describe('SettingsComponent', () => {
const openSpy = jest
.spyOn(privateApi(component).matDialog, 'open')
.mockReturnValue(createDialogRef(false));
component.appUpdateStatus.set({
component.appUpdate.status.set({
...DEFAULT_APP_UPDATE_STATUS,
latestVersion: '0.23.0',
status: ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Available,
});
component.openAppUpdateReleaseNotes();
component.appUpdate.openReleaseNotes();
expect(openSpy).toHaveBeenCalledWith(
AppUpdateReleaseNotesDialogComponent,
@@ -512,7 +533,7 @@ describe('SettingsComponent', () => {
const openSpy = jest
.spyOn(privateApi(component).matDialog, 'open')
.mockReturnValue(createDialogRef(false));
component.appUpdateStatus.set({
component.appUpdate.status.set({
...DEFAULT_APP_UPDATE_STATUS,
latestVersion: '0.21.0',
release: {
@@ -521,7 +542,7 @@ describe('SettingsComponent', () => {
status: ELECTRON_BRIDGE_APP_UPDATE_STATUSES.NotAvailable,
});
component.openAppUpdateReleaseNotes();
component.appUpdate.openReleaseNotes();
expect(openSpy).toHaveBeenCalledWith(
AppUpdateReleaseNotesDialogComponent,
@@ -549,10 +570,7 @@ describe('SettingsComponent', () => {
const dialogFixture = TestBed.createComponent(SettingsComponent);
const dialogComponent = dialogFixture.componentInstance;
dialogComponent.checkAppVersion = jest.fn();
dialogComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(dialogComponent);
dialogComponent.isDialog = true;
dialogFixture.detectChanges();
@@ -587,10 +605,7 @@ describe('SettingsComponent', () => {
scrollTo,
} as unknown as HTMLElement;
scrollComponent.checkAppVersion = jest.fn();
scrollComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(scrollComponent);
scrollFixture.detectChanges();
const scrollDirective = scrollFixture.debugElement
.query(By.directive(SettingsSectionScrollDirective))
@@ -656,7 +671,7 @@ describe('SettingsComponent', () => {
...settings,
});
component.setSettings();
component.form.hydrateFromStore();
//expect(settingsStore.loadSettings).toHaveBeenCalled();
expect(component.settingsForm.value).toEqual({
@@ -671,7 +686,7 @@ describe('SettingsComponent', () => {
webPlayerSharedControls: true,
});
component.setSettings();
component.form.hydrateFromStore();
expect(
component.settingsForm.get('webPlayerSharedControls')?.value
@@ -733,10 +748,7 @@ describe('SettingsComponent', () => {
TestBed.createComponent(SettingsComponent);
const partialBridgeComponent =
partialBridgeFixture.componentInstance;
partialBridgeComponent.checkAppVersion = jest.fn();
partialBridgeComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(partialBridgeComponent);
partialBridgeFixture.detectChanges();
expect(partialBridgeComponent.isDesktop).toBe(true);
@@ -787,10 +799,7 @@ describe('SettingsComponent', () => {
TestBed.createComponent(SettingsComponent);
const launchOnlyBridgeComponent =
launchOnlyBridgeFixture.componentInstance;
launchOnlyBridgeComponent.checkAppVersion = jest.fn();
launchOnlyBridgeComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(launchOnlyBridgeComponent);
launchOnlyBridgeFixture.detectChanges();
expect(
@@ -880,7 +889,7 @@ describe('SettingsComponent', () => {
currentVersion
);
const isOutdated =
component.isCurrentVersionOutdated(latestVersion);
component.appUpdate.isCurrentVersionOutdated(latestVersion);
expect(isOutdated).toBeTruthy();
});
@@ -889,11 +898,11 @@ describe('SettingsComponent', () => {
jest.spyOn(electronService, 'getAppVersion').mockReturnValue(
currentVersion
);
component.showVersionInformation(latestVersion);
component.appUpdate.showVersionInformation(latestVersion);
expect(translate.instant).toHaveBeenCalledWith(
'SETTINGS.NEW_VERSION_AVAILABLE'
);
expect(component.updateMessage).toBe(
expect(component.appUpdate.updateMessage()).toBe(
'New version available: 1.0.0'
);
});
@@ -906,7 +915,7 @@ describe('SettingsComponent', () => {
fixture.nativeElement as HTMLElement
).querySelector('.danger-zone__button') as HTMLButtonElement | null;
expect(component.canRemoveAllPlaylists()).toBe(false);
expect(component.playlistReset.canRemoveAll()).toBe(false);
expect(deleteButton?.disabled).toBe(true);
});
@@ -929,7 +938,7 @@ describe('SettingsComponent', () => {
component.removeAll();
expect(component.playlistDeleteSummary()).toEqual({
expect(component.playlistReset.deleteSummary()).toEqual({
total: 3,
m3u: 1,
xtream: 1,
@@ -1006,8 +1015,8 @@ describe('SettingsComponent', () => {
await Promise.resolve();
fixture.detectChanges();
expect(component.isRemovingAllPlaylists()).toBe(true);
expect(component.removeAllProgressLabel()).toBe('3/7');
expect(component.playlistReset.isRemovingAllPlaylists()).toBe(true);
expect(component.playlistReset.removeAllProgressLabel()).toBe('3/7');
expect(databaseService.deleteAllPlaylists).toHaveBeenCalledWith(
expect.objectContaining({
operationId: 'delete-all-op',
@@ -1018,8 +1027,8 @@ describe('SettingsComponent', () => {
resolveDelete(true);
await fixture.whenStable();
expect(component.isRemovingAllPlaylists()).toBe(false);
expect(component.removeAllProgress()).toBeNull();
expect(component.playlistReset.isRemovingAllPlaylists()).toBe(false);
expect(component.playlistReset.removeAllProgress()).toBeNull();
expect(dispatchSpy).toHaveBeenCalledWith(
PlaylistActions.removeAllPlaylists()
);
@@ -1042,10 +1051,7 @@ describe('SettingsComponent', () => {
const browserFixture = TestBed.createComponent(SettingsComponent);
const browserComponent = browserFixture.componentInstance;
browserComponent.checkAppVersion = jest.fn();
browserComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(browserComponent);
browserFixture.detectChanges();
expect(browserComponent.isDesktop).toBe(false);
@@ -1104,7 +1110,7 @@ describe('SettingsComponent', () => {
it('should force-fetch EPG for a single URL (bypassing freshness cache)', () => {
const url = 'http://epg-url-here/data.xml';
component.refreshEpg(url);
component.epg.refresh(url);
expect(epgBridge.forceFetchEpg).toHaveBeenCalledWith(url, {
trustedPrivateNetworkEpgUrls: [],
trustedInsecureTlsHosts: [],
@@ -1122,18 +1128,18 @@ describe('SettingsComponent', () => {
void onConfirm();
}
);
const refreshSpy = jest.spyOn(component, 'refreshAllEpg');
const refreshSpy = jest.spyOn(component.epg, 'refreshAll');
jest.spyOn(translate, 'instant').mockImplementation((key) => key);
component.clearEpgData();
component.epg.clear();
expect(component.isClearingEpgData()).toBe(true);
expect(component.epg.isClearing()).toBe(true);
expect(refreshSpy).not.toHaveBeenCalled();
resolveClear();
await fixture.whenStable();
expect(component.isClearingEpgData()).toBe(false);
expect(component.epg.isClearing()).toBe(false);
expect(snackBar.open).toHaveBeenCalledWith(
'SETTINGS.EPG_DATA_CLEARED',
undefined,
@@ -1163,7 +1169,7 @@ describe('SettingsComponent', () => {
const exportPromise = component.exportData();
expect(component.isExportingData()).toBe(true);
expect(component.backup.isExportingData()).toBe(true);
resolveExport({
defaultFileName: 'iptvnator-playlist-backup-2026-04-21.json',
@@ -1192,7 +1198,7 @@ describe('SettingsComponent', () => {
'/tmp/backup.json',
'{}'
);
expect(component.isExportingData()).toBe(false);
expect(component.backup.isExportingData()).toBe(false);
});
it('falls back to browser backup download when desktop file-save preload is incomplete', async () => {
@@ -1225,10 +1231,7 @@ describe('SettingsComponent', () => {
partialFileSaveFixture = TestBed.createComponent(SettingsComponent);
const partialFileSaveComponent =
partialFileSaveFixture.componentInstance;
partialFileSaveComponent.checkAppVersion = jest.fn();
partialFileSaveComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(partialFileSaveComponent);
partialFileSaveFixture.detectChanges();
expect(partialFileSaveComponent.isDesktop).toBe(true);
@@ -1265,14 +1268,14 @@ describe('SettingsComponent', () => {
void onConfirm();
}
);
const refreshSpy = jest.spyOn(component, 'refreshAllEpg');
const refreshSpy = jest.spyOn(component.epg, 'refreshAll');
jest.spyOn(translate, 'instant').mockImplementation((key) => key);
jest.spyOn(console, 'error').mockImplementation();
component.clearEpgData();
component.epg.clear();
await fixture.whenStable();
expect(component.isClearingEpgData()).toBe(false);
expect(component.epg.isClearing()).toBe(false);
expect(snackBar.open).toHaveBeenCalledWith(
'SETTINGS.EPG_DATA_CLEAR_FAILED',
undefined,
@@ -1492,10 +1495,7 @@ describe('SettingsComponent', () => {
const webFixture = TestBed.createComponent(SettingsComponent);
const webComponent = webFixture.componentInstance;
webComponent.checkAppVersion = jest.fn();
webComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
stubSettingsSideEffects(webComponent);
webFixture.detectChanges();
await webFixture.whenStable();
+74 -634
View File
@@ -4,14 +4,11 @@ import {
computed,
inject,
Input,
DestroyRef,
OnDestroy,
OnInit,
signal,
ViewEncapsulation,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormArray, FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
@@ -20,79 +17,45 @@ import {
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { Router } from '@angular/router';
import {
EpgRuntimeBridgeService,
EpgService,
} from '@iptvnator/epg/data-access';
import { SettingsContextService } from '@iptvnator/workspace/shell/util';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { DialogService } from '@iptvnator/ui/components';
import {
selectAllPlaylistsMeta,
selectIsEpgAvailable,
} from '@iptvnator/m3u-state';
import { take } from 'rxjs';
import { DataService, RuntimeCapabilitiesService } from '@iptvnator/services';
import {
EmbeddedMpvSupport,
CoverSize,
ELECTRON_BRIDGE_APP_UPDATE_STATUSES,
ElectronBridgeAppUpdateStatus,
EpgViewMode,
Language,
StreamFormat,
Theme,
VideoPlayer,
} from '@iptvnator/shared/interfaces';
import { RuntimeCapabilitiesService } from '@iptvnator/services';
import { Language, StreamFormat } from '@iptvnator/shared/interfaces';
import { BUILD_COMMIT } from '../../environments/build-commit';
import { SettingsStore } from '../services/settings-store.service';
import { SettingsService } from './../services/settings.service';
import { SettingsAboutSectionComponent } from './settings-about-section.component';
import { SettingsAppUpdateFacade } from './settings-app-update.facade';
import { SettingsBackupSectionComponent } from './settings-backup-section.component';
import { SettingsDashboardSectionComponent } from './settings-dashboard-section.component';
import {
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
} from './settings-delete-all-playlists-dialog.component';
import { SettingsEmbeddedMpvFacade } from './settings-embedded-mpv.facade';
import { SettingsEpgFacade } from './settings-epg.facade';
import { SettingsEpgSectionComponent } from './settings-epg-section.component';
import {
applyEpgUrlsToFormArray,
createEpgUrlControl,
createSettingsForm,
createSettingsFromFormValue,
} from './settings-form.utils';
import { SettingsFormFacade } from './settings-form.facade';
import { SettingsGeneralSectionComponent } from './settings-general-section.component';
import { SettingsSection } from './settings.models';
import {
SettingsPlaylistDeleteSummary,
SettingsSection,
} from './settings.models';
import {
buildSettingsPlayerOptions,
buildSettingsSectionNavItems,
SETTINGS_COVER_SIZE_OPTIONS,
SETTINGS_EMBEDDED_PLAYER_OPTIONS,
SETTINGS_EPG_VIEW_MODE_OPTIONS,
SETTINGS_OS_PLAYER_OPTIONS,
SETTINGS_STARTUP_BEHAVIOR_OPTIONS,
SETTINGS_THEME_OPTIONS,
} from './settings-options';
import { SettingsPlaybackSectionComponent } from './settings-playback-section.component';
import { SettingsRemoteControlFacade } from './settings-remote-control.facade';
import { SettingsRemoteControlSectionComponent } from './settings-remote-control-section.component';
import { SettingsResetSectionComponent } from './settings-reset-section.component';
import { SettingsSectionScrollDirective } from './settings-section-scroll.directive';
import { SettingsTmdbSectionComponent } from './settings-tmdb-section.component';
import { SettingsBackupFacade } from './settings-backup.facade';
import { SettingsPlaylistResetFacade } from './settings-playlist-reset.facade';
import {
buildRemoveAllProgressLabel,
buildSettingsPlaylistDeleteSummary,
} from './settings-playlist-summary.utils';
import { SettingsSnackbarService } from './settings-snackbar.service';
import { AppUpdateReleaseNotesDialogComponent } from './app-update-release-notes-dialog.component';
const APP_UPDATE_STATUS_LOAD_ATTEMPTS = 60;
const APP_UPDATE_STATUS_LOAD_RETRY_DELAY_MS = 250;
/**
* Thin coordinator for the settings page. The behaviour of each section lives
* in a dedicated facade the template binds to directly; what stays here is the
* page-level wiring: environment capabilities, section navigation, and the
* save/close flow that spans several facades.
*/
@Component({
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss'],
@@ -119,33 +82,38 @@ const APP_UPDATE_STATUS_LOAD_RETRY_DELAY_MS = 250;
SettingsTmdbSectionComponent,
],
providers: [
SettingsAppUpdateFacade,
SettingsBackupFacade,
SettingsEmbeddedMpvFacade,
SettingsEpgFacade,
SettingsFormFacade,
SettingsPlaylistResetFacade,
SettingsRemoteControlFacade,
SettingsSnackbarService,
],
})
export class SettingsComponent implements OnInit, OnDestroy {
private dialogService = inject(DialogService);
public dataService = inject(DataService);
private epgService = inject(EpgService);
private formBuilder = inject(FormBuilder);
private destroyRef = inject(DestroyRef);
private router = inject(Router);
private settingsService = inject(SettingsService);
private settingsSnackbar = inject(SettingsSnackbarService);
private store = inject(Store);
private translate = inject(TranslateService);
private matDialog = inject(MatDialog);
private readonly backupFacade = inject(SettingsBackupFacade);
private readonly playlistResetFacade = inject(SettingsPlaylistResetFacade);
readonly appUpdate = inject(SettingsAppUpdateFacade);
readonly backup = inject(SettingsBackupFacade);
readonly embeddedMpv = inject(SettingsEmbeddedMpvFacade);
readonly epg = inject(SettingsEpgFacade);
readonly form = inject(SettingsFormFacade);
readonly playlistReset = inject(SettingsPlaylistResetFacade);
readonly remoteControl = inject(SettingsRemoteControlFacade);
private readonly settingsCtx = inject(SettingsContextService);
private readonly settingsSnackbar = inject(SettingsSnackbarService);
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly epgBridge = inject(EpgRuntimeBridgeService);
private readonly matDialog = inject(MatDialog);
private readonly router = inject(Router);
private readonly translate = inject(TranslateService);
private readonly dialogData = inject<{ isDialog: boolean } | null>(
MAT_DIALOG_DATA,
{ optional: true }
);
@Input() isDialog = this.dialogData?.isDialog ?? false;
/** List with available languages as enum */
readonly languageEnum = Language;
@@ -154,114 +122,41 @@ export class SettingsComponent implements OnInit, OnDestroy {
/** Flag that indicates whether the app runs in electron environment */
readonly isDesktop = this.runtime.isElectron;
readonly isPwa = this.runtime.isPwa;
readonly supportsDesktopFileSave = this.runtime.supportsDesktopFileSave;
readonly supportsEpg =
this.epgBridge.supportsImport && this.epgBridge.supportsDataManagement;
readonly supportsEpg = this.form.supportsEpg;
readonly supportsManagedExternalPlayers =
this.runtime.supportsManagedExternalPlayers;
readonly supportsExternalPlayerPathSettings =
this.runtime.supportsExternalPlayerPathSettings;
readonly supportsRemoteControl = this.runtime.supportsRemoteControl;
readonly embeddedMpvSupport = signal<EmbeddedMpvSupport | null>(null);
readonly supportsEmbeddedMpv = computed(
() => this.isDesktop && !!this.embeddedMpvSupport()?.supported
);
readonly frameCopyAvailable = computed(
() => this.isDesktop && !!this.embeddedMpvSupport()?.frameCopyAvailable
);
readonly frameCopyActive = computed(
() => this.embeddedMpvSupport()?.engine === 'frame-copy'
);
readonly isPwa = this.runtime.isPwa;
private readonly settingsCtx = inject(SettingsContextService);
readonly activeSection = this.settingsCtx.activeSection;
readonly osPlayers = computed(() => [
...(this.supportsEmbeddedMpv()
? [
{
id: VideoPlayer.EmbeddedMpv,
labelKey: 'SETTINGS.PLAYER_EMBEDDED_MPV',
},
]
: []),
...(this.supportsManagedExternalPlayers
? SETTINGS_OS_PLAYER_OPTIONS
: []),
]);
/** Settings form object */
readonly settingsForm = this.form.form;
/** Player options */
readonly players = computed(() => [
...SETTINGS_EMBEDDED_PLAYER_OPTIONS,
...this.osPlayers(),
]);
/** Current version of the app */
version = '';
readonly players = computed(() =>
buildSettingsPlayerOptions({
supportsEmbeddedMpv: this.embeddedMpv.supported(),
supportsManagedExternalPlayers: this.supportsManagedExternalPlayers,
})
);
/** Git commit the app was built from (CI builds only) */
readonly buildCommit = BUILD_COMMIT;
/** Update message to show */
updateMessage = '';
readonly appUpdateStatus = signal<ElectronBridgeAppUpdateStatus | null>(
null
);
/** EPG availability flag */
epgAvailable$ = this.store.select(selectIsEpgAvailable);
readonly playlists = this.store.selectSignal(selectAllPlaylistsMeta);
readonly themeOptions = SETTINGS_THEME_OPTIONS;
readonly coverSizeOptions = SETTINGS_COVER_SIZE_OPTIONS;
readonly startupBehaviorOptions = SETTINGS_STARTUP_BEHAVIOR_OPTIONS;
readonly epgViewModeOptions = SETTINGS_EPG_VIEW_MODE_OPTIONS;
/** Settings form object */
settingsForm = createSettingsForm(this.formBuilder, this.supportsEpg);
/** Form array with epg sources */
epgUrl = this.settingsForm.get('epgUrl') as FormArray;
/** Local IP addresses for remote control URL display */
localIpAddresses = signal<string[]>([]);
/** Currently visible QR code IP (null = none visible) */
visibleQrCodeIp = signal<string | null>(null);
readonly isRemovingAllPlaylists =
this.playlistResetFacade.isRemovingAllPlaylists;
readonly isClearingEpgData = signal(false);
readonly isExportingData = this.backupFacade.isExportingData;
readonly removeAllProgress = this.playlistResetFacade.removeAllProgress;
private settingsStore = inject(SettingsStore);
readonly sectionNavItems: SettingsSection[] = buildSettingsSectionNavItems({
supportsEpg: this.supportsEpg,
supportsRemoteControl: this.supportsRemoteControl,
});
readonly playlistDeleteSummary = computed<SettingsPlaylistDeleteSummary>(
() => buildSettingsPlaylistDeleteSummary(this.playlists())
);
readonly canRemoveAllPlaylists = computed(
() =>
!this.isRemovingAllPlaylists() &&
this.playlistDeleteSummary().total > 0
);
private unsubscribeAppUpdateStatus: (() => void) | null = null;
readonly removeAllProgressLabel = computed(() => {
return buildRemoveAllProgressLabel({
isRemovingAllPlaylists: this.isRemovingAllPlaylists(),
progress: this.removeAllProgress(),
translate: (key, params) => this.translate.instant(key, params),
});
});
get sectionNav(): SettingsSection[] {
return this.sectionNavItems.filter((section) => section.visible);
}
@@ -272,338 +167,31 @@ export class SettingsComponent implements OnInit, OnDestroy {
*/
async ngOnInit(): Promise<void> {
// Wait for settings to load before setting the form
await this.settingsStore.loadSettings();
this.setSettings();
this.bindDashboardControlsEnabledState();
void this.loadEmbeddedMpvSupport();
this.checkAppVersion();
this.bindAppUpdateStatusEvents();
void this.loadAppUpdateStatus();
void this.fetchLocalIpAddresses();
await this.form.loadSettings();
this.form.hydrateFromStore();
this.form.bindDashboardControlsEnabledState();
void this.embeddedMpv.load();
this.appUpdate.checkAppVersion();
this.appUpdate.init();
void this.remoteControl.fetchLocalIpAddresses();
if (!this.isDialog) {
this.settingsCtx.setSections(this.sectionNav);
}
}
private async loadEmbeddedMpvSupport(): Promise<void> {
if (!this.isDesktop) {
this.embeddedMpvSupport.set({
supported: false,
platform: 'web',
reason: 'Embedded MPV requires the Electron desktop build.',
});
return;
}
if (!window.electron?.getEmbeddedMpvSupport) {
this.embeddedMpvSupport.set({
supported: false,
platform: window.electron.platform,
reason: 'Embedded MPV support is not available in this build.',
});
return;
}
try {
this.embeddedMpvSupport.set(
await window.electron.getEmbeddedMpvSupport()
);
} catch (error) {
this.embeddedMpvSupport.set({
supported: false,
platform: window.electron.platform,
reason: error instanceof Error ? error.message : String(error),
});
}
}
ngOnDestroy(): void {
this.unsubscribeAppUpdateStatus?.();
this.unsubscribeAppUpdateStatus = null;
this.appUpdate.dispose();
this.settingsCtx.reset();
}
private bindAppUpdateStatusEvents(): void {
if (!this.isDesktop || !window.electron?.onAppUpdateStatusChange) {
return;
}
this.unsubscribeAppUpdateStatus =
window.electron.onAppUpdateStatusChange((status) => {
this.appUpdateStatus.set(status);
});
}
private async loadAppUpdateStatus(): Promise<void> {
if (!this.isDesktop) {
return;
}
let lastError: unknown;
for (
let attempt = 1;
attempt <= APP_UPDATE_STATUS_LOAD_ATTEMPTS;
attempt += 1
) {
const electron = window.electron;
if (electron?.getAppUpdateStatus) {
try {
this.appUpdateStatus.set(
await electron.getAppUpdateStatus()
);
return;
} catch (error) {
lastError = error;
}
}
if (attempt === APP_UPDATE_STATUS_LOAD_ATTEMPTS) {
console.warn(
'Failed to load app update status:',
lastError ??
new Error('Desktop app update bridge is unavailable')
);
return;
}
await this.waitForAppUpdateStatusRetry();
}
}
private async waitForAppUpdateStatusRetry(): Promise<void> {
await new Promise<void>((resolve) => {
setTimeout(resolve, APP_UPDATE_STATUS_LOAD_RETRY_DELAY_MS);
});
}
async checkForAppUpdate(): Promise<void> {
if (!this.isDesktop || !window.electron?.checkForAppUpdate) {
return;
}
this.appUpdateStatus.set(await window.electron.checkForAppUpdate());
}
async downloadAppUpdate(): Promise<void> {
if (!this.isDesktop || !window.electron?.downloadAppUpdate) {
return;
}
this.appUpdateStatus.set(await window.electron.downloadAppUpdate());
}
async installAppUpdate(): Promise<void> {
if (!this.isDesktop || !window.electron?.installAppUpdate) {
return;
}
this.appUpdateStatus.set(await window.electron.installAppUpdate());
}
openManualAppUpdate(): void {
const manualDownloadUrl = this.appUpdateStatus()?.manualDownloadUrl;
if (!manualDownloadUrl) {
return;
}
window.open(manualDownloadUrl, '_blank', 'noreferrer');
}
openAppUpdateReleaseNotes(): void {
const status = this.appUpdateStatus();
const isUpdateRelease =
status?.status === ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Available ||
status?.status ===
ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Downloading ||
status?.status === ELECTRON_BRIDGE_APP_UPDATE_STATUSES.Downloaded;
const initialReleaseNotesVersion = isUpdateRelease
? (status?.latestVersion ??
status?.release?.version ??
status?.currentVersion)
: status?.currentVersion;
this.matDialog.open(AppUpdateReleaseNotesDialogComponent, {
autoFocus: false,
data: {
...(!isUpdateRelease ? { fallbackToLatest: true } : {}),
initialVersion: initialReleaseNotesVersion,
},
maxWidth: 'calc(100vw - 32px)',
restoreFocus: true,
width: '720px',
});
}
/**
* Fetches local IP addresses for remote control URL display
*/
async fetchLocalIpAddresses(): Promise<void> {
if (
this.supportsRemoteControl &&
window.electron?.getLocalIpAddresses
) {
const addresses = await window.electron.getLocalIpAddresses();
this.localIpAddresses.set(addresses);
}
}
/**
* Toggle QR code visibility for a given IP address
*/
toggleQrCode(ip: string): void {
if (this.visibleQrCodeIp() === ip) {
this.visibleQrCodeIp.set(null);
} else {
this.visibleQrCodeIp.set(ip);
}
}
/**
* Sets saved settings from the indexed db store
*/
setSettings() {
const currentSettings = this.settingsStore.getSettings();
this.settingsForm.patchValue(currentSettings);
this.syncDashboardControlsEnabledState(
currentSettings.showDashboard ?? true
);
if (this.supportsEpg && currentSettings.epgUrl) {
this.epgUrl.clear();
this.setEpgUrls(currentSettings.epgUrl);
}
}
private bindDashboardControlsEnabledState(): void {
this.settingsForm
.get('showDashboard')
?.valueChanges.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((showDashboard) =>
this.syncDashboardControlsEnabledState(showDashboard ?? true)
);
}
private syncDashboardControlsEnabledState(showDashboard: boolean): void {
const dashboardRails = this.settingsForm.get('dashboardRails');
if (!dashboardRails) {
return;
}
if (showDashboard) {
dashboardRails.enable({ emitEvent: false });
} else {
dashboardRails.disable({ emitEvent: false });
}
}
selectTheme(theme: Theme): void {
if (this.settingsForm.value.theme === theme) {
return;
}
this.settingsForm.patchValue({ theme });
this.settingsForm.get('theme')?.markAsDirty();
this.settingsForm.markAsDirty();
this.settingsService.changeTheme(theme);
}
selectCoverSize(size: CoverSize): void {
if (this.settingsForm.value.coverSize === size) {
return;
}
this.settingsForm.patchValue({ coverSize: size });
this.settingsForm.get('coverSize')?.markAsDirty();
this.settingsForm.markAsDirty();
this.settingsStore.updateSettings({ coverSize: size });
}
selectEpgViewMode(mode: EpgViewMode): void {
if (this.settingsForm.value.epgViewMode === mode) {
return;
}
this.settingsForm.patchValue({ epgViewMode: mode });
this.settingsForm.get('epgViewMode')?.markAsDirty();
this.settingsForm.markAsDirty();
this.settingsStore.updateSettings({ epgViewMode: mode });
}
/** Picks a recording folder in the desktop shell and stages it in the form */
async selectRecordingFolder(): Promise<void> {
if (
!this.isDesktop ||
!window.electron?.selectEmbeddedMpvRecordingFolder
) {
return;
const folder = await this.embeddedMpv.selectRecordingFolder();
if (folder) {
this.form.setRecordingFolder(folder);
}
const folder = await window.electron.selectEmbeddedMpvRecordingFolder();
if (!folder) {
return;
}
this.settingsForm.patchValue({ recordingFolder: folder });
this.settingsForm.get('recordingFolder')?.markAsDirty();
this.settingsForm.markAsDirty();
}
/**
* Sets the epg urls to the form array
* @param epgUrls urls of the EPG sources
*/
setEpgUrls(epgUrls: string[] | string): void {
applyEpgUrlsToFormArray(this.epgUrl, epgUrls);
}
/**
* Checks whether the latest version of the application
* is used and updates the version message in the
* settings UI
*/
checkAppVersion(): void {
this.settingsService
.getAppVersion()
.pipe(take(1))
.subscribe((version) => this.showVersionInformation(version));
}
/**
* Updates the message in settings UI about the used
* version of the app
* @param currentVersion current version of the application
*/
showVersionInformation(currentVersion: string): void {
const isOutdated = this.isCurrentVersionOutdated(currentVersion);
if (isOutdated) {
this.updateMessage = `${
this.translate.instant(
'SETTINGS.NEW_VERSION_AVAILABLE'
) as string
}: ${currentVersion}`;
} else {
this.updateMessage = this.translate.instant(
'SETTINGS.LATEST_VERSION'
);
}
}
/**
* Compares actual with latest version of the
* application
* @param latestVersion latest version
* @returns returns true if an update is available
*/
isCurrentVersionOutdated(latestVersion: string): boolean {
this.version = this.dataService.getAppVersion();
return this.settingsService.isVersionOutdated(
this.version,
latestVersion
);
}
/**
@@ -611,59 +199,19 @@ export class SettingsComponent implements OnInit, OnDestroy {
* the indexed db store
*/
onSubmit(): void {
const settings = this.createSettingsFromFormValue();
void this.form.save(() => this.applyChangedSettings());
this.settingsStore.updateSettings(settings).then(() => {
this.applyChangedSettings();
if (window.electron) {
window.electron.updateSettings(settings);
}
if (this.supportsExternalPlayerPathSettings && window.electron) {
window.electron.setMpvPlayerPath(settings.mpvPlayerPath);
window.electron.setVlcPlayerPath(settings.vlcPlayerPath);
}
});
if (this.isDialog) {
this.matDialog.closeAll();
}
}
private createSettingsFromFormValue() {
return createSettingsFromFormValue(
this.settingsForm,
this.settingsStore.getSettings()
);
}
/**
* Applies the changed settings to the app
*/
applyChangedSettings(): void {
this.settingsForm.markAsPristine();
if (this.supportsEpg) {
let epgUrls = this.settingsForm.value.epgUrl;
if (epgUrls) {
if (!Array.isArray(epgUrls)) {
epgUrls = [epgUrls];
}
const validEpgUrls = epgUrls.filter(
(url): url is string =>
typeof url === 'string' && url !== ''
);
if (validEpgUrls.length > 0) {
// Fetch all EPG URLs at once
this.epgService.fetchEpg(validEpgUrls);
}
}
}
this.translate.use(
this.settingsForm.value.language ?? Language.ENGLISH
);
this.settingsService.changeTheme(
this.settingsForm.value.theme ?? Theme.SystemTheme
);
this.form.applySavedSettings();
this.epg.fetchConfiguredEpg();
this.settingsSnackbar.open(
this.translate.instant('SETTINGS.SETTINGS_SAVED')
);
@@ -680,102 +228,24 @@ export class SettingsComponent implements OnInit, OnDestroy {
}
}
/**
* Force-fetch EPG for a single URL, bypassing the 12-hour freshness check.
* The plain fetchEpg would short-circuit on fresh data and click the
* refresh button would be a no-op — that's exactly not what the user
* intends when clicking "Refresh".
*/
refreshEpg(url: string): void {
if (!this.epgBridge.supportsDataManagement || !url) {
return;
}
void this.epgBridge.forceFetchEpg(
url,
this.settingsStore.getTrustOptions()
async exportData(): Promise<void> {
await this.backup.exportData(() => this.waitForUiFeedbackFrame());
}
importData(): void {
this.backup.importData(() => this.form.hydrateFromStore());
}
removeAll(): void {
this.playlistReset.confirmAndRemoveAll(() =>
this.waitForUiFeedbackFrame()
);
}
/**
* Force-fetch every configured EPG URL sequentially. Empty fields are
* skipped. Each URL flows through the normal progress panel so the user
* gets visible per-URL feedback.
* Lets the browser paint the pending busy state before a long running
* task blocks the main thread.
*/
refreshAllEpg(): void {
if (!this.epgBridge.supportsDataManagement) return;
const urls = (this.epgUrl.value as string[])
.map((url) => url?.trim())
.filter((url): url is string => Boolean(url));
const options = this.settingsStore.getTrustOptions();
urls.forEach((url) => void this.epgBridge.forceFetchEpg(url, options));
}
/**
* Initializes new entry in form array for EPG URL
*/
addEpgSource(): void {
this.epgUrl.insert(this.epgUrl.length, createEpgUrlControl());
}
/**
* Removes entry from form array for EPG URL
* @param index index of the item to remove
*/
removeEpgSource(index: number): void {
this.epgUrl.removeAt(index);
this.settingsForm.markAsDirty();
}
/**
* Clears all EPG data from database and immediately re-fetches every
* configured URL so the user isn't left staring at an empty state.
* Tracks progress with `isClearingEpgData` so the UI can show a spinner
* and block double-clicks, and surfaces failures via a dedicated snackbar.
*/
clearEpgData(): void {
this.dialogService.openConfirmDialog({
title: this.translate.instant('SETTINGS.CLEAR_EPG_DIALOG.TITLE'),
message: this.translate.instant(
'SETTINGS.CLEAR_EPG_DIALOG.MESSAGE'
),
onConfirm: async (): Promise<void> => {
if (
!this.epgBridge.supportsDataManagement ||
this.isClearingEpgData()
) {
return;
}
this.isClearingEpgData.set(true);
try {
const result = await this.epgBridge.clearEpgData();
if (result && result.success === false) {
throw new Error('Clear EPG returned success=false');
}
this.settingsSnackbar.open(
this.translate.instant('SETTINGS.EPG_DATA_CLEARED')
);
this.refreshAllEpg();
} catch (error) {
console.error('Failed to clear EPG data:', error);
this.settingsSnackbar.open(
this.translate.instant('SETTINGS.EPG_DATA_CLEAR_FAILED')
);
} finally {
this.isClearingEpgData.set(false);
}
},
});
}
async exportData() {
await this.backupFacade.exportData(() => this.waitForUiFeedbackFrame());
}
importData() {
this.backupFacade.importData(() => this.setSettings());
}
private async waitForUiFeedbackFrame(): Promise<void> {
if (typeof window.requestAnimationFrame !== 'function') {
await Promise.resolve();
@@ -786,34 +256,4 @@ export class SettingsComponent implements OnInit, OnDestroy {
window.requestAnimationFrame(() => resolve());
});
}
removeAll(): void {
if (!this.canRemoveAllPlaylists()) {
return;
}
this.matDialog
.open<
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
boolean
>(SettingsDeleteAllPlaylistsDialogComponent, {
autoFocus: false,
data: {
summary: this.playlistDeleteSummary(),
},
maxWidth: 'calc(100vw - 32px)',
restoreFocus: true,
width: '460px',
})
.afterClosed()
.pipe(take(1))
.subscribe((confirmed) => {
if (confirmed) {
void this.playlistResetFacade.removeAllConfirmed(() =>
this.waitForUiFeedbackFrame()
);
}
});
}
}
+4 -2
View File
@@ -222,8 +222,10 @@ Implemented UI behavior:
## Settings UI and discoverability
- Files:
- `apps/web/src/app/settings/settings.component.ts`
- `apps/web/src/app/settings/settings.component.html`
- `apps/web/src/app/settings/settings-remote-control-section.component.ts`
(+ `.html`) — the section rendered by `settings.component.html`
- `apps/web/src/app/settings/settings-remote-control.facade.ts` — LAN
address lookup and QR-code visibility state
- Features:
- Toggle `remoteControl`
- Configure `remoteControlPort`
-1
View File
@@ -43,7 +43,6 @@ export const maxLinesBaseline = [
'apps/web/src/app/services/electron.service.ts',
'apps/web/src/app/services/pwa.service.ts',
'apps/web/src/app/settings/settings.component.spec.ts',
'apps/web/src/app/settings/settings.component.ts',
'apps/xtream-mock-server/src/app/generators/marketing.generator.ts',
'libs/epg/data-access/src/lib/epg.service.spec.ts',
'libs/epg/data-access/src/lib/epg.service.ts',