Commit graph

193 commits

Author SHA1 Message Date
SergeantPanda
3c2c42ce66 fix(epg): prevent crashes for channels with null channel numbers in XMLTV export
Some checks failed
Backend Tests / Plan test groups (push) Has been cancelled
CI Pipeline / prepare (push) Has been cancelled
Build and Push Multi-Arch Docker Image / build-and-push (push) Has been cancelled
Backend Tests / (push) Has been cancelled
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Has been cancelled
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Has been cancelled
CI Pipeline / create-manifest (push) Has been cancelled
Updated the EPG generation logic to ensure that channels without a channel number do not cause crashes in the XMLTV export. Implemented a deferred assignment mechanism for channels with null numbers, allowing them to receive valid integers during processing. Added tests to verify that the XMLTV output remains stable and valid even when channels are unnumbered.
2026-07-10 02:42:50 +00:00
SergeantPanda
9ad198beb3 fix(live-streams): prevent crashes for channels with null channel numbers
Updated the handling of channels in the live streams setup to ensure that channels without a channel number do not cause crashes. Implemented logic to assign a valid number to these channels during processing. Added tests to verify that the system correctly assigns numbers to channels with null values, ensuring stability in the live streams feature.
2026-07-09 20:02:57 +00:00
SergeantPanda
27deef9ad6 feat(epg): Improve performance during cold rebuilds by yielding to gevent hub
Enhanced the `/output/epg` cold rebuild process to prevent freezing of the gevent uWSGI worker. The `_stream_build` function now yields control to the gevent hub after processing each cached chunk, allowing other requests to be handled concurrently. This change improves responsiveness during CPU-bound XMLTV generation. Additionally, introduced a new utility function, `_cooperative_yield`, to facilitate yielding in CPU-bound loops.
2026-07-09 15:32:51 +00:00
SergeantPanda
af71dc929f tests: Move tests to under tests folder. 2026-07-07 18:51:35 +00:00
SergeantPanda
fa39a594be feat(epg): Enhance generate_epg function to support xc_catchup_prev_days parameter for improved catch-up day resolution. Update related views and tests to ensure consistent behavior across EPG generation and catch-up functionality. 2026-06-26 12:53:02 -05:00
SergeantPanda
293745d568 Merge branch 'dev' of https://github.com/Dispatcharr/Dispatcharr into pr/cedric-marcoux/1242 2026-06-25 21:38:35 -05:00
SergeantPanda
78d1f70eda documentation: Add comment to disable parallel gather for DISTINCT ON query to prevent OOM issues in large VOD libraries. 2026-06-25 11:06:35 -05:00
SergeantPanda
6b4453e9ca fix: Readd prev_days logic after dev merge. 2026-06-23 21:51:24 -05:00
SergeantPanda
3b93f0a08d Merge branch 'dev' into pr/cedric-marcoux/1242 2026-06-23 21:45:57 -05:00
SergeantPanda
7b6adf62d7 enhancement(vod): optimize VOD stream retrieval and performance
- Improved `xc_get_vod_streams` and `xc_get_series` functions to utilize a new helper method for fetching distinct relations based on account priority, significantly reducing memory usage and response times for large libraries.
- Updated the handling of VOD streams to avoid unnecessary ORM instantiation, enhancing performance for endpoints dealing with extensive movie and series data.
- Added comprehensive tests to ensure the correctness of the new logic and verify that the highest priority relations are correctly selected.
2026-06-23 20:15:29 -05:00
SergeantPanda
e984b234e3 enhancement(epg): add export lookback and cutoff parameters to EPG generation
- Updated the `generate_dummy_programs` function to include `export_lookback` and `export_cutoff` parameters, allowing for more precise control over the EPG data generation window.
- Added a new test case to verify that future events are correctly represented in the grid window, ensuring upcoming fillers are displayed as expected.
2026-06-23 15:27:15 -05:00
SergeantPanda
0dc8898e8b refactor(epg): separate programme index into dedicated table for optimized data handling
- Moved the `programme_index` from the `EPGSource` model to a new `EPGSourceIndex` table, ensuring that the large JSON blob is only loaded when explicitly accessed, thus improving query performance and memory efficiency.
- Updated related queries and API views to utilize the new structure, including adjustments to EPG generation and import logic to prevent unnecessary data loading.
- Enhanced memory management in the EPG grid endpoint to reduce worker RSS during response handling.
2026-06-23 15:10:27 -05:00
SergeantPanda
107a891359 enhancement(epg): optimize XMLTV escaping and channel prefetch for improved performance 2026-06-23 13:20:17 -05:00
SergeantPanda
bccee9ebc1 refactor(epg): extract EPG generation logic into dedicated module
- Moved all XMLTV output logic from `apps/output/views.py` to `apps/output/epg.py`, streamlining the codebase and maintaining the existing HTTP endpoint functionality.
- Updated related tests and references to ensure proper integration with the new module structure.
2026-06-23 11:50:52 -05:00
SergeantPanda
3868f02c45 enhancement(epg): optimize EPG export performance and database interactions
- Streamlined `generate_epg()` to incrementally stream EPG data without loading the entire guide, improving memory efficiency.
- Reduced database load by deferring the fetching of large `programme_index` blobs, enhancing response times for EPG generation.
- Introduced a composite index on `(epg_id, id)` in `ProgramData` to optimize query performance during EPG exports.
- Updated tests to ensure proper functionality and performance of new features.
2026-06-23 10:57:06 -05:00
SergeantPanda
7139c88c35 enhancement(epg): improve custom dummy EPG generation performance
Some checks failed
CI Pipeline / prepare (push) Has been cancelled
Build and Push Multi-Arch Docker Image / build-and-push (push) Has been cancelled
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Has been cancelled
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Has been cancelled
CI Pipeline / create-manifest (push) Has been cancelled
- Optimized `generate_epg()` to reduce database queries by prefetching ordered channel streams and implementing a new method for custom dummy epg name matching.
- Enhanced handling of dummy EPG sources to minimize SQL round-trips, improving performance for large guides with numerous custom-dummy channels.
2026-06-18 17:12:43 -05:00
Cédric Marcoux
1703d6a703 feat(timeshift): address review — network gate, catch-up failover, live_proxy revert, setting moved to proxy settings
Implements all four points from the latest review, plus hardening from a
pre-submission audit pass.

