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
+174
View File
@@ -0,0 +1,174 @@
# Category Management Feature
## Overview
Xtream API playlists often contain many categories, some of which may be empty, in another language, or simply not relevant to the user. The category management feature allows users to hide unwanted categories from the sidebar while keeping them in the database for potential future use.
## User Flow
1. User navigates to an Xtream playlist (Live TV, Movies, or Series section)
2. In the sidebar header, next to "All categories", there's a **tune icon button**
3. Clicking it opens the **Category Management Dialog**
4. User sees all categories with checkboxes (checked = visible, unchecked = hidden)
5. User can:
- Individually toggle categories
- Use "Select All" / "Deselect All" buttons
- Search/filter categories by name
6. On save, visibility preferences are persisted to the database
7. Hidden categories no longer appear in the sidebar
## Technical Implementation
### Database Schema
Added `hidden` column to the `categories` table:
```sql
ALTER TABLE categories ADD COLUMN hidden INTEGER DEFAULT 0
```
- `hidden = 0` (false): Category is visible (default)
- `hidden = 1` (true): Category is hidden
**Migration**: Uses a safe migration pattern in `connection.ts` that catches errors for already-applied migrations, ensuring existing users get the new column automatically.
### Backend (Electron)
**File**: `apps/electron-backend/src/app/events/database/category.events.ts`
| IPC Handler | Purpose |
| ------------------------------- | -------------------------------------------------- |
| `DB_GET_CATEGORIES` | Returns visible categories only (`hidden = false`) |
| `DB_GET_ALL_CATEGORIES` | Returns all categories (for management dialog) |
| `DB_UPDATE_CATEGORY_VISIBILITY` | Batch updates `hidden` status for category IDs |
### Frontend Services
**File**: `libs/services/src/lib/database-electron.service.ts`
| Method | Purpose |
| ---------------------------- | ------------------------------ |
| `getXtreamCategories()` | Sidebar display (filtered) |
| `getAllXtreamCategories()` | Management dialog (unfiltered) |
| `updateCategoryVisibility()` | Save visibility changes |
### Components
**Category Management Dialog**
- Path: `libs/portal/xtream/feature/src/lib/category-management-dialog/`
- Features:
- Checkbox list of all categories
- Select All / Deselect All buttons
- Search/filter with clearable input
- Shows selected count vs total
- Saves changes to database on confirm
**Integration Points**
- `xtream-main-container.component.ts` - Movies & Series sections
- `live-stream-layout.component.ts` - Live TV section
Both components:
1. Add a "tune" icon button in the sidebar header
2. Open the dialog with playlist ID and content type
3. Call `xtreamStore.reloadCategories()` after dialog closes with changes
### Store
**File**: `libs/portal/xtream/data-access/src/lib/stores/xtream.store.ts`
Added `reloadCategories()` method to refresh categories from database after visibility changes, ensuring the sidebar updates immediately.
## Behavior Notes
- **New categories**: When a playlist is refreshed, new categories from the remote API are added with `hidden = false` (visible by default)
- **Persistence**: Visibility settings survive playlist refresh (see below)
- **Per-playlist, per-type**: Categories are managed per playlist and per content type (live/movies/series)
- **No content deletion**: Hiding a category only affects sidebar visibility; the category and its content remain in the database
### Visibility Preservation During Refresh
When a user refreshes an Xtream playlist, hidden category preferences are preserved through the following mechanism:
1. **Before deletion**: The `DB_DELETE_XTREAM_CONTENT` handler extracts and returns the `hidden` status of all categories (keyed by `xtreamId` and `type`)
2. **Temporary storage**: The hidden categories are stored in `localStorage` under key `xtream-restore-{playlistId}` along with favorites and recently viewed data
3. **During re-import**: When categories are saved via `DB_SAVE_CATEGORIES`, the data source checks `localStorage` for saved hidden category xtreamIds
4. **Restoration**: Categories matching the saved xtreamIds are inserted with `hidden = true`, preserving the user's visibility preferences
5. **ID normalization**: Xtream category IDs arrive from the API as strings, while SQLite stores `categories.xtream_id` as an integer. Restoration must normalize incoming `category_id` values before matching them against saved hidden-category xtreamIds.
This ensures that users don't lose their category visibility customizations when refreshing playlists to get updated content.
### Debugging Note
Hidden-category restoration runs through the Electron DB worker. When debugging
or validating a fix in a live Electron app:
1. rebuild the worker-backed Electron runtime
2. restart the running Electron process
3. reconnect `agent-browser --cdp 9222`
Otherwise the app may still be using an older
`dist/apps/electron-backend/workers/database.worker.js` bundle even though the
TypeScript source has already been updated.
## Files Changed
```
libs/shared/database/src/lib/
├── schema.ts # Added hidden column to categories table
└── connection.ts # Added migration for existing databases
apps/electron-backend/src/app/
├── events/database/category.events.ts # IPC handlers (including hidden category restoration)
├── events/database/xtream.events.ts # Returns hidden categories during content deletion
└── api/main.preload.ts # Exposed new IPC methods (with hidden category params)
libs/services/src/lib/
└── database-electron.service.ts # Service methods (with hidden category support)
libs/ui/components/src/lib/recent-playlists/
└── recent-playlists.component.ts # Stores hidden categories to localStorage on refresh
libs/portal/xtream/feature/src/lib/
├── category-management-dialog/ # Dialog component
│ ├── category-management-dialog.component.ts
│ ├── category-management-dialog.component.html
│ └── category-management-dialog.component.scss
├── xtream-main-container.component.ts # Added button & dialog
├── xtream-main-container.component.html
├── live-stream-layout/
│ ├── live-stream-layout.component.ts # Added button & dialog
│ └── live-stream-layout.component.html
libs/portal/xtream/data-access/src/lib/
├── data-sources/
│ └── electron-xtream-data-source.ts # Reads/passes hidden categories on save
└── stores/xtream.store.ts # Added reloadCategories method
apps/web/src/assets/i18n/
└── en.json # Added translation keys
global.d.ts # TypeScript types for IPC methods
```
## Translation Keys
```json
{
"XTREAM": {
"CATEGORY_MANAGEMENT": {
"TITLE": "Manage Categories",
"LOADING": "Loading categories...",
"SELECTED": "Selected",
"SELECT_ALL": "Select All",
"DESELECT_ALL": "Deselect All",
"SEARCH_PLACEHOLDER": "Search categories...",
"NO_RESULTS": "No matching categories found",
"NO_CATEGORIES": "No categories available",
"SAVE": "Save"
}
}
}
```
+25
View File
@@ -0,0 +1,25 @@
# Date Handling
## Rules
- Use native `Date`, ISO strings, and epoch timestamps as the stored/runtime values.
- Use `date-fns` for parsing, arithmetic, and normalization logic.
- Use Angular `DatePipe` in templates when the value is already a `Date`, ISO string, or epoch timestamp.
- Use cached `Intl.DateTimeFormat` helpers in TypeScript-only formatting paths where Angular pipes are not available.
- Do not add new `moment` usage. The app no longer depends on it.
## Locale Strategy
- Date display should follow the user-selected app language from `TranslateService`.
- When a template renders localized month or weekday names, pass the normalized app locale explicitly to `DatePipe`.
- Angular locale data is registered in [apps/web/src/app/app-date-locales.ts](/Users/4gray/Code/iptvnator/apps/web/src/app/app-date-locales.ts).
- App language aliases are normalized in [libs/ui/pipes/src/lib/date-format.util.ts](/Users/4gray/Code/iptvnator/libs/ui/pipes/src/lib/date-format.util.ts):
- `ary` -> `ar-MA`
- `by` -> `be`
- `zhtw` -> `zh-Hant`
## Parsing Boundaries
- Normalize provider-specific or legacy date strings to ISO as early as possible.
- Keep optional epoch fields such as `startTimestamp` and `stopTimestamp` when the provider already supplies them.
- Avoid new non-standard `Date.parse(...)` usage for provider formats; prefer explicit `date-fns` parsing when the input is not ISO.
+41
View File
@@ -0,0 +1,41 @@
# Download Manager Architecture
The download manager is a desktop-only feature that layers a curated queue, progress tracking, storage configuration, and playback controls on top of the existing Xtream (xtream-electron folder) + Stalker viewers. Backend work is handled in the Electron process while the Angular renderer surface exposes a dedicated `/downloads` route, contextual buttons, and theme-aware styling.
## Backend responsibilities
- **Queue control (apps/electron-backend/src/app/events/downloads.events.ts)**
`DownloadTask` mirrors the shared `DownloadItem` table plus transient cancel/progress helpers. `enqueueDownload()` resolves a unique file path, persists a `queued` row in `downloads`, pushes the task onto `downloadQueue`, and triggers `processQueue()`. `processQueue()` keeps one active download, updates the row to `downloading`, and calls `startDownload()`.
- **electron-dl integration**
`startDownload()` now calls `electron-dl`’s `download()` helper. Headers (user agent, referer, origin) are attached, and the `onStarted`, `onProgress`, `onCompleted`, and `onCancel` callbacks translate the helper’s payload into Drizzle updates. The handler throttles progress broadcast, saves `filePath`/`fileName` from `electron-dl`, and marks failures/cancellations cleanly. Errors and cancellations delete partial files.
- **IPC surface**
The backend exposes `DOWNLOADS_*` handlers for list retrieval, start/cancel/retry/remove operations, folder selection/reveal, and the `DOWNLOADS_UPDATE_EVENT` emitter that the renderer listens to in order to refresh its signal store.
## Renderer architecture
- **Downloads service** (`apps/web/src/app/services/downloads.service.ts`)
Signals back the current download list while `hasDownloads` and `isAvailable` gates UI rendering. Before each download the service resolves a download folder (stored in `SettingsStore` or fetched via `downloadsGetDefaultFolder`) and calls `downloadsStart`. The backend extracts the file extension from the URL or falls back to `mp4`. `onDownloadsUpdate` updates the signal, while helper methods `retryDownload`, `removeDownload`, `cancelDownload`, and `playDownload` talk to the corresponding IPC commands so retries reuse existing rows and completed items can open the recorded path.
- **Downloads view** (`libs/portal/downloads/feature`)
A standalone page exposes the queue, desktop-only messaging, folder picker, and action buttons. `downloads.component.html` now wraps the list inside a scrollable panel (`downloads__list-wrapper`) so long queues stay reachable, and `downloads.component.scss` drives a bold two-tone aesthetic inspired by the frontend-design mandate—gradient cards, floating avatars, and theme-aware variables triggered via `body.dark-theme`.
Failed/canceled cards now show retry/delete controls, queued/downloading cards show a cancel icon, and completed cards render inline play/open buttons with `mat-icon` cues. The header also shows the resolved download folder and a `CHANGE FOLDER` action.
- **Theme fixes**
To keep typography legible in both modes, `app-search-result-item` now inherits color from `:host-context(body.dark-theme)` and `:host-context(body:not(.dark-theme))`, ensuring dense light-theme grids no longer show white text on white backgrounds.
## Global API surface
- **Preload + types**
`apps/electron-backend/src/app/api/main.preload.ts` wires every download IPC command plus the `onDownloadsUpdate` listener to `window.electron`. `global.d.ts` now mirrors those methods, adds playback-position helpers, and exposes `onPlaybackPositionUpdate` / `removePlaybackPositionListener` so Angular can type-check the new APIs. This keeps the renderer typing in sync with the backend implementation.
## Routing and navigation
- `/downloads` is available under both portal flavors: the Xtream routes already load `DownloadsComponent`, and the Stalker routes now import the same component so the sidebar link can target `/stalker/:id/downloads` without returning to the startup screen.
- The navigation component already points `routerLink="./downloads"` inside the shared nav pane, so both portals reuse the same download page.
## Queuing, persistence, and UX notes
- Every download row writes to the shared `downloads` table with statuses (`queued`, `downloading`, `completed`, `failed`, `canceled`) plus metadata such as `bytesDownloaded`, `totalBytes`, `errorMessage`, and Xtream identifiers. Stale downloads reset to `failed` on startup.
- Queue cancellation removes the task or calls `downloadItem.cancel()` if the item is active; retries reuse the same database entry, preventing duplicate rows.
- Folder selection first checks stored preferences, falls back to the OS default downloads path, and finally prompts the user to pick a folder. The downloads service persists the chosen path via `SettingsStore`.
- The new UI leverages CSS variables for theme-specific backgrounds/borders, ensures `.downloads__list` can scroll inside its panel, and brings consistent badge/typography treatments to each card.
Keeping the backend queue, IPC handlers, shared schema, and renderer signals synchronized minimizes drift between platform rules and the UI. Future work might cover download list filters, cancel-all actions, or integration with upcoming playback analytics.
@@ -0,0 +1,138 @@
# Embedded Inline Playback
This document records the current contract for embedded playback in portal detail views.
## Summary
- Embedded web players are `videojs`, `html5`, and `artplayer`.
- External players are `mpv` and `vlc`.
- Flatpak launches external players on the host via `flatpak-spawn --host`.
- Live playback stays inline in dedicated live layouts.
- VOD and series detail playback now also stays inline on canonical detail surfaces.
- Material dialog playback remains only as a fallback for older non-detail callers.
## Scope
The first pass is intentionally limited:
- Xtream VOD detail route
- Xtream series detail route
- Stalker VOD detail view
- Stalker series detail view
Not migrated in this pass:
- Generic non-detail playback entry points that still call `PlayerService.openPlayer(...)`
- Any collection/search surface that does not host a canonical detail surface of its own
## Components
Shared inline player shell:
- `/Users/4gray/Code/iptvnator/libs/ui/components/src/lib/portal-inline-player/portal-inline-player.component.ts`
Xtream detail hosts:
- `/Users/4gray/Code/iptvnator/libs/portal/xtream/feature/src/lib/vod-details/vod-details-route.component.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/xtream/feature/src/lib/serial-details/serial-details.component.ts`
Stalker detail hosts:
- `/Users/4gray/Code/iptvnator/libs/portal/catalog/feature/src/lib/category-content-view/category-content-view.component.ts`
- `/Users/4gray/Code/iptvnator/libs/ui/components/src/lib/stalker-series-view/stalker-series-view.component.ts`
Fallback dialog path:
- `/Users/4gray/Code/iptvnator/apps/web/src/app/services/player.service.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/xtream/feature/src/lib/player-dialog/player-dialog.component.ts`
## Playback Decision Rule
When a detail view starts playback:
1. Resolve or construct a typed playback payload.
2. Check the active player setting.
3. If the player is embedded, render the inline player inside the current detail view.
4. If the player is external, hand the same payload to `PlayerService` for MPV/VLC playback.
The detail host owns inline state. `PlayerService` is no longer the primary owner of UI playback state for canonical VOD/series detail screens.
## Flatpak External Players
Flatpak cannot execute host-installed `mpv` or `vlc` binaries directly from the sandbox.
Current contract:
- Flatpak launches external players through `flatpak-spawn --host`.
- AppImage, deb/rpm, snap, macOS, and Windows keep the existing direct process spawn flow.
- VLC keeps the current external-session flow in Flatpak, including the RC port used for progress polling.
- MPV is intentionally reduced in Flatpak: the app does not reuse an existing MPV instance there and does not open the Unix socket bridge used for non-Flatpak progress polling.
This keeps non-Flatpak behavior unchanged while allowing Flatpak builds to open host-installed external players.
## Typed Playback Payload
Shared playback payloads live in:
- `/Users/4gray/Code/iptvnator/libs/shared/interfaces/src/lib/portal-playback.interface.ts`
Types introduced:
- `PlayerContentInfo`
- `ResolvedPortalPlayback`
These provide a single shape for:
- `streamUrl`
- `title`
- optional thumbnail and resume start time
- playback-position metadata
- optional external-player headers and request metadata
## Xtream Behavior
Xtream detail views already own canonical routes, so they construct playback locally and decide inline vs external locally.
Behavior to preserve:
- resume/playback position continues saving from `timeUpdate`
- back navigation clears inline playback with the route
- favorites, recent, and search still route into canonical Xtream detail screens before playback
## Stalker Behavior
Stalker previously resolved playback and opened UI in the same method.
Current contract:
- `resolveVodPlayback(...)` returns a `ResolvedPortalPlayback`
- `createLinkToPlayVod(...)` remains as a compatibility wrapper for untouched callers
- canonical Stalker detail views use the resolver directly and decide inline vs external locally
This keeps:
- inline/store-state detail navigation intact
- series and VOD-as-series support intact
- non-detail callers working until they are migrated
## Playback Position Saving
The old dialog path saved playback positions from inside `PlayerDialogComponent`.
The new contract is:
- inline detail hosts listen to `timeUpdate`
- each host throttles saves
- each host persists via existing playback-position infrastructure
This avoids coupling inline UI state to a global dialog.
## Future Migration Rule
If a non-detail surface is converted away from dialog playback:
- give that surface a canonical inline host
- switch it to `ResolvedPortalPlayback`
- do not move portal-specific navigation into `PlayerService`
The preferred direction is view-owned inline playback, not a larger dialog manager.
+97
View File
@@ -0,0 +1,97 @@
# External Wiki Sync
Related:
- [Workspace Shell](./workspace-shell.md)
- [SQLite DB Worker](./sqlite-db-worker.md)
## Summary
- Repo docs are canonical, even when they were originally drafted by an LLM.
- The external Obsidian wiki imports canonical repo docs read-only into `_repo-context/`.
- Higher-level synthesis pages stay outside `_repo-context/` in the wiki's own folders.
- Sync is one-way by default: repo docs -> wiki context.
## Ownership Model
Canonical repo docs include:
1. `docs/architecture/**/*.md`
2. top-level workflow docs such as `README.md`, `GETTING-STARTED.md`, `AGENTS.md`, and `CLAUDE.md`
3. selected module `README.md` files when they describe current code behavior or workflows
The external wiki can add cross-links, feature pages, decision notes, and synthesis pages, but it must not become a second source of truth for the same implementation details.
## Export Scope
The repo-owned exporter writes only to `_repo-context/` inside the external vault.
Current default export scope:
1. `docs/architecture/**/*.md`
2. `README.md`
3. `GETTING-STARTED.md`
4. `AGENTS.md`
5. `CLAUDE.md`
6. selected module `README.md` files
The exporter also generates:
1. `_repo-context/index.md`
2. `_repo-context/repo-map.md`
3. `_repo-context/recent-changes.md`
4. `_repo-context/manifest.json`
5. `_repo-context/state.json`
## Running The Exporter
Set the external vault path in the shell environment:
```bash
export IPTVNATOR_WIKI_VAULT=/absolute/path/to/your/obsidian-vault
```
Then run:
```bash
pnpm wiki:export --mode full
pnpm wiki:export --mode changed
```
You can also override the vault path per command:
```bash
pnpm wiki:export --mode changed --vault /absolute/path/to/your/obsidian-vault
```
If the vault path is missing, the exporter skips cleanly and reports why it did not run.
## Agent Workflow After Changes
After a meaningful implementation change, agents must assess whether canonical repo docs need updates.
Documentation-worthy changes include:
1. new or changed user-visible behavior
2. architecture or data-flow changes
3. non-obvious maintenance workflows
4. new setup, debugging, or operational steps
5. new subsystem contracts or boundaries
Prefer updating an existing authoritative doc before creating a new one:
1. `README.md` for top-level developer or user workflows
2. `docs/architecture/` for architecture, ownership, and behavior contracts
3. the nearest module `README.md` for local usage or behavior
If docs changed and `IPTVNATOR_WIKI_VAULT` is configured, agents should run `pnpm wiki:export --mode changed` before considering the task complete.
## Promotion Workflow
If a wiki page becomes stable enough to be canonical:
1. promote that content back into a repo doc
2. treat the repo doc as the source of truth
3. export again so `_repo-context/` reflects the promoted canonical doc
The wiki page can then either link to the repo-backed generated page or remain as a smaller synthesis page that references the canonical doc.
@@ -0,0 +1,252 @@
# IPTVnator UI Guidelines
This document captures the current UI language used across IPTVnator, with emphasis on channel lists, EPG views, settings surfaces, and shared selection patterns.
Use it when changing existing views or introducing new list-based UI in the workspace, Xtream, or Stalker flows.
## Core Principles
1. Prefer shared components over duplicated markup.
The canonical channel row is `app-channel-list-item`.
2. Drive emphasis through selection state, not through constant decoration.
Neutral rows should stay quiet. Only active or current items should pick up strong color.
3. Use the same selection language everywhere.
Selected nav items, channels, and current EPG cards should feel like the same system.
4. Keep dark and light themes intentionally different.
Dark theme can carry more density and tinted surfaces.
Light theme should be flatter and cleaner, with white or near-white cards.
5. Scroll ownership must be explicit.
Headers stay visible. Lists scroll. Do not let nested panes compete for scroll.
## Canonical References
- Channel row:
`libs/ui/components/src/lib/channel-list-container/channel-list-item/channel-list-item.component.html`
- Channel row styles:
`libs/ui/components/src/lib/channel-list-container/channel-list-item/channel-list-item.component.scss`
- Shared EPG pane:
`libs/ui/shared-portals/src/lib/epg-view/epg-view.component.html`
- Shared EPG pane styles:
`libs/ui/shared-portals/src/lib/epg-view/epg-view.component.scss`
- Shared list selection style:
`apps/web/src/nav-list.scss`
- Theme tokens:
`apps/web/src/m3-theme.scss`
- Settings surfaces:
`apps/web/src/app/settings/settings.component.scss`
## Shared Tokens
These tokens are the base for interactive emphasis:
- `--app-selection-color`
- `--app-selection-surface`
- `--app-selection-surface-strong`
- `--app-selection-border`
- `--app-selection-glow`
Use Material surface tokens for neutral surfaces:
- `--mat-sys-surface`
- `--mat-sys-surface-container-low`
- `--mat-sys-surface-container`
- `--mat-sys-surface-container-high`
- `--mat-sys-outline-variant`
- `--mat-sys-on-surface`
- `--mat-sys-on-surface-variant`
Do not hardcode unrelated accent colors for selected state when these tokens already exist.
## Selection Pattern
Apply the same visual recipe to selected list items, active channels, and current EPG items:
- Background:
`linear-gradient(135deg, var(--app-selection-surface-strong), var(--app-selection-surface))`
- Border:
`var(--app-selection-border)`
- Glow:
outer shadow using `var(--app-selection-glow)`
- Lift:
`transform: translateY(-1px)` for selected list items only
- Text:
selected text should inherit `var(--app-selection-color)`
Use this pattern for:
- `.nav-item.selected` / `.nav-item.active`
- `.channel-list-item.active`
- `.epg-item.current-program`
Do not add extra badges, left rails, or second selection systems unless there is a strong reason.
## Channel List Item
The shared row should be reused instead of rebuilding channel markup per view.
### Structure
- Min height:
`68px`
- Horizontal gap:
`12px`
- Padding:
`8px 10px 8px 12px`
- Radius:
`12px`
- Logo shell:
`44x44`, rounded, subtle inset treatment
- Compact variant:
`52px` min height with slightly tighter padding
### Content Layout
- Title is one line, medium-bold, slightly condensed
- Program title is a secondary line with lower emphasis
- Timeline uses three columns:
start time, progress bar, end time
- Action buttons sit on the trailing edge and inherit row color
### Logo Rules
- Show fallback icon only when no image is available or image loading fails
- Do not render placeholder and real logo at the same time
- Keep logos contained with `object-fit: contain`
## EPG Views
### Shared EPG Pane
- Header title stays sticky
- Program list is the only scrolling region
- Add bottom padding so the last program is not clipped
- Current program card uses the same selection treatment as selected channels
### EPG Card
- Radius:
`14px`
- Neutral cards use low-contrast surface treatment
- Current card uses selection surface and selection border
- Description should clamp rather than overflow
### Sticky Header
- Keep the title readable above content
- Use a solid or near-solid backing surface
- Do not let it overlap or cover player controls
## Progress Bars
Channel preview progress and EPG current-program progress should stay visually aligned.
### Track
- Height:
`6px`
- Shape:
full pill radius
- Neutral background:
medium gray or neutral surface tint
- Include a slight inset edge so the remaining duration is visible
### Fill
- Use `--app-selection-color`
- Add a subtle sheen, not a heavy gradient
- Add a restrained glow, not a neon effect
The progress bar should clearly communicate:
- completed duration
- remaining duration
Avoid making the track too faint, especially in dark theme.
## Navigation Lists
Use the shared `nav-list.scss` treatment for sidebar and context-panel list items.
### Rules
- Keep labels one line with ellipsis
- Keep icon area clear from the selection border and any decorative rail
- Hover is neutral surface, not the selected color
- Selected state uses the shared selection recipe
If the label is too long for the rail, shorten the label key instead of shrinking the component until it becomes inconsistent.
## Settings Surfaces
Settings use the same system but are flatter than content-heavy views.
### Light Theme
- Prefer white or near-white cards
- Use neutral borders from `--mat-sys-outline-variant`
- Keep active sections mostly defined by outline and subtle tint
- Avoid dark translucent backgrounds
### Dark Theme
- Denser tinted surfaces are acceptable
- Neutral rows can use low-opacity dark overlays
- Keep strong blue tint reserved for active sections and selected items
## Theme Guidance
### Light Theme
- Flat beats glossy
- White and surface-container layers should separate content
- Selection should read as a blue outline plus soft tint, not a solid slab
### Dark Theme
- Slight translucency is acceptable
- Background layers can be deeper and more cinematic
- Keep contrast readable without going pure white everywhere
## Reuse Strategy
Before creating new markup or CSS:
1. Check whether `app-channel-list-item` can be reused.
2. Check whether `app-epg-view` already provides the correct structure.
3. Check whether `nav-list.scss` already solves the list-selection problem.
4. Extend tokens first, duplicate styles last.
## Implementation Workflow
When updating IPTVnator UI:
1. Inspect the current shared component first.
2. Reuse the shared structure where possible.
3. Keep selection, progress, and spacing in sync across Xtream, Stalker, and shared portal views.
4. Verify in both light and dark themes.
5. Verify in the running Electron app when the change is visual or layout-sensitive.
## Anti-Patterns
Avoid these:
- introducing a new selected-state color unrelated to the theme tokens
- duplicating channel row markup in portal-specific views
- showing placeholder logos behind real logos
- making entire panes scroll when only the list should scroll
- using dark translucent fills unchanged in light theme
- solving cramped sidebars with smaller fonts instead of shorter labels
## Definition Of Done For UI Changes
A visual change is not done until:
1. Shared component reuse was considered first.
2. Light theme and dark theme both look intentional.
3. Selection and progress states match existing IPTVnator patterns.
4. Scroll behavior is correct.
5. The result was checked in the running app for layout-sensitive work.
+424
View File
@@ -0,0 +1,424 @@
# M3U Playlist Module Architecture
This document describes the M3U playlist module architecture, which handles traditional M3U/M3U8 playlists (as opposed to Xtream Codes or Stalker Portal).
## Overview
The M3U playlist module provides:
- Channel list display with virtual scrolling (90,000+ channels support)
- EPG (Electronic Program Guide) integration
- Favorites management with drag-and-drop reordering
- Channel grouping and search
- Per-playlist group visibility management in the groups view
- Video playback with multiple player backends
## Module Structure
```
┌─────────────────────────────────────────────────────────────────────┐
│ VIDEO PLAYER PAGE │
│ libs/playlist/m3u/feature-player/src/lib/video-player/ │
├─────────────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌──────────────────────┐ ┌────────────────────┐ │
│ │ Sidebar │ │ Video Player │ │ EPG List │ │
│ │ │ │ (ArtPlayer/Video.js)│ │ (Right drawer) │ │
│ │ ┌─────────┐ │ │ │ │ │ │
│ │ │Channel │ │ │ │ │ │ │
│ │ │List │ │ │ │ │ │ │
│ │ │Container│ │ │ │ │ │ │
│ │ └─────────┘ │ │ │ │ │ │
│ └─────────────┘ └──────────────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ NgRx STORE (m3u-state) │
│ libs/m3u-state/ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Playlist │ │ Channel │ │ EPG │ │Favorites │ │ Filter │ │
│ │ Reducer │ │ Reducer │ │ Reducer │ │ Reducer │ │ Reducer │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────────────┘
```
## State Management (libs/m3u-state/)
### State Structure
```typescript
interface PlaylistState {
// Active channel being played
active: Channel | undefined;
// Whether the current route is still resolving channel data
channelsLoading: boolean;
// All channels from current playlist
channels: Channel[];
// EPG state
epg: {
epgAvailable: boolean;
activeEpgProgram: EpgProgram | undefined;
currentEpgProgram: EpgProgram | undefined;
};
// Playlist metadata (entity adapter)
playlistsMeta: {
ids: string[];
entities: Record<string, PlaylistMeta>;
selectedId: string | undefined;
allPlaylistsLoaded: boolean;
selectedFilters: PlaylistSourceFilter[];
};
}
```
`PlaylistMeta` is the persisted playlist-facing subset of the playlist entity.
For M3U playlists it now also carries `hiddenGroupTitles?: string[]`, which is
used by the groups view to remember which group titles the user has hidden.
### Actions
| Action Group | Actions | Purpose |
|--------------|---------|---------|
| **PlaylistActions** | `loadPlaylists`, `addPlaylist`, `removePlaylist`, `parsePlaylist`, `setActivePlaylist` | Playlist CRUD |
| **ChannelActions** | `setChannels`, `setActiveChannel`, `setAdjacentChannelAsActive` | Channel selection & navigation |
| **EpgActions** | `setActiveEpgProgram`, `setCurrentEpgProgram`, `setEpgAvailableFlag` | EPG state |
| **FavoritesActions** | `updateFavorites`, `setFavorites` | Favorites management |
| **FilterActions** | `setSelectedFilters` | Playlist type filtering |
### Key Selectors
```typescript
// Channel selectors
selectActive // Current playing channel
selectChannelsLoading // Channel list loading flag
selectChannels // All channels array
selectFavorites // Favorite channel URLs
// Playlist selectors
selectAllPlaylistsMeta // All playlists
selectActivePlaylistId // Selected playlist ID
selectCurrentPlaylist // Active playlist object
selectPlaylistTitle // Title with "Global favorites" fallback
// EPG selectors
selectIsEpgAvailable // EPG data available flag
selectCurrentEpgProgram // Current playing program
```
## Channel List Container
**Location**: `libs/ui/components/src/lib/channel-list-container/`
### Component Architecture
```
channel-list-container/
├── channel-list-container.component.ts # Parent - shared state coordinator
├── channel-list-container.component.html
├── channel-list-container.component.scss
│
├── all-channels-tab/ # Virtual scroll + search
│ ├── all-channels-tab.component.ts
│ ├── all-channels-tab.component.html
│ └── all-channels-tab.component.scss
│
├── groups-tab/ # Expansion panels + infinite scroll
│ ├── groups-tab.component.ts
│ ├── groups-tab.component.html
│ └── groups-tab.component.scss
│
├── favorites-tab/ # Drag-drop reordering
│ ├── favorites-tab.component.ts
│ ├── favorites-tab.component.html
│ └── favorites-tab.component.scss
│
└── channel-list-item/ # Individual channel display
├── channel-list-item.component.ts
├── channel-list-item.component.html
└── channel-list-item.component.scss
```
### Data Flow
```
┌──────────────────────────────────────────────────────────────┐
│ ChannelListContainerComponent │
│ (Parent) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Shared State (Signals): │ │
│ │ - channelEpgMap: Map<string, EpgProgram> │ │
│ │ - progressTick: number (30s interval) │ │
│ │ - shouldShowEpg: boolean │ │
│ │ - favoriteIds: Set<string> │ │
│ └────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────┼─────────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌─────────┐ ┌──────────┐ ┌───────────┐ │
│ │ All │ │ Groups │ │ Favorites │ │
│ │Channels │ │ Tab │ │ Tab │ │
│ │ Tab │ │ │ │ │ │
│ └────┬────┘ └────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └───────────────────┴─────────────────────┘ │
│ │ │
│ ▼ │
│ (channelSelected) output │
│ │ │
└──────────────────────────┼───────────────────────────────────┘
▼
Store Dispatch
ChannelActions.setActiveChannel
```
### Loading States
- `M3uWorkspaceRouteSession` owns route-driven channel loading for the player/sidebar routes: `all` and `groups`.
- The route session sets `channelsLoading` before `getPlaylist()` resolves and clears it when `ChannelActions.setChannels` lands.
- `ChannelListContainerComponent` now renders a dedicated skeleton state while `channelsLoading` is true.
- `ChannelListContainerComponent` no longer clears `channels` on destroy; route/session code is the single owner of shared list lifecycle during navigation.
- The dedicated `/workspace/playlists/:id/favorites` and `/workspace/playlists/:id/recent` collection routes do not drive the shared sidebar channel list; they default to the `playlist` scope so rail links always open the current playlist view, not the last persisted global scope.
- Empty playlists and empty search results are no longer conflated:
- loading: skeletons
- empty source: no channels in the playlist after loading completes
- empty search: no matches within an already loaded playlist
### Group Visibility Management
- `GroupsViewComponent` owns the M3U-only "Manage groups" action and dialog in
`libs/ui/components/src/lib/channel-list-container/groups-view/`.
- The groups rail header also owns an inline search toggle that filters the
currently visible groups without mutating the workspace-level route search
term used by the broader channel views.
- The dialog operates on the full grouped dataset, while the left rail and
channel pane render only groups whose titles are not listed in
`hiddenGroupTitles`.
- `ChannelListContainerComponent` reads `hiddenGroupTitles` from the active M3U
playlist metadata and passes it into the groups view. Saving dialog changes
dispatches `PlaylistActions.updatePlaylistMeta`.
- `PlaylistsService.updatePlaylistMeta()` persists `hiddenGroupTitles` into the
stored playlist payload, and M3U refresh/update flows preserve the existing
value when refreshed playlist data omits the field.
- The groups route keeps the manage action reachable even when every group is
hidden by separating "playlist has no groups" from "no visible/search-matching
groups" empty states.
### EnrichedChannel Pattern
For performance optimization, channels are pre-enriched with EPG data:
```typescript
interface EnrichedChannel extends Channel {
epgProgram: EpgProgram | null | undefined;
logo: string; // Playlist tvg-logo first, XMLTV icon fallback second
progressPercentage: number; // Pre-computed by parent
}
```
The renderer now keeps two lookup maps for M3U collection views:
- `channelEpgMap` for current-program preview data
- `channelIconMap` for XMLTV channel icon fallback data
Logo resolution is runtime-only and follows this rule:
1. playlist `tvg-logo`
2. matched XMLTV `<channel><icon src="...">`
3. generic `live_tv` fallback in the list item component
EPG lookup keys use the same precedence in both program and icon paths:
1. `tvg-id`
2. `tvg-name`
3. channel name
### Performance Optimizations
| Optimization | Implementation |
|--------------|----------------|
| **Virtual Scroll** | CDK virtual scroll for 90,000+ channels |
| **Computed Signals** | `enrichedChannels` computed signal replaces template pipe |
| **Debounced Search** | 300ms debounce on search input |
| **Global Progress Tick** | Single 30s interval instead of per-item intervals |
| **OnPush Change Detection** | All components use OnPush |
| **Infinite Scroll in Groups** | IntersectionObserver loads 50 channels at a time |
| **Memoized Group Enrichment** | `enrichedGroupChannelsMap` computed signal |
### Tab Components
#### AllChannelsTabComponent
- **Inputs**: `channels`, `channelEpgMap`, `channelIconMap`, `progressTick`, `shouldShowEpg`, `itemSize`, `activeChannelUrl`, `favoriteIds`
- **Outputs**: `channelSelected`, `favoriteToggled`
- **Features**: Search with 300ms debounce, virtual scrolling, no-results placeholder
#### GroupsTabComponent
- **Inputs**: Same as AllChannelsTab + `groupedChannels`
- **Outputs**: `channelSelected`, `favoriteToggled`
- **Features**: Expansion panels, infinite scroll with IntersectionObserver, lazy loading
#### FavoritesTabComponent
- **Inputs**: `favorites`, `channelEpgMap`, `channelIconMap`, `progressTick`, `shouldShowEpg`, `activeChannelUrl`
- **Outputs**: `channelSelected`, `favoriteToggled`, `favoritesReordered`
- **Features**: Drag-and-drop reordering with CDK DragDrop
## EPG Integration
### EpgService (libs/services/)
```typescript
class EpgService {
// Fetch EPG for multiple URLs
fetchEpg(urls: string[]): void;
// Get programs for a channel
getChannelPrograms(channelId: string): void;
// Batch fetch current programs
getCurrentProgramsForChannels(channelIds: string[]): Observable<Map<string, EpgProgram>>;
// Batch fetch XMLTV channel metadata for logo fallback
getChannelMetadataForChannels(channelIds: string[]): Observable<Map<string, EpgChannelMetadata | null>>;
// Observables
epgAvailable$: Observable<boolean>;
currentEpgPrograms$: Observable<EpgProgram[]>;
}
```
### EPG Components
| Component | Purpose |
|-----------|---------|
| `EpgListComponent` | Timeline view for single channel |
| `EpgListItemComponent` | Individual program in timeline |
| `EpgItemDescriptionComponent` | Program details dialog |
| `MultiEpgContainerComponent` | Grid view of all channels' schedules |
## Video Player
**Location**: `libs/playlist/m3u/feature-player/src/lib/video-player/`
### Supported Players
- **ArtPlayer** (default) - Modern player with plugins
- **Video.js** - Fallback with HLS support
- **HTML5** - Basic video element
- **Audio** - For radio streams
### Player Features
- Channel navigation (prev/next)
- Favorites toggle
- EPG sidebar
- Multi-EPG modal view
- Channel info overlay
- External player support (MPV, VLC) in Electron
- M3U archive/catch-up playback for supported replay schemes
### Archive / Catch-Up Playback
- The shared EPG UI only shows the archive replay badge when the host confirms
that the selected M3U channel has a playable replay scheme. Archive days
alone are not enough.
- M3U catch-up support is resolved in `m3u-utils` from channel metadata and
the archived program start time.
- Supported replay precedence:
1. `catchup.source` if it is an HTTP(S) URL. IPTVNator rewrites or appends
standard `utc` and `lutc` query params on that URL.
2. Legacy same-stream shift playback when `catchup.type === 'shift'`. In
that case IPTVNator rewrites or appends `utc` and `lutc` on `channel.url`.
3. Legacy same-stream shift fallback when no explicit catch-up mode is
declared, archive-day metadata exists (`tvg.rec`, `timeshift`, or
`catchup.days`), and `channel.url` itself is an HTTP(S) stream URL. This
covers providers that only advertise archive retention such as
`tvg-rec="7"` but still expect standard `utc` and `lutc` query params on
the live URL.
- `tvg.rec`, `timeshift`, and `catchup.days` still define the archive window
shown in the EPG, but replay remains unavailable when the provider declares a
different explicit catch-up scheme that IPTVNator does not understand or when
the stream URL itself is not an HTTP(S) replay target.
- Active replay is stored separately from the selected channel in
`playlistState.activePlaybackUrl`. Inline and external players use
`activePlaybackUrl ?? activeChannel.url`, and returning to live playback
clears the override.
## Interfaces
### Channel Interface
```typescript
interface Channel {
id: string;
url: string;
name: string;
group: { title: string };
tvg: {
id: string; // For EPG matching
name: string;
url: string;
logo: string;
rec: string;
};
epgParams?: string;
timeshift?: string;
catchup?: { type?: string; source?: string; days?: string };
radio: string;
http: {
referrer: string;
'user-agent': string;
origin: string;
};
}
```
### Playlist State Additions
```typescript
interface PlaylistState {
active: Channel | undefined;
activePlaybackUrl: string | null;
currentEpgProgram: EpgProgram | undefined;
epgAvailable: boolean;
channels: Channel[];
}
```
### EpgProgram Interface
```typescript
interface EpgProgram {
start: string; // ISO string
stop: string; // ISO string
channel: string; // TVG ID
title: string;
desc: string | null;
category: string | null;
episodeNum?: string | null;
iconUrl?: string | null;
rating?: string | null;
}
```
## Routes
```
/playlists/:id # Video player with playlist
/iptv # Default IPTV route
```
## Adding New Features
### To add a new tab to channel list:
1. Create component in `channel-list-container/new-tab/`
2. Accept inputs: `channels`, `channelEpgMap`, `progressTick`, `shouldShowEpg`, `activeChannelUrl`
3. Emit `channelSelected` output
4. Add to parent template and imports
### To add EPG-related features:
1. Use `EpgService` for data fetching
2. Subscribe to `channelEpgMap` signal for current programs
3. Dispatch `EpgActions` for state updates
### To modify favorites behavior:
1. Dispatch `FavoritesActions.updateFavorites` for toggle
2. Dispatch `FavoritesActions.setFavorites` for reordering
3. Effects automatically persist to database
+119
View File
@@ -0,0 +1,119 @@
# UX/UI Analysis: Header vs Rail Navigation
Date: 2026-03-22
## Overview
Evaluation of IPTVnator's navigation architecture — specifically the separation between **global actions in the top header** and **playlist-local actions in the left rail sidebar**, assessed from a user understanding perspective.
## Current Architecture
| Region | Intended Scope | Actual Contents |
|--------|---------------|-----------------|
| **Header** (top) | Global / app-wide | Playlist switcher, search, add playlist, global favorites, downloads, **context menu with local actions** |
| **Rail** (left) | Local / playlist-specific | Dashboard (global), Sources (global), **dynamic provider links** (local), Settings (global) |
Neither region is purely global or purely local. Both mix scopes, which muddies the mental model.
## Strengths
- **Playlist switcher in the header** is excellent placement. Acts like a "workspace context selector" — similar to Slack's workspace switcher or VS Code's project selector.
- **Command palette** nails the global-vs-local distinction with explicit "GLOBAL ACTIONS" and "THIS PLAYLIST" section headers. Clearest articulation of scope in the entire UI.
- **Rail dividers** between static workspace links (Dashboard, Sources) and dynamic provider links provide a subtle visual boundary hinting at the scope change.
- **Search bar adapting its placeholder text** per route is good contextual affordance.
- **Settings at the rail bottom** follows a well-established pattern (Slack, Discord, VS Code).
## Confusion Points
### A. Rail Mixes Global and Local Without Explaining Why
When a user selects an Xtream playlist, the rail shows:
```
Dashboard <- global
Sources <- global
-----------------
Movies <- local (Xtream)
Live TV <- local (Xtream)
Series <- local (Xtream)
-----------------
Search <- local (Xtream)
Recently viewed <- local (Xtream)
Favorites <- local (Xtream)
-----------------
Settings <- global
```
When switching to M3U:
```
Dashboard <- global
Sources <- global
-----------------
All channels <- local (M3U)
Groups <- local (M3U)
Recently viewed <- local (M3U)
Favorites <- local (M3U)
-----------------
Settings <- global
```
**Issue:** The dynamic links change silently. There's no label like "rucolor.tv" or "clean.m3u" above the provider links to indicate *which* playlist these links belong to. Users who switch playlists via the header dropdown may not immediately notice the rail updated.
**Severity:** Medium.
### B. Header's Three-Dot Menu Breaks the "Global Header" Mental Model
The context actions menu in the header contains:
- **Playlist Info** — local to the current playlist
- **Account Info** — local to the current Xtream portal
- **Clear Recently Viewed** — local bulk action
These are playlist-scoped actions living in what should be the "global" header area.
**Severity:** Low-Medium.
### C. "Favorites" Appears in Both Global and Local Contexts
- **Header:** Global Favorites star icon (cross-playlist)
- **Rail:** Favorites link (playlist-specific)
A user clicking the star in the header vs the heart in the rail gets *different* favorites views with *no* clear labeling of "global" vs "this playlist."
**Severity:** Medium-High. Most likely source of user confusion.
### D. Search Bar Scope Is Invisible
The search bar disables itself on some routes and changes behavior on others. The placeholder text changes, but "Search in this section..." doesn't clarify *which* section.
**Severity:** Low.
## Recommendations
### Quick Wins (Low Effort, High Impact)
1. **Add a playlist name label above the dynamic rail links.** Small, muted text showing "clean.m3u" or "rucolor.tv" above the provider-specific navigation.
2. **Keep Global Favorites as a single left-rail destination.** Avoid reintroducing a second header shortcut for the same global destination; reserve header actions for contextual controls.
3. **Add a scope label to the search bar** when active: "Searching in Live TV" or "Searching in clean.m3u" instead of generic "Search in this section..."
### Medium Effort
4. **Consider moving the three-dot context menu into the context panel** rather than the header, keeping the header purely global.
5. **Animate the rail transition** when switching playlists — a subtle slide or fade to signal that links changed.
## Overall Assessment
**Score: 7/10 — Good, with clear improvement opportunities.**
The architecture follows patterns users will recognize from Slack, VS Code, and Spotify. The main risks are the **silent dynamic rail** and the **favorites scope ambiguity**. Fixing those two issues would bring this to a 9/10 for navigational clarity.
### Design Principle
The command palette already has the right model: **explicit scope labels**. Apply this same principle to the rail and header. Anywhere an action's scope isn't obvious from its placement, label it.
## Key Files
- `libs/workspace/shell/feature/src/lib/workspace-shell/workspace-shell.component.html`
- `libs/workspace/shell/feature/src/lib/workspace-shell/workspace-shell.component.ts`
- `libs/portal/shared/ui/src/lib/navigation/portal-rail-links.component.ts`
- `libs/portal/shared/util/src/lib/navigation/portal-rail-links.ts`
- `libs/playlist/shared/ui/src/lib/playlist-switcher/playlist-switcher.component.ts`
- `libs/workspace/shell/feature/src/lib/workspace-command-palette/workspace-command-palette.component.ts`
@@ -0,0 +1,171 @@
# Playlist Backup/Restore Architecture
This document describes the versioned playlist backup/restore flow used by the
settings screen.
## Entry Points
- UI: `/Users/4gray/Code/iptvnator/apps/web/src/app/settings/settings.component.ts`
- Backup service: `/Users/4gray/Code/iptvnator/libs/services/src/lib/playlist-backup.service.ts`
- Manifest types: `/Users/4gray/Code/iptvnator/libs/shared/interfaces/src/lib/playlist-backup.interface.ts`
- Xtream pending restore storage:
`/Users/4gray/Code/iptvnator/libs/services/src/lib/xtream-pending-restore.service.ts`
## Manifest Contract
Backups are versioned JSON manifests, not raw `Playlist[]` dumps and not SQLite
database snapshots.
Top-level shape:
- `kind: "iptvnator-playlist-backup"`
- `version: 1`
- `exportedAt`
- `includeSecrets`
- `settings?.epgUrls`
- `playlists[]`
The manifest is portable across machines because it stores playlist definitions
and portable user state, while excluding cache-only database content.
## Export Scope
### M3U
M3U backups are self-contained.
- Always export canonical `rawM3u` from `PlaylistsService.getRawPlaylistById()`
- Preserve source metadata when available:
- original source kind: `url`, `file`, or `text`
- original URL
- `userAgent`, `referrer`, `origin`
- `filePathHint` for provenance only
- Export playlist-scoped user state:
- favorites by channel URL
- recently viewed M3U items
- hidden group titles
The embedded raw text is the canonical restore artifact. The internal parsed
playlist object graph is not the backup format.
### Xtream
Xtream backups export only connection metadata plus portable user state.
- Connection metadata:
- `serverUrl`
- `username`
- `password`
- User state:
- hidden categories by `{ categoryType, xtreamId }`
- favorites by `{ contentType, xtreamId, addedAt?, position? }`
- recently viewed by `{ contentType, xtreamId, viewedAt }`
- playback positions as `PlaybackPositionData[]`
Explicitly excluded:
- cached categories/content rows
- import-status flags and other app-state cache markers
- downloads
### Stalker
Stalker backups export connection metadata plus playlist-scoped favorites/recent
state.
- Exported connection fields:
- `portalUrl`
- `macAddress`
- `isFullStalkerPortal`
- `username`
- `password`
- `userAgent`
- `referrer`
- `origin`
- serial/device/signature fields when present
- Exported user state:
- favorites snapshots
- recently viewed snapshots
Explicitly excluded:
- `stalkerToken`
- `stalkerAccountInfo`
- playback positions in v1
### App Settings
Only EPG source URLs are backed up at the app-settings level.
- Exported: `settings.epgUrls`
- Excluded: cached EPG database content
## Import Flow
The settings component hands file contents to `PlaylistBackupService`.
The service:
1. Validates the manifest kind/version before any writes.
2. Rejects legacy raw `Playlist[]` JSON blobs.
3. Builds stable source fingerprints for merge-vs-create decisions.
4. Upserts playlists into app playlist storage.
5. Restores provider-specific user state.
Fingerprint rules:
- M3U URL playlists: normalized URL
- M3U without URL: hash of canonical `rawM3u`
- Xtream: normalized `serverUrl + username`
- Stalker: normalized `portalUrl + macAddress`
If a fingerprint matches an existing playlist:
- keep the existing playlist ID
- update mutable metadata from the backup
- replace playlist-scoped state with the backup payload
If no fingerprint matches:
- create a new playlist
- reuse `exportedId` only when it is unused
- otherwise generate a new UUID
## Xtream Restore Contract
Xtream restore is type-aware end to end. The app no longer stores plain
`xtream_id[]` arrays for refresh/import restore because IDs can collide across
`live`, `movie`, and `series`.
Runtime contract:
- shared shape: `XtreamPendingRestoreState`
- persisted in local storage by playlist ID
- consumed by:
- Xtream refresh actions
- settings backup import
- Xtream content initialization
Electron restore behavior:
1. Category import reads pending hidden-category state while saving categories.
2. After content import, favorites/recent state is restored by typed
`{ contentType, xtreamId }` matching.
3. Playback positions are cleared and re-applied from backup state.
For existing Xtream playlists with a fully populated offline cache, backup
import applies the restore immediately. Otherwise the typed restore payload is
left pending until the next Xtream initialization/import.
## Current UX
The settings page now exports/imports “playlist backups” instead of the old
raw JSON application dump.
- Export filename:
`iptvnator-playlist-backup-YYYY-MM-DD.json`
- Import summary reports:
- imported
- merged
- skipped
- failed
@@ -0,0 +1,152 @@
# Portal Detail Navigation
This document records the current navigation contract for Xtream and Stalker detail flows, especially for favorites, recently viewed, search, and category content.
Related:
- [Embedded Inline Playback](./embedded-inline-playback.md)
## Summary
- Xtream category browsing uses a route-first detail model.
- Stalker uses an inline/store-state detail model.
- Favorites and recently viewed collections now use collection-owned inline detail
for non-live Xtream and Stalker items.
- Provider-scoped collection routes fall back to the matching global collection
route when `All playlists` shows a non-live item from the other portal type,
so the correct detail host still opens without switching playlist context.
- Dashboard `Global Favorites` and `Recently Watched` widgets hand off Xtream and
Stalker movies/series into the matching global collection route with detail
pre-opened.
- Do not force both portals into the same browse/detail behavior unless the full
portal detail architecture is being changed.
## Xtream
Xtream category and search details are represented by canonical routes.
Examples:
- `/xtreams/:id/vod/:categoryId/:vodId`
- `/xtreams/:id/series/:categoryId/:serialId`
Implication:
- Category browsing and search can still redirect to the original Xtream content
route and item route.
- This keeps the URL, browser history, and detail rendering model aligned with
normal Xtream browsing.
Current code paths:
- `libs/portal/xtream/feature/src/lib/favorites/favorites.component.ts`
- `libs/portal/xtream/feature/src/lib/search-results/search-results.component.ts`
- `libs/portal/catalog/feature/src/lib/category-content-view/category-content-view.component.ts`
Collection behavior to preserve:
- Selecting a non-live Xtream item from favorites/recent should keep the current
collection route and open inline detail inside the collection pane when the
current collection host is already Xtream-aware.
- If a Stalker or M3U collection route is showing `All playlists` and the user
selects an Xtream movie/series item, route into `/workspace/global-favorites`
or `/workspace/global-recent` with detail pre-opened instead of trying to
render Xtream detail inside the wrong host.
- The current playlist context must stay unchanged even when the selected item
belongs to a different Xtream source playlist.
- The workspace/sidebar category panel should stay hidden for these collection
detail opens.
- Back from a collection-owned detail should restore the previous collection
view state, including the active content tab and playlist/all-playlists
scope.
- Live streams can still open through the player path rather than a detail
route.
Dashboard behavior to preserve:
- Dashboard `Global Favorites` and `Recently Watched` widgets should route
Xtream movie/series items into `/workspace/global-favorites` or
`/workspace/global-recent` with collection detail pre-opened from navigation
state.
- Back from the collection detail should return to the dashboard handoff state,
not switch the active playlist.
Search behavior to preserve:
- Selecting an Xtream item from search should still navigate to the canonical
Xtream content type/category/item route when the item is not a live stream.
## Stalker
Stalker details are represented by store state and inline detail rendering on the current screen.
Examples:
- Category content sets `selectedItem` and renders details inline.
- Search sets `selectedItem` and stays on the search view.
- Favorites and recently viewed stay on their current collection screen and open
inline detail when the current collection host is already Stalker-aware.
Implication:
- Favorites, recently viewed, and search should remain in the current Stalker view when opening VOD/series details.
- This keeps Stalker behavior aligned with its normal category-content and search flow.
Current code paths:
- `libs/portal/stalker/feature/src/lib/stalker-favorites/stalker-favorites.component.ts`
- `libs/portal/stalker/feature/src/lib/recently-viewed/recently-viewed.component.ts`
- `libs/portal/stalker/feature/src/lib/stalker-search/stalker-search.component.ts`
- `libs/portal/catalog/feature/src/lib/category-content-view/category-content-view.component.ts` (Stalker branch)
Behavior to preserve:
- Favorites/recent/search should not navigate away to a canonical Stalker detail route because Stalker does not currently use one.
- If an Xtream or M3U collection route is showing `All playlists` and the user
selects a Stalker VOD/series item, route into `/workspace/global-favorites`
or `/workspace/global-recent` with detail pre-opened so the Stalker inline
detail host still renders on a compatible screen.
- ITV/live items can still trigger playback immediately.
- Stalker VOD items that are displayed as series because of `is_series=1`
remain VOD-backed when opened from favorites/recent/global collections; the
collection host must not convert them into regular `/series` detail mode.
- Dashboard `Global Favorites` and `Recently Watched` widgets should route
Stalker movie/series items into `/workspace/global-favorites` or
`/workspace/global-recent` with detail pre-opened inline, again without
switching playlist context or showing the workspace category sidebar.
- Back from the collection-owned detail should restore the previous collection
tab and scope instead of resetting the collection screen to its defaults.
## Decision Rule For Future Changes
When deciding how a favorites/recent/search click should behave:
1. Follow the portal's canonical detail model.
2. Prefer local consistency within the portal over cross-portal sameness.
3. Only unify Xtream and Stalker behavior if the full detail architecture is being unified as well.
That means:
- Xtream browse/search: navigate to the canonical route.
- Xtream favorites/recent/global collection widgets: open collection-owned
detail without switching playlist context. Use the current route when it can
host Xtream detail, otherwise fall back to the matching global collection
route.
- Stalker non-live items: open collection-owned detail without switching
playlist context. Use the current route when it can host Stalker detail,
otherwise fall back to the matching global collection route.
## Refactor Guidance
If a future change proposes that Stalker favorites/recent should deep-link into category routes:
- also update Stalker category-content and search behavior
- define a canonical Stalker detail route model first
- update architecture docs and portal skills together
If a future change proposes that Xtream favorites/recent should stay inline:
- keep the existing route-based detail pages reusable from the collection-owned
detail host
- verify history/back behavior, playlist preservation, and dashboard handoff
behavior still make sense
+245
View File
@@ -0,0 +1,245 @@
# Remote Control Architecture
This document describes the current remote control implementation in IPTVnator, including:
- HTTP API exposed by Electron main process
- IPC bridge between Electron main and Angular renderer
- Feature support and integration points for M3U, Xtream, and Stalker
- Remote web UI structure and behavior
Related architecture docs:
- [Stalker Portal Architecture](./stalker-portal.md)
- [Stalker Portal EPG Architecture](./stalker-epg.md)
## Scope
Remote control is a desktop-only feature that serves a mobile-friendly web app from the Electron backend and routes remote actions into the running renderer.
Current capabilities:
- Channel up / down
- Channel select by number
- Volume commands (implemented in command layer; active support currently in M3U flow)
- Playback status polling (portal, live-state, channel name/number, EPG now, volume capability)
## High-Level Flow
1. User opens remote web UI (`http://<local-ip>:<port>`).
2. Remote web app calls `/api/remote-control/*`.
3. Electron main handles API request and sends IPC to renderer:
- `CHANNEL_CHANGE` for up/down
- `REMOTE_CONTROL_COMMAND` for numeric/volume commands
4. Renderer-specific feature module (M3U/Xtream/Stalker) applies action.
5. Renderer pushes status snapshots back to main via:
- `REMOTE_CONTROL_STATUS_UPDATE`
6. Remote web app polls `/api/remote-control/status` and updates UI.
## Backend (Electron Main)
### HTTP server and static app hosting
- File: `apps/electron-backend/src/app/server/http-server.ts`
- Responsibilities:
- Serves static remote app from:
- dev: `dist/apps/remote-control-web/browser`
- prod: `<appPath>/remote-control-web/browser`
- Routes `/api/remote-control/*` to registered handlers.
- Starts/stops/restarts on settings updates.
### Remote control event module
- File: `apps/electron-backend/src/app/events/remote-control.events.ts`
- Bootstrapped in: `apps/electron-backend/src/main.ts` via `RemoteControlEvents.bootstrapRemoteControlEvents()`
Registered endpoints:
- `POST /api/remote-control/channel/up`
- `POST /api/remote-control/channel/down`
- `POST /api/remote-control/channel/select-number` with `{ number: <int> }`
- `POST /api/remote-control/volume/up`
- `POST /api/remote-control/volume/down`
- `POST /api/remote-control/volume/toggle-mute`
- `GET /api/remote-control/status`
IPC emitted to renderer:
- `CHANNEL_CHANGE` payload: `{ direction: 'up' | 'down' }`
- `REMOTE_CONTROL_COMMAND` payload:
- `{ type: 'channel-select-number', number }`
- `{ type: 'volume-up' | 'volume-down' | 'volume-toggle-mute' }`
Status ingestion from renderer:
- Listens on `REMOTE_CONTROL_STATUS_UPDATE`
- Maintains in-memory `RemoteControlStatus` object returned by `/status`
### Settings integration
- Main handler: `apps/electron-backend/src/app/events/settings.events.ts`
- On `SETTINGS_UPDATE`, reads `remoteControl` and `remoteControlPort`, persists to store, and calls:
- `httpServer.updateSettings(enabled, port)`
## Preload Bridge
- File: `apps/electron-backend/src/app/api/main.preload.ts`
Exposed APIs relevant to remote control:
- `onChannelChange(callback) => unsubscribe`
- `onRemoteControlCommand(callback) => unsubscribe`
- `updateRemoteControlStatus(status) => void`
Type definitions:
- `apps/web/src/typings.d.ts`
- `global.d.ts`
## Renderer Integrations
## Shared helpers
- File: `libs/portal/shared/util/src/lib/remote-channel-navigation.ts`
Functions:
- `getAdjacentChannelItem(...)`: wraps around on boundaries for up/down
- `getChannelItemByNumber(...)`: 1-based number to list item mapping
Used by M3U, Xtream, and Stalker live integrations.
## M3U integration
- File: `libs/playlist/m3u/feature-player/src/lib/video-player/video-player.component.ts`
Implemented behavior:
- Subscribes to:
- `onChannelChange` (up/down)
- `onRemoteControlCommand` (number + volume)
- Applies channel up/down by active channel URL over `channels$`
- Applies number select through existing `switchToChannelByNumber(...)`
- Applies volume commands:
- up/down in 0.1 increments
- toggle mute with last non-zero volume restore
- persists to `localStorage`
- Publishes status snapshots via `updateRemoteControlStatus(...)`:
- `portal: 'm3u'`
- `isLiveView: true`
- channel name/number
- EPG now fields
- `supportsVolume: true`, `volume`, `muted`
- Cleans listeners/subscriptions in `ngOnDestroy`.
## Xtream integration (live view)
- File: `libs/portal/xtream/feature/src/lib/live-stream-layout/live-stream-layout.component.ts`
Implemented behavior:
- Subscribes to:
- `onChannelChange` for up/down
- `onRemoteControlCommand` for number select
- Up/down:
- Uses selected live item `selectedItem().xtream_id`
- Navigates inside `selectItemsFromSelectedCategory()`
- Calls `playLive(nextItem)`
- Number select:
- Maps number to item in current category list
- Calls `playLive(channel)`
- Publishes status via effect:
- `portal: 'xtream'`
- `isLiveView` only when selected content type is `live` and item is selected
- channel name/number + current EPG item
- `supportsVolume: false`
- Cleans listeners in `ngOnDestroy`.
## Stalker integration (ITV live view)
- File: `libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/stalker-live-stream-layout.component.ts`
Implemented behavior:
- Subscribes to:
- `onChannelChange` for up/down
- `onRemoteControlCommand` for number select
- Up/down:
- Uses `selectedItem().id`
- Navigates inside `itvChannels()`
- Calls `playChannel(nextItem)`
- Number select:
- Maps number into `itvChannels()`
- Calls `playChannel(channel)`
- Publishes status via effect:
- `portal: 'stalker'`
- `isLiveView` only for selected content type `itv` with active item
- channel name/number + current EPG item
- `supportsVolume: false`
- Cleans listeners in `ngOnDestroy`.
## Remote Web App
### App shell
- App: `apps/remote-control-web/src/app/app.ts`
- Template: `apps/remote-control-web/src/app/app.html`
- Style: `apps/remote-control-web/src/app/app.scss`
- Renders shared library component: `<lib-remote-control />`
### Shared remote UI library
- Component:
- `libs/ui/remote-control/src/lib/remote-control/remote-control.component.ts`
- `libs/ui/remote-control/src/lib/remote-control/remote-control.component.html`
- `libs/ui/remote-control/src/lib/remote-control/remote-control.component.scss`
- Service:
- `libs/ui/remote-control/src/lib/remote-control/remote-control.service.ts`
Implemented UI behavior:
- Channel pad (`CH+`, `CH-`)
- Numeric keypad (`0-9`, `DEL`, `CLR`, `OK`)
- Volume controls (`VOL-`, `MUTE/UNMUTE`, `VOL+`)
- Status card (portal, channel name/number, current program)
- Polls `/status` every 2s
- Uses action wrapper to refresh status after command execution
## Settings UI and discoverability
- Files:
- `apps/web/src/app/settings/settings.component.ts`
- `apps/web/src/app/settings/settings.component.html`
- Features:
- Toggle `remoteControl`
- Configure `remoteControlPort`
- Display local URLs and QR codes for remote access
- Local IP list loaded via `getLocalIpAddresses()`
## Feature Matrix (Current)
| Capability | M3U | Xtream Live | Stalker ITV |
|---|---|---|---|
| Channel up/down | Yes | Yes | Yes |
| Number select | Yes | Yes | Yes |
| Status publish | Yes | Yes | Yes |
| Volume command handling | Yes | No | No |
| `supportsVolume` in status | true | false | false |
## Known limitations
- Volume commands are currently no-op in Xtream and Stalker integrations.
- Remote status uses polling from web UI (2s), not push/WebSocket.
- Number-based selection is list-position based (1-based index in active list scope), not global EPG number mapping.
- Remote API currently has no auth/TLS; intended for trusted local networks.
## Operational notes
- UI updates in remote web app require rebuilding `remote-control-web` so Electron serves fresh `dist` assets.
- If stale UI appears, clear browser cache/hard-refresh mobile browser.
## Future extension points
- Add optional auth token for `/api/remote-control/*` endpoints.
- Add WebSocket/SSE status push for lower latency and reduced polling.
- Add cross-portal volume abstraction and capability negotiation.
- Add last-channel, favorites navigation, and search/select commands.
+558
View File
@@ -0,0 +1,558 @@
# SQLite DB Worker
This document records the current non-EPG SQLite worker implementation in the
Electron app.
Related:
- [Category Management](./category-management.md)
- [Workspace Shell](./workspace-shell.md)
## Summary
- Heavy non-EPG SQLite work no longer runs on Electron's main thread.
- A dedicated long-lived database worker now handles the slow Xtream and
playlist database operations that were freezing the UI.
- Renderer APIs stay stable. The main change is that progress and long-running
state now flow through a request-scoped `DB_OPERATION_EVENT` contract instead
of a single global progress event.
## Goals
The worker cutover addresses three concrete problems:
1. Main-process UI stalls during large SQLite operations.
2. Xtream import progress events were global and unsafe for concurrent jobs.
3. EPG and non-EPG writers needed shared SQLite concurrency settings so they
can coexist without `SQLITE_BUSY` regressions.
## Current Ownership
### Main-process runtime wiring
These files own worker lifecycle and IPC bridging:
1. `apps/electron-backend/src/app/services/database-worker-client.ts`
2. `apps/electron-backend/src/app/events/database/category.events.ts`
3. `apps/electron-backend/src/app/events/database/content.events.ts`
4. `apps/electron-backend/src/app/events/database/playlist.events.ts`
5. `apps/electron-backend/src/app/events/database/xtream.events.ts`
6. `apps/electron-backend/src/main.ts`
### Worker runtime
These files own the worker protocol and the SQLite work itself:
1. `apps/electron-backend/src/app/workers/database-worker.types.ts`
2. `apps/electron-backend/src/app/workers/database.worker.ts`
3. `apps/electron-backend/src/app/workers/database.worker-connection.ts`
4. `apps/electron-backend/src/app/workers/worker-runtime-paths.ts`
### Pure database operation modules
Keep SQL-heavy logic here so the worker entry remains a thin dispatcher:
1. `apps/electron-backend/src/app/database/operations/category.operations.ts`
2. `apps/electron-backend/src/app/database/operations/content.operations.ts`
3. `apps/electron-backend/src/app/database/operations/playlist.operations.ts`
4. `apps/electron-backend/src/app/database/operations/xtream.operations.ts`
## Worker Architecture
### Request flow
1. Renderer calls the existing preload API such as `window.electron.dbSaveContent`.
2. `ipcMain.handle(...)` in the Electron backend builds a payload and delegates
to `DatabaseWorkerClient`.
3. `DatabaseWorkerClient` lazily starts one long-lived `worker_threads` worker
and correlates requests with a generated `requestId`.
4. The worker executes SQLite work and sends back either:
1. `ready`
2. `event`
3. `response`
5. The main process resolves the IPC request and forwards worker events back to
the originating renderer process.
### Why one long-lived worker
- It avoids worker startup cost on every search/delete/import.
- It centralizes failure handling and restart behavior.
- It mirrors the existing EPG worker approach without multiplying writable
SQLite owners.
### Packaged worker bootstrap
Packaged Electron builds do not load worker scripts and native modules from the
same place:
1. worker scripts live under `Resources/dist/apps/electron-backend/workers`
2. unpacked native modules live under one of the approved
`app.asar.unpacked/.../node_modules` locations
Both the EPG worker and the DB worker now share the same runtime helper:
1. `resolveWorkerRuntimeBootstrap(...)` for main-process worker launch
2. `loadNativeModuleFromSearchPaths(...)` for worker-side native module loading
The helper uses `process.resourcesPath` as the primary packaged base and keeps
`path.dirname(app.getAppPath())` only as a fallback.
## Worker Message Contract
The worker contract lives in
`apps/electron-backend/src/app/workers/database-worker.types.ts`.
### Core message types
1. `DbWorkerRequestMessage`
2. `DbWorkerResponseMessage`
3. `DbWorkerEventMessage`
4. `DbOperationEvent`
### Progress event contract
The worker now emits request-scoped events with:
- `operationId`
- `operation`
- `playlistId`
- `status`
- optional `phase`
- optional `current`
- optional `total`
- optional `increment`
Current shipped operation names:
1. `save-content`
2. `delete-xtream-content`
3. `restore-xtream-user-data`
4. `delete-playlist`
5. `delete-all-playlists`
The event is forwarded to the renderer as `DB_OPERATION_EVENT`.
### Cancellation contract
Long-running Xtream and playlist operations now support best-effort
cancellation.
Renderer requests cancellation via:
1. `DB_CANCEL_OPERATION`
2. `window.electron.dbCancelOperation(operationId)`
3. `DatabaseService.cancelOperation(operationId)`
If a worker operation is canceled:
1. the worker emits a final `cancelled` event
2. the request rejects with an `AbortError`
3. the UI clears its busy state without treating the operation as success
Cancellation is cooperative and chunk-based. Already committed SQLite batches
stay committed.
## Renderer Contract
The preload bridge keeps the existing database methods but adds scoped worker
events.
### Important preload APIs
1. `onDbOperationEvent(callback)`
2. `dbSaveContent(playlistId, streams, type, operationId?)`
3. `dbDeleteXtreamContent(playlistId, operationId?)`
4. `dbRestoreXtreamUserData(..., operationId?)`
5. `dbDeletePlaylist(playlistId, operationId?)`
6. `dbDeleteAllPlaylists(operationId?)`
7. `dbCancelOperation(operationId)`
8. legacy compatibility:
1. `onDbSaveContentProgress(callback)`
2. `removeDbSaveContentProgress()`
`DatabaseService.saveXtreamContent(...)` now generates an `operationId`,
subscribes to `onDbOperationEvent`, filters by that `operationId`, and only
falls back to the legacy progress API if the newer event channel is missing.
`DatabaseService` also owns:
1. `createOperationId(...)`
2. `cancelOperation(operationId)`
3. `isDbAbortError(error)`
## Migrated Operations
The worker now owns all heavy non-EPG SQLite paths plus the remaining portal
state handlers that still used direct main-thread SQLite access.
### Categories
1. `DB_HAS_CATEGORIES`
2. `DB_GET_CATEGORIES`
3. `DB_SAVE_CATEGORIES`
4. `DB_GET_ALL_CATEGORIES`
5. `DB_UPDATE_CATEGORY_VISIBILITY`
### Content
1. `DB_HAS_CONTENT`
2. `DB_GET_CONTENT`
3. `DB_SAVE_CONTENT`
4. `DB_GET_CONTENT_BY_XTREAM_ID`
5. `DB_SEARCH_CONTENT`
6. `DB_GLOBAL_SEARCH`
7. `DB_GET_GLOBAL_RECENTLY_ADDED`
### Playlist metadata
1. `DB_CREATE_PLAYLIST`
2. `DB_UPSERT_APP_PLAYLIST`
3. `DB_UPSERT_APP_PLAYLISTS`
4. `DB_GET_APP_PLAYLISTS`
5. `DB_GET_APP_PLAYLIST`
6. `DB_GET_PLAYLIST`
7. `DB_UPDATE_PLAYLIST`
8. `DB_DELETE_PLAYLIST`
9. `DB_DELETE_ALL_PLAYLISTS`
10. `DB_GET_APP_STATE`
11. `DB_SET_APP_STATE`
### Xtream refresh helpers
1. `DB_DELETE_XTREAM_CONTENT`
2. `DB_RESTORE_XTREAM_USER_DATA`
### Favorites
1. `DB_ADD_FAVORITE`
2. `DB_REMOVE_FAVORITE`
3. `DB_IS_FAVORITE`
4. `DB_GET_FAVORITES`
5. `DB_GET_GLOBAL_FAVORITES`
6. `DB_GET_ALL_GLOBAL_FAVORITES`
7. `DB_REORDER_GLOBAL_FAVORITES`
### Recently viewed
1. `DB_GET_RECENTLY_VIEWED`
2. `DB_CLEAR_RECENTLY_VIEWED`
3. `DB_GET_RECENT_ITEMS`
4. `DB_ADD_RECENT_ITEM`
5. `DB_CLEAR_PLAYLIST_RECENT_ITEMS`
6. `DB_REMOVE_RECENT_ITEM`
### Playback positions
1. `DB_SAVE_PLAYBACK_POSITION`
2. `DB_GET_PLAYBACK_POSITION`
3. `DB_GET_SERIES_PLAYBACK_POSITIONS`
4. `DB_GET_RECENT_PLAYBACK_POSITIONS`
5. `DB_GET_ALL_PLAYBACK_POSITIONS`
6. `DB_CLEAR_PLAYBACK_POSITION`
## SQLite Concurrency Rules
EPG remains on its own worker, so both workers must use compatible SQLite
pragmas.
Applied now in both the shared connection path and worker-owned connections:
1. `foreign_keys = ON`
2. `journal_mode = WAL`
3. `busy_timeout = 5000`
Current sources:
1. `libs/shared/database/src/lib/connection.ts`
2. `apps/electron-backend/src/app/workers/database.worker-connection.ts`
3. `apps/electron-backend/src/app/workers/epg-parser.worker.ts`
## UI Behavior Changes
### Search
Xtream search now guards against stale async responses:
1. local playlist search uses a monotonically increasing request version
2. global search uses a separate request version in the dialog component
3. clearing search invalidates older pending results
This prevents an older worker response from repainting over a newer query or a
cleared search state.
### Xtream type-aware content lookup
Xtream UI flows must treat `xtream_id` as only partially unique.
Current contract:
1. `xtream_id` can collide across `live`, `movie`, and `series` within the same
playlist.
2. Any DB-backed lookup that starts from an Xtream result card, favorite button,
recent-item update, continue-watching flow, or detail route must resolve
content by:
- `playlist_id`
- `xtream_id`
- `content.type`
3. Mixed Xtream collection identity must key entries by `type + xtream_id`,
not `xtream_id` alone. This includes favorites maps, recent-item lists,
dashboard collection payloads, and other UI state keyed off persisted
Xtream content.
Why this matters:
- Search results are already type-filtered, so resolving favorites by only
`playlist_id + xtream_id` can favorite the wrong persisted row when IDs
collide.
- Continue-watching / recently-viewed flows that resolve by only
`playlist_id + xtream_id` can store the wrong persisted row when a series or
movie ID collides with a live entry.
- Mixed favorites maps keyed only by `xtream_id` can mark an unrelated live row
as favorited when the actual favorite is a movie or series with the same
numeric ID.
- Mixed recent/favorites collection items keyed only by `xtream_id` can cause
local UI state to remove, reorder, or reactivate the wrong Xtream entry when
different content types collide.
Current implementation paths:
1. `apps/electron-backend/src/app/database/operations/content.operations.ts`
2. `libs/portal/xtream/data-access/src/lib/with-favorites.feature.ts`
3. `libs/portal/xtream/data-access/src/lib/with-recent-items.ts`
4. `libs/portal/xtream/feature/src/lib/portal-channels-list/portal-channels-list.component.ts`
5. `libs/portal/shared/util/src/lib/collection/unified-recent-data.service.ts`
6. `libs/portal/shared/util/src/lib/collection/unified-favorites-data.service.ts`
### Busy states
The UI now has explicit long-running state for destructive operations:
1. recent playlist rows show row-level refresh/delete spinners
2. Xtream import overlay shows phase text and a cancel action
3. Xtream playlist rows show request-scoped progress and cancel actions
4. busy rows block repeat clicks while an operation is in flight
5. settings "remove all playlists" owns its own spinner/disabled state and
consumes request-scoped DB operation events for progress text while the
worker deletes playlist data
These changes matter because once SQLite work leaves the main thread, the
renderer can actually paint the loading state instead of freezing.
## Build And Packaging Notes
### Worker bundling
`apps/electron-backend/build-worker.js` now bundles both:
1. `epg-parser.worker.ts`
2. `database.worker.ts`
The worker build also aliases:
1. `database-schema`
2. `database-path-utils`
These aliases avoid importing the shared database barrel from inside the worker,
which would otherwise pull in runtime code that assumes the main Electron
process environment.
### Worker path resolution
`DatabaseWorkerClient` resolves:
1. development path from `__dirname`
2. packaged path from `process.resourcesPath/dist/apps/electron-backend/workers/...`
3. fallback packaged path from `path.dirname(app.getAppPath())`
### Packaged artifact verification
`tools/packaging/verify-electron-package-layout.mjs` verifies packaged worker
artifacts for:
1. Linux unpacked resources
2. macOS app bundles
3. Windows unpacked app resources
The script checks:
1. `epg-parser.worker.js`
2. `database.worker.js`
3. `better-sqlite3` in one approved unpacked node_modules location
4. Snap packaging compatibility settings for `better-sqlite3`:
- `snap.base = core22`
- Snap launch args keep the X11 fallback
- Snap and the other non-Flatpak Linux artifacts build on Ubuntu 22.04, while Flatpak builds on a separate Ubuntu 24.04 CI runner
### Development rebuild rule
Worker-backed database logic is executed from the compiled bundle at:
1. `dist/apps/electron-backend/workers/database.worker.js`
Do not assume a source edit is active in the live app. If a fix touches:
1. `apps/electron-backend/src/app/database/operations/`
2. `apps/electron-backend/src/app/workers/`
3. `apps/electron-backend/src/app/events/database/`
4. preload-backed DB methods consumed by the renderer
then the safe workflow is:
1. rebuild the worker bundle, or the full `electron-backend` target if preload,
main-process, or web output also changed
2. confirm the new `dist/` artifact exists or has a fresh timestamp
3. restart the Electron process
4. only then rerun CDP/manual checks or Electron E2E
A running Electron app keeps using the worker bundle it already loaded at
startup. This is a common reason a worker fix appears "not working" in manual
verification even when the source patch is correct.
## Testing
### Unit coverage added
`apps/electron-backend/src/app/services/database-worker-client.spec.ts`
covers:
1. worker ready -> request -> response flow
2. event forwarding to a pending request
3. serialized worker error propagation
4. `AbortError` propagation for cancelled work
5. cancel message routing to the live worker
6. worker exit recovery and fresh worker startup
`apps/electron-backend/src/app/events/epg.events.spec.ts` covers:
1. shared worker bootstrap usage for the EPG worker
2. `nativeModuleSearchPaths` forwarding into workerData
3. actionable worker-path resolution failures
`apps/electron-backend/src/app/workers/worker-runtime-paths.spec.ts` covers:
1. packaged and development worker path resolution
2. packaged native-module search path ordering
3. aggregated native module resolution errors
### Electron responsiveness coverage
`apps/electron-backend-e2e/src/xtream-responsiveness.e2e.ts` covers:
1. large Xtream import shows the overlay promptly
2. DB worker progress events advance during import
3. renderer animation frames continue while import/delete are in progress
4. large Xtream playlist delete shows row-level busy UI and completes cleanly
`apps/electron-backend-e2e/src/electron-test-fixtures.ts` now also captures:
1. `DB_OPERATION_EVENT` history in the renderer
2. a requestAnimationFrame counter for repaint assertions
For deterministic E2E timing, tests may set:
```bash
IPTVNATOR_DB_WORKER_BATCH_DELAY_MS=20
```
This delay is test-only and disabled by default.
### Useful verification commands
```bash
pnpm exec jest --config apps/electron-backend/jest.config.ts --runInBand apps/electron-backend/src/app/services/database-worker-client.spec.ts apps/electron-backend/src/app/events/epg.events.spec.ts apps/electron-backend/src/app/workers/worker-runtime-paths.spec.ts
pnpm nx run electron-backend:build-worker
pnpm exec tsc -p apps/electron-backend/tsconfig.app.json --noEmit
pnpm exec tsc -p apps/web/tsconfig.app.json --noEmit
pnpm nx run electron-backend-e2e:e2e -- --project=electron --grep "Electron Xtream Responsiveness"
pnpm run verify:package-layout -- macos arm64
pnpm run verify:package-layout -- linux
pnpm run verify:package-layout -- windows
```
### Electron runtime validation
```bash
pnpm nx serve electron-backend
agent-browser --cdp 9222 tab list
agent-browser --cdp 9222 tab 1
agent-browser --cdp 9222 snapshot -i -c -d 3
pnpm run smoke:packaged -- macos arm64
```
When worker-backed behavior changed, rebuild and restart before reconnecting:
```bash
pnpm nx run electron-backend:build-worker
CI=1 NX_TASKS_RUNNER_DYNAMIC_OUTPUT=false pnpm nx run electron-backend:build --skip-nx-cache
stat -f "%Sm %N" dist/apps/electron-backend/workers/database.worker.js
```
Then restart the Electron process and reconnect to `127.0.0.1:9222`.
### Electron freeze tracing
When a renderer route freezes before DevTools become usable, start Electron with
one of these opt-in trace flags and inspect the terminal output:
```bash
IPTVNATOR_TRACE_STARTUP=1 pnpm run serve:backend
```
Available trace flags:
1. `IPTVNATOR_TRACE_STARTUP=1`
Enables the broad startup trace set: BrowserWindow lifecycle, renderer
bridge calls, DB worker requests/events, and SQL tracing.
2. `IPTVNATOR_TRACE_IPC=1`
Logs `window.electron.*` method calls crossing the preload bridge so you can
see whether the renderer is still reaching Electron main.
3. `IPTVNATOR_TRACE_DB=1`
Logs `DatabaseWorkerClient` request dispatch, completion timing, and emitted
`DB_OPERATION_EVENT` payloads.
4. `IPTVNATOR_TRACE_SQL=1`
Logs SQLite statements for the shared main-process connection and the DB
worker connection using `better-sqlite3` verbose hooks.
5. `IPTVNATOR_TRACE_WINDOW=1`
Logs BrowserWindow loading, navigation, `unresponsive`, and
`render-process-gone` transitions.
6. `IPTVNATOR_TRACE_RENDERER_CONSOLE=1`
Mirrors renderer console messages into the Electron terminal output when the
renderer itself is the thing getting wedged.
### Electron E2E troubleshooting
If a production-mode Electron or Electron E2E launch shows `ERR_FILE_NOT_FOUND`
for hashed `chunk-*.js`, `main-*.js`, or `styles-*.css` assets:
1. treat `dist/apps/web` as stale first
2. rerun a deterministic production build, for example:
```bash
CI=1 NX_TASKS_RUNNER_DYNAMIC_OUTPUT=false pnpm nx run electron-backend:build --skip-nx-cache
```
3. verify `dist/apps/web/index.html` uses `<base href="./">` before relaunching
Electron in file-backed mode
## Current Limitations
These are intentionally still out of scope for this first cut:
1. request cancellation
2. moving network-heavy Xtream fetches off the current path
3. migrating every remaining small SQLite IPC handler to the worker
4. richer delete progress reporting for bulk destructive operations
5. repo-wide Angular/Jest cleanup for the currently failing web test baseline
## Extending The Worker
When adding another heavy SQLite operation:
1. Put SQL-heavy logic in `apps/electron-backend/src/app/database/operations/`.
2. Add the channel name to `database-worker.types.ts`.
3. Handle it in `database.worker.ts`.
4. Proxy the IPC handler through `DatabaseWorkerClient`.
5. If the renderer needs progress, emit a request-scoped `DbOperationEvent`.
6. Reuse existing preload/service APIs where possible instead of creating a new
renderer-facing contract.
7. Re-run the worker unit test and at least one Electron runtime smoke.
+267
View File
@@ -0,0 +1,267 @@
# Stalker Portal EPG Architecture
This document describes the current EPG implementation for Stalker/Ministra ITV
channels in IPTVnator.
Related architecture docs:
- [Stalker Portal Architecture](./stalker-portal.md)
- [Remote Control Architecture](./remote-control.md)
## Overview
Stalker now uses two EPG paths with different purposes:
- The active channel EPG panel uses `get_epg_info` as a bulk endpoint, fetches a
7-day window once per playlist session, caches programs by channel id, and
renders the selected channel through the shared `app-epg-list` component.
- Channel rows no longer send preview EPG requests during initial category load.
They stay empty until bulk EPG has been fetched once, then derive their
current program and progress bar from the cached bulk map.
- If a portal does not return usable bulk data for the selected channel, the
active panel falls back to `get_short_epg`.
This keeps the live list cheap while giving the active panel the same
date-navigator UI used in the M3U/Xtream flows.
## Architecture
```text
┌────────────────────────────────────────────────────────────────────────────┐
│ StalkerLiveStreamLayoutComponent │
│ libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/ │
│ │
│ sidebar rows active channel panel │
│ ──────────── ─────────────────── │
│ row preview map playChannel() │
│ from bulk cache │ │
│ │ ▼ │
│ │ ensureBulkItvEpg(168) │
│ │ selectedItvEpgPrograms() │
│ ▼ │ │
│ current program preview ├── bulk hit → app-epg-list │
│ after first bulk load └── empty/unsupported → short fallback │
└────────────────────────────────────────────────────────────────────────────┘
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────────┐
│ with-stalker-epg.feature │
│ │
│ bulkItvEpgByChannel: Record<string, EpgProgram[]> │
│ bulkItvEpgPlaylistId / bulkItvEpgPeriodHours / bulkItvEpgLoaded │
│ ensureBulkItvEpg() selectedItvEpgPrograms() │
└────────────────────────────────────────────────────────────────────────────┘
│ │
▼ ▼
┌────────────────────────────────────────────────────────────────────────────┐
│ Stalker Portal API │
│ │
│ action=create_link action=get_short_epg action=get_epg_info │
└────────────────────────────────────────────────────────────────────────────┘
```
## Stalker EPG API
### `get_short_epg` (active-panel fallback)
**Request**
```text
GET load.php?type=itv&action=get_short_epg&ch_id={channel_id}&size={n}&JsHttpRequest=1-xml
```
**Current usage**
- Active panel fallback path: `size=10`
**Response**
```json
{
"js": {
"data": [
{
"id": "123",
"ch_id": "45",
"name": "Program Title",
"descr": "Program description",
"time": "2025-01-15 14:00:00",
"time_to": "2025-01-15 14:30:00",
"duration": "1800",
"start_timestamp": "1736949600",
"stop_timestamp": "1736951400"
}
]
}
}
```
**Notes**
- The response is normalized into shared `EpgItem[]`
- The list-preview path uses this directly
- The active-panel fallback maps the result into controlled `EpgProgram[]`
### `get_epg_info` (bulk active-panel source)
**Request**
```text
GET load.php?type=itv&action=get_epg_info&period={hours}&JsHttpRequest=1-xml
```
**Current usage**
- Fetched once with `period=168`
- Scoped to the current playlist session
- Not refetched on active-channel change
**Expected response**
```json
{
"js": {
"data": {
"45": [
{
"id": "1",
"name": "Program Title",
"descr": "Program description",
"time": "2025-01-15 14:00:00",
"time_to": "2025-01-15 16:00:00",
"start_timestamp": "1736949600",
"stop_timestamp": "1736956800"
}
]
}
}
}
```
**Notes**
- The store supports the channel-keyed bulk shape above as the primary contract
- For weak or mock-style portals that still return array-style data, the store
treats the result as compatibility input and leaves the short-EPG fallback path
available
## Data Mapping
### Fallback data (`get_short_epg`) → `EpgItem`
The short EPG path now exists only for the active-panel fallback flow.
Key mapped fields:
| Stalker field | `EpgItem` field |
| --- | --- |
| `id` | `id` |
| `ch_id` | `channel_id` |
| `name` | `title` |
| `descr` | `description` |
| `time` | `start` |
| `time_to` | `end`, `stop` |
| `start_timestamp` | `start_timestamp` |
| `stop_timestamp` | `stop_timestamp` |
### Active panel data (`get_epg_info` / fallback) → `EpgProgram`
The active panel uses controlled `EpgProgram[]` because `app-epg-list` filters
and groups by day.
Normalization rules:
- `start` / `end` are converted to ISO strings
- `startTimestamp` / `stopTimestamp` are always populated
- Programs are sorted by start time per channel
- `selectedItvId` is used to project cached bulk data to the active channel
## Implementation Details
### Key files
| File | Purpose |
| --- | --- |
| `libs/portal/stalker/data-access/src/lib/stores/features/with-stalker-epg.feature.ts` | bulk cache and fallback handling |
| `libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/stalker-live-stream-layout.component.ts` | active-channel EPG loading and controlled `app-epg-list` wiring |
| `libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/stalker-live-stream-layout.component.html` | active panel template |
| `libs/portal/stalker/feature/src/lib/stalker-collection-channels-list/stalker-collection-channels-list.component.ts` | row preview loading |
| `libs/ui/shared-portals/src/lib/epg-list/epg-list.component.ts` | shared controlled EPG list with date navigator |
### Store API
The Stalker EPG feature exposes one bulk method plus the short-EPG fallback:
```ts
fetchChannelEpg(channelId: number | string, size?: number): Promise<EpgItem[]>
ensureBulkItvEpg(periodHours = 168): Promise<void>
```
It also exposes:
- `selectedItvEpgPrograms`
- `clearBulkItvEpgCache()`
Bulk state is keyed by playlist so cached results do not leak between Stalker
playlists.
### Active panel flow
1. User activates a live channel
2. The component ensures playback link resolution as before
3. The component calls `ensureBulkItvEpg(168)` on first use for the playlist
4. `selectedItvEpgPrograms()` feeds `app-epg-list`
5. If the selected channel has no bulk programs, the component falls back to
`get_short_epg`
The active panel no longer uses local EPG pagination or a "Load more" button.
### Channel row preview flow
Before the first live-channel playback, channel rows do not fetch EPG at all.
After bulk EPG has been loaded once for the playlist, visible row previews are
derived locally from `bulkItvEpgByChannel`:
- pick the current program for the channel, if one exists
- compute progress from the cached program timestamps
- leave the row in its existing placeholder state when no current program exists
## Cache Lifecycle
- Bulk EPG is fetched once per playlist session
- Channel switches only read from `bulkItvEpgByChannel`
- The cache is cleared when the Stalker playlist changes
- This implementation does not add TTL-based refresh or background polling
## Authentication
EPG requests follow the standard Stalker request path:
| Portal type | Auth path |
| --- | --- |
| Full Stalker portal | `StalkerSessionService.makeAuthenticatedRequest()` |
| Simple Stalker portal | generic IPC request path via Electron |
No EPG-specific backend transport was needed; the Electron Stalker request
handler forwards portal params directly.
## Fallback Behavior
Some providers do not implement `get_epg_info` consistently. The active panel
therefore falls back to `get_short_epg` when:
- the bulk request fails
- the bulk response is empty
- the selected channel has no programs in the cached bulk map
This keeps the panel usable even on limited portals, while still taking
advantage of the richer bulk API when it is available. Row previews do not
fallback to per-channel requests in this mode; they remain empty until bulk EPG
is available.
## Future Enhancements
- add cache refresh / invalidation for long-running live sessions
- add Stalker catch-up support to `app-epg-list` once the playback flow exists
- optionally add category-level prefetch timing metrics for bulk EPG
+280
View File
@@ -0,0 +1,280 @@
# Stalker Mock Server Architecture
This document describes the design decisions, data flow, and extension points of the `stalker-mock-server` development tool.
## Related Docs
- [Stalker Portal Architecture](./stalker-portal.md)
- [Stalker EPG Architecture](./stalker-epg.md)
## Purpose
The mock server enables:
1. **Local development** without access to a real Stalker portal
2. **Playwright E2E testing** with predictable, deterministic data
3. **Scenario-based testing** via predefined MAC addresses that map to specific data shapes
## Key Design Decisions
### Seeded Determinism (Not Per-Request Random)
Per-request random data would break navigation: if category IDs change between calls, content fetched under a category ID won't match the category list. Instead:
- Data is generated **once per MAC address** on first request, then cached in memory.
- `@faker-js/faker` is seeded with a numeric value derived from the MAC address before generation.
- Same MAC → identical data on every server restart.
- Restart the server to reshuffle all data.
### MAC Address as Identity
Stalker portals use MAC address as the primary credential. The mock server follows the same model:
- Each unique MAC gets its own isolated dataset.
- Predefined MACs map to specific `ScenarioConfig` shapes (see `src/app/scenarios.ts`).
- Unknown MACs use the sum of their byte values as a seed, producing unique but deterministic data.
### In-Memory Only
No files or databases are written. All state (generated content + favorites) lives in process memory and resets on server restart. This is intentional — tests should not share state across runs.
## Data Generation Pipeline
```
faker.seed(macToNumber(mac))
│
├── generateCategories('itv', N) → itvCategories[]
│ └── generateChannels() → channels Map<categoryId, channel[]>
│ └── generateEpg() → epg Map<channelId, program[]>
│
├── generateCategories('vod', N) → vodCategories[]
│ └── generateVodItems() → vod Map<categoryId, item[]>
│ ├── normal VOD items
│ ├── is_series=1 items (fraction, Ministra flow)
│ └── embedded series[] items (fraction)
│
└── generateCategories('series', N) → seriesCategories[]
└── generateSeriesItems() → series Map<categoryId, item[]>
└── generateSeasons() → seasons Map<seriesItemId, season[]>
```
## Response Shapes
All responses follow the Stalker `portal.php` envelope:
```json
{ "js": <action-specific payload> }
```
### `get_categories`
```json
{
"js": [
{ "id": "2001", "title": "Action", "alias": "action" },
...
]
}
```
### `get_ordered_list` (content)
```json
{
"js": {
"data": [
{
"id": "20001",
"name": "...",
"cmd": "ffrt4://vod/20001/index.m3u8",
"screenshot_uri": "https://picsum.photos/seed/vod-20001/300/200",
"cover": "https://picsum.photos/seed/vod-cover-20001/300/450",
"description": "...",
"actors": "...",
"director": "...",
"year": "2019",
"rating_imdb": "7.3",
"category_id": "2001",
"is_series": 0,
"has_files": 1
}
],
"total_items": 40,
"max_page_items": 14,
"cur_page": 1,
"total_pages": 3
}
}
```
### `get_ordered_list` (seasons — when `movie_id` is present)
```json
{
"js": [
{
"id": "30001-s1",
"name": "Season 1",
"cmd": "ffrt4://series/30001/season/1",
"series": ["30001-s1-e1", "30001-s1-e2", ...],
"screenshot_uri": "https://picsum.photos/seed/30001-s1/300/200",
"director": "...",
"actors": "...",
"year": "2021",
"rating_imdb": "8.1"
}
]
}
```
### `create_link`
```json
{
"js": {
"cmd": "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
"streamer_id": "1",
"load": "",
"error": ""
}
}
```
The stream URL is selected from a pool of 4 real public HLS test streams. The choice is deterministic based on the `cmd` field's character sum, so the same item always returns the same stream.
### `get_short_epg`
```json
{
"js": {
"data": [
{
"id": "1",
"name": "Channel Name: Program Title",
"start": "2026-02-21T10:00:00.000Z",
"stop": "2026-02-21T12:00:00.000Z",
"start_timestamp": 1740128400,
"stop_timestamp": 1740135600,
"descr": "...",
"category": "News"
}
]
}
}
```
`get_short_epg` returns the current program and upcoming items from the
generated schedule, limited by the requested `size`.
### `get_epg_info`
```json
{
"js": {
"data": {
"10000": [
{
"id": "1",
"name": "Channel Name: Program Title",
"start": "2026-02-21T10:00:00.000Z",
"stop": "2026-02-21T12:00:00.000Z",
"start_timestamp": 1740128400,
"stop_timestamp": 1740135600,
"descr": "...",
"category": "News"
}
]
}
}
}
```
`get_epg_info` returns bulk EPG keyed by channel id and filters the generated
7-day schedule from the current UTC day start through `now + period`.
EPG programs are generated as 2-hour slots across 7 days for each channel,
starting at the current UTC day boundary.
## Scenarios
Scenarios are defined in `src/app/scenarios.ts`. Each scenario is a `ScenarioConfig`:
```typescript
interface ScenarioConfig {
name: string;
description: string;
seed: number;
categoryCount: { itv: number; vod: number; series: number };
itemsPerCategory: number;
seasonsPerSeries: number;
episodesPerSeason: number;
isSeriesFraction: number; // 0–1: fraction of VOD with is_series=1
embeddedSeriesFraction: number; // 0–1: fraction of VOD with embedded series[]
}
```
### Adding a New Scenario
1. Add an entry to the `SCENARIOS` map in `src/app/scenarios.ts`.
2. Use any unique MAC address as the key (lowercase, colon-separated).
3. Document it in `README.md` and this file.
## Favorites
Favorites are stored in a `Map<mac, Set<itemId>>` in `src/app/data-store.ts`. They persist for the lifetime of the server process and are shared across all requests for the same MAC.
Call `POST /reset` to clear all favorites (and regenerated data) between test runs.
## Playwright Integration
`apps/web-e2e/playwright.config.ts` registers the mock server as a second `webServer` entry:
```typescript
webServer: [
{
command: 'pnpm nx run web:serve',
url: 'http://localhost:4200',
reuseExistingServer: !process.env['CI'],
},
{
command: 'pnpm nx run stalker-mock-server:serve',
url: 'http://localhost:3210/health',
reuseExistingServer: !process.env['CI'],
},
]
```
Playwright waits for both servers to be healthy before starting tests. If either is already running (e.g. in local dev), it reuses the existing instance.
### Test Isolation
Each stalker e2e test calls `POST http://localhost:3210/reset` in `beforeEach` to clear in-memory state. This ensures tests don't bleed favorites or other mutable state into each other.
The generated content (categories, items) is **not** cleared on reset — it's deterministic and doesn't need to be. Only in-memory favorites are cleared.
### Recommended Test Structure
```typescript
import { test, expect } from '@playwright/test';
const MOCK_URL = 'http://localhost:3210/portal.php';
const MOCK_MAC = '00:1A:79:00:00:01'; // default scenario
test.beforeEach(async ({ request }) => {
await request.post('http://localhost:3210/reset');
});
test('browse VOD categories', async ({ page }) => {
// Add portal via UI or programmatically via IndexedDB
// Navigate to portal
// Assert category list matches expected count (8 for default scenario)
});
```
## Extension Points
- **New content types**: Add a new generator function in `data-generator.ts` and a new handler in `handlers/`.
- **New scenarios**: Add to `SCENARIOS` in `scenarios.ts`.
- **Stateful session tokens**: `handshake.handler.ts` generates a token from the MAC — extend this to track token expiry for testing re-auth flows.
- **Error simulation**: Add a special MAC or query param to trigger error responses (e.g. 401, 500) for testing error handling in the Stalker store.
- **Slow responses**: Add a `MOCK_DELAY_MS` env var and apply it in middleware for testing loading states.
+233
View File
@@ -0,0 +1,233 @@
# Stalker Portal Architecture
This document describes the Stalker portal implementation in IPTVnator and where each feature is integrated.
## Related Docs
- [Stalker Portal EPG Architecture](./stalker-epg.md)
- [Playlist Backup/Restore Architecture](./playlist-backup-restore.md)
- [Portal Detail Navigation](./portal-detail-navigation.md)
- [Embedded Inline Playback](./embedded-inline-playback.md)
- [Remote Control Architecture](./remote-control.md)
- [Download Manager](./download-manager.md)
- [Category Management](./category-management.md)
- [Stalker Store API Baseline](./stalker-store-api-baseline.md)
## Scope
Stalker support covers:
- Live TV (`itv`)
- VOD (`vod`)
- Series (`series`)
- VOD-as-series flows (`is_series=1` and embedded `series[]`)
- Favorites and recently viewed collections
- Search
- External player playback (shared Xtream player infrastructure)
- Remote control for live ITV navigation
## Routing Structure
Primary route tree lives in `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-feature.routes.ts`.
- `/stalker/:id/vod`
- `/stalker/:id/series`
- `/stalker/:id/itv`
- `/stalker/:id/favorites`
- `/stalker/:id/recent`
- `/stalker/:id/search`
- `/stalker/:id/downloads` (shared downloads module from Xtream UI)
## Runtime Architecture
1. Angular Stalker screens call methods/resources in `StalkerStore`.
2. `StalkerStore` builds request params based on selected content type and current view state.
3. Requests go through `DataService.sendIpcEvent(STALKER_REQUEST, ...)` or `StalkerSessionService` (full portal auth).
4. Electron main process handles `STALKER_REQUEST` in `/Users/4gray/Code/iptvnator/apps/electron-backend/src/app/events/stalker.events.ts`.
5. Axios calls Stalker `load.php` API with required headers/cookies and returns normalized payloads to renderer.
## Main UI Components
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-main-container.component.ts`
- Category + content layout for `vod` and `series`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/stalker-live-stream-layout.component.ts`
- ITV live playback, channel navigation, EPG panel integration
- `/Users/4gray/Code/iptvnator/libs/ui/components/src/lib/stalker-series-view/stalker-series-view.component.ts`
- Season/episode UI for all Stalker series modes
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-favorites/stalker-favorites.component.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/recently-viewed/recently-viewed.component.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-search/stalker-search.component.ts`
## Store and Data Flow
Stalker store is now feature-composed:
- Facade: `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/stalker.store.ts`
- Feature slices: `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/stores/features/*`
- Shared helpers: `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/*`
Important store responsibilities:
- Selected content/category/item state
- Category and paginated content resources
- ITV channel list + pagination
- Regular series seasons resource
- VOD-series (`is_series=1`) seasons + episodes resources
- Playback link creation (`create_link` flow)
- Favorites and recently viewed persistence helpers
Internal structure to preserve:
- `stalker.store.ts` stays as the thin facade that composes feature slices.
- Cross-slice contracts live in `stores/stalker-store.contracts.ts` so
feature dependencies are declared instead of repeated `unknown` casts.
- Request execution is centralized in `stores/utils/stalker-request.utils.ts`
for both authenticated full-portal calls and simple IPC-backed requests.
- Playback link resolution and Stalker collection persistence live in
dedicated `stores/utils/` helpers so player/favorites/recent slices stay
focused on orchestration.
- Category/content resources stay internal to the store slices. Feature
consumers should read `getCategoryResource()` and `getPaginatedContent()`,
which now always return arrays, and pair them with
`isCategoryResourceFailed()` / `isPaginatedContentFailed()` for explicit
error handling.
Failure-handling rule:
- Failed category or content requests must degrade into empty/error UI state,
not `undefined` collections or renderer exceptions. The workspace Stalker
context panel and live layout rely on this guarantee.
## VOD/Series Modes
Stalker has multiple real-world data shapes. The current implementation supports all three:
1. Regular Series (`/series`):
- Seasons come from API resource (`serialSeasonsResource`).
- Episodes are derived from season payload.
2. VOD with Embedded `series[]`:
- Item is opened under VOD, but already contains episodes.
- `StalkerSeriesViewComponent` creates a pseudo-season and renders episodes directly.
3. VOD with `is_series=1` (Ministra plugin behavior):
- Treated as series flow from VOD context.
- Seasons are fetched lazily.
- Episodes are fetched on season select.
- Uses unique generated tracking IDs for episode playback position compatibility.
Core decision logic and normalization are centralized in:
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/stalker-vod.utils.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/models/*.ts`
## Favorites and Recently Viewed
Current implementation is shared via Stalker-specific helpers:
- `createPortalCollectionResource(...)` generic collection loader
- `createPortalFavoritesResource(...)` favorites wrapper
- `createStalkerDetailViewState(...)` unified "open detail" decision
- `toggleStalkerVodFavorite(...)` shared add/remove behavior
- `normalizeStalkerEntityId(...)` and `normalizeStalkerEntityIdAsNumber(...)` for stable ID matching
- `matchesFavoriteById(...)` for cross-shape favorite matching
Where this is used:
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-favorites/stalker-favorites.component.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/recently-viewed/recently-viewed.component.ts`
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-search/stalker-search.component.ts`
- `/Users/4gray/Code/iptvnator/libs/ui/components/src/lib/stalker-favorites-button/stalker-favorites-button.component.ts`
Navigation rule to preserve:
- Stalker favorites, recently viewed, and search stay in their current screen and open inline detail state.
- They should not redirect into a canonical content/category/item route because Stalker detail rendering is currently store-state/inline driven, not route driven.
- VOD-backed series favorites can be displayed in series collections, but detail
opening must preserve their VOD origin: `is_series=1` favorites set the
selected content type to `vod` so the lazy Ministra season/episode resources
run, and embedded `series[]` favorites render through the embedded VOD-series
branch.
- See [Portal Detail Navigation](./portal-detail-navigation.md).
## Backup and Restore
Versioned playlist backups include Stalker connection metadata plus playlist-
scoped favorites/recent snapshots.
Exported fields:
- `portalUrl`
- `macAddress`
- `isFullStalkerPortal`
- optional `username` / `password`
- optional request headers (`userAgent`, `referrer`, `origin`)
- full-portal serial/device/signature fields when present
- favorites and recently viewed collections
Excluded fields:
- `stalkerToken`
- `stalkerAccountInfo`
- playback positions in backup v1
Import rule:
- backups restore the saved portal definition and replace the stored
favorites/recent state for the matched playlist
- a fresh handshake must happen after import for full-portal sessions; imported
backups never trust a serialized token
## Remote Control Integration
Stalker live remote control is implemented in:
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/feature/src/lib/stalker-live-stream-layout/stalker-live-stream-layout.component.ts`
Supported today:
- Channel up/down
- Numeric channel selection (list-position based)
- Status publish for remote UI (portal/channel/current program)
See full backend and web-remote flow in [Remote Control Architecture](./remote-control.md).
## EPG Integration
Stalker ITV now splits EPG usage:
- active channel panel: bulk `get_epg_info` cached once per playlist and rendered
through shared `app-epg-list`
- channel row preview: no pre-playback network requests; previews are derived
from cached bulk EPG only after the first active-channel fetch succeeds
- active panel fallback: `get_short_epg` when bulk EPG is missing or unsupported
Full details are documented in [Stalker Portal EPG Architecture](./stalker-epg.md).
## Shared/Reusable Infrastructure
Stalker reuses some Xtream UI infrastructure deliberately:
- Category content rendering route uses Xtream category content component
- Season container for episodes uses shared Xtream season UI component
- Playback position handling for series episodes reuses Xtream store position mechanisms
- Downloads route reuses shared downloads feature
This reduces duplicate UI logic across portal types and keeps compatibility behavior aligned.
## Regression Coverage
Focused regression tests for Stalker VOD mode branching live in:
- `/Users/4gray/Code/iptvnator/libs/portal/stalker/data-access/src/lib/stalker-vod.utils.spec.ts`
Covered scenarios include:
- Embedded `series[]` opens series view state
- `is_series=1` opens lazy series state
- VOD-backed series favorites keep VOD-series loading semantics when opened from
favorites/global favorites
- Favorite toggle helper path invokes the expected add/remove flow
@@ -0,0 +1,133 @@
# Stalker Store API Baseline
This is the compatibility baseline for refactoring `libs/portal/stalker/data-access/src/lib/stalker.store.ts`.
Goal: keep this public surface stable while splitting to feature stores.
## Source of Truth
- Store implementation: `libs/portal/stalker/data-access/src/lib/stalker.store.ts`
- Baseline created on current branch state before feature-store extraction.
## Public State Signals
Direct signal properties currently exposed by `signalStore`:
- `selectedContentType: 'vod' | 'itv' | 'series'`
- `selectedCategoryId: string | null | undefined`
- `selectedVodId: string | undefined`
- `selectedSerialId: string | undefined`
- `selectedItvId: string | undefined`
- `limit: number`
- `page: number`
- `searchPhrase: string`
- `currentPlaylist: PlaylistMeta | undefined`
- `totalCount: number`
- `selectedItem: StalkerVodSource | null | undefined`
- `vodCategories: StalkerCategoryItem[]`
- `seriesCategories: StalkerCategoryItem[]`
- `itvCategories: StalkerCategoryItem[]`
- `hasMoreChannels: boolean`
- `itvChannels: StalkerItvChannel[]`
- `vodSeriesSeasons: StalkerVodSeriesSeason[]`
- `vodSeriesEpisodes: StalkerVodSeriesEpisode[]`
- `selectedVodSeriesSeasonId: string | undefined`
## Public Computed Selectors
- `getTotalPages: number`
- `getPaginatedContent: StalkerContentItem[]`
- `isPaginatedContentLoading: boolean`
- `isPaginatedContentFailed: unknown`
- `getSerialSeasonsResource: StalkerSeason[]`
- `isSerialSeasonsLoading: boolean`
- `getVodSeriesSeasonsResource: StalkerVodSeriesSeason[]`
- `isVodSeriesSeasonsLoading: boolean`
- `getCategoryResource: StalkerCategoryItem[]`
- `isCategoryResourceLoading: boolean`
- `isCategoryResourceFailed: unknown`
- `getSelectedCategoryName: string`
## Exposed Resources/Props
These are currently reachable on the store object and used internally by computed selectors:
- `getCategoryResource` (computed selector with stable array output)
- `categoryResource` (internal resource)
- `getContentResource` (resource)
- `serialSeasonsResource` (resource)
- `vodSeriesSeasonsResource` (resource)
- `makeStalkerRequest(...)`
During refactor:
- Keep compatibility for external callers that may read these directly.
- If moved/renamed internally, provide facade aliases.
## Public Methods (Compatibility Contract)
- `setSelectedContentType(type: 'vod' | 'itv' | 'series'): void`
- `setSelectedCategory(id: string | number | null): void`
- `setSelectedSerialId(id: string): void`
- `setSelectedVodId(id: string): void`
- `setSelectedItvId(id: string): void`
- `setLimit(limit: number): void`
- `setPage(page: number): void`
- `setCurrentPlaylist(playlist: PlaylistMeta | undefined): Promise<void>`
- `setSelectedItem(selectedItem: StalkerVodSource | null | undefined): void`
- `clearSelectedItem(): void`
- `setCategories(type: 'vod' | 'series' | 'itv', categories: StalkerCategoryItem[]): void`
- `resetCategories(): void`
- `setItvChannels(channels: StalkerItvChannel[]): void`
- `setSearchPhrase(phrase: string): void`
- `fetchVodSeriesEpisodes(videoId: string, seasonId: string): Promise<StalkerVodSeriesEpisode[]>`
- `getSelectedCategory(): { id: string | number; name: string; type: 'vod' | 'itv' | 'series' }`
Backed by `withComputed` for compatibility, not by `withMethods`.
- `fetchLinkToPlay(portalUrl: string, macAddress: string, cmd: string, series?: number): Promise<string>`
- `getExpireDate(): Promise<string>`
- `addToFavorites(item: any, onDone?: () => void): void`
- `removeFromFavorites(favoriteId: string, onDone?: () => void): void`
- `fetchMovieFileId(movieId: string): Promise<string | null>`
- `createLinkToPlayVod(cmd?: string, title?: string, thumbnail?: string, episodeNum?: number, episodeId?: number, startTime?: number): Promise<void>`
- `addToRecentlyViewed(item: any): void`
- `removeFromRecentlyViewed(itemId: number, onComplete?: () => void): void`
- `fetchChannelEpg(channelId: number | string, size?: number): Promise<EpgItem[]>`
## Current Consumers (Observed)
Top observed store API usage in app code:
- `currentPlaylist` (16 references)
- `setSelectedContentType` (9)
- `selectedItem` (9)
- `setSelectedItem` (7)
- `setSelectedCategory` (6)
- `createLinkToPlayVod` (6)
- `removeFromFavorites` (5)
- `setPage` (4)
- `addToFavorites` (4)
- `fetchChannelEpg` (3)
- plus lower-frequency calls for paging/resources/series/recent.
Consumer directories sampled:
- `libs/portal/stalker/**`
- `libs/portal/xtream/feature/**`
- `libs/portal/catalog/feature/**`
- `libs/ui/components/**`
## Invariants to Preserve During Refactor
- Selection IDs (`selectedVodId`, `selectedSerialId`, `selectedItvId`) are synchronized in `setSelectedItem`.
- `setSelectedCategory(...)` resets `page` to `0`.
- `getPaginatedContent()` and `getCategoryResource()` always return arrays,
even when the underlying request fails.
- Request failures must surface through `isPaginatedContentFailed()` and
`isCategoryResourceFailed()` rather than resource reads that throw.
- `createLinkToPlayVod(...)` continues to:
- support episode playback metadata
- append recently viewed
- preserve external player payload shape
- Full-portal auth path continues through `StalkerSessionService`.
- Non-auth/simple path continues through `DataService.sendIpcEvent(STALKER_REQUEST, ...)`.
- Resource-driven loading signals preserve existing names.
+167
View File
@@ -0,0 +1,167 @@
# Workspace Dashboard
This document records the current dashboard implementation inside the workspace
shell.
Related:
- [Workspace Shell](./workspace-shell.md)
## Summary
- The dashboard is the default `/workspace` landing page.
- It is a **rail-based** content surface (Netflix / Apple TV pattern), not a
customizable widget grid.
- Layout is static and curated — there is no edit mode, drag-drop, size
stepper, show/hide toggle, or persisted layout. Rails auto-hide when empty.
- First-run users see the shared welcome empty-state with a single primary
CTA to add their first playlist.
Core implementation:
1. `libs/workspace/dashboard/feature/src/lib/rails/workspace-dashboard-rails.component.ts`
— the page-level facade.
2. `libs/workspace/dashboard/feature/src/lib/rails/dashboard-rail.component.ts`
— the reusable horizontal rail.
3. `libs/workspace/dashboard/data-access/src/lib/dashboard-data.service.ts`
— data aggregation (recent items, favorites, playlist stats). Shared across
rails.
4. `libs/playlist/shared/ui/src/lib/recent-playlists/empty-state/empty-state.component.ts`
— reused welcome state with the primary "Add your first playlist" CTA.
## Page Structure
```
┌─────────────────────────────────────────────────────────────────────┐
│ Hero — Continue Watching (most recent item) │
├─────────────────────────────────────────────────────────────────────┤
│ Recently Watched · See all → │
│ [poster][poster][poster][poster] →→ │
├─────────────────────────────────────────────────────────────────────┤
│ Global Favorites · See all → │
│ [poster][poster][poster] →→ │
├─────────────────────────────────────────────────────────────────────┤
│ Recently Used Sources · See all → │
│ [tile][tile][tile][tile] →→ │
├─────────────────────────────────────────────────────────────────────┤
│ Recently Added on Xtream (aggregated across providers) │
│ [poster][poster][poster] →→ │
└─────────────────────────────────────────────────────────────────────┘
```
Render rules:
1. `dashboardReady() === false` → render the page-level skeleton rails/hero.
The first-load gate waits for playlist metadata plus the first global
recent/global favorites reloads and, when Xtream playlists exist, the first
Xtream recently-added reload.
2. `hasPlaylists() === false` → render `<app-empty-state type="welcome">`
full-bleed. All rails and the hero are skipped.
3. `hero()` = `globalRecentItems()[0]`. If present, render the hero panel.
4. Each rail is emitted via `@if (cards.length > 0)`. Empty rails are hidden
— there is no "empty widget" placeholder.
5. The continue-watching hero prefers a stored Xtream `backdrop_url`; when it
is missing the UI falls back to a blurred poster treatment instead of
showing a flat panel.
## Rail Contract
`DashboardRailComponent` is purely presentational:
1. Inputs: `label`, `items: DashboardRailCard[]`, optional `seeAllLink`,
optional `aspectRatio` (default `'2 / 3'`), optional `testId`.
2. Behavior: horizontal flex track with `scroll-snap-type: x mandatory`.
3. Chevron buttons fade in on hover (desktop only via `@media (hover: none)`).
4. Cards are keyboard-focusable router links; `scroll-snap-align: start`
means arrow-key nav lands on card boundaries.
5. Image handling: `loading="lazy"`, `decoding="async"`, fallback icon tile
when `imageUrl` is missing or `error` fires.
6. Dashboard hero, rail containers, rail cards, and "Manage all" links expose
stable `data-test-id` hooks. Treat these as the supported Electron E2E
selector surface; do not target internal CSS class names.
## Data Flow
1. `WorkspaceDashboardRailsComponent` injects `DashboardDataService`.
2. It derives five signals via `computed()`:
1. `hero` — first item of `globalRecentItems()`.
2. `recentlyWatchedCards` — maps `globalRecentItems()` to rail cards.
3. `xtreamRecentlyAddedCards` — maps `xtreamRecentlyAddedItems()` to rail
cards. Aggregates newly added VOD and series across *all* Xtream
playlists via `DashboardDataService.reloadXtreamRecentlyAddedItems()`,
which calls `getGlobalRecentlyAdded('all', limit, 'xtream')` with the
DB-level `playlists.type = 'xtream'` filter. The rail is Electron-only
(PWA returns `[]`) and auto-hides when empty, so users without Xtream
playlists never see it. Cards carry a `playlist_name · type` subtitle
so users can tell which provider each item came from. Driven by an
effect that re-runs whenever the Xtream playlist count changes.
4. `favoriteCards` — maps `globalFavoriteItems()` to rail cards.
5. `sourceCards` — maps `recentPlaylists()` to rail cards. `recentPlaylists()`
ranks M3U, Xtream, and Stalker sources by their latest recent activity
from `globalRecentItems()`, then falls back to playlist
`updateDate` / `importDate` for sources that have never been used.
3. `DashboardDataService` is passive on construction. The dashboard feature
owns the initial reloads for recent items, favorites, and Xtream recently
added rows on page entry.
4. No `Layout` state, no localStorage keys, no migrations.
5. Navigation state + deep-link targets come from the existing
`getRecentItemLink()` / `getGlobalFavoriteLink()` / `getPlaylistLink()`
helpers on `DashboardDataService` and reuse the workspace navigation
helpers in `@iptvnator/portal/shared/util`.
6. Xtream VOD and series detail pages opportunistically backfill
`content.backdrop_url` when metadata exposes a backdrop, but that write
must not refresh recently viewed ordering by itself.
7. The dashboard feature triggers a fresh reload of DB-backed recent/favorite
rows on dashboard entry so newly backfilled backdrop data is visible as soon
as the user returns from a detail page.
## Empty State
The welcome state is rendered via the existing
`EmptyStateComponent` (`type="welcome"`) from
`libs/playlist/shared/ui`:
1. Illustration + headline + description from the existing M3U welcome
strings (`HOME.PLAYLISTS.WELCOME_*`).
2. Primary button emits `addPlaylistClicked`. The dashboard page wires this
to `WORKSPACE_SHELL_ACTIONS.openAddPlaylistDialog()`.
3. Feature chips (M3U / Xtream / Stalker) are provided by the component.
## UX Rules
1. Rails represent content the user is likely to resume, not provider
internals. Never surface raw API objects.
2. Each rail must auto-hide when its data source is empty.
3. Image assets must degrade to a typed icon fallback — never show broken
images or empty tiles.
4. The page must never show "No widgets" style text. If there is no content
and no playlists, render the welcome state; otherwise render whatever
rails have data.
5. Navigation from a rail card must deep-link into the appropriate workspace
route without switching the active playlist in the header switcher.
6. `Recently Used Sources` reflects recent source usage across all provider
types, not just recent imports.
## Adding Or Changing Rails
Current workflow:
1. Add a new `computed()` signal for the card list in
`WorkspaceDashboardRailsComponent`, mapping your source data to
`DashboardRailCard`.
2. Drop a `<lib-dashboard-rail>` in the template, gated by
`@if (cards.length > 0)`.
3. If the data source is new, extend `DashboardDataService` rather than
reaching into DB services directly from the component.
4. Provide a `seeAllLink` only if there is a dedicated "manage all" route
for that content type.
## Deferred Work
Intentionally out of scope:
1. Customizable layout (drag/drop, resize, show/hide toggles, layout
persistence). Removed in favor of a curated, opinionated order.
2. Freeform widget grid with collision management.
3. External data rails such as RSS, sports, or news adapters.
4. Per-user A/B variants of rail ordering.
+141
View File
@@ -0,0 +1,141 @@
# Workspace Shell
This document records the current workspace-first shell contract. It is the
stable replacement for the older UI refactor summary.
Related:
- [Workspace Dashboard](./workspace-dashboard.md)
## Summary
- `/workspace` is the primary app surface.
- `WorkspaceShellComponent` owns the persistent frame: rail, header, optional
context panel, content outlet, and external playback footer.
- Descendant workspace pages inherit `layout = 'workspace'` from the
`/workspace` root route.
- Provider route trees now bootstrap through route-scoped session providers
instead of nested provider shell components.
Core implementation:
1. `apps/web/src/app/app.routes.ts`
2. `libs/workspace/shell/feature/src/lib/workspace-shell/workspace-shell.component.ts`
3. `libs/workspace/shell/feature/src/lib/workspace-shell/workspace-shell.component.html`
4. `libs/portal/shared/util/src/lib/navigation/portal-route.utils.ts`
5. `libs/portal/shared/util/src/lib/navigation/portal-rail-links.ts`
6. `libs/portal/shared/ui/src/lib/navigation/portal-rail-links.component.ts`
## Route Contract
Current workspace routes:
1. `/` -> `/workspace`
2. `/workspace` -> `/workspace/dashboard`
3. `/workspace/dashboard`
4. `/workspace/sources`
5. `/workspace/playlists/:id/:view`
6. `/workspace/global-favorites`
7. `/workspace/downloads`
8. `/workspace/settings`
9. `/workspace/xtreams/:id/...`
10. `/workspace/stalker/:id/...`
Compatibility redirect:
1. `/settings` -> `/workspace/settings`
Provider route integration:
1. `apps/web/src/app/app.routes.ts` marks the `/workspace` root route with
`data.layout = 'workspace'`.
2. `isWorkspaceLayoutRoute(...)` treats that layout marker as inherited route
state for all descendants.
3. Xtream and Stalker parent routes attach route-scoped session providers that
bootstrap the active playlist, sync provider section state, and clean up
provider-local state when the route is destroyed.
4. Workspace routes no longer rely on nested provider shell components for
hidden local chrome.
## Shell Structure
The shell is intentionally split into four persistent regions:
1. Left rail:
1. Static workspace links for dashboard, sources, global favorites, and recently viewed.
2. Provider-aware context links derived from the active or current playlist.
3. Settings remains a persistent footer shortcut in the rail.
2. Top header:
1. Playlist switcher.
2. Route-aware search input and command palette trigger.
3. Add source action.
4. Optional playlist refresh and route-specific shortcut actions.
5. Downloads shortcut in Electron.
3. Main body:
1. Optional left context panel.
2. Main router outlet content.
4. Optional footer:
1. External playback session bar when a docked session is visible.
## Context Panel Rules
The shell decides which secondary panel to show from the current route:
1. `/workspace/sources`
1. `WorkspaceSourcesFiltersPanelComponent`
2. Xtream category sections (`live`, `vod`, `series`)
1. `WorkspaceContextPanelComponent`
3. Stalker category sections (`itv`, `vod`, `series`)
1. `WorkspaceContextPanelComponent`
4. `/workspace/settings`
1. `WorkspaceSettingsContextPanelComponent`
5. Downloads sections
1. `WorkspaceCollectionContextPanelComponent`
The context panel is part of the shell contract. New workspace-level routes
should explicitly decide whether they need one rather than adding local
sidebars inside feature pages.
## Search And Navigation Rules
Search is shell-owned and route-aware:
1. Disabled on settings routes.
2. Enabled on sources routes.
3. Enabled for supported Xtream and Stalker content/search views.
4. Placeholder text and search handling vary by provider and section.
5. Input changes are debounced before route/store updates are applied.
Rail navigation is also shell-owned:
1. Workspace-global entries are static.
2. Provider entries come from `buildPortalRailLinks(...)`.
3. On dashboard, sources, settings, and global favorites, the shell falls back
to the currently selected playlist so provider navigation remains available
even outside a provider route.
Command palette behavior is shell-owned but view-extensible:
1. The shell resolves commands into three groups in fixed order: current view,
this playlist, then global.
2. Shell-owned commands are derived from route context and current playlist
state; empty groups are omitted instead of rendering disabled placeholders.
3. Workspace features contribute current-view commands through
`WorkspaceViewCommandService`.
4. Header shortcut actions can opt into palette exposure by attaching palette
metadata through `WorkspaceHeaderContextService`.
5. Filtering matches command labels, descriptions, and keywords, and keyboard
selection always lands on the first enabled command.
## Maintenance Guidance
Use this document as the source of truth when changing workspace shell behavior.
1. New top-level user destinations should default to child routes under
`/workspace`.
2. Shared provider navigation logic belongs in portal-shared util/UI libraries,
not duplicated inside the shell.
3. If a provider route changes how playlist/session bootstrap works, update the
route-session provider and shell-facing route contract together.
4. Historical migration notes, cleanup lists, and one-off refactor steps should
stay out of this file; track them in issues or PR notes instead.
+323
View File
@@ -0,0 +1,323 @@
# Xtream Mock Server — Architecture
## Purpose
`apps/xtream-mock-server` is a self-contained Express server that emulates the
Xtream Codes API protocol. It is used for:
- **Local development** — run a full portal without a real Xtream subscription
- **E2E testing** — Playwright spins it up alongside the Angular dev server
---
## Data Pipeline
```
credentials (username + password)
│
▼
credentialsToSeed(u, p) ←── deterministic polynomial hash
│
▼
faker.seed(seed) ←── all faker calls use same seed per credentials
│
▼
generateCategories() ←── live / vod / series categories
│
generateLiveStreams() ←── live TV stream list
scenario EPG fixture? ←── optional deterministic per-stream EPG override
generateVodStreams() ←── VOD movie list
generateSeriesItems() ←── series list
generateSeriesInfo() ←── nested seasons + episodes (pre-populated)
│
▼
PortalData (cached) ←── Map<"username:password", PortalData>
```
Re-requesting with the same credentials returns the exact same data until
`POST /reset` clears all caches.
---
## File Structure
```
apps/xtream-mock-server/
├── project.json ← Nx targets: serve (port 3211), serve-with-watch
├── public/
│ └── marketing/ ← committed fictional release artwork PNGs
├── tsconfig.json
└── src/
├── main.ts ← Express app bootstrap, all routes wired up
└── app/
├── scenarios.ts ← Credential → ScenarioConfig mapping
├── data-store.ts ← Lazy cache, per-credentials generation
├── generators/
│ ├── categories.generator.ts
│ ├── live.generator.ts ← Live streams + EPG listings
│ ├── marketing.generator.ts ← Fictional release screenshot fixture
│ ├── vod.generator.ts ← VOD streams + VodDetails
│ └── series.generator.ts ← Series items + SeriesInfo
├── handlers/
│ ├── get-account-info.handler.ts
│ ├── get-categories.handler.ts ← live/vod/series categories
│ ├── get-full-epg.handler.ts ← full EPG + legacy typo alias
│ ├── get-streams.handler.ts ← live/vod/series stream lists
│ ├── get-vod-info.handler.ts
│ ├── get-series-info.handler.ts
│ └── get-short-epg.handler.ts
└── routes/
└── dispatch.ts ← Action → handler routing
```
---
## API Protocol
### Direct Xtream endpoint
```
GET /player_api.php?action=<action>&username=<u>&password=<p>[&...]
```
Response: raw JSON (no envelope). Matches the real Xtream Codes API format.
### PWA proxy endpoint
IPTVnator's PWA routes Xtream calls through:
```
GET /xtream?url=<serverUrl>&action=<action>&username=<u>&password=<p>
```
Response: `{ payload: <data>, action: <action> }`
This mirrors the backend proxy in `apps/electron-backend` so the same
Angular service code works in both environments.
### Stream stub endpoints
```
GET /live/<username>/<password>/<streamId>.m3u8
GET /movie/<username>/<password>/<streamId>.<ext>
GET /series/<username>/<password>/<streamId>.<ext>
```
All redirect to a publicly available HLS test stream
(`https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8`).
---
## Key Response Shapes
### `get_account_info`
```json
{
"user_info": {
"username": "user1",
"password": "pass1",
"status": "active",
"exp_date": "4102444799",
"is_trial": "0",
"active_cons": "1",
"max_connections": "2",
"allowed_output_formats": ["m3u8", "ts", "rtmp"]
},
"server_info": {
"url": "http://localhost:3211",
"port": "3211",
"timezone": "UTC",
"timestamp_now": 1234567890
}
}
```
### `get_live_categories` / `get_vod_categories` / `get_series_categories`
```json
[
{ "category_id": "101", "category_name": "News", "parent_id": 0 },
...
]
```
### `get_live_streams` (sample item)
```json
{
"num": 1,
"name": "Acme Corp TV",
"stream_type": "live",
"stream_id": 10000,
"stream_icon": "https://picsum.photos/seed/live-10000/100/100",
"epg_channel_id": "channel-10000.mock",
"category_id": "101",
"tv_archive": 0,
"tv_archive_duration": 0
}
```
### `get_short_epg` (sample item)
```json
{
"epg_listings": [
{
"id": "1000000",
"epg_id": "channel-10000.mock",
"title": "base64encodedTitle",
"description": "base64encodedDescription",
"start": "2024-01-01 12:00:00",
"end": "2024-01-01 12:30:00",
"start_timestamp": "1704110400",
"stop_timestamp": "1704112200"
}
]
}
```
Note: `title` and `description` are **base64-encoded**, matching the real Xtream API.
### `get_simple_data_table` / `get_simple_date_table`
Both actions return the same full per-channel schedule shape:
```json
{
"epg_listings": [
{
"id": "10000-current",
"epg_id": "channel-10000.mock",
"title": "base64encodedTitle",
"description": "base64encodedDescription",
"start": "2026-04-05 04:30:00",
"end": "2026-04-05 05:00:00",
"start_timestamp": "1775363400",
"stop_timestamp": "1775365200",
"channel_id": "channel-10000.mock"
}
]
}
```
The legacy `get_simple_date_table` typo alias exists because real Xtream panels
sometimes only respond to that misspelled action.
### `get_series_info` (structure)
```json
{
"seasons": [
{
"id": 3000100, "name": "Season 1", "season_number": 1,
"episode_count": 8, "air_date": "2022-05-14",
"cover": "https://picsum.photos/seed/season-30001-1/300/450"
}
],
"info": { "name": "...", "cover": "...", "plot": "...", "cast": "...", ... },
"episodes": {
"1": [
{
"id": "80001", "episode_num": 1, "title": "Series Name S1E1",
"season": 1, "container_extension": "mkv",
"info": { "duration_secs": 2400, "rating": 8.3, ... }
}
]
}
}
```
---
## Scenarios
| Key (`username:password`) | Seed | Categories | Items/cat | Account status |
| ------------------------- | ---- | ------------------------ | --------- | -------------- |
| `user1:pass1` | 1001 | 8 each | 40 | active |
| `large:large` | 9999 | 20 each | 200 | active |
| `stress:stress` | 7777 | 16 each | 120 | active |
| `series:series` | 2002 | live:3, vod:4, series:15 | 30 | active |
| `minimal:minimal` | 3003 | 2 each | 5 | active |
| `epg:epg` | 6006 | live:2, vod:1, series:1 | 3 | active |
| `emptyvod:emptyvod` | 7007 | 2 each | 5 | active |
| `marketing:marketing` | 8020 | live:4, vod:4, series:4 | curated | active |
| `expired:expired` | 4004 | 4 each | 10 | Expired |
| `inactive:inactive` | 5005 | 4 each | 10 | Disabled |
| `<any other>` | hash | 6 each | 30 | active |
### `epg:epg` fixture details
This scenario is reserved for Xtream EPG tests:
- live category `EPG Focus` contains deterministic channels such as `Timezone News`
- `Timezone News` serves a fixed `get_short_epg` window and a full `get_simple_data_table` schedule
- the full schedule includes a program that spans a UTC midnight boundary and another program after midnight
- raw `start` / `end` strings are intentionally offset from `start_timestamp` / `stop_timestamp`
That deliberate mismatch lets Electron tests verify the renderer uses timestamp
fields for sorting, current-program selection, progress bars, and local clock
labels instead of trusting provider-local strings.
### `marketing:marketing` fixture details
This scenario is reserved for release screenshots and marketing materials:
- VOD and series data use 30 curated fictional titles instead of faker-generated
titles or real media metadata
- posters and backdrops are served from committed PNG files in
`apps/xtream-mock-server/public/marketing/{poster,backdrop}/`
- `tools/release/generate-marketing-artwork.ts` generates the PNGs with
`gpt-image-2` only when `OPENAI_API_KEY` is present; it also writes the
prompt/asset manifest at `apps/xtream-mock-server/public/marketing/manifest.json`
- the manifest assigns distinct genre and visual-medium profiles per title,
including documentary, noir, animated family, retro rescue drama, cyberpunk,
anime-inspired space school, and workplace dramedy styles
- screenshot capture remains deterministic and offline because
`tools/release/capture-v020-screenshots.ts` consumes the local mock server
assets and never calls OpenAI
- the SVG renderer in `marketing.generator.ts` remains the fallback for missing
assets, live logos, season covers, and episode thumbnails
---
## Playwright Integration
### Configuration (`apps/web-e2e/playwright.config.ts`)
The mock server is listed as a third `webServer` entry:
```typescript
{
command: 'pnpm nx run xtream-mock-server:serve',
url: 'http://localhost:3211/health',
reuseExistingServer: !process.env['CI'],
cwd: workspaceRoot,
}
```
### Request Interception
The Angular PWA calls `localhost:3000/xtream?...`. Playwright intercepts these:
```typescript
await page.route('**/localhost:3000/xtream**', async (route) => {
const originalUrl = new URL(route.request().url());
const mockUrl = new URL('http://localhost:3211/xtream');
originalUrl.searchParams.forEach((v, k) => mockUrl.searchParams.set(k, v));
await route.continue({ url: mockUrl.toString() });
});
```
---
## Extension Points
- **Add new actions**: Implement a handler function and add a `case` in `routes/dispatch.ts`
- **Add new scenarios**: Add an entry to `SCENARIOS` in `scenarios.ts`
- **Add deterministic EPG fixtures**: Extend `ScenarioConfig.epgFixture` and populate `epgListingsByStreamId` in `data-store.ts`
- **Refresh release artwork**: Run `pnpm release:artwork:dry-run`, then
`OPENAI_API_KEY=... pnpm release:artwork:generate`, inspect the generated PNGs,
and finish with `pnpm release:artwork:validate`
- **Adjust data volume**: Change `itemsPerCategory`, `seasonsPerSeries`, or `episodesPerSeason` per scenario
- **Custom stream URLs**: Edit the HLS stub redirect in `main.ts`