2024-08-25 08:55:24 -05:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import abc
|
2022-04-17 15:58:28 -05:00
|
|
|
import contextlib
|
2017-09-23 12:08:27 -05:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import subprocess
|
|
|
|
import tempfile
|
2024-06-11 18:09:58 -05:00
|
|
|
import urllib.parse
|
2024-08-25 08:55:24 -05:00
|
|
|
import typing
|
2024-12-29 19:27:00 -06:00
|
|
|
import http.cookiejar
|
2024-08-25 08:55:24 -05:00
|
|
|
|
2017-01-25 10:27:22 -06:00
|
|
|
|
2016-03-20 03:49:44 -05:00
|
|
|
from ..utils import (
|
2022-04-11 17:32:57 -05:00
|
|
|
ExtractorError,
|
|
|
|
Popen,
|
2024-08-02 18:35:28 -05:00
|
|
|
classproperty,
|
2022-08-18 11:04:47 -05:00
|
|
|
format_field,
|
2017-09-23 12:08:27 -05:00
|
|
|
get_exe_version,
|
|
|
|
is_outdated_version,
|
2022-08-18 11:04:47 -05:00
|
|
|
shell_quote,
|
2024-12-29 19:27:00 -06:00
|
|
|
int_or_none,
|
|
|
|
unified_timestamp,
|
2016-03-20 03:49:44 -05:00
|
|
|
)
|
2024-08-25 08:55:24 -05:00
|
|
|
from .common import JSI, register_jsi
|
2016-03-20 02:54:58 -05:00
|
|
|
|
|
|
|
|
2017-09-23 12:08:27 -05:00
|
|
|
def cookie_to_dict(cookie):
|
|
|
|
cookie_dict = {
|
|
|
|
'name': cookie.name,
|
|
|
|
'value': cookie.value,
|
|
|
|
}
|
|
|
|
if cookie.port_specified:
|
|
|
|
cookie_dict['port'] = cookie.port
|
|
|
|
if cookie.domain_specified:
|
|
|
|
cookie_dict['domain'] = cookie.domain
|
|
|
|
if cookie.path_specified:
|
|
|
|
cookie_dict['path'] = cookie.path
|
|
|
|
if cookie.expires is not None:
|
|
|
|
cookie_dict['expires'] = cookie.expires
|
|
|
|
if cookie.secure is not None:
|
|
|
|
cookie_dict['secure'] = cookie.secure
|
|
|
|
if cookie.discard is not None:
|
|
|
|
cookie_dict['discard'] = cookie.discard
|
2022-04-17 15:58:28 -05:00
|
|
|
with contextlib.suppress(TypeError):
|
2019-05-10 15:56:22 -05:00
|
|
|
if (cookie.has_nonstandard_attr('httpOnly')
|
|
|
|
or cookie.has_nonstandard_attr('httponly')
|
|
|
|
or cookie.has_nonstandard_attr('HttpOnly')):
|
2017-09-23 12:08:27 -05:00
|
|
|
cookie_dict['httponly'] = True
|
|
|
|
return cookie_dict
|
|
|
|
|
|
|
|
|
|
|
|
def cookie_jar_to_list(cookie_jar):
|
|
|
|
return [cookie_to_dict(cookie) for cookie in cookie_jar]
|
|
|
|
|
|
|
|
|
2024-08-11 15:23:58 -05:00
|
|
|
class TempFileWrapper:
|
2024-08-11 19:05:46 -05:00
|
|
|
"""Wrapper for NamedTemporaryFile, auto closes file after io and deletes file upon wrapper object gc"""
|
2024-08-11 22:22:24 -05:00
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
def __init__(self, content: str | bytes | None = None, text: bool = True,
|
|
|
|
encoding='utf-8', suffix: str | None = None):
|
2024-08-11 15:23:58 -05:00
|
|
|
self.encoding = None if not text else encoding
|
|
|
|
self.text = text
|
2024-08-25 08:55:24 -05:00
|
|
|
self._file = tempfile.NamedTemporaryFile('w' if text else 'wb', encoding=self.encoding,
|
|
|
|
suffix=suffix, delete=False)
|
2024-08-11 15:23:58 -05:00
|
|
|
if content:
|
2024-08-25 08:55:24 -05:00
|
|
|
self._file.write(content)
|
|
|
|
self._file.close()
|
2024-08-11 15:23:58 -05:00
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
|
|
|
return self._file.name
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def opened_file(self, mode, *, seek=None, seek_whence=0):
|
|
|
|
mode = mode if (self.text or 'b' in mode) else mode + 'b'
|
|
|
|
with open(self._file.name, mode, encoding=self.encoding) as f:
|
|
|
|
if seek is not None:
|
|
|
|
self._file.seek(seek, seek_whence)
|
|
|
|
yield f
|
|
|
|
|
|
|
|
def write(self, s, seek=None, seek_whence=0):
|
|
|
|
with self.opened_file('w', seek=seek, seek_whence=seek_whence) as f:
|
2024-08-11 19:05:46 -05:00
|
|
|
return f.write(s)
|
2024-08-11 15:23:58 -05:00
|
|
|
|
|
|
|
def append_write(self, s, seek=None, seek_whence=0):
|
|
|
|
with self.opened_file('a', seek=seek, seek_whence=seek_whence) as f:
|
2024-08-11 19:05:46 -05:00
|
|
|
return f.write(s)
|
2024-08-11 15:23:58 -05:00
|
|
|
|
|
|
|
def read(self, n=-1, seek=None, seek_whence=0):
|
|
|
|
with self.opened_file('r', seek=seek, seek_whence=seek_whence) as f:
|
|
|
|
return f.read(n)
|
|
|
|
|
|
|
|
def cleanup(self):
|
2024-08-08 10:07:27 -05:00
|
|
|
with contextlib.suppress(OSError):
|
2024-08-11 15:23:58 -05:00
|
|
|
os.remove(self._file.name)
|
2024-08-08 10:07:27 -05:00
|
|
|
|
2024-08-11 15:23:58 -05:00
|
|
|
def __del__(self):
|
|
|
|
self.cleanup()
|
2024-08-11 09:43:15 -05:00
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
self.cleanup()
|
|
|
|
|
2024-08-11 09:43:15 -05:00
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
class ExternalJSI(JSI, abc.ABC):
|
2024-12-29 01:56:58 -06:00
|
|
|
_EXE_NAME: str
|
2024-08-25 08:55:24 -05:00
|
|
|
|
2024-08-02 18:35:28 -05:00
|
|
|
@classproperty(cache=True)
|
2024-12-29 01:56:58 -06:00
|
|
|
def exe_version(cls):
|
2024-08-08 10:07:27 -05:00
|
|
|
return get_exe_version(cls._EXE_NAME, args=getattr(cls, 'V_ARGS', ['--version']), version_re=r'([0-9.]+)')
|
2024-08-02 18:35:28 -05:00
|
|
|
|
|
|
|
@classproperty
|
|
|
|
def exe(cls):
|
2024-12-29 01:56:58 -06:00
|
|
|
return cls._EXE_NAME if cls.exe_version else None
|
2024-08-02 18:35:28 -05:00
|
|
|
|
2024-12-29 01:56:58 -06:00
|
|
|
@classmethod
|
2024-12-28 02:52:00 -06:00
|
|
|
def is_available(cls):
|
|
|
|
return bool(cls.exe)
|
2024-08-02 15:53:30 -05:00
|
|
|
|
2024-08-02 18:35:28 -05:00
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
@register_jsi
|
|
|
|
class DenoJSI(ExternalJSI):
|
|
|
|
"""JS interpreter class using Deno binary"""
|
2024-12-29 01:56:58 -06:00
|
|
|
_SUPPORTED_FEATURES = {'js', 'wasm', 'location'}
|
2024-12-29 19:34:05 -06:00
|
|
|
_BASE_PREFERENCE = 5
|
|
|
|
_EXE_NAME = 'deno'
|
2024-12-29 01:56:58 -06:00
|
|
|
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check']
|
|
|
|
_INIT_SCRIPT = 'localStorage.clear(); delete window.Deno; global = window;\n'
|
2024-08-02 15:53:30 -05:00
|
|
|
|
2024-12-29 01:56:58 -06:00
|
|
|
def __init__(self, downloader: YoutubeDL, timeout=None, flags=[], replace_flags=False, init_script=None):
|
2024-08-25 08:55:24 -05:00
|
|
|
super().__init__(downloader, timeout)
|
2024-12-29 01:56:58 -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-08-02 15:53:30 -05:00
|
|
|
|
2024-12-29 19:27:00 -06:00
|
|
|
def _run_deno(self, cmd):
|
2024-12-29 01:56:58 -06:00
|
|
|
self.write_debug(f'Deno command line: {shell_quote(cmd)}')
|
2024-08-11 15:23:58 -05:00
|
|
|
try:
|
|
|
|
stdout, stderr, returncode = Popen.run(
|
2024-12-29 01:56:58 -06:00
|
|
|
cmd, timeout=self.timeout, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
2024-08-11 15:23:58 -05:00
|
|
|
except Exception as e:
|
|
|
|
raise ExtractorError('Unable to run Deno binary', cause=e)
|
|
|
|
if returncode:
|
|
|
|
raise ExtractorError(f'Failed with returncode {returncode}:\n{stderr}')
|
2024-12-29 01:56:58 -06:00
|
|
|
elif stderr:
|
2024-12-29 19:27:00 -06:00
|
|
|
self.report_warning(f'JS console error msg:\n{stderr.strip()}')
|
2024-08-11 15:23:58 -05:00
|
|
|
return stdout.strip()
|
2024-08-11 01:48:20 -05:00
|
|
|
|
2024-12-29 19:27:00 -06:00
|
|
|
def execute(self, jscode, video_id=None, note='Executing JS in Deno', location=None):
|
2024-12-29 01:56:58 -06:00
|
|
|
self.report_note(video_id, note)
|
2024-12-29 19:27:00 -06:00
|
|
|
location_args = ['--location', location] if location else []
|
2024-12-29 19:34:05 -06:00
|
|
|
with TempFileWrapper(f'{self._init_script};\n{jscode}', suffix='.js') as js_file:
|
|
|
|
cmd = [self.exe, 'run', *self._flags, *location_args, js_file.name]
|
|
|
|
return self._run_deno(cmd)
|
2024-08-02 15:53:30 -05:00
|
|
|
|
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
@register_jsi
|
|
|
|
class DenoJITlessJSI(DenoJSI):
|
2024-12-29 01:56:58 -06:00
|
|
|
_SUPPORTED_FEATURES = {'js', 'location'}
|
2024-12-29 19:34:05 -06:00
|
|
|
_BASE_PREFERENCE = 6
|
|
|
|
_EXE_NAME = DenoJSI._EXE_NAME
|
2024-12-29 01:56:58 -06:00
|
|
|
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check', '--v8-flags=--jitless,--noexpose-wasm']
|
2024-08-25 08:55:24 -05:00
|
|
|
|
|
|
|
@classproperty
|
2024-12-29 01:56:58 -06:00
|
|
|
def exe_version(cls):
|
|
|
|
return DenoJSI.exe_version
|
2024-08-25 08:55:24 -05:00
|
|
|
|
2024-12-29 01:56:58 -06:00
|
|
|
|
|
|
|
class DenoJSDomJSI(DenoJSI):
|
2024-12-29 19:27:00 -06:00
|
|
|
_SUPPORTED_FEATURES = {'js', 'wasm', 'location', 'dom', 'cookies'}
|
2024-12-29 19:34:05 -06:00
|
|
|
_BASE_PREFERENCE = 4
|
2024-12-29 01:56:58 -06:00
|
|
|
_DENO_FLAGS = ['--cached-only', '--no-prompt', '--no-check']
|
2024-12-29 19:34:05 -06:00
|
|
|
_JSDOM_IMPORT_CHECKED = False
|
2024-12-29 01:56:58 -06:00
|
|
|
|
2024-12-29 19:27:00 -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': []})
|
|
|
|
cookies: list[http.cookiejar.Cookie] = [cookie for cookie in cookiejar.get_cookies_for_url(url)]
|
|
|
|
return json.dumps({'cookies': [{
|
|
|
|
'key': cookie.name,
|
|
|
|
'value': cookie.value,
|
|
|
|
# leading dot must be removed, otherwise will fail to match
|
|
|
|
'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, {}))
|
|
|
|
|
2024-12-29 01:56:58 -06:00
|
|
|
def _ensure_jsdom(self):
|
2024-12-29 19:34:05 -06:00
|
|
|
if self._JSDOM_IMPORT_CHECKED:
|
2024-12-29 01:56:58 -06:00
|
|
|
return
|
2024-12-29 19:34:05 -06:00
|
|
|
with TempFileWrapper('import jsdom from "https://cdn.esm.sh/jsdom"', suffix='.js') as js_file:
|
|
|
|
cmd = [self.exe, 'run', js_file.name]
|
|
|
|
self._run_deno(cmd)
|
|
|
|
self._JSDOM_IMPORT_CHECKED = True
|
2024-12-29 01:56:58 -06:00
|
|
|
|
2024-12-29 19:27:00 -06:00
|
|
|
def execute(self, jscode, video_id=None, note='Executing JS in Deno', location='', html='', cookiejar=None):
|
2024-12-29 01:56:58 -06:00
|
|
|
self.report_note(video_id, note)
|
2024-12-29 19:27:00 -06:00
|
|
|
self._ensure_jsdom()
|
|
|
|
script = f'''{self._init_script};
|
|
|
|
import jsdom from "https://cdn.esm.sh/jsdom";
|
|
|
|
const callback = (() => {{
|
|
|
|
const jar = jsdom.CookieJar.deserializeSync({json.dumps(self.serialize_cookie(cookiejar, location))});
|
|
|
|
const dom = new jsdom.JSDOM({json.dumps(str(html))}, {{
|
|
|
|
{'url: %s,' % json.dumps(str(location)) if location else ''}
|
|
|
|
cookieJar: jar,
|
|
|
|
}});
|
|
|
|
Object.keys(dom.window).forEach((key) => {{try {{window[key] = dom.window[key]}} catch (e) {{}}}});
|
|
|
|
delete window.jsdom;
|
|
|
|
const stdout = [];
|
|
|
|
const origLog = console.log;
|
|
|
|
console.log = (...msg) => stdout.push(msg.map(m => m.toString()).join(' '));
|
|
|
|
return () => {{ origLog(JSON.stringify({{
|
|
|
|
stdout: stdout.join('\\n'), cookies: jar.serializeSync().cookies}})); }}
|
|
|
|
}})();
|
|
|
|
await (async () => {{
|
|
|
|
{jscode}
|
|
|
|
}})().finally(callback);
|
|
|
|
'''
|
|
|
|
|
|
|
|
location_args = ['--location', location] if location else []
|
2024-12-29 19:34:05 -06:00
|
|
|
with TempFileWrapper(script, suffix='.js') as js_file:
|
|
|
|
cmd = [self.exe, 'run', *self._flags, *location_args, js_file.name]
|
|
|
|
data = json.loads(self._run_deno(cmd))
|
2024-12-29 19:27:00 -06:00
|
|
|
self.apply_cookies(cookiejar, data['cookies'])
|
|
|
|
return data['stdout']
|
2024-08-11 07:03:00 -05:00
|
|
|
|
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
class PuppeteerJSI(ExternalJSI):
|
2024-08-11 01:48:20 -05:00
|
|
|
_PACKAGE_VERSION = '16.2.0'
|
2024-08-08 10:07:27 -05:00
|
|
|
_HEADLESS = False
|
2024-08-25 08:55:24 -05:00
|
|
|
_EXE_NAME = DenoJSI._EXE_NAME
|
2024-08-08 10:07:27 -05:00
|
|
|
|
|
|
|
@classproperty
|
|
|
|
def INSTALL_HINT(cls):
|
2024-08-11 01:48:20 -05:00
|
|
|
msg = f'Run "deno run -A https://deno.land/x/puppeteer@{cls._PACKAGE_VERSION}/install.ts" to install puppeteer'
|
2024-08-25 08:55:24 -05:00
|
|
|
if not DenoJSI.is_available:
|
|
|
|
msg = f'{DenoJSI.INSTALL_HINT}. Then {msg}'
|
2024-08-08 10:07:27 -05:00
|
|
|
return msg
|
|
|
|
|
2024-08-11 01:48:20 -05:00
|
|
|
@classproperty(cache=True)
|
|
|
|
def full_version(cls):
|
2024-08-25 08:55:24 -05:00
|
|
|
if not DenoJSI.is_available:
|
2024-08-11 01:48:20 -05:00
|
|
|
return
|
|
|
|
try:
|
2024-08-25 08:55:24 -05:00
|
|
|
browser_version = DenoJSI._execute(f'''
|
|
|
|
import puppeteer from "https://deno.land/x/puppeteer@{cls._PACKAGE_VERSION}/mod.ts";
|
2024-08-11 01:48:20 -05:00
|
|
|
const browser = await puppeteer.launch({{headless: {json.dumps(bool(cls._HEADLESS))}}});
|
|
|
|
try {{
|
|
|
|
console.log(await browser.version())
|
|
|
|
}} finally {{
|
|
|
|
await browser.close();
|
|
|
|
}}''', flags=['--allow-all'])
|
|
|
|
return f'puppeteer={cls._PACKAGE_VERSION} browser={browser_version}'
|
|
|
|
except ExtractorError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
@classproperty
|
2024-12-29 01:56:58 -06:00
|
|
|
def exe_version(cls):
|
|
|
|
return DenoJSI.exe_version if cls.full_version else None
|
2024-08-11 01:48:20 -05:00
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
def __init__(self, downloader: YoutubeDL, timeout: float | int | None = None):
|
|
|
|
super().__init__(downloader, timeout)
|
|
|
|
self.deno = DenoJSI(downloader, timeout=(self.timeout + 30000))
|
2024-08-08 10:07:27 -05:00
|
|
|
|
|
|
|
def _deno_execute(self, jscode, note=None):
|
|
|
|
return self.deno.execute(f'''
|
2024-08-11 01:48:20 -05:00
|
|
|
import puppeteer from "https://deno.land/x/puppeteer@{self._PACKAGE_VERSION}/mod.ts";
|
2024-08-08 10:07:27 -05:00
|
|
|
const browser = await puppeteer.launch({{
|
|
|
|
headless: {json.dumps(bool(self._HEADLESS))}, args: ["--disable-web-security"]}});
|
|
|
|
try {{
|
|
|
|
{jscode}
|
|
|
|
}} finally {{
|
|
|
|
await browser.close();
|
2024-08-11 01:48:20 -05:00
|
|
|
}}''', note=note, flags=['--allow-all'], base_js='')
|
2024-08-08 10:07:27 -05:00
|
|
|
|
2024-08-11 07:03:00 -05:00
|
|
|
def execute(self, jscode, video_id=None, note='Executing JS in Puppeteer', url='about:blank'):
|
2024-08-25 08:55:24 -05:00
|
|
|
self._downloader.to_screen(f'{format_field(video_id, None, "%s: ")}{note}')
|
2024-08-11 07:03:00 -05:00
|
|
|
return self._deno_execute(f'''
|
2024-08-08 10:07:27 -05:00
|
|
|
const page = await browser.newPage();
|
|
|
|
window.setTimeout(async () => {{
|
|
|
|
console.error('Puppeteer execution timed out');
|
|
|
|
await browser.close();
|
|
|
|
Deno.exit(1);
|
|
|
|
}}, {int(self.timeout)});
|
|
|
|
page.resourceTimeout = {int(self.timeout)};
|
|
|
|
|
2024-08-11 07:03:00 -05:00
|
|
|
// drop network requests
|
2024-08-08 10:07:27 -05:00
|
|
|
await page.setRequestInterception(true);
|
|
|
|
page.on("request", request => request.abort());
|
2024-08-11 07:03:00 -05:00
|
|
|
// capture console output
|
|
|
|
page.on("console", msg => {{
|
|
|
|
msg.type() === 'log' && console.log(msg.text());
|
|
|
|
msg.type() === 'error' && console.error(msg.text());
|
|
|
|
}});
|
2024-08-08 10:07:27 -05:00
|
|
|
|
|
|
|
const url = {json.dumps(str(url))};
|
|
|
|
await page.evaluate(`window.history.replaceState('', '', ${{JSON.stringify(url)}})`);
|
|
|
|
|
2024-08-11 07:03:00 -05:00
|
|
|
await page.evaluate({json.dumps(str(jscode))});
|
2024-08-08 10:07:27 -05:00
|
|
|
await browser.close();
|
|
|
|
Deno.exit(0);
|
|
|
|
''')
|
|
|
|
|
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
@register_jsi
|
|
|
|
class PhantomJSJSI(ExternalJSI):
|
2024-08-08 10:07:27 -05:00
|
|
|
_EXE_NAME = 'phantomjs'
|
2024-12-29 19:34:05 -06:00
|
|
|
_SUPPORTED_FEATURES = {'js', 'location', 'cookies'}
|
|
|
|
_BASE_PREFERENCE = 3
|
2022-08-30 06:53:59 -05:00
|
|
|
|
2022-08-18 11:04:47 -05:00
|
|
|
_BASE_JS = R'''
|
2017-09-23 12:08:27 -05:00
|
|
|
phantom.onError = function(msg, trace) {{
|
|
|
|
var msgStack = ['PHANTOM ERROR: ' + msg];
|
|
|
|
if(trace && trace.length) {{
|
|
|
|
msgStack.push('TRACE:');
|
|
|
|
trace.forEach(function(t) {{
|
|
|
|
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
|
|
|
|
+ (t.function ? ' (in function ' + t.function +')' : ''));
|
|
|
|
}});
|
|
|
|
}}
|
|
|
|
console.error(msgStack.join('\n'));
|
|
|
|
phantom.exit(1);
|
|
|
|
}};
|
2022-08-18 11:04:47 -05:00
|
|
|
'''
|
|
|
|
|
|
|
|
_TEMPLATE = R'''
|
2017-09-23 12:08:27 -05:00
|
|
|
var page = require('webpage').create();
|
|
|
|
var fs = require('fs');
|
|
|
|
var read = {{ mode: 'r', charset: 'utf-8' }};
|
|
|
|
var write = {{ mode: 'w', charset: 'utf-8' }};
|
2024-12-29 19:34:05 -06:00
|
|
|
JSON.parse(fs.read({cookies_fn}, read)).forEach(function(x) {{
|
2017-09-23 12:08:27 -05:00
|
|
|
phantom.addCookie(x);
|
|
|
|
}});
|
|
|
|
page.settings.resourceTimeout = {timeout};
|
2024-12-29 19:34:05 -06:00
|
|
|
page.settings.userAgent = {ua};
|
2017-09-23 12:08:27 -05:00
|
|
|
page.onLoadStarted = function() {{
|
|
|
|
page.evaluate(function() {{
|
|
|
|
delete window._phantom;
|
|
|
|
delete window.callPhantom;
|
|
|
|
}});
|
|
|
|
}};
|
|
|
|
var saveAndExit = function() {{
|
2024-12-29 19:34:05 -06:00
|
|
|
fs.write({html_fn}, page.content, write);
|
|
|
|
fs.write({cookies_fn}, JSON.stringify(phantom.cookies), write);
|
2017-09-23 12:08:27 -05:00
|
|
|
phantom.exit();
|
|
|
|
}};
|
|
|
|
page.onLoadFinished = function(status) {{
|
|
|
|
if(page.url === "") {{
|
2024-12-29 19:34:05 -06:00
|
|
|
page.setContent(fs.read({html_fn}, read), {url});
|
2017-09-23 12:08:27 -05:00
|
|
|
}}
|
|
|
|
else {{
|
|
|
|
{jscode}
|
|
|
|
}}
|
|
|
|
}};
|
|
|
|
page.open("");
|
|
|
|
'''
|
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
def _save_cookies(self, url, cookiejar):
|
|
|
|
cookies = cookie_jar_to_list(cookiejar) if cookiejar else []
|
|
|
|
for cookie in cookies:
|
|
|
|
if 'path' not in cookie:
|
|
|
|
cookie['path'] = '/'
|
|
|
|
if 'domain' not in cookie:
|
|
|
|
cookie['domain'] = urllib.parse.urlparse(url).netloc
|
|
|
|
return json.dumps(cookies)
|
|
|
|
|
|
|
|
def _load_cookies(self, cookies_json: str, cookiejar):
|
|
|
|
if not cookiejar:
|
|
|
|
return
|
|
|
|
cookies = json.loads(cookies_json)
|
|
|
|
for cookie in cookies:
|
|
|
|
cookiejar.set_cookie(http.cookiejar.Cookie(
|
|
|
|
0, cookie['name'], cookie['value'], cookie.get('port'), cookie.get('port') is not None,
|
|
|
|
cookie['domain'], True, cookie['domain'].startswith('.'),
|
|
|
|
cookie.get('path', '/'), True,
|
|
|
|
cookie.get('secure', False), cookie.get('expiry'),
|
|
|
|
cookie.get('discard', False), None, None,
|
|
|
|
{'httpOnly': None} if cookie.get('httponly') is True else {}
|
|
|
|
))
|
|
|
|
|
|
|
|
def _execute(self, jscode: str, video_id=None, *, note='Executing JS in PhantomJS'):
|
|
|
|
"""Execute JS and return stdout"""
|
|
|
|
if 'phantom.exit();' not in jscode:
|
|
|
|
jscode += ';\nphantom.exit();'
|
|
|
|
jscode = self._BASE_JS + jscode
|
|
|
|
|
|
|
|
self.report_note(video_id, note)
|
|
|
|
with TempFileWrapper(jscode, suffix='.js') as js_file:
|
|
|
|
cmd = [self.exe, '--ssl-protocol=any', js_file.name]
|
|
|
|
self.write_debug(f'PhantomJS 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(f'{note} failed: Unable to run PhantomJS binary', cause=e)
|
|
|
|
if returncode:
|
|
|
|
raise ExtractorError(f'{note} failed with returncode {returncode}:\n{stderr.strip()}')
|
|
|
|
return stdout
|
|
|
|
|
|
|
|
def _execute_html(self, jscode: str, url: str, html: str, cookiejar, video_id=None, note='Executing JS on webpage'):
|
|
|
|
if 'saveAndExit();' not in jscode:
|
|
|
|
raise ExtractorError('`saveAndExit();` not found in `jscode`')
|
|
|
|
|
|
|
|
html_file = TempFileWrapper(html, suffix='.html')
|
|
|
|
cookie_file = TempFileWrapper(self._save_cookies(url, cookiejar), suffix='.json')
|
|
|
|
|
|
|
|
jscode = self._TEMPLATE.format(**{
|
|
|
|
'url': json.dumps(str(url)),
|
|
|
|
'ua': json.dumps(str(self.user_agent)),
|
|
|
|
'jscode': jscode,
|
|
|
|
'html_fn': json.dumps(html_file.name),
|
|
|
|
'cookies_fn': json.dumps(cookie_file.name),
|
|
|
|
'timeout': int(self.timeout * 1000),
|
|
|
|
})
|
|
|
|
|
|
|
|
stdout = self._execute(jscode, video_id, note=note)
|
|
|
|
self._load_cookies(cookie_file.read(), cookiejar)
|
|
|
|
new_html = html_file.read()
|
|
|
|
|
|
|
|
return new_html, stdout
|
|
|
|
|
|
|
|
def execute(self, jscode, video_id=None,
|
|
|
|
note='Executing JS in PhantomJS', location=None, html='', cookiejar=None):
|
|
|
|
if location:
|
|
|
|
return self._execute_html(jscode, location, html, cookiejar, video_id=video_id, note=note)[1]
|
|
|
|
if html:
|
|
|
|
self.report_warning('`location` is required to use `html`')
|
|
|
|
if cookiejar:
|
|
|
|
self.report_warning('`location` and `html` are required to use `cookiejar`')
|
|
|
|
return self._execute(jscode, video_id, note=note)
|
|
|
|
|
|
|
|
|
|
|
|
class PhantomJSwrapper:
|
|
|
|
"""PhantomJS wrapper class
|
|
|
|
|
|
|
|
This class is experimental.
|
|
|
|
"""
|
|
|
|
INSTALL_HINT = 'Please download PhantomJS from https://phantomjs.org/download.html'
|
2017-09-23 12:08:27 -05:00
|
|
|
|
2024-08-02 18:35:28 -05:00
|
|
|
@classmethod
|
|
|
|
def _version(cls):
|
2024-12-29 19:34:05 -06:00
|
|
|
return PhantomJSJSI.exe_version
|
2017-09-23 12:08:27 -05:00
|
|
|
|
2024-08-25 08:55:24 -05:00
|
|
|
def __init__(self, extractor: InfoExtractor, required_version=None, timeout=10000):
|
2024-12-29 19:34:05 -06:00
|
|
|
self._jsi = PhantomJSJSI(extractor._downloader, timeout=timeout / 1000)
|
2017-12-24 06:47:42 -06:00
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
if not self._jsi.is_available():
|
2022-08-30 06:53:59 -05:00
|
|
|
raise ExtractorError(f'PhantomJS not found, {self.INSTALL_HINT}', expected=True)
|
2017-09-23 12:08:27 -05:00
|
|
|
|
|
|
|
self.extractor = extractor
|
|
|
|
|
|
|
|
if required_version:
|
2024-12-29 19:34:05 -06:00
|
|
|
if is_outdated_version(self._jsi.exe_version, required_version):
|
|
|
|
self._jsi.report_warning(
|
2017-09-23 12:08:27 -05:00
|
|
|
'Your copy of PhantomJS is outdated, update it to version '
|
2024-06-11 18:09:58 -05:00
|
|
|
f'{required_version} or newer if you encounter any errors.')
|
2017-09-23 12:08:27 -05:00
|
|
|
|
|
|
|
def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
|
|
|
|
"""
|
|
|
|
Downloads webpage (if needed) and executes JS
|
|
|
|
|
|
|
|
Params:
|
|
|
|
url: website url
|
|
|
|
html: optional, html code of website
|
|
|
|
video_id: video id
|
|
|
|
note: optional, displayed when downloading webpage
|
|
|
|
note2: optional, displayed when executing JS
|
|
|
|
headers: custom http headers
|
|
|
|
jscode: code to be executed when page is loaded
|
|
|
|
|
|
|
|
Returns tuple with:
|
|
|
|
* downloaded website (after JS execution)
|
|
|
|
* anything you print with `console.log` (but not inside `page.execute`!)
|
|
|
|
|
|
|
|
In most cases you don't need to add any `jscode`.
|
|
|
|
It is executed in `page.onLoadFinished`.
|
|
|
|
`saveAndExit();` is mandatory, use it instead of `phantom.exit()`
|
2022-08-14 07:04:13 -05:00
|
|
|
It is possible to wait for some element on the webpage, e.g.
|
2017-09-23 12:08:27 -05:00
|
|
|
var check = function() {
|
|
|
|
var elementFound = page.evaluate(function() {
|
|
|
|
return document.querySelector('#b.done') !== null;
|
|
|
|
});
|
|
|
|
if(elementFound)
|
|
|
|
saveAndExit();
|
|
|
|
else
|
|
|
|
window.setTimeout(check, 500);
|
|
|
|
}
|
|
|
|
|
|
|
|
page.evaluate(function(){
|
|
|
|
document.querySelector('#a').click();
|
|
|
|
});
|
|
|
|
check();
|
|
|
|
"""
|
|
|
|
if 'saveAndExit();' not in jscode:
|
|
|
|
raise ExtractorError('`saveAndExit();` not found in `jscode`')
|
|
|
|
if not html:
|
|
|
|
html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
|
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
self._jsi.user_agent = headers.get('User-Agent') or self.extractor.get_param('http_headers')['User-Agent']
|
2017-09-23 12:08:27 -05:00
|
|
|
|
2024-12-29 19:34:05 -06:00
|
|
|
return self._jsi._execute_html(jscode, url, html, self.extractor.cookiejar, video_id=video_id, note=note2)
|
2022-08-18 11:04:47 -05:00
|
|
|
|
2024-08-08 10:07:27 -05:00
|
|
|
def execute(self, jscode, video_id=None, *, note='Executing JS in PhantomJS'):
|
2022-08-18 11:04:47 -05:00
|
|
|
"""Execute JS and return stdout"""
|
2024-12-29 19:34:05 -06:00
|
|
|
return self._jsi.execute(jscode, video_id=video_id, note=note)
|
2024-08-25 08:55:24 -05:00
|
|
|
|
|
|
|
|
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from ..YoutubeDL import YoutubeDL
|
|
|
|
from ..extractor.common import InfoExtractor
|
2024-12-29 19:27:00 -06:00
|
|
|
from ..cookies import YoutubeDLCookieJar
|