1. Access control: timeshift_proxy now enforces
   network_access_allowed(request, "STREAMS", user) — same key and placement
   as the live XC stream endpoint.

2. Catch-up failover: the proxy walks the channel's catch-up streams in
   channelstream order (get_channel_catchup_streams), mirroring live
   playback. Each attempt carries its own provider context: account
   credentials, provider stream id, reported server_info timezone (the
   UTC->provider conversion is recomputed per attempt), user-agent, and the
   per-account URL-format cache. The first streamable response wins; if all
   providers fail the last failure is returned.
   Ban-safety is per account: a decisive auth/ban-class failure (401/403/406)
   marks the account and skips its remaining streams (e.g. FHD/HD variants of
   the same channel) instead of hammering a banning provider, while other
   accounts — different hosts — are still tried. Streams from disabled M3U
   accounts are excluded, same as live dispatch. Redirects stay enabled on
   purpose (XC providers legitimately 302 to load-balanced streaming nodes);
   the 3xx decisive branch is kept as defense-in-depth and documented as such.

3. apps/proxy/live_proxy/views.py restored byte-identical to upstream — the
   leftover channel-id wrapper from the removed provider-stream-id fallback
   is gone (zero-line diff).

4. Single remaining setting relocated: xmltv_prev_days_override now lives in
   proxy_settings (backend default in get_proxy_settings, consumed by the
   XMLTV prev_days resolution). The timeshift_settings group,
   TIMESHIFT_DEFAULTS, get_timeshift_settings, the Settings → Timeshift form
   and tab are all removed; the field appears under Settings → Proxy Settings
   (0 = auto-detect, capped at 30).

Audit hardening in the same pass:
- Updated the proxy-settings defaults unit test for the new key (would have
  failed CI otherwise).
- Migration backfills use schema_editor.connection instead of the global
  connection (multi-database correctness).
