1
0
Fork 0
mirror of https://github.com/yt-dlp/yt-dlp.git synced 2025-03-09 12:50:23 -05:00
yt-dlp/yt_dlp/jsinterp/_deno.py

209 lines
8.4 KiB
Python
Raw Normal View History

2024-12-30 04:52:47 -06:00
from __future__ import annotations
import http.cookiejar
import json
import subprocess
import typing
import urllib.parse
from ..utils import (
ExtractorError,
Popen,
classproperty,
int_or_none,
shell_quote,
unified_timestamp,
)
2024-12-31 03:34:27 -06:00
from ._helper import TempFileWrapper, random_string, override_navigator_js, extract_script_tags
2024-12-30 04:52:47 -06:00
from .common import ExternalJSI, register_jsi
@register_jsi
class DenoJSI(ExternalJSI):
"""JS interpreter class using Deno binary"""
2025-01-11 12:34:38 -06:00
_SUPPORTED_FEATURES = {'wasm', 'location'}
2024-12-30 04:52:47 -06:00
_BASE_PREFERENCE = 5
_EXE_NAME = 'deno'
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check']
_INIT_SCRIPT = 'localStorage.clear(); delete window.Deno; global = window;\n'
2024-12-30 16:09:47 -06:00
def __init__(self, *args, flags=[], replace_flags=False, init_script=None, **kwargs):
super().__init__(*args, **kwargs)
2024-12-30 04:52:47 -06:00
self._flags = flags if replace_flags else [*self._DENO_FLAGS, *flags]
self._init_script = self._INIT_SCRIPT if init_script is None else init_script
2024-12-30 16:09:47 -06:00
@property
def _override_navigator_js(self):
2024-12-31 03:34:27 -06:00
return override_navigator_js(self.user_agent)
2024-12-30 16:09:47 -06:00
2024-12-30 04:52:47 -06:00
def _run_deno(self, cmd):
self.write_debug(f'Deno command line: {shell_quote(cmd)}')
try:
stdout, stderr, returncode = Popen.run(
cmd, timeout=self.timeout, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
raise ExtractorError('Unable to run Deno binary', cause=e)
if returncode:
raise ExtractorError(f'Failed with returncode {returncode}:\n{stderr}')
elif stderr:
self.report_warning(f'JS console error msg:\n{stderr.strip()}')
return stdout.strip()
2024-12-31 05:25:12 -06:00
def execute(self, jscode, video_id=None, note='Executing JS in Deno'):
2024-12-30 04:52:47 -06:00
self.report_note(video_id, note)
2024-12-31 05:25:12 -06:00
location_args = ['--location', self._url] if self._url else []
2024-12-30 16:09:47 -06:00
with TempFileWrapper(f'{self._init_script};\n{self._override_navigator_js}\n{jscode}', suffix='.js') as js_file:
2024-12-30 04:52:47 -06:00
cmd = [self.exe, 'run', *self._flags, *location_args, js_file.name]
return self._run_deno(cmd)
@register_jsi
class DenoJITlessJSI(DenoJSI):
2025-01-11 12:34:38 -06:00
_SUPPORTED_FEATURES = {'location'}
2024-12-30 04:52:47 -06:00
_BASE_PREFERENCE = 6
_EXE_NAME = DenoJSI._EXE_NAME
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check', '--v8-flags=--jitless,--noexpose-wasm']
@classproperty
def exe_version(cls):
return DenoJSI.exe_version
2024-12-31 12:42:36 -06:00
@register_jsi
2024-12-30 04:52:47 -06:00
class DenoJSDomJSI(DenoJSI):
2025-01-11 12:34:38 -06:00
_SUPPORTED_FEATURES = {'wasm', 'location', 'dom', 'cookies'}
2024-12-30 04:52:47 -06:00
_BASE_PREFERENCE = 4
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check']
_JSDOM_IMPORT_CHECKED = False
2024-12-30 14:53:04 -06:00
_JSDOM_URL = 'https://cdn.esm.sh/jsdom'
2024-12-30 04:52:47 -06:00
@staticmethod
def serialize_cookie(cookiejar: YoutubeDLCookieJar | None, url: str):
"""serialize netscape-compatible fields from cookiejar for tough-cookie loading"""
# JSDOM use tough-cookie as its CookieJar https://github.com/jsdom/jsdom/blob/main/lib/api.js
# tough-cookie use Cookie.fromJSON and Cookie.toJSON for cookie serialization
# https://github.com/salesforce/tough-cookie/blob/master/lib/cookie/cookie.ts
if not cookiejar:
return json.dumps({'cookies': []})
2024-12-30 14:53:04 -06:00
cookies: list[http.cookiejar.Cookie] = list(cookiejar.get_cookies_for_url(url))
2024-12-30 04:52:47 -06:00
return json.dumps({'cookies': [{
'key': cookie.name,
'value': cookie.value,
2024-12-30 14:53:04 -06:00
# leading dot of domain must be removed, otherwise will fail to match
2024-12-30 04:52:47 -06:00
'domain': cookie.domain.lstrip('.') or urllib.parse.urlparse(url).hostname,
'expires': int_or_none(cookie.expires, invscale=1000),
'hostOnly': not cookie.domain_initial_dot,
'secure': bool(cookie.secure),
'path': cookie.path,
} for cookie in cookies if cookie.value]})
@staticmethod
def apply_cookies(cookiejar: YoutubeDLCookieJar | None, cookies: list[dict]):
"""apply cookies from serialized tough-cookie"""
# see serialize_cookie
if not cookiejar:
return
for cookie_dict in cookies:
if not all(cookie_dict.get(k) for k in ('key', 'value', 'domain')):
continue
if cookie_dict.get('hostOnly'):
cookie_dict['domain'] = cookie_dict['domain'].lstrip('.')
else:
cookie_dict['domain'] = '.' + cookie_dict['domain'].lstrip('.')
cookiejar.set_cookie(http.cookiejar.Cookie(
0, cookie_dict['key'], cookie_dict['value'],
None, False,
cookie_dict['domain'], True, not cookie_dict.get('hostOnly'),
cookie_dict.get('path', '/'), True,
bool(cookie_dict.get('secure')),
unified_timestamp(cookie_dict.get('expires')),
False, None, None, {}))
def _ensure_jsdom(self):
if self._JSDOM_IMPORT_CHECKED:
return
2024-12-30 14:53:04 -06:00
with TempFileWrapper(f'import jsdom from "{self._JSDOM_URL}"', suffix='.js') as js_file:
2024-12-30 04:52:47 -06:00
cmd = [self.exe, 'run', js_file.name]
self._run_deno(cmd)
self._JSDOM_IMPORT_CHECKED = True
2024-12-31 12:42:36 -06:00
def execute(self, jscode, video_id=None, note='Executing JS in Deno with jsdom', html='', cookiejar=None):
2024-12-30 04:52:47 -06:00
self.report_note(video_id, note)
self._ensure_jsdom()
2024-12-31 05:25:12 -06:00
if cookiejar and not self._url:
self.report_warning('No valid url scope provided, cookiejar is not applied')
cookiejar = None
2024-12-30 16:09:47 -06:00
2024-12-31 03:34:27 -06:00
html, inline_scripts = extract_script_tags(html)
wrapper_scripts = '\n'.join(['try { %s } catch (e) {}' % script for script in inline_scripts])
2024-12-30 16:09:47 -06:00
2024-12-31 05:25:12 -06:00
callback_varname = f'__callback_{random_string()}'
2024-12-30 04:52:47 -06:00
script = f'''{self._init_script};
2024-12-30 14:53:04 -06:00
import jsdom from "{self._JSDOM_URL}";
2024-12-30 16:54:45 -06:00
let {callback_varname} = (() => {{
2024-12-31 05:25:12 -06:00
const jar = jsdom.CookieJar.deserializeSync({json.dumps(self.serialize_cookie(cookiejar, self._url))});
2024-12-30 04:52:47 -06:00
const dom = new jsdom.JSDOM({json.dumps(str(html))}, {{
2024-12-31 05:25:12 -06:00
{'url: %s,' % json.dumps(str(self._url)) if self._url else ''}
2024-12-30 04:52:47 -06:00
cookieJar: jar,
2024-12-31 12:42:36 -06:00
pretendToBeVisual: true,
}});
2025-01-01 12:33:16 -06:00
Object.keys(dom.window).filter(key => !['atob', 'btoa', 'crypto', 'location'].includes(key))
.filter(key => !(window.location? [] : ['sessionStorage', 'localStorage']).includes(key))
.forEach((key) => {{
try {{window[key] = dom.window[key]}} catch (e) {{ console.error(e) }}
2024-12-30 04:52:47 -06:00
}});
2025-01-01 12:33:16 -06:00
{self._override_navigator_js};
2024-12-31 12:42:36 -06:00
window.screen = {{
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
isExtended: true,
onchange: null,
orientation: {{angle: 0, type: 'landscape-primary', onchange: null}},
pixelDepth: 24,
}}
Object.defineProperty(document.body, 'clientWidth', {{value: 1903}});
2025-01-01 12:33:16 -06:00
Object.defineProperty(document.body, 'clientHeight', {{value: 2000}});
document.domain = location?.hostname;
2024-12-31 12:42:36 -06:00
2024-12-30 04:52:47 -06:00
delete window.jsdom;
2024-12-31 03:34:27 -06:00
const origLog = console.log;
console.log = () => {{}};
console.info = () => {{}};
2024-12-30 16:54:45 -06:00
return () => {{
const stdout = [];
2024-12-31 12:42:36 -06:00
console.log = (...msg) => stdout.push(msg.map(m => '' + m).join(' '));
2024-12-30 16:54:45 -06:00
return () => {{ origLog(JSON.stringify({{
stdout: stdout.join('\\n'), cookies: jar.serializeSync().cookies}})); }}
}}
2024-12-30 04:52:47 -06:00
}})();
2024-12-31 03:34:27 -06:00
{wrapper_scripts}
{callback_varname} = {callback_varname}(); // begin to capture console.log
try {{
2024-12-30 04:52:47 -06:00
{jscode}
2024-12-31 03:34:27 -06:00
}} finally {{
{callback_varname}();
}}
2024-12-30 04:52:47 -06:00
'''
2024-12-31 05:25:12 -06:00
location_args = ['--location', self._url] if self._url else []
2024-12-30 04:52:47 -06:00
with TempFileWrapper(script, suffix='.js') as js_file:
cmd = [self.exe, 'run', *self._flags, *location_args, js_file.name]
2024-12-31 03:34:27 -06:00
result = self._run_deno(cmd)
try:
data = json.loads(result)
except json.JSONDecodeError as e:
raise ExtractorError(f'Failed to parse JSON output from Deno: {result}', cause=e)
2024-12-30 04:52:47 -06:00
self.apply_cookies(cookiejar, data['cookies'])
return data['stdout']
if typing.TYPE_CHECKING:
from ..cookies import YoutubeDLCookieJar