From a3e8bad6af435097b8b0381e6a7b7c06a1204d2b Mon Sep 17 00:00:00 2001 From: Yoav Date: Tue, 3 Nov 2026 00:09:03 -0500 Subject: [PATCH 1/3] Add AIOStreams, TorBox and dual-debrid stream diversity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stream selection now resolves through AIOStreams or the direct providers, and users can keep RealDebrid and TorBox keys at once so both resolvers feed the same list: providers are merged, deduplicated by info hash and file index, and the preferred service's streams are ordered first. Playback also gains selectable quality rungs with HDR tone mapping and hardware encoder auto-detection, so slow links and HDR sources transcode predictably. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- .env.example | 33 +++- README.md | 60 ++++++- app/controllers/admin/settings_controller.rb | 29 ++++ app/controllers/application_controller.rb | 15 ++ app/controllers/hls_controller.rb | 3 +- app/controllers/settings_controller.rb | 52 ++++-- app/controllers/streaming_controller.rb | 12 +- app/controllers/transcode_controller.rb | 6 +- .../controllers/video_player_controller.js | 106 +++++++++++- app/javascript/player/hls_session_client.js | 1 + app/javascript/player/playback_paths.js | 13 +- app/models/app_setting.rb | 15 ++ app/models/resolved_source.rb | 46 +++-- app/models/user.rb | 88 +++++++++- app/services/available_streams_service.rb | 38 +++- app/services/comet_service.rb | 12 +- app/services/hls_session_manager.rb | 5 +- app/services/media/transcoder.rb | 160 +++++++++++++++-- app/services/playback_start_service.rb | 2 +- app/services/stream_provider.rb | 96 +++++++++-- app/services/streams/aio_streams_provider.rb | 138 +++++++++++++++ app/services/streams/resolver.rb | 42 ++++- app/services/streams/torrentio_provider.rb | 11 +- app/services/tor_box_service.rb | 44 +++++ app/views/admin/settings/show.html.erb | 54 ++++++ app/views/content/show.html.erb | 4 +- app/views/home/index.html.erb | 4 +- app/views/layouts/application.html.erb | 9 + app/views/settings/show.html.erb | 59 ++++++- app/views/streaming/show.html.erb | 15 ++ config/routes.rb | 5 + ...0000_add_debrid_account_fields_to_users.rb | 9 + .../20261030120100_create_app_settings.rb | 12 ++ db/schema.rb | 138 ++++++++------- spec/factories/users.rb | 12 ++ spec/models/resolved_source_spec.rb | 55 ++++++ spec/models/user_spec.rb | 79 ++++++++- spec/requests/admin_settings_spec.rb | 67 +++++++ spec/requests/settings_spec.rb | 29 ++++ .../available_streams_service_spec.rb | 19 ++ spec/services/comet_service_spec.rb | 16 ++ spec/services/media_transcoder_spec.rb | 163 +++++++++++++++++- spec/services/stream_provider_spec.rb | 97 ++++++++++- .../streams/aio_streams_provider_spec.rb | 92 ++++++++++ spec/services/streams_resolver_spec.rb | 62 ++++++- spec/services/tor_box_service_spec.rb | 39 +++++ 46 files changed, 1879 insertions(+), 187 deletions(-) create mode 100644 app/controllers/admin/settings_controller.rb create mode 100644 app/models/app_setting.rb create mode 100644 app/services/streams/aio_streams_provider.rb create mode 100644 app/services/tor_box_service.rb create mode 100644 app/views/admin/settings/show.html.erb create mode 100644 db/migrate/20261030120000_add_debrid_account_fields_to_users.rb create mode 100644 db/migrate/20261030120100_create_app_settings.rb create mode 100644 spec/models/resolved_source_spec.rb create mode 100644 spec/requests/admin_settings_spec.rb create mode 100644 spec/services/streams/aio_streams_provider_spec.rb create mode 100644 spec/services/tor_box_service_spec.rb diff --git a/.env.example b/.env.example index 08711f6..1b2e549 100644 --- a/.env.example +++ b/.env.example @@ -49,10 +49,11 @@ TORRENTIO_API_BASE_URL=https://torrentio.strem.fun # ── Stream Provider ─────────────────────────────────────────────── # Which addon to use for stream listings and resolution. -# torrentio → Torrentio only (default, backward-compatible) -# comet → Comet primary, Torrentio fallback -# auto → Comet if COMET_URL is set, else Torrentio; Comet first -# with Torrentio fallback when both are configured +# torrentio → Torrentio only (default, backward-compatible) +# comet → Comet primary, Torrentio fallback +# aiostreams → AIOStreams primary, Torrentio fallback +# auto → AIOStreams (if configured), Comet (if configured), +# then Torrentio # Self-host Comet for maximum stability (no Cloudflare blocks, no rate # limits, no peak-hour congestion). See proxy/comet/ for docker setup. STREAM_PROVIDER=torrentio @@ -62,6 +63,15 @@ STREAM_PROVIDER=torrentio # Leave blank to disable Comet. # COMET_URL=http://100.x.x.x:8000 +# AIOStreams addon URL. Use the install/manifest link generated by your +# instance (the part ending in /manifest.json is optional), for example: +# https://aiostreams.example.com/stremio/ +# AIOStreams owns its source/debrid configuration, so no key is needed here. +# AIOSTREAMS_URL=https://aiostreams.example.com/stremio/ + +# Forward proxy for AIOStreams requests. Leave commented to connect directly. +# AIOSTREAMS_PROXY=http://:8888 + # Forward proxy for Comet requests. Set if Comet needs a proxy to reach # torrent indexers or RealDebrid. Usually blank (Comet runs on the VPS # which has direct access). Leave commented to connect directly. @@ -81,6 +91,21 @@ STREAM_PROVIDER=torrentio # RealDebrid API base URL. REALDEBRID_API_BASE_URL=https://api.real-debrid.com/rest/1.0 +# Optional installation-wide debrid keys. Accounts normally enter their own +# key in Settings; when they have none these are used, and an administrator +# can also set a team key in Team settings (which takes precedence over env). +# Leave blank to require per-account keys. +# REALDEBRID_API_KEY= +# TORBOX_API_KEY= + +# TorBox API base URL. +TORBOX_API_BASE_URL=https://api.torbox.app/v1/api + +# Extra hosts that may serve the final media file (comma-separated). +# RealDebrid/TorBox CDNs and configured addon hosts are already allowed; use +# this when an addon proxies playback through another domain. +# STREAM_SOURCE_HOSTS=stremthru.example.com + # OMDB API key for ratings metadata. Get one at https://www.omdbapi.com/apikey.aspx OMDB_API_KEY= diff --git a/README.md b/README.md index f2b4430..a1ead90 100644 --- a/README.md +++ b/README.md @@ -110,9 +110,11 @@ StreamVault relies on several external services. Here's what each one does and h | Service | Role | Required? | How to get access | |---------|------|-----------|-------------------| -| **RealDebrid** | Resolves selected files and provides direct streaming links | **Yes** — streaming won't work without it | Sign up at [real-debrid.com](https://real-debrid.com), then get your API key at [real-debrid.com/apitoken](https://real-debrid.com/apitoken) | +| **RealDebrid** | Resolves selected files and provides direct streaming links | One debrid service is required | Sign up at [real-debrid.com](https://real-debrid.com), then get your API key at [real-debrid.com/apitoken](https://real-debrid.com/apitoken) | +| **TorBox** | Alternative debrid resolver (preliminary support) | One debrid service is required | Sign up at [torbox.app](https://torbox.app), then get your API key at [torbox.app/settings](https://torbox.app/settings) | | **Torrentio** | Finds available streams for a given title | Yes (default provider) | Works out of the box with the public instance. May need a proxy if your server IP is blocked (see below) | | **Comet** | Alternative stream provider — self-hosted, independent of Torrentio | Optional (recommended) | Self-host via Docker — see [proxy/comet](proxy/comet) | +| **AIOStreams** | Aggregating stream provider — one addon over your sources and debrid services | Optional (preliminary support) | Run an instance or use one you trust, configure its sources/services, then set `AIOSTREAMS_URL` to its install link | | **Cinemeta** | Provides content metadata (titles, posters, plots, episodes) | Yes (built-in) | No setup needed — uses the public Stremio metadata service | | **OMDB** | Enriches content with IMDb, Rotten Tomatoes, and Metacritic ratings | Yes | Get a free API key at [omdbapi.com/apikey.aspx](https://www.omdbapi.com/apikey.aspx) | | **TMDB** | Powers the "Recommended for You" feature using your watch history | Optional | Create an account at [themoviedb.org](https://www.themoviedb.org), then get a Read Access Token at [themoviedb.org/settings/api](https://www.themoviedb.org/settings/api) | @@ -120,9 +122,9 @@ StreamVault relies on several external services. Here's what each one does and h ### How the services work together -- **Torrentio and Comet** are both stream *providers*. They search torrent networks for available streams and return a list with quality, size, and language information. You can use either one or both — when both are configured (`STREAM_PROVIDER=auto`), StreamVault queries them in parallel and picks the best stream regardless of which provider found it. If one is down, the other fills in. +- **Torrentio, Comet and AIOStreams** are stream *providers*. They search torrent networks for available streams and return a list with quality, size, and language information. When more than one is configured (`STREAM_PROVIDER=auto`), StreamVault queries them in parallel and picks the best stream regardless of which provider found it. If one is down, the other fills in. -- **RealDebrid** is the *resolver*. Once you pick a stream, StreamVault sends its magnet link to RealDebrid, which retrieves or resolves the selected file and returns a direct HTTPS link. StreamVault does not add the source file to a persistent local media library, but its bytes pass through the server on demand and may be buffered temporarily during proxying or transcoding. +- **RealDebrid and TorBox** are the *resolvers*. Once you pick a stream, StreamVault sends its magnet link or provider URL to the selected debrid service, which retrieves the file and returns a direct HTTPS link. StreamVault does not add the source file to a persistent local media library, but its bytes pass through the server on demand and may be buffered temporarily during proxying or transcoding. Each account can use its own key, an administrator can set a team key, and `REALDEBRID_API_KEY` / `TORBOX_API_KEY` provide an installation fallback. - **FFmpeg** is the *translator*. StreamVault bypasses it for sources the browser can play directly. Otherwise FFmpeg copies compatible video when safe, normalises audio to AAC with timestamp correction, or re-encodes incompatible/UHD video to browser-friendly 1080p H.264. It also produces HLS for iPhone playback and burns image-based subtitles that browsers cannot render. @@ -151,7 +153,7 @@ The most demanding component is **FFmpeg transcoding**, which happens on-the-fly ### Prerequisites - A server or VPS with **Docker** and **Docker Compose** installed -- A **RealDebrid subscription** (starts at ~€3/month) +- A **RealDebrid or TorBox subscription** (RealDebrid starts at ~€3/month) - API keys for **OMDB** (free) and optionally **TMDB** (free) and **SubDL** (free) ### Quick start @@ -196,9 +198,28 @@ Store the generated password in your password manager, then sign in and change i To enable self-registration, set `ENABLE_SIGNUPS=true` in `.env` and restart. -### Configure your RealDebrid key +### Configure debrid keys -After logging in, go to **Settings** and enter your RealDebrid API key. The app verifies the key automatically and shows a confirmation. Your key is encrypted at rest using Active Record Encryption — it never appears in logs or is transmitted in plain text. +After logging in, go to **Settings** and choose RealDebrid or TorBox, then enter that service's API key. The app verifies the key automatically and shows a confirmation. Keys are encrypted at rest using Active Record Encryption — they never appear in logs or are transmitted in plain text. + +Keys are resolved in this order: + +1. the account's own key in Settings; +2. the team key an administrator sets under **Team settings**; +3. `REALDEBRID_API_KEY` or `TORBOX_API_KEY` from the environment. + +Each account can therefore bring its own debrid subscription, while a team can share one key without putting it in every profile. + +### Create your first administrator + +Promote an existing account after the first sign-in: + +```bash +docker compose exec web bin/rails c +> User.first.update!(admin: true) +``` + +Administrators see a **Team** link in the sidebar where they can set team-wide RealDebrid and TorBox keys. ### Auto-start on boot @@ -231,10 +252,16 @@ docker compose up -d --build | `POSTGRES_PASSWORD` | PostgreSQL database password (generate with `openssl rand -hex 16`) | Required | | `POSTGRES_DB` | PostgreSQL database name | `streamvault` | | `PORT` | Host port to expose the app on | `3000` | -| `STREAM_PROVIDER` | Which stream provider to use: `torrentio`, `comet`, or `auto` (see below) | `torrentio` | +| `STREAM_PROVIDER` | Which stream provider to use: `torrentio`, `comet`, `aiostreams`, or `auto` (see below) | `torrentio` | | `TORRENTIO_API_BASE_URL` | Torrentio API base URL | `https://torrentio.strem.fun` | | `COMET_URL` | URL of your self-hosted Comet instance | Optional | +| `AIOSTREAMS_URL` | AIOStreams install/manifest URL (the `/manifest.json` suffix is optional) | Optional | +| `AIOSTREAMS_PROXY` | Forward proxy URL for AIOStreams requests | Optional | | `REALDEBRID_API_BASE_URL` | RealDebrid API base URL | `https://api.real-debrid.com/rest/1.0` | +| `REALDEBRID_API_KEY` | Installation-wide RealDebrid key for accounts without their own | Optional | +| `TORBOX_API_BASE_URL` | TorBox API base URL | `https://api.torbox.app/v1/api` | +| `TORBOX_API_KEY` | Installation-wide TorBox key for accounts without their own | Optional | +| `STREAM_SOURCE_HOSTS` | Extra comma-separated hosts allowed to serve the final media file | Optional | | `OMDB_API_KEY` | OMDB API key for ratings metadata | Required | | `TMDB_READ_ACCESS_TOKEN` | TMDB v4 bearer token for recommendations | Optional | | `SUBDL_API_KEY` | SubDL API key for external subtitle fallback | Optional | @@ -335,7 +362,24 @@ If you run StreamVault on your home computer (which has a residential IP that Re |-------|---------|----------|-------------| | `torrentio` | Torrentio | — | Default, simplest setup (no Comet needed) | | `comet` | Comet | Torrentio | Explicit Comet-first with Torrentio fallback | -| `auto` | Comet (if `COMET_URL` set) | Torrentio | **Recommended** — best of both worlds | +| `aiostreams` | AIOStreams | Torrentio | You already run AIOStreams and want it to aggregate your sources | +| `auto` | AIOStreams (if set), then Comet (if set) | Torrentio | **Recommended** — best of both worlds | + +### AIOStreams notes + +AIOStreams is an addon aggregator. The install link you put in `AIOSTREAMS_URL` +already carries the sources and debrid accounts configured on that instance, so +a shared AIOStreams instance uses the keys configured there — not the +per-account RealDebrid/TorBox keys stored in StreamVault. Those per-account +keys are used by the Torrentio and Comet providers. When AIOStreams is selected +(and configured), accounts without their own key can still stream through the +instance. If every account should use its own debrid subscription, prefer +`STREAM_PROVIDER=torrentio` or `comet`, or run an AIOStreams instance per +account and point that account at its own link. + +AIOStreams can return either its own proxy URL or a direct debrid CDN link. +StreamVault accepts both: direct RealDebrid and TorBox hosts are recognised, and +the RealDebrid bearer token is only ever sent to RealDebrid hosts. ## Testing diff --git a/app/controllers/admin/settings_controller.rb b/app/controllers/admin/settings_controller.rb new file mode 100644 index 0000000..52675cc --- /dev/null +++ b/app/controllers/admin/settings_controller.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module Admin + class SettingsController < ApplicationController + before_action :authenticate_user! + before_action :require_admin! + + def show + @settings = AppSetting.current + end + + def update + @settings = AppSetting.current + attributes = settings_params.to_h.compact_blank + # Blank fields keep the current team key. + if @settings.update(attributes) + redirect_to admin_settings_path, notice: "Team settings updated." + else + render :show, status: :unprocessable_entity + end + end + + private + + def settings_params + params.require(:app_setting).permit(:realdebrid_api_key, :torbox_api_key) + end + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 08953ea..9732a09 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -19,9 +19,24 @@ def signups_enabled? end # Rating-limit policy for child accounts (no-op for regular accounts). + helper_method :debrid_access_configured? + + # True when playback can resolve streams: the account has a key (own, team, + # or environment), or a shared AIOStreams instance supplies its own debrid + # credentials. + def debrid_access_configured? + current_user&.debrid_configured? || StreamProvider.keyless_provider_available? + end + private def parental_content_policy ParentalControls::ContentPolicy.new(current_user) end + + def require_admin! + return if current_user&.admin? + + redirect_to root_path, alert: "That page is restricted to administrators." + end end diff --git a/app/controllers/hls_controller.rb b/app/controllers/hls_controller.rb index abb2469..3dd3e4b 100644 --- a/app/controllers/hls_controller.rb +++ b/app/controllers/hls_controller.rb @@ -29,7 +29,8 @@ def start audio_stream: params[:audio_stream], subtitle_stream: params[:subtitle_stream], default_language: current_user.default_stream_language, - preferred_languages: current_user.preferred_stream_languages + preferred_languages: current_user.preferred_stream_languages, + quality: params[:quality] ) playback_id = params[:playback_id].to_s.gsub(/[^a-zA-Z0-9_-]/, "").first(80).presence || "unknown" Rails.logger.info("[HLS] playback_id=#{playback_id} session_id=#{session.session_id} started") diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index fd79844..6a5c24f 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -10,10 +10,10 @@ def show def update @user = current_user - # Preserve existing RD key if not provided - if params[:user][:realdebrid_api_key].blank? - params[:user].delete(:realdebrid_api_key) - end + # Blank key fields mean "keep the stored key"; there is no way to clear a + # key from this form. + params[:user].delete(:realdebrid_api_key) if params[:user][:realdebrid_api_key].blank? + params[:user].delete(:torbox_api_key) if params[:user][:torbox_api_key].blank? if params[:user][:password].present? update_with_password @@ -38,32 +38,52 @@ def update_with_password end def update_without_password + realdebrid_key = params.dig(:user, :realdebrid_api_key) + torbox_key = params.dig(:user, :torbox_api_key) + if @user.update(settings_params) - if params[:user][:realdebrid_api_key].present? - rd = RealDebridService.new(@user.realdebrid_api_key) - result = rd.verify_key - if result.success? - redirect_to settings_path, notice: "Settings updated. RealDebrid connection verified." - else - redirect_to settings_path, alert: "Settings saved, but RealDebrid key could not be verified: #{result.error_message}" - end + failures = key_verification_failures(realdebrid_key, torbox_key) + if failures.any? + redirect_to settings_path, alert: "Settings saved, but #{failures.to_sentence} could not be verified." else - redirect_to settings_path, notice: "Settings updated." + redirect_to settings_path, notice: verification_notice(realdebrid_key, torbox_key) end else render :show, status: :unprocessable_entity end end + def key_verification_failures(realdebrid_key, torbox_key) + failures = [] + if realdebrid_key.present? + result = RealDebridService.new(realdebrid_key).verify_key + failures << "the RealDebrid key (#{result.error_message})" if result.failure? + end + if torbox_key.present? + result = TorBoxService.new(torbox_key).verify_key + failures << "the TorBox key (#{result.error_message})" if result.failure? + end + failures + end + + def verification_notice(realdebrid_key, torbox_key) + verified = [] + verified << "RealDebrid" if realdebrid_key.present? + verified << "TorBox" if torbox_key.present? + return "Settings updated." if verified.empty? + + "Settings updated. #{verified.to_sentence} connection verified." + end + def settings_params_with_password - params.require(:user).permit(:realdebrid_api_key, :default_language, :password, :password_confirmation, :current_password, + params.require(:user).permit(:realdebrid_api_key, :torbox_api_key, :debrid_service, :default_language, + :password, :password_confirmation, :current_password, :child_account, :max_rating_age, :child_lock_password, :child_lock_password_confirmation, :child_lock_current_password, preferred_languages: []) end - def settings_params - params.require(:user).permit(:realdebrid_api_key, :default_language, + params.require(:user).permit(:realdebrid_api_key, :torbox_api_key, :debrid_service, :default_language, :child_account, :max_rating_age, :child_lock_password, :child_lock_password_confirmation, :child_lock_current_password, preferred_languages: []) end diff --git a/app/controllers/streaming_controller.rb b/app/controllers/streaming_controller.rb index 44867d2..b6e7fce 100644 --- a/app/controllers/streaming_controller.rb +++ b/app/controllers/streaming_controller.rb @@ -6,10 +6,10 @@ class StreamingController < ApplicationController layout "player" before_action :authenticate_user! # stall_telemetry is a diagnostic endpoint — it should work even if - # the user hasn't configured an RD key yet (so we can see stalls from + # the user hasn't configured a debrid key yet (so we can see stalls from # the player regardless of auth state). progress is excluded because # it's a fire-and-forget save that doesn't need the key. - before_action :verify_realdebrid_key!, except: [ :progress, :stall_telemetry ] + before_action :verify_debrid_key!, except: [ :progress, :stall_telemetry ] # POST /streaming — start stream, redirect to player page def create @@ -184,9 +184,9 @@ def start_resume(imdb_id, type, target) end end - def verify_realdebrid_key! - unless current_user.has_realdebrid_key? - redirect_to settings_path, alert: "RealDebrid API key not configured. Please add it in Settings." - end + def verify_debrid_key! + return if debrid_access_configured? + + redirect_to settings_path, alert: "Debrid API key not configured. Add your own in Settings, or ask an administrator to set a team key." end end diff --git a/app/controllers/transcode_controller.rb b/app/controllers/transcode_controller.rb index 0f2ca0c..270b415 100644 --- a/app/controllers/transcode_controller.rb +++ b/app/controllers/transcode_controller.rb @@ -42,7 +42,8 @@ def stream default_language: current_user.default_stream_language, preferred_languages: current_user.preferred_stream_languages, remux: params[:remux] == "1", - telemetry_id: playback_id + telemetry_id: playback_id, + quality: params[:quality] ) do |chunk| response.stream.write(chunk) written_bytes += chunk.bytesize @@ -74,7 +75,8 @@ def stream elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at Rails.logger.info( "[TranscodeStream] playback_id=#{playback_id} load_id=#{load_id} " \ - "remux=#{params[:remux] == '1'} start_seconds=#{start_seconds.round(2)} " \ + "remux=#{params[:remux] == '1'} quality=#{Media::Transcoder.normalized_quality(params[:quality]) || 'auto'} " \ + "start_seconds=#{start_seconds.round(2)} " \ "outcome=#{outcome} written_bytes=#{written_bytes} elapsed=#{elapsed.round(2)}s" ) response.stream.close diff --git a/app/javascript/controllers/video_player_controller.js b/app/javascript/controllers/video_player_controller.js index e5c0dbc..398f5a0 100644 --- a/app/javascript/controllers/video_player_controller.js +++ b/app/javascript/controllers/video_player_controller.js @@ -43,6 +43,9 @@ const REMUX_SEEK_TOLERANCE_SECONDS = 0.25 const REMUX_SEEK_TIMEOUT_MS = 500 const INTERACTIVE_SELECTOR = "button, a, input, textarea, select, [contenteditable='true']" const SAFARI_AUTOPLAY_GUIDANCE_KEY = "streamvault:safari-autoplay-guidance-seen" +// Remembers the quality menu across page loads; episode changes keep the rung. +const QUALITY_STORAGE_KEY = "streamvault:quality" +const QUALITY_OPTIONS = [ "auto", "1080p", "720p", "480p" ] export default class extends Controller { static get targets() { @@ -53,7 +56,7 @@ export default class extends Controller { "seekingOverlay", "seekingOverlayMessage", "sourceInfo", "sourceToggle", "sourceDetails", "sourceUrl", "sourceFilename", "backButton", "audioControls", "audioMenu", "audioOptions", "audioButtonLabel", "subtitleControls", "subtitleMenu", "subtitleOptions", "subtitleButtonLabel", "subtitleOverlay", - "nextEpisodePrompt", "nextEpisodeButton", "nextEpisodeStatus" + "quality", "nextEpisodePrompt", "nextEpisodeButton", "nextEpisodeStatus" ] } static get values() { @@ -96,6 +99,13 @@ export default class extends Controller { this.bufferingOverlayTimer = null this.updateNextEpisodePrompt() } + // Transcode quality: "auto" lets the server pick (CRF, capped at 1080p). + // A fixed rung caps resolution and bitrate; auto mode also steps down a + // rung after repeated stalls so a slow link settles instead of looping. + this.quality = this.storedQuality() + this.autoQuality = this.quality === "auto" + this.autoQualityStalls = 0 + this.syncQualitySelect() this.audioTracks = [] this.subtitleTracks = [] this.selectedAudioStream = this.currentUrlParam("audio_stream") @@ -1209,9 +1219,99 @@ export default class extends Controller { } handleStreamStall(eventType = "stall") { + this.maybeDowngradeAutoQuality() return this.recoveryMonitor().handleStreamStall(eventType) } + // Quality menu: "auto" keeps the server's default encode, a fixed rung caps + // resolution and bitrate. Playback restarts at the same position so the + // change takes effect immediately instead of on the next episode. + changeQuality(event) { + const value = event?.target?.value || "auto" + this.quality = value === "auto" ? "auto" : value + this.autoQuality = value === "auto" + this.autoQualityStalls = 0 + this.element.dataset.videoPlayerQualityValue = this.quality + this.persistQuality() + + if (!this.playbackStarted) return + + // Direct play copies the source untouched, so a fixed rung has to move + // playback onto the transcode path. + if (this.isDirectPlay()) { + this.directPlayActive = false + this.remuxDirectPlay = false + } + + this.restartPlaybackAt(Math.floor(this.currentPlaybackPosition())) + } + + // The rung the user pinned, or null when the server should decide. + fixedQuality() { + return this.quality === "auto" ? null : this.quality + } + + storedQuality() { + try { + const stored = window.localStorage.getItem(QUALITY_STORAGE_KEY) + return QUALITY_OPTIONS.includes(stored) ? stored : "auto" + } catch { + return "auto" + } + } + + persistQuality() { + try { + window.localStorage.setItem(QUALITY_STORAGE_KEY, this.quality) + } catch { + // Private browsing modes can refuse storage; the choice still applies + // for this page. + } + } + + // Keeps the menu in sync when automatic quality steps down on its own. + syncQualitySelect() { + if (this.hasQualityTarget) this.qualityTarget.value = this.quality + } + + // Automatic quality: every second stall drops one rung (720p, then 480p). + // One stall is normal on a torrent-backed link; two mean the encoder is + // outrunning the connection. + maybeDowngradeAutoQuality() { + if (!this.autoQuality) return + + this.autoQualityStalls += 1 + if (this.autoQualityStalls % 2 !== 0) return + + const ladder = [ "720p", "480p" ] + const current = ladder.indexOf(this.quality) + const next = current === -1 ? ladder[0] : ladder[current + 1] + if (!next) return + + this.quality = next + this.syncQualitySelect() + console.info(`[Player] Auto quality stepped down to ${next} after repeated stalls`) + this.reportStall("quality_downgrade", { quality: next }) + } + + // Every rebuild of the transcode URL carries the selected rung, so seeks, + // stall recovery and manual quality changes agree on the encoder settings. + // Streaming URL for the current quality selection (used by the MSE path, + // whose URL otherwise comes straight from the server-rendered data value). + transcodeUrlWithQuality(streamUrl) { + const url = new URL(streamUrl, window.location.origin) + this.applyQualityParam(url) + return url.pathname + url.search + } + + applyQualityParam(url) { + if (this.quality && this.quality !== "auto") { + url.searchParams.set("quality", this.quality) + } else { + url.searchParams.delete("quality") + } + } + // Restart direct/remux playback from the current position. Unlike // reconnectFromCurrentPosition (which switches to MSE), this keeps // the same direct/remux path — just reloads the URL with the current @@ -1348,6 +1448,8 @@ export default class extends Controller { url.searchParams.delete("subtitle_stream") } + this.applyQualityParam(url) + const nextSrc = url.pathname + url.search this.streamingUrlValue = nextSrc this.element.dataset.videoPlayerStreamingUrlValue = nextSrc @@ -2369,6 +2471,8 @@ export default class extends Controller { url.searchParams.delete("subtitle_stream") } + this.applyQualityParam(url) + const nextSrc = url.pathname + url.search this.streamingUrlValue = nextSrc this.element.dataset.videoPlayerStreamingUrlValue = nextSrc diff --git a/app/javascript/player/hls_session_client.js b/app/javascript/player/hls_session_client.js index 29e0cba..2490fbb 100644 --- a/app/javascript/player/hls_session_client.js +++ b/app/javascript/player/hls_session_client.js @@ -138,6 +138,7 @@ export class HlsSessionClient { const params = new URLSearchParams({ source }) params.set("playback_id", this.player.playbackId) if (startSeconds && startSeconds > 0) params.set("start_seconds", startSeconds) + if (this.player.quality && this.player.quality !== "auto") params.set("quality", this.player.quality) this.player.appendSelectedHlsTracks(params) const response = await this.fetcher("/hls/start", { diff --git a/app/javascript/player/playback_paths.js b/app/javascript/player/playback_paths.js index 003e598..f6263fc 100644 --- a/app/javascript/player/playback_paths.js +++ b/app/javascript/player/playback_paths.js @@ -27,7 +27,7 @@ class MsePath { eligible() { return true } start() { this.player.primedDirectPlayUrl = null - this.player.setupMseSource(this.player.streamingUrlValue) + this.player.setupMseSource(this.player.transcodeUrlWithQuality(this.player.streamingUrlValue)) } } @@ -50,11 +50,18 @@ export class PlaybackPaths { if (!this.player.mseSupported && !this.player.isSafari()) return this.mse.start() + // A fixed quality rung has to be encoded by ffmpeg, so direct play and + // remux (which copy the source bytes as-is) are skipped on the first load. + const fixedQuality = this.player.fixedQuality() + const tracks = this.player.loadMediaTracks() - if (this.player.directPlayHintValue) this.player.primeDirectPlay() + if (!fixedQuality && this.player.directPlayHintValue) this.player.primeDirectPlay() await tracks - const path = [ this.native, this.hls, this.remux, this.mse ].find((candidate) => candidate.eligible()) + const candidates = fixedQuality + ? [ this.hls, this.mse ] + : [ this.native, this.hls, this.remux, this.mse ] + const path = candidates.find((candidate) => candidate.eligible()) path.start() } } diff --git a/app/models/app_setting.rb b/app/models/app_setting.rb new file mode 100644 index 0000000..1d344de --- /dev/null +++ b/app/models/app_setting.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +# Installation-wide settings an administrator can change without a deploy. +# Credentials are encrypted at rest with Active Record Encryption and are +# never rendered back to the browser. +class AppSetting < ApplicationRecord + encrypts :realdebrid_api_key, deterministic: false + encrypts :torbox_api_key, deterministic: false + + # The table holds a single row. Creating it lazily keeps existing installs + # working without a data migration. + def self.current + first_or_create! + end +end diff --git a/app/models/resolved_source.rb b/app/models/resolved_source.rb index 839a574..507e88e 100644 --- a/app/models/resolved_source.rb +++ b/app/models/resolved_source.rb @@ -8,6 +8,7 @@ class ResolvedSource PURPOSE = "resolved-source" TOKEN_TTL = 12.hours REALDEBRID_HOSTS = %w[real-debrid.com download.real-debrid.com streaming.real-debrid.com].freeze + TORBOX_HOSTS = %w[torbox.app].freeze PRIVATE_NETWORKS = %w[ 0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.0.0.0/24 192.0.2.0/24 192.168.0.0/16 @@ -17,20 +18,21 @@ class ResolvedSource class Invalid < StandardError; end - attr_reader :url, :filename + attr_reader :url, :filename, :service - def initialize(url:, filename: nil) + def initialize(url:, filename: nil, service: nil) @url = url.to_s @filename = filename.to_s.presence || inferred_filename + @service = (service.presence || inferred_service).to_s.presence raise Invalid, "untrusted stream host" unless trusted_host? freeze end - def self.issue(user:, url:, filename: nil) - source = new(url: url, filename: filename) + def self.issue(user:, url:, filename: nil, service: nil) + source = new(url: url, filename: filename, service: service) ApplicationToken.issue( - { "user_id" => user.id, "url" => source.url, "filename" => source.filename }, + { "user_id" => user.id, "url" => source.url, "filename" => source.filename, "service" => source.service }, purpose: PURPOSE, expires_in: TOKEN_TTL ) @@ -40,7 +42,7 @@ def self.resolve(token:, user:, verify_dns: true) payload = ApplicationToken.verify(token, purpose: PURPOSE) raise Invalid, "source belongs to another user" unless payload.fetch("user_id").to_i == user.id - source = new(url: payload.fetch("url"), filename: payload["filename"]) + source = new(url: payload.fetch("url"), filename: payload["filename"], service: payload["service"]) raise Invalid, "stream host did not resolve publicly" if verify_dns && !source.public_address? source @@ -48,10 +50,15 @@ def self.resolve(token:, user:, verify_dns: true) raise Invalid, "invalid or expired source" end + # Only RealDebrid download hosts need the account bearer token. Sending a + # RealDebrid key to a TorBox or AIOStreams host would leak it. def request_headers(user) - return {} unless user.has_realdebrid_key? + return {} unless service == "realdebrid" - { "Authorization" => "Bearer #{user.realdebrid_api_key}" } + key = user.respond_to?(:effective_realdebrid_api_key) ? user.effective_realdebrid_api_key : user.realdebrid_api_key + return {} if key.blank? + + { "Authorization" => "Bearer #{key}" } end def public_address? @@ -62,7 +69,7 @@ def public_address? end def to_h - { url: url, filename: filename } + { url: url, filename: filename, service: service } end private @@ -77,7 +84,26 @@ def trusted_host? return false unless uri.is_a?(URI::HTTPS) && uri.host.present? host = uri.host.downcase - REALDEBRID_HOSTS.any? { |allowed| host == allowed || host.end_with?(".#{allowed}") } + return true if REALDEBRID_HOSTS.any? { |allowed| host_matches?(host, allowed) } + return true if TORBOX_HOSTS.any? { |allowed| host_matches?(host, allowed) } + + # A provider/addon host is optional configuration; a failure to read it + # must not reject RealDebrid or TorBox URLs. + StreamProvider.source_hosts.any? { |allowed| host_matches?(host, allowed.to_s.downcase) } + rescue StandardError + false + end + + def host_matches?(host, allowed) + allowed.present? && (host == allowed || host.end_with?(".#{allowed}")) + end + + def inferred_service + host = uri.host.to_s.downcase + return "realdebrid" if REALDEBRID_HOSTS.any? { |allowed| host_matches?(host, allowed) } + return "torbox" if TORBOX_HOSTS.any? { |allowed| host_matches?(host, allowed) } + + nil end def inferred_filename diff --git a/app/models/user.rb b/app/models/user.rb index 4be20fa..30063b6 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -6,6 +6,7 @@ class User < ApplicationRecord # Encryption encrypts :realdebrid_api_key, deterministic: false + encrypts :torbox_api_key, deterministic: false # Associations has_many :collection_entries, dependent: :destroy @@ -31,6 +32,16 @@ class User < ApplicationRecord validates :display_name, length: { maximum: 50 } + # Debrid services. Each account can use its own key; when it has none the + # installation-wide key set by an administrator (or the environment) is used. + DEBRID_SERVICES = { + "realdebrid" => "RealDebrid", + "torbox" => "TorBox" + }.freeze + + validates :debrid_service, inclusion: { in: DEBRID_SERVICES.keys } + before_validation :normalize_debrid_service + # Child accounts / parental controls CHILD_LOCK_MIN_LENGTH = 4 MAX_RATING_AGE_RANGE = 0..18 @@ -66,7 +77,58 @@ def valid_child_lock_password?(attempt) end def has_realdebrid_key? - realdebrid_api_key.present? + effective_realdebrid_api_key.present? + end + + def has_torbox_key? + effective_torbox_api_key.present? + end + + # Whether any debrid account is usable. Both services are queried when both + # keys exist, so this is not limited to the selected service. + def debrid_configured? + debrid_credentials.any? + end + + # Every (service, key) pair this account can use for streams, most-preferred + # first. Both services are included so their streams can be merged for more + # diversity instead of picking a single pool. + def debrid_credentials + pairs = [] + pairs << [ "realdebrid", effective_realdebrid_api_key ] if effective_realdebrid_api_key.present? + pairs << [ "torbox", effective_torbox_api_key ] if effective_torbox_api_key.present? + pairs.sort_by { |service, _key| service == effective_debrid_service ? 0 : 1 } + end + + def effective_realdebrid_api_key + realdebrid_api_key.presence || shared_debrid_setting(:realdebrid_api_key) + end + + def effective_torbox_api_key + torbox_api_key.presence || shared_debrid_setting(:torbox_api_key) + end + + def effective_debrid_api_key + debrid_service.to_s == "torbox" ? effective_torbox_api_key : effective_realdebrid_api_key + end + + def effective_debrid_service + DEBRID_SERVICES.key?(debrid_service.to_s) ? debrid_service.to_s : "realdebrid" + end + + def debrid_service_label + DEBRID_SERVICES.fetch(effective_debrid_service, effective_debrid_service) + end + + # :user, :global (admin setting), :environment, or nil. The value is used + # for a status line only; the key itself is never rendered. + def debrid_key_source + own_key = debrid_service.to_s == "torbox" ? torbox_api_key : realdebrid_api_key + return :user if own_key.present? + return :global if app_settings.public_send(debrid_setting_column).present? + return :environment if ENV[debrid_env_var].present? + + nil end def preferred_stream_languages @@ -86,6 +148,30 @@ def stream_language_priority private + def normalize_debrid_service + self.debrid_service = debrid_service.to_s.presence || "realdebrid" + end + + def debrid_setting_column + debrid_service.to_s == "torbox" ? :torbox_api_key : :realdebrid_api_key + end + + def debrid_env_var + debrid_service.to_s == "torbox" ? "TORBOX_API_KEY" : "REALDEBRID_API_KEY" + end + + # Admin-set key first, then an environment key. Blank values are ignored so + # an empty .env line does not shadow a configured one. The settings row is + # read once per user instance; media segment requests therefore do not each + # add a settings query. + def shared_debrid_setting(column) + app_settings.public_send(column).presence || ENV[column == :torbox_api_key ? "TORBOX_API_KEY" : "REALDEBRID_API_KEY"].presence + end + + def app_settings + @app_settings ||= AppSetting.current + end + def digest_child_lock_password return if child_lock_password.blank? diff --git a/app/services/available_streams_service.rb b/app/services/available_streams_service.rb index b8cdf34..14b7f8c 100644 --- a/app/services/available_streams_service.rb +++ b/app/services/available_streams_service.rb @@ -1,11 +1,17 @@ # frozen_string_literal: true +require "digest" + class AvailableStreamsService CACHE_TTL = 60.seconds def initialize(user, providers: nil, cache: Rails.cache, logger: Rails.logger) @user = user - @providers = providers || StreamProvider.providers(rd_api_key: user&.realdebrid_api_key) + @providers = providers || StreamProvider.providers( + rd_api_key: user&.effective_realdebrid_api_key, + torbox_api_key: user&.effective_torbox_api_key, + debrid_service: user&.effective_debrid_service + ) @cache = cache @logger = logger end @@ -24,7 +30,13 @@ def call(imdb_id:, type:, season: nil, episode: nil, title: nil) def cache_key_for(imdb_id, type, season, episode) language_key = Array(@user.stream_language_priority).join(",") - "streams/v2/#{@user.cache_key_with_version}/#{imdb_id}/#{type}/#{season}/#{episode}/#{language_key}" + # A team key can change without touching the user row, so include a + # fingerprint of every usable credential instead of relying on the cache + # version alone. + credential_key = Digest::SHA256.hexdigest( + [ @user.effective_debrid_service, @user.effective_realdebrid_api_key.to_s, @user.effective_torbox_api_key.to_s ].join(":") + )[0, 12] + "streams/v4/#{@user.cache_key_with_version}/#{credential_key}/#{imdb_id}/#{type}/#{season}/#{episode}/#{language_key}" end def fetch_streams(imdb_id, type, season, episode, title) @@ -35,9 +47,31 @@ def fetch_streams(imdb_id, type, season, episode, title) end.map(&:value) streams = results.filter_map { |result| result.data if result&.success? }.flatten(1) + streams = deduplicate(streams) streams.empty? ? ServiceResult.failure("No streams available") : ServiceResult.success(streams) end + # Every debrid variant of an addon returns the same torrents, so keep the + # first copy: providers for the account's preferred service run first. + def deduplicate(streams) + seen = {} + streams.each_with_object([]) do |stream, unique| + key = torrent_key(stream) + next if key && seen[key] + + seen[key] = true if key + unique << stream + end + end + + def torrent_key(stream) + info_hash = stream.respond_to?(:info_hash) ? stream.info_hash : stream[:info_hash] + return if info_hash.blank? + + file_idx = stream.respond_to?(:file_idx) ? stream.file_idx : stream[:file_idx] + [ info_hash, file_idx ].join(":") + end + def fetch_provider(provider, imdb_id, type, season, episode, title) started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) result = provider.streams( diff --git a/app/services/comet_service.rb b/app/services/comet_service.rb index b57000a..7461ad0 100644 --- a/app/services/comet_service.rb +++ b/app/services/comet_service.rb @@ -30,8 +30,10 @@ def self.comet_proxy ENV.fetch("COMET_PROXY", "") end - def initialize(rd_api_key: nil) - @rd_api_key = rd_api_key + def initialize(rd_api_key: nil, api_key: nil, debrid_service: "realdebrid") + @api_key = api_key.presence || rd_api_key + @rd_api_key = @api_key + @debrid_service = debrid_service.to_s.presence || "realdebrid" @parser = Streams::ReleaseParser.new @comet = Faraday.new(url: self.class.comet_url) do |f| f.request :json @@ -99,11 +101,11 @@ def build_stream_path(imdb_id, type, season: nil, episode: nil) # Build the base64-encoded config path segment. When the RD key is # absent, return nil so Comet serves at the default (no-config) path. def build_config - return nil if @rd_api_key.blank? + return nil if @api_key.blank? config = { - "debridService" => "realdebrid", - "debridApiKey" => @rd_api_key, + "debridService" => @debrid_service, + "debridApiKey" => @api_key, "cachedOnly" => true, "enableTorrent" => false, "scrapeDebridAccountTorrents" => true diff --git a/app/services/hls_session_manager.rb b/app/services/hls_session_manager.rb index 331a4a9..f3d16a4 100644 --- a/app/services/hls_session_manager.rb +++ b/app/services/hls_session_manager.rb @@ -21,7 +21,7 @@ class HlsSessionManager @processes = {} @mutex = Mutex.new - def self.create(user_id:, input_url:, headers:, start_seconds:, audio_stream:, subtitle_stream:, default_language:, preferred_languages:) + def self.create(user_id:, input_url:, headers:, start_seconds:, audio_stream:, subtitle_stream:, default_language:, preferred_languages:, quality: nil) session_id = SecureRandom.hex(16) record = HlsSession.create!(user_id: user_id, session_id: session_id) dir = record.storage_path @@ -35,7 +35,8 @@ def self.create(user_id:, input_url:, headers:, start_seconds:, audio_stream:, s default_language: default_language, preferred_languages: preferred_languages, wait_for_first_segment: false, - telemetry_id: session_id + telemetry_id: session_id, + quality: quality ) @mutex.synchronize { @processes[session_id] = process } diff --git a/app/services/media/transcoder.rb b/app/services/media/transcoder.rb index 409db51..b80b917 100644 --- a/app/services/media/transcoder.rb +++ b/app/services/media/transcoder.rb @@ -97,6 +97,40 @@ class Media::Transcoder "-pix_fmt", "yuv420p", "-bf", "0" ].freeze + # Selectable transcode qualities. "auto" keeps the CRF encode at the source + # resolution (capped at 1080p); a fixed rung caps resolution and bitrate so a + # slow connection gets predictable bandwidth instead of guessing. + QUALITY_LADDER = { + "1080p" => { max_height: 1080, max_rate: "6000k", buffer_size: "12000k" }, + "720p" => { max_height: 720, max_rate: "3000k", buffer_size: "6000k" }, + "480p" => { max_height: 480, max_rate: "1200k", buffer_size: "2400k" } + }.freeze + # Transfer functions that mark a stream as HDR. Transcoding HDR to SDR + # without tone mapping produces washed-out grey output, so these streams get + # the linear-light tonemap chain. + HDR_TRANSFER_FUNCTIONS = %w[smpte2084 arib-std-b67].freeze + HDR_TONEMAP_FILTER = [ + "zscale=t=linear:npl=100", + "format=gbrpf32le", + "zscale=p=bt709", + "tonemap=tonemap=hable:desat=0", + "zscale=t=bt709:m=bt709:r=tv", + "format=yuv420p" + ].join(",").freeze + # Hardware H.264 encoders tried in order when FFMPEG_ENCODER is not set. + # Each candidate is verified with a one-frame test encode, so a build that + # lists an encoder without a working driver falls through to software instead + # of failing playback. + HARDWARE_ENCODERS = [ + { name: "h264_videotoolbox", hwaccel: [ "-hwaccel", "videotoolbox" ], + args: [ "-c:v", "h264_videotoolbox", "-b:v", "4000k", "-pix_fmt", "yuv420p", "-bf", "0" ] }, + { name: "h264_nvenc", hwaccel: [ "-hwaccel", "cuda" ], + args: [ "-c:v", "h264_nvenc", "-preset", "p4", "-pix_fmt", "yuv420p", "-bf", "0" ] }, + { name: "h264_qsv", hwaccel: [], + args: [ "-c:v", "h264_qsv", "-pix_fmt", "yuv420p", "-bf", "0" ] }, + { name: "h264_amf", hwaccel: [], + args: [ "-c:v", "h264_amf", "-pix_fmt", "yuv420p", "-bf", "0" ] } + ].freeze SAFE_H264_PIXEL_FORMATS = %w[yuv420p].freeze TEXT_SUBTITLE_CODECS = %w[subrip ass ssa webvtt mov_text].freeze PARTIAL_SUBTITLE_TITLE_PATTERN = /\b(forced|signs?|signs?\s*(?:&|and)?\s*songs?|songs?\s*(?:&|and)?\s*signs?|lyrics?|karaoke|commentary|comment)\b/i @@ -179,7 +213,7 @@ def empty_window? # (bad URL, auth failure, expired link). When the caller stops reading # (client disconnect → exception propagates through the yield), the # ensure block kills ffmpeg. - def self.transcode_to_fmp4(input_url, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], remux: false, telemetry_id: nil, &block) + def self.transcode_to_fmp4(input_url, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], remux: false, telemetry_id: nil, quality: nil, &block) cmd = build_ffmpeg_command( input_url, headers: headers, @@ -189,7 +223,8 @@ def self.transcode_to_fmp4(input_url, headers: {}, start_seconds: 0, audio_strea default_language: default_language, preferred_languages: preferred_languages, remux: remux, - telemetry_id: telemetry_id + telemetry_id: telemetry_id, + quality: quality ) transcode_to_fmp4_internal(cmd, telemetry_id: telemetry_id, &block) @@ -201,7 +236,7 @@ def self.transcode_to_fmp4(input_url, headers: {}, start_seconds: 0, audio_strea # caller must retain it until ffmpeg exits or the session is stopped; # closing the reader while ffmpeg is alive would leave stderr attached # to a readerless pipe and can terminate ffmpeg on its next diagnostic. - def self.transcode_to_hls(input_url, segment_dir:, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], wait_for_first_segment: true, telemetry_id: nil) + def self.transcode_to_hls(input_url, segment_dir:, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], wait_for_first_segment: true, telemetry_id: nil, quality: nil) FileUtils.mkdir_p(segment_dir) cmd = build_ffmpeg_command( @@ -214,7 +249,8 @@ def self.transcode_to_hls(input_url, segment_dir:, headers: {}, start_seconds: 0 preferred_languages: preferred_languages, output_spec: :hls, segment_dir: segment_dir, - telemetry_id: telemetry_id + telemetry_id: telemetry_id, + quality: quality ) err_rd, err_wr = IO.pipe @@ -697,7 +733,7 @@ def self.format_vtt_timestamp(seconds) end private_class_method :format_vtt_timestamp - def self.build_ffmpeg_command(input_url, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], output_spec: :fmp4, segment_dir: nil, remux: false, telemetry_id: nil) + def self.build_ffmpeg_command(input_url, headers: {}, start_seconds: 0, audio_stream: nil, subtitle_stream: nil, default_language: nil, preferred_languages: [], output_spec: :fmp4, segment_dir: nil, remux: false, telemetry_id: nil, quality: nil) header_str = ffmpeg_headers(headers) # Probe video stream and media tracks in parallel — these are # independent ffprobe calls that each take 1-3s on a cold cache. @@ -730,15 +766,18 @@ def self.build_ffmpeg_command(input_url, headers: {}, start_seconds: 0, audio_st # intended preceding cue. The seek plan separately gives the browser the # copied keyframe's presentation anchor and local pre-roll. Standard MSE # seeks still transcode for exactness. - effective_remux = remux && !selected_burn_subtitle_track + quality_rung = normalized_quality(quality) + # A fixed rung needs a re-encode, so remux (and the HLS copy shortcut) + # are only used for automatic quality. + effective_remux = remux && !selected_burn_subtitle_track && quality_rung.nil? video_args = if selected_burn_subtitle_track - transcode_args + [ *transcode_args, *bitrate_cap_args(quality_rung) ] elsif effective_remux [ "-c:v", "copy" ] - elsif output_spec == :hls && browser_safe_video?(video_stream) && seek_start_seconds.zero? + elsif output_spec == :hls && browser_safe_video?(video_stream) && seek_start_seconds.zero? && quality_rung.nil? [ "-c:v", "copy" ] else - [ "-vf", SAFE_VIDEO_FILTER, *transcode_args ] + [ "-vf", video_filter(video_stream, quality_rung), *transcode_args, *bitrate_cap_args(quality_rung) ] end if defined?(Rails) @@ -747,6 +786,7 @@ def self.build_ffmpeg_command(input_url, headers: {}, start_seconds: 0, audio_st Rails.logger.info( "[Transcode] playback_id=#{id} codec=#{video_stream[:codec_name]} " \ "resolution=#{video_stream[:width]}x#{video_stream[:height]} encoder=#{encoder} " \ + "quality=#{quality_rung || 'auto'} hdr=#{hdr_video?(video_stream)} " \ "start_seconds=#{seek_start_seconds.round(2)} remux=#{effective_remux}" ) end @@ -818,7 +858,9 @@ def self.build_ffmpeg_command(input_url, headers: {}, start_seconds: 0, audio_st cmd += [ "-ss", seek_start_seconds.to_s ] if seek_start_seconds.positive? cmd += [ "-i", input_url ] if selected_burn_subtitle_track - cmd += [ "-filter_complex", subtitle_burn_filter(selected_burn_subtitle_track[:position]) ] + cmd += [ "-filter_complex", subtitle_burn_filter( + selected_burn_subtitle_track[:position], video_stream: video_stream, quality: quality_rung + ) ] cmd += [ "-map", "[v]" ] else cmd += [ "-map", "0:v:0" ] @@ -894,10 +936,92 @@ def self.transcode_args return VIDEOTOOLBOX_TRANSCODE_ARGS if videotoolbox_available? + detected = detect_hardware_encoder + return detected[:args] if detected + VIDEO_TRANSCODE_ARGS end private_class_method :transcode_args + # First hardware H.264 encoder that actually produces a frame on this host, + # cached for the life of the process. Detection runs a one-frame encode + # because -encoders lists encoders that the build supports even when the + # driver or device is missing. + def self.detect_hardware_encoder + return @detected_hardware_encoder if defined?(@detected_hardware_encoder) + + @detected_hardware_encoder = HARDWARE_ENCODERS.find { |encoder| hardware_encoder_works?(encoder) } + end + + def self.hardware_encoder_works?(encoder) + result = capture_command( + [ + FFMPEG_PATH, "-hide_banner", "-loglevel", "error", + "-f", "lavfi", "-i", "testsrc=size=320x240:rate=1", "-frames:v", "1", + *encoder[:args], "-f", "null", "-" + ], + timeout_seconds: 15 + ) + result.status&.success? && !result.timed_out + rescue StandardError + false + end + private_class_method :hardware_encoder_works? + + # The quality rung requested by the client, or nil for "auto". + def self.normalized_quality(value) + key = value.to_s.strip.downcase + QUALITY_LADDER.key?(key) ? key : nil + end + public_class_method :normalized_quality + + def self.bitrate_cap_args(quality) + rung = QUALITY_LADDER[quality] + return [] unless rung + + [ "-maxrate", rung[:max_rate], "-bufsize", rung[:buffer_size] ] + end + private_class_method :bitrate_cap_args + + # Scale filter for a rung. "auto" keeps the historical 1080p cap. + def self.scale_filter(quality) + rung = QUALITY_LADDER[quality] + return SAFE_VIDEO_FILTER unless rung + + max_height = rung[:max_height] + max_width = max_height * 16 / 9 + "scale=w='min(#{max_width},iw)':h='min(#{max_height},ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p" + end + private_class_method :scale_filter + + # Tone mapping must run before the SDR scale/format step, otherwise the + # HDR-to-SDR conversion is applied to already-clipped values. + def self.video_filter(video_stream, quality) + filters = [] + filters << HDR_TONEMAP_FILTER if hdr_video?(video_stream) && tonemap_available? + filters << scale_filter(quality) + filters.join(",") + end + private_class_method :video_filter + + def self.hdr_video?(stream) + return false unless stream.is_a?(Hash) + + HDR_TRANSFER_FUNCTIONS.include?(stream[:color_transfer].to_s.downcase) || + stream[:color_primaries].to_s.downcase == "bt2020" + end + public_class_method :hdr_video? + + # Tonemapping needs zimg (zscale) plus the tonemap filter. A build without + # them would fail the whole transcode, so the chain is skipped instead. + def self.tonemap_available? + return @tonemap_available if defined?(@tonemap_available) + + result = capture_command([ FFMPEG_PATH, "-hide_banner", "-filters" ], timeout_seconds: 10) + filters = result.status&.success? ? result.stdout : "" + @tonemap_available = filters.include?("zscale") && filters.include?(" tonemap ") + end + def self.videotoolbox_available? return @videotoolbox_available if defined?(@videotoolbox_available) @@ -922,6 +1046,9 @@ def self.hwaccel_args return [ "-hwaccel", "videotoolbox" ] if videotoolbox_available? + detected = detect_hardware_encoder + return detected[:hwaccel] if detected && detected[:hwaccel].present? + [] end private_class_method :hwaccel_args @@ -939,8 +1066,10 @@ def self.selected_burn_subtitle_track(input_url, headers:, subtitle_stream:) end private_class_method :selected_burn_subtitle_track - def self.subtitle_burn_filter(subtitle_position) - "[0:v:0][0:s:#{subtitle_position}]overlay,#{SAFE_VIDEO_FILTER}[v]" + # Tone mapping and scaling happen before the overlay so subtitle colours are + # not pushed through the HDR transfer function. + def self.subtitle_burn_filter(subtitle_position, video_stream: nil, quality: nil) + "[0:v:0]#{video_filter(video_stream, quality)}[vbase];[vbase][0:s:#{subtitle_position}]overlay,format=yuv420p[v]" end private_class_method :subtitle_burn_filter @@ -1255,7 +1384,7 @@ def self.probe_video_stream(input_url, headers: {}) cmd += [ "-headers", header_str + "\r\n" ] if header_str.present? cmd += [ "-select_streams", "v:0", - "-show_entries", "stream=codec_name,codec_tag_string,width,height,pix_fmt,has_b_frames", + "-show_entries", "stream=codec_name,codec_tag_string,width,height,pix_fmt,has_b_frames,color_transfer,color_primaries,color_space", "-of", "json", input_url ] @@ -1318,7 +1447,10 @@ def self.extract_video_stream(output) width: positive_integer(stream["width"]), height: positive_integer(stream["height"]), pix_fmt: stream["pix_fmt"].to_s.downcase, - has_b_frames: positive_integer(stream["has_b_frames"]).to_i > 0 + has_b_frames: positive_integer(stream["has_b_frames"]).to_i > 0, + color_transfer: stream["color_transfer"].to_s.downcase, + color_primaries: stream["color_primaries"].to_s.downcase, + color_space: stream["color_space"].to_s.downcase } rescue JSON::ParserError {} diff --git a/app/services/playback_start_service.rb b/app/services/playback_start_service.rb index 51a1a9a..b6ab428 100644 --- a/app/services/playback_start_service.rb +++ b/app/services/playback_start_service.rb @@ -114,7 +114,7 @@ def playback_descriptor(stream:, content_ref:, title:, poster_url:, resume_at:, source ||= ResolvedSource.new(url: stream.fetch(:streaming_url), filename: stream[:filename]) PlaybackDescriptor.new( - source_token: ResolvedSource.issue(user: @user, url: source.url, filename: source.filename), + source_token: ResolvedSource.issue(user: @user, url: source.url, filename: source.filename, service: source.respond_to?(:service) ? source.service : nil), filename: source.filename, content_ref: content_ref, title: title, diff --git a/app/services/stream_provider.rb b/app/services/stream_provider.rb index 15231b8..0f9f2e6 100644 --- a/app/services/stream_provider.rb +++ b/app/services/stream_provider.rb @@ -3,10 +3,17 @@ # Factory that returns the configured stream provider(s). # # STREAM_PROVIDER env var: -# "comet" → Comet primary, Torrentio fallback -# "torrentio" → Torrentio only (default) -# "auto" → configured Comet followed by Torrentio -# "comet" → configured Comet followed by Torrentio +# "torrentio" → Torrentio only (default) +# "comet" → Comet primary, Torrentio fallback +# "aiostreams" → AIOStreams primary, Torrentio fallback +# "auto" → AIOStreams (if configured), Comet (if configured), +# then Torrentio +# +# Every usable debrid credential is passed to Torrentio and Comet, which embed +# it in their addon URL/config: with both RealDebrid and TorBox keys the addons +# are queried once per service so the merged result has more stream diversity. +# The account's selected service comes first, so its streams win ties. +# AIOStreams is configured on its own instance, so it needs no key here. # # Each provider implements: # streams(imdb_id, type, season:, episode:, title:, preferred_languages:, default_language:) @@ -15,22 +22,87 @@ module StreamProvider module_function - # Returns an ordered array of provider instances configured for the user. - # The first provider is primary; subsequent ones are fallbacks used when - # the primary returns no streams or fails to connect. - def providers(rd_api_key:) - torrentio = Streams::TorrentioProvider.new(rd_api_key: rd_api_key) + def providers(rd_api_key: nil, torbox_api_key: nil, debrid_service: "realdebrid") + credentials = debrid_credentials(rd_api_key, torbox_api_key, debrid_service) + torrentio = credentials.map do |service, api_key| + Streams::TorrentioProvider.new(api_key: api_key, debrid_service: service) + end + comet = credentials.filter_map { |service, api_key| comet_provider(api_key, service) } setting = ENV.fetch("STREAM_PROVIDER", "torrentio").to_s.downcase - return [ torrentio ] unless %w[comet auto].include?(setting) - [ (CometService.new(rd_api_key: rd_api_key) if CometService.comet_url.present?), torrentio ].compact + case setting + when "comet" + comet + torrentio + when "aiostreams" + [ aiostreams_provider, *torrentio ].compact + when "auto" + [ aiostreams_provider, *comet, *torrentio ].compact + else + torrentio + end + end + + # One (service, key) pair per usable credential, preferred service first. An + # account with no key of its own still queries the addons keylessly, since the + # addon may serve links that need no debrid account. + def debrid_credentials(rd_api_key, torbox_api_key, debrid_service) + preferred = debrid_service.to_s.presence || "realdebrid" + pairs = [] + pairs << [ "realdebrid", rd_api_key ] if rd_api_key.present? + pairs << [ "torbox", torbox_api_key ] if torbox_api_key.present? + return [ [ preferred, nil ] ] if pairs.empty? + + pairs.sort_by { |service, _api_key| service == preferred ? 0 : 1 } + end + + # AIOStreams instances are configured with their own debrid accounts, so a + # shared instance can serve accounts that have no per-account key. This is + # only true when AIOStreams is actually selected and configured. + def keyless_provider_available? + setting = ENV.fetch("STREAM_PROVIDER", "torrentio").to_s.downcase + %w[aiostreams auto].include?(setting) && Streams::AioStreamsProvider.configured? end # All origins from which the resolver may follow a provider URL. def resolve_base_urls urls = [ Streams::TorrentioProvider::BASE_URL, "https://torrentio.strem.fun" ] setting = ENV.fetch("STREAM_PROVIDER", "torrentio").to_s.downcase - urls.unshift(CometService.comet_url) if %w[comet auto].include?(setting) && CometService.comet_url.present? + + if %w[comet auto].include?(setting) && CometService.comet_url.present? + urls.unshift(CometService.comet_url) + end + if %w[aiostreams auto].include?(setting) && Streams::AioStreamsProvider.configured? + urls.unshift(Streams::AioStreamsProvider.base_url) + end urls.uniq end + + # Hosts a provider is allowed to serve the final media from. RealDebrid and + # TorBox CDN hosts are recognised by ResolvedSource itself; these cover + # addons that proxy playback (Comet/AIOStreams) plus explicit operator + # additions. + def source_hosts + urls = [ Streams::AioStreamsProvider.base_url, CometService.comet_url ] + urls.concat(ENV.fetch("STREAM_SOURCE_HOSTS", "").split(",").map(&:strip)) + urls.filter_map do |value| + text = value.to_s.strip + next nil if text.blank? + + URI.parse(text).host || (text unless text.include?("://") || text.include?("/")) + rescue URI::InvalidURIError + nil + end.uniq + end + + def comet_provider(api_key, service) + return nil if CometService.comet_url.blank? + + CometService.new(api_key: api_key, debrid_service: service) + end + + def aiostreams_provider + return nil unless Streams::AioStreamsProvider.configured? + + Streams::AioStreamsProvider.new + end end diff --git a/app/services/streams/aio_streams_provider.rb b/app/services/streams/aio_streams_provider.rb new file mode 100644 index 0000000..53f7773 --- /dev/null +++ b/app/services/streams/aio_streams_provider.rb @@ -0,0 +1,138 @@ +# frozen_string_literal: true + +# Stream provider for AIOStreams (https://github.com/Viren070/AIOStreams). +# +# AIOStreams is a Stremio addon aggregator: an operator configures the +# sources and debrid services once and installs the generated addon URL. +# The install link is the manifest URL, for example: +# +# https://aiostreams.example.com/stremio//manifest.json +# +# Set AIOSTREAMS_URL to that install link (or its base without +# /manifest.json). Streams are requested at: +# +# /stream/{movie|series}/{imdb_id}.json +# +# AIOStreams may proxy playback through its own host or redirect to the +# configured debrid CDN; both are accepted by the resolver as long as the +# returned link is HTTPS and comes from the AIOStreams host or a trusted +# source host. +module Streams + class AioStreamsProvider + REQUEST_TIMEOUT = 30 + OPEN_TIMEOUT = 5 + + def self.base_url + raw = ENV.fetch("AIOSTREAMS_URL", "").to_s.strip + return "" if raw.blank? + + # Strip trailing slashes first so a pasted install link that ends in + # "/manifest.json/" normalises too; otherwise the manifest suffix + # survives and every stream request below it 404s. + raw.sub(%r{/+\z}, "").sub(%r{/+manifest\.json\z}, "") + end + + def self.configured? + base_url.present? + end + + def self.proxy_url + ENV.fetch("AIOSTREAMS_PROXY", "") + end + + def initialize(connection: nil, parser: ReleaseParser.new, logger: Rails.logger) + @parser = parser + @logger = logger + @connection = connection || Faraday.new(url: self.class.base_url) do |faraday| + faraday.request :json + faraday.response :json + faraday.response :follow_redirects + faraday.adapter Faraday.default_adapter + faraday.options.timeout = REQUEST_TIMEOUT + faraday.options.open_timeout = OPEN_TIMEOUT + faraday.proxy = self.class.proxy_url if self.class.proxy_url.present? + end + end + + def streams(imdb_id, type, season: nil, episode: nil, title: nil, preferred_languages: nil, default_language: nil) + return ServiceResult.failure("IMDB ID is required") if imdb_id.blank? + return ServiceResult.failure("AIOStreams URL not configured") unless self.class.configured? + + path = stream_path(imdb_id, type, season: season, episode: episode) + return ServiceResult.failure("Season and episode are required for a series") if path.nil? + + response = @connection.get(path) + + if response.success? && response.body.is_a?(Hash) && response.body["streams"] + candidates = Array(response.body["streams"]).filter_map { |stream| parse(stream) } + ranked = Ranker.new( + default_language: default_language, + preferred_languages: preferred_languages + ).call(candidates) + ServiceResult.success(ranked) + elsif response.status == 404 + ServiceResult.success([]) + else + @logger.error("[Streams::AioStreamsProvider] HTTP #{response.status}") + ServiceResult.failure("Failed to fetch streams from AIOStreams (HTTP #{response.status})") + end + rescue Faraday::TimeoutError + ServiceResult.failure("AIOStreams stream request timed out") + rescue Faraday::ConnectionFailed + ServiceResult.failure("Could not connect to AIOStreams") + rescue StandardError => e + @logger.error("[Streams::AioStreamsProvider] #{e.class}: #{e.message}") + ServiceResult.failure("An unexpected error occurred") + end + + private + + def stream_path(imdb_id, type, season:, episode:) + if type.to_s.in?(%w[show series]) + # A series request without coordinates must not silently become a + # movie request for the same IMDb ID. + return nil if season.blank? || episode.blank? + + return "stream/series/#{imdb_id}:#{season}:#{episode}.json" + end + + "stream/movie/#{imdb_id}.json" + end + + def parse(stream) + return nil unless stream.is_a?(Hash) + + url = stream["url"].to_s + return nil if url.blank? + + name = stream["name"].to_s + description = stream["description"].to_s + hints = stream["behaviorHints"] || {} + filename = hints["filename"].to_s + title = filename.presence || name.presence || description + attributes = @parser.analyze(title: title, filename: filename.presence || description) + size = hints["videoSize"] || @parser.size_bytes(description) || attributes[:raw_size] + info_hash = hints["bingeGroup"].to_s.split("|").last.presence || stream["infoHash"] + + StreamCandidate.new( + title: title, + info_hash: info_hash, + file_idx: stream["fileIdx"], + name: name, + quality: @parser.quality(name.presence || title), + seeders: stream["seeders"].to_i, + size: @parser.format_size(size), + raw_size: size, + rd_plus: name.include?("⚡") || description.include?("⚡"), + filename: filename, + resolve_url: url, + languages: @parser.languages(description.presence || title), + video_codec: attributes[:video_codec], + audio_codec: attributes[:audio_codec], + container: attributes[:container], + compatibility_score: attributes[:compatibility_score], + provider: self.class.name + ) + end + end +end diff --git a/app/services/streams/resolver.rb b/app/services/streams/resolver.rb index fda3748..a1000cd 100644 --- a/app/services/streams/resolver.rb +++ b/app/services/streams/resolver.rb @@ -16,7 +16,7 @@ def initialize(user, available_streams: AvailableStreamsService.new(user), logge end def start(content_ref) - return ServiceResult.failure("RealDebrid API key not configured") unless @user.has_realdebrid_key? + return ServiceResult.failure(missing_key_message) unless debrid_access? streams_result = available(content_ref) return streams_result if streams_result.failure? @@ -26,7 +26,7 @@ def start(content_ref) end def resolve(candidate, content_ref:, duration: nil) - return ServiceResult.failure("RealDebrid API key not configured") unless @user.has_realdebrid_key? + return ServiceResult.failure(missing_key_message) unless debrid_access? selected = StreamCandidate.from(candidate) resolved = playback_safe_alternative(selected, content_ref, duration) if oversized_transcode_source?(selected, duration) @@ -161,7 +161,31 @@ def resolve_candidate(candidate) source && { source: source, stream: candidate } end + # A shared AIOStreams instance already holds its own debrid credentials; + # Torrentio and Comet need a key for the account's selected service. + def debrid_access? + @user.debrid_configured? || StreamProvider.keyless_provider_available? + end + + def missing_key_message + label = @user.respond_to?(:debrid_service_label) ? @user.debrid_service_label : "Debrid" + "#{label} API key not configured" + end + + # AIOStreams and some addons return the final debrid CDN link directly + # instead of an addon URL that redirects to it. Accept a direct link when + # its host is a trusted debrid host, so it does not fail the origin + # allowlist check for provider endpoints. + def direct_debrid_source(value) + source = ResolvedSource.new(url: value) + source if source.service.present? + rescue ResolvedSource::Invalid + nil + end + def resolve_url(resolve_url) + direct = direct_debrid_source(resolve_url) + return direct if direct return unless allowed_resolve_url?(resolve_url) response = with_retries { connection_for(resolve_url).get(resolve_url) } @@ -183,7 +207,7 @@ def success(resolved, content_ref) candidate = resolved.fetch(:stream) source = resolved.fetch(:source) filename = candidate.filename.presence || source.filename - source = ResolvedSource.new(url: source.url, filename: filename) + source = ResolvedSource.new(url: source.url, filename: filename, service: source.service) ServiceResult.success({ source: source, stream: candidate.merge(filename: filename), @@ -222,6 +246,9 @@ def allowed_origins def connection_for(resolve_url) return direct_connection if CometService.comet_url.present? && resolve_url.start_with?(CometService.comet_url) + if Streams::AioStreamsProvider.configured? && resolve_url.start_with?(Streams::AioStreamsProvider.base_url) + return aiostreams_connection + end @proxy_connection ||= Faraday.new do |faraday| faraday.adapter Faraday.default_adapter @@ -238,5 +265,14 @@ def direct_connection faraday.options.open_timeout = 5 end end + + def aiostreams_connection + @aiostreams_connection ||= Faraday.new do |faraday| + faraday.adapter Faraday.default_adapter + faraday.options.timeout = 15 + faraday.options.open_timeout = 5 + faraday.proxy = Streams::AioStreamsProvider.proxy_url if Streams::AioStreamsProvider.proxy_url.present? + end + end end end diff --git a/app/services/streams/torrentio_provider.rb b/app/services/streams/torrentio_provider.rb index c05f0c5..76af77b 100644 --- a/app/services/streams/torrentio_provider.rb +++ b/app/services/streams/torrentio_provider.rb @@ -6,8 +6,11 @@ class TorrentioProvider REQUEST_TIMEOUT = 30 OPEN_TIMEOUT = 5 - def initialize(rd_api_key: nil, connection: nil, parser: ReleaseParser.new, logger: Rails.logger) - @rd_api_key = rd_api_key + def initialize(rd_api_key: nil, api_key: nil, debrid_service: "realdebrid", connection: nil, parser: ReleaseParser.new, logger: Rails.logger) + @api_key = api_key.presence || rd_api_key + # Keep the old accessor name for callers that still pass rd_api_key. + @rd_api_key = @api_key + @debrid_service = debrid_service.to_s.presence || "realdebrid" @parser = parser @logger = logger @connection = connection || Faraday.new(url: BASE_URL) do |faraday| @@ -51,7 +54,7 @@ def streams(imdb_id, type, season: nil, episode: nil, title: nil, preferred_lang private def stream_path(imdb_id, type, season:, episode:) - prefix = @rd_api_key.present? ? "/realdebrid=#{@rd_api_key}" : "" + prefix = @api_key.present? ? "/#{@debrid_service}=#{@api_key}" : "" content = if type.to_s.in?(%w[show series]) && season && episode "series/#{imdb_id}:#{season}:#{episode}" else @@ -88,7 +91,7 @@ def rewritten_resolve_url(url) end def redacted(path) - @rd_api_key.present? ? path.to_s.gsub(@rd_api_key, "[REDACTED]") : path + @api_key.present? ? path.to_s.gsub(@api_key, "[REDACTED]") : path end end end diff --git a/app/services/tor_box_service.rb b/app/services/tor_box_service.rb new file mode 100644 index 0000000..b3dd4d0 --- /dev/null +++ b/app/services/tor_box_service.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +# Minimal TorBox client. Stream resolution goes through the configured +# provider (Torrentio/Comet/AIOStreams), which embeds the TorBox key and +# returns a direct CDN link; this client verifies the key an account or an +# administrator enters. +class TorBoxService + BASE_URL = ENV.fetch("TORBOX_API_BASE_URL", "https://api.torbox.app/v1/api") + + def initialize(api_key) + @conn = Faraday.new(url: BASE_URL) do |faraday| + faraday.response :json + faraday.adapter Faraday.default_adapter + faraday.options.timeout = 30 + faraday.options.open_timeout = 10 + faraday.headers["Authorization"] = "Bearer #{api_key}" + end + end + + def verify_key + response = @conn.get("user/me") + return ServiceResult.success(response.body) if response.success? && response.body.is_a?(Hash) && response.body["success"] != false + + ServiceResult.failure(parse_error(response), response.status) + rescue Faraday::TimeoutError + ServiceResult.failure("Request timed out") + rescue Faraday::ConnectionFailed + ServiceResult.failure("Could not connect to TorBox") + rescue StandardError => e + Rails.logger.error("TorBoxService#verify_key error: #{e.class}: #{e.message}") + ServiceResult.failure("Failed to verify API key") + end + + private + + def parse_error(response) + return "Request failed with status #{response.status}" unless response.body.is_a?(Hash) + + # `error` is a machine-readable code; `detail` is the user-facing message + # (see https://api-docs.torbox.app). Prefer the readable one. + response.body["detail"].presence || response.body["error"].presence || + "Request failed with status #{response.status}" + end +end diff --git a/app/views/admin/settings/show.html.erb b/app/views/admin/settings/show.html.erb new file mode 100644 index 0000000..efb71fa --- /dev/null +++ b/app/views/admin/settings/show.html.erb @@ -0,0 +1,54 @@ +
+
+
+