- CHANGELOG and module docstring brought in line with the final architecture
  (PATH-first cascade, failover, setting under Proxy Settings).
- Tests grown to 69 backend tests: failover success/exhaustion/skip
  semantics, decisive-account skip vs soft-failure retry, per-stream
  timezone conversion (different zones per provider), 406/connection-error
  cascade paths, stream-limit and no-eligible-stream outcomes,
  network-gate 403, server_info strict-UTC guarantee, EPG duration window
  resolution, and DB-backed coverage of xc_password auth, user_level access
  and the failover stream ordering (catch-up-only, active accounts,
  channelstream order). The format-cache test now runs on an isolated
  locmem cache.
2026-06-11 20:08:16 +02:00
Cédric Marcoux
b6bbd39469 fix(timeshift): PATH-first catch-up + strict-UTC API surface with proxy-time provider timezone conversion
Two coupled fixes that make catch-up play the requested programme:

1. Try the PATH catch-up form (/timeshift/.../{start}/{id}.ts) BEFORE the
   timeshift.php query form. Empirical testing showed some XC providers
   return the LIVE stream on the query form (HTTP 200, silently ignoring
   `start`) — a valid MPEG-TS indistinguishable from a real archive, so the
   cascade accepted it and the user always got live content. The PATH form
   actually seeks. Candidate ordering now lives in
   build_timeshift_candidate_urls() with the full rationale.

2. Strict-UTC XC API surface + single proxy-time timezone conversion:
   - xc_get_epg start/end always UTC, server_info.timezone always "UTC",
     time_now UTC — the timezone triple is consistently UTC.
   - Removed the global default_timezone setting and the
     _convert_xmltv_to_local_timezone rewrite entirely.
   - The proxy converts the client's UTC timestamp to the SERVING provider's
     own zone (server_info.timezone captured on account refresh, read from
     the account's default profile) right before building the upstream URL —
     DST-correct via ZoneInfo, no-op for UTC/unknown zones. Verified against
     a real provider: it interprets the URL timestamp as its LOCAL wall
     clock, so pure UTC pass-through seeks 1-2h off.
   - EPG duration lookup keeps the ORIGINAL UTC timestamp (programmes are
     stored in UTC) — exactly one conversion in the whole chain.

Also per review feedback:
- Removed the debug_logging toggle — verbose timeshift logging now follows
  the standard logger DEBUG level (DISPATCHARR_LOG_LEVEL).
- Removed the dead default_language setting (never read anywhere; the EPG
  lang field is hardcoded). TIMESHIFT_DEFAULTS is down to
  xmltv_prev_days_override, and the Settings UI shows that single field
  with accurate help text.
- Validate the timestamp up front (400 on malformed input) instead of
  forwarding it verbatim into the upstream URL.
- Redact the upstream URL in the connection-error log (requests exceptions
  embed the full URL, which carries XC credentials).
- URL-encode XC credentials in both URL builders.
- Request identity encoding upstream (the TS-sync peek reads raw bytes).
- Poll the stop key on the 5-second heartbeat cadence instead of every 100
  chunks (~25 MB), so stream-limit terminations free the provider slot fast.
- New tests: proxy timestamp wiring (converted value reaches the URL
  builder, original UTC value reaches the duration lookup), _redact_url,
  decisive 3xx break (anti ban), invalid timestamp rejection; deflaked the
  format-cache promotion test (django cache persists across runs).
2026-06-10 22:04:44 +02:00
Cédric Marcoux
19acdcc29d Merge remote-tracking branch 'upstream/dev' into feat/timeshift-native-v2
# Conflicts:
#	apps/m3u/tasks.py
2026-06-10 08:42:33 +02:00
SergeantPanda
f0c69fd286 refactor(epg): optimize logo URL generation for EPG channels
- Precompute base URL and logo path components once per request to reduce redundant calls to `build_absolute_uri_with_port()`, enhancing performance.
- Update logo URL construction for both cached and direct logos to utilize the precomputed values, ensuring consistency and efficiency in URL handling.
2026-06-07 14:45:59 -05:00
SergeantPanda
86f39cb7f1 refactor(m3u): optimize URL generation for M3U streams and logos
- Precompute base URLs for M3U stream and logo paths to reduce redundant calls to `build_absolute_uri_with_port()`, improving performance.
- Update the generation of EPG and stream URLs to utilize the precomputed base URL, ensuring consistency and efficiency in URL handling.
- Enhance the handling of logo URLs by consolidating logic for cached and direct logo retrieval, streamlining the process and reducing overhead.
2026-06-07 14:38:44 -05:00
SergeantPanda
8f060e8b3a feat: Output SD program poster images during xml output and enhance caching logic 2026-06-04 15:17:58 -05:00
Cédric Marcoux
341c133c74 Merge remote-tracking branch 'upstream/dev' into rewrite-feature
# Conflicts:
#	apps/output/views.py
#	frontend/src/utils/pages/SettingsUtils.js
2026-06-01 13:43:56 +02:00
SergeantPanda
ddd1105d5b security: Remove post body from response. 2026-05-31 16:20:55 -05:00
SergeantPanda
ae16e1202c feat(views): import build_absolute_uri_with_port in views.py 2026-05-30 17:58:01 -05:00
SergeantPanda
20f54b2bf6 feat(utils): move get_host_and_port and build_absolute_uri_with_port to core/utils.py 2026-05-30 17:26:58 -05:00
SergeantPanda
effa03b2a5 Enhancementvod): optimize xc_get_series for performance and reduce API response time 2026-05-30 09:08:54 -05:00
SergeantPanda
157c87ce4d feat(vod): optimize xc_get_vod_streams for performance and reduce API response time 2026-05-29 22:12:55 -05:00
SergeantPanda
e871010366 feat(vod): enhance xc_get_vod_streams with additional movie details and updated trailer field 2026-05-29 20:55:29 -05:00
Cédric Marcoux
3b8717c4ce fix: timeshift stream management, channel resolution, and streaming throughput
- Channel resolution: resolve by Channel.id first (what the XC API emits
  to clients), fall back to provider stream_id for backward compatibility.
  Fixes 404 on all timeshift requests from XC clients.

