initial support for base_url with invidious companion + proxy invidious_companion

This commit is contained in:
Emilien
2025-05-03 01:10:12 +02:00
committed by Émilien (perso)
parent 89c8b1b901
commit 324a416fd4
7 changed files with 103 additions and 29 deletions

View File

@@ -46,8 +46,22 @@ struct YoutubeConnectionPool
end
end
class CompanionWrapper
property client : HTTP::Client
property companion : Config::CompanionConfig
def initialize(companion : Config::CompanionConfig)
@companion = companion
@client = HTTP::Client.new(companion.private_url)
end
def close
@client.close
end
end
struct CompanionConnectionPool
property pool : DB::Pool(HTTP::Client)
property pool : DB::Pool(CompanionWrapper)
def initialize(capacity = 5, timeout = 5.0)
options = DB::Pool::Options.new(
@@ -57,26 +71,28 @@ struct CompanionConnectionPool
checkout_timeout: timeout
)
@pool = DB::Pool(HTTP::Client).new(options) do
@pool = DB::Pool(CompanionWrapper).new(options) do
companion = CONFIG.invidious_companion.sample
next make_client(companion.private_url, use_http_proxy: false)
client = make_client(companion.private_url, use_http_proxy: false)
CompanionWrapper.new(companion: companion)
end
end
def client(&)
conn = pool.checkout
wrapper = pool.checkout
begin
response = yield conn
response = yield wrapper
rescue ex
conn.close
wrapper.client.close
companion = CONFIG.invidious_companion.sample
conn = make_client(companion.private_url, use_http_proxy: false)
client = make_client(companion.private_url, use_http_proxy: false)
wrapper = CompanionWrapper.new(companion: companion)
response = yield conn
response = yield wrapper
ensure
pool.release(conn)
pool.release(wrapper)
end
response

View File

@@ -701,22 +701,28 @@ module YoutubeAPI
# Send the POST request
begin
response = COMPANION_POOL.client &.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}"
)
response_body = ""
COMPANION_POOL.client do |wrapper|
companion_base_url = wrapper.companion.private_url.path
puts "Using companion: #{wrapper.companion.private_url}"
response = wrapper.client.post(companion_base_url + endpoint, headers: headers, body: data.to_json)
response_body = response.body
if response.status_code != 200
raise Exception.new(
"Error while communicating with Invidious companion: " \
"status code: #{response.status_code} and body: #{response_body.dump}"
)
end
end
# Convert result to Hash
return JSON.parse(response_body).as_h
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
####################################################################