Commit graph

191 commits

Author SHA1 Message Date
SergeantPanda
14bfd25d9a feat(timeshift): enhance catch-up session handling with optional duration support
- Introduced an optional `duration` parameter for catch-up sessions, allowing clients to specify the programme length in minutes. This value is preferred over EPG-derived durations and includes a buffer for provider lag.
- Updated the API views and serializers to accept and process the new `duration` field.
- Enhanced the catch-up proxy implementation to utilize the client-supplied duration, improving playback accuracy.
- Added tests to validate the new duration handling and ensure proper integration with existing functionality.
2026-07-16 21:26:06 +00:00
Dillard Blom
e5d33861e6 Accept QUERY-style incoming catch-up requests (streaming/timeshift.php)
Clients that build catch-up requests in QUERY layout (e.g. Open-TV /
Fred TV: /streaming/timeshift.php?username=...&stream=...&start=...)
had no matching urlpattern, so the request silently fell through to
the frontend's <path:unused_path> catch-all and got served index.html
(200 OK, wrong content) instead of reaching the proxy — no error, no
log line, the client just fails to play.

The PATH-style layout (timeshift/<user>/<pass>/<stream_id>/<ts>/<dur>)
already worked; QUERY-style autodetection already existed for outgoing
provider requests (helpers.build_timeshift_url_format_a/_b) but was
never mirrored to the incoming route.

Split timeshift_proxy into a shared _timeshift_proxy_impl plus two thin
entry points (PATH-style timeshift_proxy, new QUERY-style
timeshift_proxy_query) so both incoming layouts are recognized.