- Stream management: timeshift is now a first-class citizen alongside live
  and VOD in the stream-limits system.  get_user_active_connections()
  detects type='timeshift', attempt_stream_termination() sets a Redis
  stop key (same pattern as VOD), and the timeshift view calls
  check_user_stream_limits() before connecting upstream.  The stream
  generator checks the stop key every 100 chunks.  Fixes infinite retry
  loops on max_connections=1 providers for live→timeshift and
  timeshift→timeshift transitions.

- Streaming: replaced HTTPStreamReader thread+pipe with direct
  iter_content+yield (same pattern as VOD proxy).  The pipe approach
  deadlocked under gevent because the reader thread's select() competed
  with the greenlet's pipe read for hub scheduling.  Throughput went
  from ~74 B/s to 13+ MB/s.

- TS preamble: peek now strips pre-sync bytes (PHP warnings, BOM) before
  prepending to the stream, preventing corrupt TS output.

- Credential safety: _redact_url() now truncates to scheme://host/...
  to avoid leaking XC path-based credentials in logs.

- Tests: updated 5 tests that referenced the removed HTTPStreamReader.
  21/21 timeshift tests pass.

- Migration: fixed SyntaxWarning for unescaped regex in 0038.
2026-05-27 23:32:57 +02:00
Cédric Marcoux
2781b21a89 feat: built-in XC catch-up (timeshift) support
Adds native catch-up/timeshift replay for Xtream Codes providers through
the same HTTPStreamReader transport pipeline as live TV.

Timeshift proxy (apps/timeshift/):
- URL cascade: 3 candidate timestamp formats per provider, per-account
  format cache for fast-forward seek performance
- MPEG-TS preamble stripping (shared with HTTPStreamReader)
- Stats integration: timeshift viewers appear on /stats with TIMESHIFT badge
- Auth via hmac.compare_digest on XC password

Catchup detection — denormalized for zero-cost output queries:
- Stream.is_catchup + Stream.catchup_days populated at XC import time
- Channel.has_catchup + Channel.catchup_days + Channel.catchup_provider_stream_id
  rolled up via ChannelStream post_save signal (UI path) and explicit SQL
  after bulk_create (import path)
