Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[networking] Add response extensions for impersonate info #9756

Merged
merged 11 commits into from
May 4, 2024
19 changes: 19 additions & 0 deletions test/test_networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,25 @@ def test_supported_impersonate_targets(self, handler):
assert res.status == 200
assert std_headers['user-agent'].lower() not in res.read().decode().lower()

def test_response_extensions(self, handler):
with handler() as rh:
for target in rh.supported_targets:
request = Request(
f'http://127.0.0.1:{self.http_port}/gen_200', extensions={'impersonate': target})
res = validate_and_send(rh, request)
assert res.extensions['impersonate'] == rh._get_request_target(request)

def test_http_error_response_extensions(self, handler):
with handler() as rh:
for target in rh.supported_targets:
request = Request(
f'http://127.0.0.1:{self.http_port}/gen_404', extensions={'impersonate': target})
try:
validate_and_send(rh, request)
except HTTPError as e:
res = e.response
assert res.extensions['impersonate'] == rh._get_request_target(request)


class TestRequestHandlerMisc:
"""Misc generic tests for request handlers, not related to request or validation testing"""
Expand Down
9 changes: 9 additions & 0 deletions yt_dlp/networking/_curlcffi.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,15 @@ def _check_extensions(self, extensions):
extensions.pop('cookiejar', None)
extensions.pop('timeout', None)

def send(self, request: Request) -> Response:
try:
response = super().send(request)
except HTTPError as e:
e.response.extensions['impersonate'] = self._get_request_target(request)
raise
response.extensions['impersonate'] = self._get_request_target(request)
return response

def _send(self, request: Request):
max_redirects_exceeded = False
session: curl_cffi.requests.Session = self._get_instance(
Expand Down
1 change: 1 addition & 0 deletions yt_dlp/networking/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@ def __init__(
self.reason = reason or HTTPStatus(status).phrase
except ValueError:
self.reason = None
self.extensions = {}
bashonly marked this conversation as resolved.
Show resolved Hide resolved

def readable(self):
return self.fp.readable()
Expand Down