diff --git a/config/config.example.yml b/config/config.example.yml index f5beaf81..5d14749d 100644 --- a/config/config.example.yml +++ b/config/config.example.yml @@ -54,6 +54,43 @@ db: ## #signature_server: +## +## Invidious companion is an external program +## for loading the video streams from YouTube servers. +## +## When this setting is commented out, Invidious companion is not used. +## Otherwise, Invidious will proxy the requests to Invidious companion. +## +## Note: multiple URL can be configured. In this case, invidious will +## randomly pick one every time video data needs to be retrieved. This +## URL is then kept in the video metadata cache to allow video playback +## to work. Once said cache has expired, requesting that video's data +## again will cause a new companion URL to be picked. +## +## The parameter private_url needs to be configured for the internal +## communication between the companion and Invidious. +## And public_url is the public URL from which companion is listening +## to the requests from the user(s). +## Both parameter can have identical URL when Invidious is hosted in +## an internal network or at home. +## +## Accepted values: "http(s)://:" +## Default: +## +#invidious_companion: +# - private_url: "http://localhost:8282" +# public_url: "http://localhost:8282" + +## +## API key for Invidious companion +## +## Needed when invidious_companion is configured +## +## Accepted values: "http(s)://:" +## Default: +## + +#invidious_companion_key: "CHANGE_ME!!" ######################################### # diff --git a/src/invidious/config.cr b/src/invidious/config.cr index 718a262b..cacc081b 100644 --- a/src/invidious/config.cr +++ b/src/invidious/config.cr @@ -67,6 +67,16 @@ end class Config include YAML::Serializable + class CompanionConfig + include YAML::Serializable + + @[YAML::Field(converter: Preferences::URIConverter)] + property private_url : URI = URI.parse("") + + @[YAML::Field(converter: Preferences::URIConverter)] + property public_url : URI = URI.parse("") + end + # Number of threads to use for crawling videos from channels (for updating subscriptions) property channel_threads : Int32 = 1 # Time interval between two executions of the job that crawls channel videos (subscriptions update). @@ -175,6 +185,12 @@ class Config # poToken for passing bot attestation property po_token : String? = nil + # Invidious companion + property invidious_companion : Array(CompanionConfig) = [] of CompanionConfig + + # Invidious companion API key + property invidious_companion_key : String = "" + # Saved cookies in "name1=value1; name2=value2..." format @[YAML::Field(converter: Preferences::StringToCookies)] property cookies : HTTP::Cookies = HTTP::Cookies.new @@ -330,6 +346,21 @@ class Config end {% end %} + if !config.invidious_companion.empty? + # invidious_companion and signature_server can't work together + if config.signature_server + puts "Config: You can not run inv_sig_helper and invidious_companion at the same time." + exit(1) + end + if config.invidious_companion_key.empty? + puts "Config: Please configure a key if you are using invidious companion." + exit(1) + elsif config.invidious_companion_key == "CHANGE_ME!!" + puts "Config: The value of 'invidious_companion_key' needs to be changed!!" + exit(1) + end + end + # HMAC_key is mandatory # See: https://github.com/iv-org/invidious/issues/3854 if config.hmac_key.empty? diff --git a/src/invidious/routes/api/manifest.cr b/src/invidious/routes/api/manifest.cr index c353ea75..a7ca6235 100644 --- a/src/invidious/routes/api/manifest.cr +++ b/src/invidious/routes/api/manifest.cr @@ -8,6 +8,11 @@ module Invidious::Routes::API::Manifest id = env.params.url["id"] region = env.params.query["region"]? + if !CONFIG.invidious_companion.empty? + invidious_companion = CONFIG.invidious_companion.sample + return env.redirect "#{invidious_companion.public_url}/api/manifest/dash/id/#{id}?#{env.params.query}" + end + # Since some implementations create playlists based on resolution regardless of different codecs, # we can opt to only add a source to a representation if it has a unique height within that representation unique_res = env.params.query["unique_res"]?.try { |q| (q == "true" || q == "1").to_unsafe } diff --git a/src/invidious/routes/embed.cr b/src/invidious/routes/embed.cr index 00f24159..49aeade5 100644 --- a/src/invidious/routes/embed.cr +++ b/src/invidious/routes/embed.cr @@ -203,6 +203,13 @@ module Invidious::Routes::Embed return env.redirect url end + if companion_base_url = video.invidious_companion.try &.["baseUrl"].as_s + env.response.headers["Content-Security-Policy"] = + env.response.headers["Content-Security-Policy"] + .gsub("media-src", "media-src #{companion_base_url}") + .gsub("connect-src", "connect-src #{companion_base_url}") + end + rendered "embed" end end diff --git a/src/invidious/routes/video_playback.cr b/src/invidious/routes/video_playback.cr index d301d2e5..338f8faf 100644 --- a/src/invidious/routes/video_playback.cr +++ b/src/invidious/routes/video_playback.cr @@ -258,6 +258,11 @@ module Invidious::Routes::VideoPlayback # YouTube /videoplayback links expire after 6 hours, # so we have a mechanism here to redirect to the latest version def self.latest_version(env) + if !CONFIG.invidious_companion.empty? + invidious_companion = CONFIG.invidious_companion.sample + return env.redirect "#{invidious_companion.public_url}/latest_version?#{env.params.query}" + end + id = env.params.query["id"]? itag = env.params.query["itag"]?.try &.to_i? diff --git a/src/invidious/routes/watch.cr b/src/invidious/routes/watch.cr index 10a851ff..9417a7b7 100644 --- a/src/invidious/routes/watch.cr +++ b/src/invidious/routes/watch.cr @@ -347,14 +347,18 @@ module Invidious::Routes::Watch env.params.query["label"] = URI.decode_www_form(label.as_s) return Invidious::Routes::API::V1::Videos.captions(env) - elsif itag = download_widget["itag"]?.try &.as_i + elsif itag = download_widget["itag"]?.try &.as_i.to_s # URL params specific to /latest_version env.params.query["id"] = video_id - env.params.query["itag"] = itag.to_s env.params.query["title"] = filename env.params.query["local"] = "true" - return Invidious::Routes::VideoPlayback.latest_version(env) + if (!CONFIG.invidious_companion.empty?) + video = get_video(video_id) + return env.redirect "#{video.invidious_companion["baseUrl"].as_s}/latest_version?#{env.params.query}" + else + return Invidious::Routes::VideoPlayback.latest_version(env) + end else return error_template(400, "Invalid label or itag") end diff --git a/src/invidious/videos.cr b/src/invidious/videos.cr index c6e69ee5..4a1dcb50 100644 --- a/src/invidious/videos.cr +++ b/src/invidious/videos.cr @@ -15,7 +15,7 @@ struct Video # NOTE: don't forget to bump this number if any change is made to # the `params` structure in videos/parser.cr!!! # - SCHEMA_VERSION = 2 + SCHEMA_VERSION = 3 property id : String @@ -192,6 +192,10 @@ struct Video } end + def invidious_companion : Hash(String, JSON::Any)? + info["invidiousCompanion"]?.try &.as_h || {} of String => JSON::Any + end + # Macros defining getters/setters for various types of data private macro getset_string(name) diff --git a/src/invidious/videos/parser.cr b/src/invidious/videos/parser.cr index a670ac36..7b6cb333 100644 --- a/src/invidious/videos/parser.cr +++ b/src/invidious/videos/parser.cr @@ -105,7 +105,8 @@ def extract_video_info(video_id : String) params = parse_video_info(video_id, player_response) params["reason"] = JSON::Any.new(reason) if reason - new_player_response = nil + if !CONFIG.invidious_companion.empty? + new_player_response = nil # Don't use Android test suite client if po_token is passed because po_token doesn't # work for Android test suite client. @@ -118,17 +119,18 @@ def extract_video_info(video_id : String) new_player_response = try_fetch_streaming_data(video_id, client_config) end - # Replace player response and reset reason - if !new_player_response.nil? - # Preserve captions & storyboard data before replacement - new_player_response["storyboards"] = player_response["storyboards"] if player_response["storyboards"]? - new_player_response["captions"] = player_response["captions"] if player_response["captions"]? + # Replace player response and reset reason + if !new_player_response.nil? + # Preserve captions & storyboard data before replacement + new_player_response["storyboards"] = player_response["storyboards"] if player_response["storyboards"]? + new_player_response["captions"] = player_response["captions"] if player_response["captions"]? - player_response = new_player_response - params.delete("reason") + player_response = new_player_response + params.delete("reason") + end end - {"captions", "playabilityStatus", "playerConfig", "storyboards"}.each do |f| + {"captions", "playabilityStatus", "playerConfig", "storyboards", "invidiousCompanion"}.each do |f| params[f] = player_response[f] if player_response[f]? end diff --git a/src/invidious/views/components/player.ecr b/src/invidious/views/components/player.ecr index 5c28358b..975a25be 100644 --- a/src/invidious/views/components/player.ecr +++ b/src/invidious/views/components/player.ecr @@ -22,6 +22,7 @@ audio_streams.each_with_index do |fmt, i| src_url = "/latest_version?id=#{video.id}&itag=#{fmt["itag"]}" src_url += "&local=true" if params.local + src_url = video.invidious_companion["baseUrl"].as_s + src_url if (!CONFIG.invidious_companion.empty?) bitrate = fmt["bitrate"] mimetype = HTML.escape(fmt["mimeType"].as_s) @@ -34,8 +35,11 @@ <% end %> <% end %> <% else %> - <% if params.quality == "dash" %> - + <% if params.quality == "dash" + src_url = "/api/manifest/dash/id/" + video.id + "?local=true&unique_res=1" + src_url = video.invidious_companion["baseUrl"].as_s + src_url if (!CONFIG.invidious_companion.empty?) + %> + <% end %> <% @@ -44,6 +48,7 @@ fmt_stream.each_with_index do |fmt, i| src_url = "/latest_version?id=#{video.id}&itag=#{fmt["itag"]}" src_url += "&local=true" if params.local + src_url = video.invidious_companion["baseUrl"].as_s + src_url if (!CONFIG.invidious_companion.empty?) quality = fmt["quality"] mimetype = HTML.escape(fmt["mimeType"].as_s) diff --git a/src/invidious/yt_backend/youtube_api.cr b/src/invidious/yt_backend/youtube_api.cr index beb3f821..db776c67 100644 --- a/src/invidious/yt_backend/youtube_api.cr +++ b/src/invidious/yt_backend/youtube_api.cr @@ -491,7 +491,11 @@ module YoutubeAPI data["params"] = params end - return self._post_json("/youtubei/v1/player", data, client_config) + if !CONFIG.invidious_companion.empty? + return self._post_invidious_companion("/youtubei/v1/player", data) + else + return self._post_json("/youtubei/v1/player", data, client_config) + end end #################################################################### @@ -657,6 +661,51 @@ module YoutubeAPI return initial_data end + #################################################################### + # _post_invidious_companion(endpoint, data) + # + # Internal function that does the actual request to Invidious companion + # and handles errors. + # + # The requested data is an endpoint (URL without the domain part) + # and the data as a Hash object. + # + def _post_invidious_companion( + endpoint : String, + data : Hash + ) : Hash(String, JSON::Any) + headers = HTTP::Headers{ + "Content-Type" => "application/json; charset=UTF-8", + "Authorization" => "Bearer #{CONFIG.invidious_companion_key}", + } + + # Logging + LOGGER.debug("Invidious companion: Using endpoint: \"#{endpoint}\"") + LOGGER.trace("Invidious companion: POST data: #{data}") + + # Send the POST request + + begin + invidious_companion = CONFIG.invidious_companion.sample + response = make_client(invidious_companion.private_url, + &.post(endpoint, headers: headers, body: data.to_json)) + body = response.body + if (response.status_code != 200) + raise Exception.new( + "Error while communicating with Invidious companion: \ + status code: #{response.status_code} and body: #{body.dump}" + ) + end + rescue ex + raise InfoException.new("Error while communicating with Invidious companion: " + (ex.message || "no extra info found")) + end + + # Convert result to Hash + initial_data = JSON.parse(body).as_h + + return initial_data + end + #################################################################### # _decompress(body_io, headers) #