Team settings

+

Installation-wide debrid keys. Accounts use their own key first, then these, then the environment.

+
+ <%= link_to "Back to settings", settings_path, class: "text-sm text-sv-accent" %> +
+ + <%= form_with model: @settings, url: admin_settings_path, method: :patch, class: "space-y-6" do |f| %> + <% if @settings.errors.any? %> +
+
    + <% @settings.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> + +
+

RealDebrid

+

Used by accounts that have not entered their own RealDebrid key.

+ + <%= f.label :realdebrid_api_key, "Team API key", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> + <%= f.password_field :realdebrid_api_key, class: "input-field", value: "", placeholder: "Enter the team RealDebrid API key" %> + <% if @settings.realdebrid_api_key.present? %> +

A team RealDebrid key is set. Leave the field blank to keep it.

+ <% else %> +

No team RealDebrid key is set.

+ <% end %> +
+ +
+

TorBox

+

Used by accounts that select TorBox and have not entered their own TorBox key.

+ + <%= f.label :torbox_api_key, "Team API key", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> + <%= f.password_field :torbox_api_key, class: "input-field", value: "", placeholder: "Enter the team TorBox API key" %> + <% if @settings.torbox_api_key.present? %> +

A team TorBox key is set. Leave the field blank to keep it.

+ <% else %> +