Reported against the predecessor plugin as dispatcharr_timeshift#10;
reproduced identically against dispatcharr:dev (confirmed via nginx
access log: a QUERY-style request returned 200 with a response body
exactly matching the size of frontend/dist/index.html).
2026-07-13 22:13:42 +02:00
SergeantPanda
d93cb6265f refactor: Eagerly import celery_app to ensure proper configuration in production
Updated the import mechanism for celery_app to avoid issues with lazy-loading, ensuring the default Celery app is correctly configured in production environments. Removed the __getattr__ function for celery_app, simplifying the module structure.
2026-07-08 13:11:17 +00:00
SergeantPanda
8b22f1c63a refactor: Lazy load celery_app in __getattr__ to improve module attribute access and reduce initial import overhead. 2026-07-07 21:33:49 +00:00
SergeantPanda
b26916dc7c refactor: Replace custom test label iteration with centralized test discovery functions for improved maintainability and consistency in test suite management. 2026-07-07 21:30:20 +00:00
SergeantPanda
c6dfce167b test: Add custom test runner for improved test execution in settings_test.py 2026-07-07 18:58:18 +00:00
SergeantPanda
2a09ce49da Enhancement: Update changelog to reflect changes in ChannelPagination, ensuring pagination works correctly with only page_size provided. Refactor tests to improve reliability and consistency, including adjustments to database connection management in various test cases. Modify EPG name normalization tests for accuracy and clarity, and enhance program data serializer tests to utilize precomputed season and episode values. 2026-07-07 18:30:06 +00:00
SergeantPanda
de3a0a0713 refactor(celery): Replace worker_ready signal with worker_process_init for plugin discovery and close inherited DB connections. Use djangos PostgrSQL backend for celery tasks. 2026-07-02 13:33:04 -05:00
SergeantPanda
96a39ce5d2 refactor(tasks): Improve stream processing logic by adding bulk update functionality for unchanged streams. Enhance memory management and error handling in database queries, and update cleanup functions to optimize memory usage. 2026-06-27 11:13:17 -05:00
SergeantPanda
e596a508c7 refactor(models): Simplify comments for catch-up fields in Stream and Channel models, clarifying their population process. Update migration docstring for consistency. Remove outdated comments in ProxyServer and URLs related to timeshift handling. 2026-06-26 12:39:54 -05:00
SergeantPanda
3b93f0a08d Merge branch 'dev' into pr/cedric-marcoux/1242 2026-06-23 21:45:57 -05:00
SergeantPanda
53fa1e42a0 enhancement(tests): introduce isolated backend test settings and improve test documentation
- Added `dispatcharr.settings_test` for isolated testing, automatically creating an empty PostgreSQL test database and ensuring transaction isolation during tests.
- Updated `manage.py` to switch to the test settings when running tests.
- Enhanced the CONTRIBUTING.md file with detailed instructions on running the backend test suite and handling Celery tasks in tests.
- Refactored test cases to use static methods for `worker_id` in `test_process_label.py` and adjusted assertions in `test_user_preferences.py` for better clarity and correctness.
2026-06-23 20:54:12 -05:00
SergeantPanda
46695588f7 fix(m3u): enhance custom properties handling and DB connection management
- Implemented `ensure_custom_properties_dict()` to normalize custom properties across various models and serializers, addressing issues with legacy JSON-encoded strings.
- Updated M3U account and channel group models to ensure custom properties are consistently stored as dictionaries during save operations.
- Enhanced Celery task management by ensuring old DB connections are closed before and after tasks, improving reliability and preventing errors during account refresh operations. (Fixes #1338)
2026-06-18 14:59:09 -05:00
SergeantPanda
a7b4db83fa feat(process_label): enhance uWSGI process role detection
- Added a new function `_is_uwsgi_worker` to accurately identify when the application is running within a uWSGI worker.
- Updated `get_process_role` to label processes as "uwsgi" based on the new function or command-line arguments, improving process role accuracy.
- Expanded unit tests to cover various scenarios for uWSGI role detection, ensuring robust validation of the new logic.
2026-06-16 16:21:22 -05:00
SergeantPanda
5d424adbe8 perf(vod): optimize VOD batch processing and memory management
- Introduced `lookup_by_name_year` function to limit database scans for movies and series without TMDB/IMDB IDs, enhancing performance by scoping lookups to current batch names.
- Updated `process_movie_batch` and `process_series_batch` to utilize the new lookup function, reducing memory usage and improving efficiency.
- Registered `refresh_vod_content` and `batch_refresh_series_episodes` for post-task memory cleanup in Celery, ensuring better resource management during VOD content refreshes.
2026-06-16 14:45:24 -05:00
SergeantPanda
c1ff5e35aa feat(process_label): add process role labeling for PostgreSQL connections
- Introduced a new module to determine the process role based on command-line arguments, enhancing PostgreSQL connection labeling for better monitoring.
- Updated the database connection parameters to include the application name derived from the process role.
- Added unit tests to validate the process role detection logic for different scenarios, including Celery and uWSGI.
2026-06-16 11:26:12 -05:00
SergeantPanda
d06455d3c8 Merge branch 'dev' of https://github.com/Dispatcharr/Dispatcharr into custom-psycopg3-pool 2026-06-15 20:25:27 -05:00
SergeantPanda
34c938b1ce feat(epg): implement staging and batch processing for EPG program updates
- Introduced a temporary staging table for efficient batch processing of EPG program inserts, reducing memory and I/O contention during updates.
- Enhanced the `parse_programs_for_source` function to stream parsed rows into the staging table before swapping them atomically into the main program data.
- Added unit tests to validate the new staging and swapping logic, ensuring existing programs are preserved during failures and that batch processing works as intended.
2026-06-15 19:50:50 -05:00
SergeantPanda
38389a81e6 feat(settings): add DATABASE_POOL_CONN_MAX_LIFETIME for connection management and update database engine path (Fixes #1343)
- Introduced DATABASE_POOL_CONN_MAX_LIFETIME to manage pooled connection lifecycle, improving performance and resource management.
- Updated database engine path to use 'dispatcharr.db.backends.postgresql_psycopg3' for consistency.
- Enhanced logging configuration for geventpool connection lifecycle tracking.
2026-06-12 11:31:09 -05: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
7086f41d64 feat(epg): overhaul EPG auto-matching logic and improve performance
- Moved matching logic to a dedicated module for better organization and testability.
- Made single-channel auto-matching asynchronous, allowing for larger EPG libraries without hitting HTTP timeouts.
- Enhanced memory management and throughput during EPG matching, including optimizations for fuzzy matching and bulk processing.
- Fixed various reliability issues in the auto-matching process, ensuring accurate channel assignments and improved UI feedback.
- Updated API views and frontend components to reflect changes in the matching process and provide real-time notifications.
- Added tests for EPG matching functionality and name normalization.
- Single-channel and selected-channel auto-match always run, even when the channel already has EPG assigned; match-all (no channel IDs) still only processes channels without EPG.
2026-06-08 18:12:29 -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
Cédric Marcoux
4f45249067 fix(timeshift): resolve catch-up channel by Channel.id only + cleanup
- timeshift_proxy(): drop the resolve_channel_by_provider_stream_id
  fallback. The client only ever sends Dispatcharr's internal Channel.id,
  so resolve by id and return 404 on miss. Remove the dead `channel = None`
  sentinel and the now-unused import.
- Delete the now-orphaned resolve_channel_by_provider_stream_id helper and
  its local Stream import from apps/channels/utils.py (zero remaining refs).
- Import django.core.cache.cache at module top-level instead of inside
  _get_cached_format_index / _set_cached_format_index.
- Fix the stale dispatcharr/urls.py comment: the "duration" slot carries
  Channel.id, not the provider stream_id.
- Genericize provider host references in code comments.
2026-06-01 12:51:14 +02:00
SergeantPanda
c081354150 feat(websocket): enhance connection handling with cached IP lookup 2026-05-31 19:28:19 -05:00
Seth Van Niekerk
16cb9edcbd
blur public IP in sidebar, add ip lookup toggle and env var, make lookup non-blocking 2026-05-30 13:07:07 -04:00
SergeantPanda
a2656184e8 perf/fix: migrate DB driver to psycopg3, fix pool settings
- Switch engine to postgresql_psycopg3 (PR had wrong engine name,
  and we're migrating from psycopg2 to psycopg3 as part of this work)
- Set CONN_MAX_AGE=0 (required by geventpool; PR had None)
- Reduce MAX_CONNS 20→8, REUSE_CONNS 10→3 to avoid exhausting
  pg max_connections across 4 uWSGI workers + Celery
- Add pool=False to explicitly disable Django's native psycopg3 pool
2026-05-28 19:31:50 -05:00
SergeantPanda
80b72d8cfa Enhancement: Update psycopg2 to 3. 2026-05-28 19:27:52 -05: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
Jonathan Caicedo
94c8bd36bf perf: replace per-request DB connections with geventpool 2026-05-25 11:12:46 -04:00
SergeantPanda
108bd52e7f perf: replace local cache with django-redis for improved EPG caching
Some checks failed
Base Image Build / prepare (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
Base Image Build / docker (amd64, ubuntu-24.04) (push) Has been cancelled
Base Image Build / docker (arm64, ubuntu-24.04-arm) (push) Has been cancelled
Base Image Build / create-manifest (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
2026-05-17 20:23:57 -05:00
SergeantPanda
bdfad0f314 fix: clarify comments in gevent_patch.py regarding blocking behavior in send_websocket_update 2026-05-16 10:59:09 -05:00
SergeantPanda
c33d456743 Enable gevent in uWSGI workers; fix WS delivery and DB exhaustion
- Enable gevent cooperative multitasking in all uWSGI worker configs
  (gevent-early-monkey-patch + import dispatcharr.gevent_patch)
- Rewrite WebSocket group sends to bypass asyncio in gevent workers:
  _gevent_ws_send() replicates the channels_redis 4.x wire format
  directly via synchronous Redis so send_websocket_update() and
  _send_async() no longer fail silently after epoll is patched out
- Fix PostgreSQL connection exhaustion: CONN_MAX_AGE=0 + explicit
  close_old_connections() in stream manager and cleanup watchdog loops
- Fix stream proxy race: register client before the connect-wait loop
  so the cleanup watchdog never sees zero clients on a live channel
- Channel list/logo/profile queryset optimisations: conditional DISTINCT,
  EXISTS semi-joins for filter-options, channel_count annotation to
  eliminate N+1 in LogoSerializer, prefetched memberships in
  ChannelProfileSerializer
- JsonResponse for channel ID list and summary endpoints
2026-05-14 18:55:09 -05:00
SergeantPanda
e61539fc80 fix: Update plugin discovery comments and improve weakref handling in tests. Update changelog. 2026-05-13 17:02:34 -05:00
R3XCHRIS
f38d3a4f17 fix: register plugin @shared_tasks on worker startup (#1244)
Plugins live in /data/plugins/<slug>/plugin.py, outside INSTALLED_APPS,
so celery's autodiscover_tasks() never imports them. Any plugin using
module-level @shared_task for cron-scheduled work therefore has its
task unregistered with the worker after every worker restart, until
something else (a connect/utils.trigger_event call, etc.) lazily
imports the plugin module via PluginManager.discover_plugins.

In the meantime, beat fires the periodic task on time and the worker
rejects it:

  ERROR celery.worker.consumer.consumer Received unregistered task of
  type 'telegram_alerts.send_daily_report'.

PeriodicTask.last_run_at advances anyway, so the failure is silent at
the default INFO log level.

Fix: hook celery's worker_ready signal in dispatcharr/celery.py to
call PluginManager.discover_plugins(sync_db=False) on every worker
boot. Importing the plugin modules runs their @shared_task decorators,
registering the tasks before beat starts firing.

Exception handling is intentionally broad: if one plugin's plugin.py
has an import error, the worker must still come up — discovery failure
should not be a fatal error for the whole worker process.

Tests in tests/test_celery_plugin_discovery.py verify:
  - the handler calls discover_plugins(sync_db=False)
  - the handler swallows PluginManager.get() exceptions
  - the handler swallows discover_plugins() exceptions
  - the handler is actually connected to the worker_ready signal
Confirmed the test fails against current dev with the exact
'cannot import name discover_plugins_on_worker_ready' that motivates
this change, and passes with the fix.
2026-05-13 17:00:31 +01:00
SergeantPanda
84fbbfa3c4 refactor: Clean up get_client_ip() function in utils.py
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
2026-05-09 09:48:53 -05:00
SergeantPanda
dc649ffd88 Enhancement: Initial fmp4 support and major ts_proxy refactor 2026-05-08 17:46:47 -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
a01814069a
code review & pivot 2026-05-01 09:10:37 -04:00
SergeantPanda
1e5298a8d3 Bug Fix: Implement Redis locks in run_recording and worker_ready to prevent duplicate ffmpeg processes and ensure single execution across workers 2026-04-30 10:15:03 -05:00
Seth Van Niekerk
8894d51877
restrict XC access per user by configurable IP allowlist 2026-04-28 16:35:32 -04:00
SergeantPanda
c956672587 Enhancement: Route long-running DVR recordings to a dedicated queue. 2026-04-26 09:34:20 -05:00
SergeantPanda
e861fca092 Enhancement: Enhanced Swagger UI authorization dialog: registered a custom OpenApiAuthenticationExtension for ApiKeyAuthentication so drf-spectacular now generates an ApiKeyAuth (apiKey) entry alongside jwtAuth. Both entries include descriptive text linking to the relevant endpoints (/api/accounts/token/, /api/accounts/api-keys/generate/, /api/accounts/api-keys/revoke/). 2026-04-10 18:29:13 -05:00
SergeantPanda
66ee67da30 security: Change from default of "Authenticated" to "IsAdmin" 2026-04-10 10:46:16 -05:00
SergeantPanda
04a684b359 security: Removed CORS_ALLOW_CREDENTIALS = True from CORS configuration. Dispatcharr authenticates via JWT Authorization headers and API keys — not cookies — so credentials are never sent cross-origin by browsers. The setting was also redundant: browsers reject Access-Control-Allow-Credentials: true when Access-Control-Allow-Origin is a wildcard (*), so it had no effect in practice. 2026-04-10 08:34:13 -05:00
SergeantPanda
b535f28ac5 security: Added rate limiting to the login endpoint (POST /api/accounts/token/) using DRF's built-in throttling. A LoginRateThrottle (3 requests/minute per IP, sliding window) is applied to the TokenObtainPairView. Repeated failed attempts from the same IP receive 429 Too Many Requests. 2026-04-09 21:46:50 -05:00
SergeantPanda
47427d4b0f security:
- Set `DEFAULT_PERMISSION_CLASSES` to `Authenticated` in the DRF configuration.
- Explicitly marked the HDHomeRun discovery endpoints (`DiscoverAPIView`, `LineupAPIView`, `LineupStatusAPIView`, `HDHRDeviceXMLAPIView`) and the version endpoint with `permission_classes = [AllowAny]` to document their intentionally public access now that the global default is `Authenticated`.
2026-04-09 21:36:51 -05:00
SergeantPanda
086cc74959 Bug Fix: M3U profile URL rewriting now uses the regex module instead of re across all URL transform code paths (url_utils.transform_url, core/views.py, vod_proxy/_transform_url, tasks.get_transformed_credentials, and the WebSocket live-preview handler in consumers.py). The regex module natively accepts JavaScript/PCRE-style named capture groups ((?<name>...)) without any conversion, eliminating the root cause of patterns that matched in the frontend live preview but failed on the backend with a re.error. As a further improvement, regex also supports variable-length lookbehind assertions (e.g. (?<=a+)), which re rejects with an error; patterns using these will now work correctly on the backend as well. Replace-pattern JS tokens are still normalised before calling regex.sub: $<name>\g<name> and $1/$2/… → \1/\2/… (Python replacement syntax). Also fixed a bug in the WebSocket preview handler where a pattern error was incorrectly returning the search pattern string as the preview output instead of the original URL. (Fixes #1005)
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-03-29 17:55:08 -05:00
dekzter
90a600b48f merged in dev 2026-03-26 12:17:43 -04:00
dekzter
a19be96ced fleshed out user limits and termination logic 2026-03-25 17:33:26 -04:00
None
b30a24e2fb feat: add TLS connection support for Redis and PostgreSQL (#950)
- Add 10 env vars for Redis/PostgreSQL TLS (REDIS_SSL, REDIS_SSL_VERIFY, REDIS_SSL_CA_CERT, REDIS_SSL_CERT, REDIS_SSL_KEY, POSTGRES_SSL, POSTGRES_SSL_MODE, POSTGRES_SSL_CA_CERT, POSTGRES_SSL_CERT, POSTGRES_SSL_KEY)
- Propagate SSL params to all Redis connection points: RedisClient, stream view, PubSub, client manager, Celery broker/result backend, Django Channels, and pre-Django startup scripts
- Add Celery SSL config via URL query string params (required by Kombu's internal URL parsing)
- Add PostgreSQL sslmode and certificate options to DATABASES config
- Add startup validation: cert file existence, URL scheme conflict detection, TLS status logging
- Add TLS error hints to Redis connection failure messages
- Add Connection Security panel in System Settings (modular mode only) showing encryption, verification, and mTLS status
- Add PG client key permission fix in web and celery entrypoints for Docker Desktop compatibility (0777 to 0600)
- Add TLS env var passthrough in entrypoint for su - login shells
- Document TLS env vars in modular docker-compose.yml
- Change env_mode from dev/prod to actual DISPATCHARR_ENV value for modular mode detection
2026-03-21 17:24:09 -05:00