- _xc_channel_entry() reads denormalized fields instead of per-channel
  custom_properties JSON introspection (eliminates N+1 queries)
- Migration 0038 backfills existing data via raw SQL

XC API enhancements:
- server_info.timezone + start/end + time_now use configured timezone
  (triple consistency rule — fixes wrong-programme-plays bug)
- Dynamic has_archive flag + auto prev_days for catch-up channels
- XMLTV timestamps rewritten to local timezone for catch-up clients

HTTPStreamReader extended (apps/proxy/live_proxy/input/http_streamer.py):
- 1 MB pipe buffer via fcntl F_SETPIPE_SZ (eliminates producer/consumer
  ping-pong that halved throughput)
- Pre-opened response= for URL cascade workflows
- strip_ts_preamble= for XC servers emitting PHP warnings before TS
- find_ts_sync() as shared utility
- Builds on upstream O_NONBLOCK + select() write loop

Provider stream_id lookup order:
- stream_xc() and xc_get_epg() try internal Channel.id first, fall back
  to provider stream_id only when needed (avoids unconditional query on
  every request)

Also includes:
- VOD provider cascade in stream_vod() — iterates all M3U relations by
  priority when first provider is at capacity
- Defensive null-safety: custom_sid: None → "" in get_live_streams,
  get_vod_streams, get_vod_info, get_series_info (fixes iPlayTV crash on
  JSON null for string fields)