No team TorBox key is set.

+ <% end %> +
+ +
+

Environment fallback

+

If no team key is set, REALDEBRID_API_KEY and TORBOX_API_KEY from the environment are used. Environment values are never shown here.

+
+ + <%= f.submit "Save team keys", class: "btn-primary cursor-pointer" %> + <% end %> +
diff --git a/app/views/content/show.html.erb b/app/views/content/show.html.erb index 326670a..ea4831a 100644 --- a/app/views/content/show.html.erb +++ b/app/views/content/show.html.erb @@ -133,8 +133,8 @@ <% else %>

No streams available for this content.

- <% unless current_user.has_realdebrid_key? %> -

Add your RealDebrid API key in <%= link_to "Settings", settings_path, class: "text-sv-accent" %> to enable streaming.

+ <% unless debrid_access_configured? %> +

Add a debrid API key in <%= link_to "Settings", settings_path, class: "text-sv-accent" %> to enable streaming, or ask an administrator for a team key.

<% end %>
<% end %> diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb index a622ffd..9eb28d0 100644 --- a/app/views/home/index.html.erb +++ b/app/views/home/index.html.erb @@ -9,9 +9,9 @@ <% end %> - <% unless current_user.has_realdebrid_key? %> + <% unless debrid_access_configured? %>
-

Welcome to StreamVault! Add your RealDebrid API key in <%= link_to "Settings", settings_path, class: "text-sv-accent font-medium hover:underline" %> to start streaming.

+

Welcome to StreamVault! Add a RealDebrid or TorBox API key in <%= link_to "Settings", settings_path, class: "text-sv-accent font-medium hover:underline" %> to start streaming, or ask an administrator for a team key.

<% end %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index bc12d3f..7e31c09 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -93,6 +93,15 @@ Settings <% end %> + + <% if current_user.admin? %> + <%= link_to admin_settings_path, class: "sidebar-link" do %> + + + + Team + <% end %> + <% end %> <%# User info %> diff --git a/app/views/settings/show.html.erb b/app/views/settings/show.html.erb index a48b99b..0b59bb5 100644 --- a/app/views/settings/show.html.erb +++ b/app/views/settings/show.html.erb @@ -40,20 +40,63 @@
-

RealDebrid

+

Debrid

+

Pick the debrid service you prefer; its streams are listed first. When keys for both services are available, both are queried and their streams merged, so you get more results to choose from. Your own API key takes precedence; if you leave it blank, the team key set by an administrator (or in the environment) is used.

- <%= f.label :realdebrid_api_key, "API Key", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> + <%= f.label :debrid_service, "Preferred service", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> + <%= f.select :debrid_service, + options_for_select(User::DEBRID_SERVICES.map { |value, label| [ label, value ] }, @user.effective_debrid_service), + {}, + class: "input-field w-auto" %> +
+ +
+ <%= f.label :realdebrid_api_key, "RealDebrid API key", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> <%= f.password_field :realdebrid_api_key, class: "input-field", placeholder: "Enter your RealDebrid API key", value: "" %>