- Timeshift settings UI (timezone selector, debug toggle)
- StreamConnectionCard violet TIMESHIFT badge
- Orphan cleanup skips timeshift_* virtual channels
2026-05-27 13:13:20 +02:00
SergeantPanda
59587cbe66 Fix XC stream URL format output handling and improve M3U playlist generation performance. Removed unused imports in apps\output 2026-05-22 11:51:16 -05:00
SergeantPanda
d09674cd95 fix: update xc_stream_live_streams to yield opening bracket at start. 2026-05-16 11:08:41 -05:00
SergeantPanda
98f201e803 perf: Refactor get_live_stream into a streaming endpoint as well as reduce number of passes needed. (Fixes #1220) 2026-05-14 13:14:38 -05:00
SergeantPanda
dc649ffd88 Enhancement: Initial fmp4 support and major ts_proxy refactor 2026-05-08 17:46:47 -05:00
SergeantPanda
90fadc9bf4 Merge branch 'dev' of https://github.com/Dispatcharr/Dispatcharr into pr/CodeBormen/1215 2026-05-04 18:27:20 -05:00
SergeantPanda
883390308b
Merge pull request #1214 from sv-dispatcharr/feat/restrict-xc-user-access
restrict XC access per user by IP & CIDR allowlist
2026-05-03 15:41:37 -05:00
Seth Van Niekerk
0d3eed81ba
Code review changes 2026-05-02 16:59:50 -04:00
None
b2b108bfe5 rename Channel.user_hidden to Channel.hidden_from_output
The previous name suggested "hidden from a specific user account" rather than "hidden from downstream client output", which was the actual
behavior. The new name is unambiguous and matches the help_text language ("Exclude this channel from downstream client output").

Mechanical rename across the migration, model, serializer, signals, sync logic, output endpoints, frontend forms / tables / utils, tests, and CHANGELOG. 77 occurrences across 20 files.

No behavior change.
2026-05-01 19:44:16 -05:00
None
6fed444e43 feat: Auto-sync overhaul (FR #1196)
Per-field channel overrides for auto-synced channels, hide-from-output flag, range-bounded auto-numbering with re-pack, multi-stream channel safety, multi-provider shared-range merging, and an across-the-board move from per-row sync writes to bulk operations.

Migrations:

apps/channels:

0036_channeloverride_and_user_hidden,
0037_backfill_auto_created_by_null,
0038_channelgroupm3uaccount_auto_sync_channel_end,
0039_channel_channel_number_nullable

apps/m3u:
0020_m3uaccount_auto_cleanup_unused_channels

See CHANGELOG.md for the full commit log
2026-05-01 14:05:06 -05:00
Seth Van Niekerk
a01814069a
code review & pivot 2026-05-01 09:10:37 -04:00
SergeantPanda
37922a44ab Enhancement: Update user connection reporting in xc_get_info to reflect active connections and max connections based on user stream limits. (Fixes #990)
Some checks are pending
CI Pipeline / prepare (push) Waiting to run
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Blocked by required conditions
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
CI Pipeline / create-manifest (push) Blocked by required conditions
Build and Push Multi-Arch Docker Image / build-and-push (push) Waiting to run
Frontend Tests / test (push) Waiting to run
2026-04-30 20:33:30 -05:00
Seth Van Niekerk
8894d51877
restrict XC access per user by configurable IP allowlist 2026-04-28 16:35:32 -04:00
SergeantPanda
54ab3e8981 performance:
- Performance: `xc_get_epg` now uses `select_related('epg_data__epg_source')` on all three channel fetch paths. Previously each request triggered 2 additional queries to resolve `channel.epg_data` and `channel.epg_data.epg_source`.
- Performance: `generate_m3u` now uses `prefetch_related` for streams when `?direct=true` is requested, eliminating N+1 stream queries (one per channel) on that code path.
- Performance: `EPGGridAPIView` (`apps/epg/api_views.py`) now uses `select_related('epg_data__epg_source')` on the `channels_with_custom_dummy` queryset, eliminating 2 extra queries per channel (for `epg_data` and `epg_source`) in the dummy EPG generation loop.
2026-04-16 13:19:19 -05:00
SergeantPanda
16984bc386 performance:
Some checks are pending
CI Pipeline / prepare (push) Waiting to run
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Blocked by required conditions
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
CI Pipeline / create-manifest (push) Blocked by required conditions
Build and Push Multi-Arch Docker Image / build-and-push (push) Waiting to run
- `generate_epg` now uses `select_related('epg_data__epg_source')` on all EPG channel querysets
- `generate_epg` now issues a single cross-channel `ProgramData` bulk query. `.values()` returns plain dicts
- `xc_get_live_streams` no longer calls `ChannelGroup.objects.get_or_create(name="Default Group")` once per null-group channel
2026-04-16 11:12:53 -05:00
SergeantPanda
04ce2dacd1
Merge pull request #1165 from xBOBxSAGETx:perf/select-related-channel-queries
Some checks failed
CI Pipeline / prepare (push) Has been cancelled
Build and Push Multi-Arch Docker Image / build-and-push (push) Has been cancelled
Frontend Tests / test (push) Has been cancelled
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Has been cancelled
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Has been cancelled
CI Pipeline / create-manifest (push) Has been cancelled
Add select_related to Channel queries in output views
2026-04-14 17:50:10 -05:00
SergeantPanda
f8407610c8 Bug Fix/Enhancement: Improve logic for get xc epg endpoint for short epgs. Also support epg_days from xc user for xc epg endpoint.
Some checks failed
CI Pipeline / prepare (push) Waiting to run
CI Pipeline / docker (amd64, ubuntu-24.04) (push) Blocked by required conditions
CI Pipeline / docker (arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
CI Pipeline / create-manifest (push) Blocked by required conditions
Build and Push Multi-Arch Docker Image / build-and-push (push) Waiting to run
Frontend Tests / test (push) Has been cancelled
2026-04-12 18:51:40 -05:00
SergeantPanda
9f3d4ff7ff Enhancement: Improved the EPG response cache key 2026-04-12 18:19:19 -05:00
SergeantPanda
ba967f47d9 Enhancement: **EPG historical data window**: the EPG XML output and XC EPG API now support a prev_days URL parameter (e.g. &prev_days=3) to include past programs in the EPG response. This allows third-party players that request historical program schedules to receive the data they need. The EPG URL builder in the Channels page exposes "Days forward" and "Days back" controls. Per-user defaults for both values (epg_days / epg_prev_days) can be configured in the User settings modal and are applied automatically when no URL parameter is present. (Closes #1154) 2026-04-12 16:34:15 -05:00
xbobxsagetx
0d77884758 Add select_related to Channel queries in output views 2026-04-01 15:14:15 -07:00