Get your API key from real-debrid.com/apitoken

+ <% if @user.realdebrid_api_key.present? %> +

Your RealDebrid key is saved.

+ <% elsif @user.effective_realdebrid_api_key.present? %> +

Using the team RealDebrid key.

+ <% else %> +

No RealDebrid key configured.

+ <% end %>
- <% if @user.has_realdebrid_key? %> -
- - API key configured -
- <% end %> +
+ <%= f.label :torbox_api_key, "TorBox API key", class: "block text-sm font-medium text-sv-text-muted mb-1.5" %> + <%= f.password_field :torbox_api_key, class: "input-field", placeholder: "Enter your TorBox API key", value: "" %> +

Get your API key from torbox.app/settings

+ <% if @user.torbox_api_key.present? %> +

Your TorBox key is saved.

+ <% elsif @user.effective_torbox_api_key.present? %> +

Using the team TorBox key.

+ <% else %> +

No TorBox key configured.

+ <% end %> +
+ +
+ Preferred service: <%= @user.debrid_service_label %>. + <% extra = @user.debrid_credentials.map(&:first) - [ @user.effective_debrid_service ] %> + <% if extra.any? %> + Streams from <%= extra.map { |service| User::DEBRID_SERVICES.fetch(service, service) }.to_sentence %> are merged in. + <% end %> + <% source = @user.debrid_key_source %> + <% if source == :user %> + Using your own key. + <% elsif source == :global %> + Using the administrator's team key. + <% elsif source == :environment %> + Using the installation key from the environment. + <% else %> + No key available for this service. + <% end %> + <% if @user.admin? %> +
<%= link_to "Manage team keys", admin_settings_path, class: "text-sv-accent" %>
+ <% end %> +
diff --git a/app/views/streaming/show.html.erb b/app/views/streaming/show.html.erb index 0f86d6d..2495af7 100644 --- a/app/views/streaming/show.html.erb +++ b/app/views/streaming/show.html.erb @@ -172,6 +172,21 @@
+ <%# Transcode quality: auto keeps the server default (CRF, 1080p cap); + a fixed rung caps resolution and bitrate on slow connections. %> + + <%# Fullscreen %>