]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/openload.py
[docs] Consistent use of `e.g.` (#4643)
[yt-dlp.git] / yt_dlp / extractor / openload.py
1 import contextlib
2 import json
3 import os
4 import subprocess
5 import tempfile
6
7 from ..compat import compat_urlparse
8 from ..utils import (
9 ExtractorError,
10 Popen,
11 check_executable,
12 get_exe_version,
13 is_outdated_version,
14 )
15
16
17 def cookie_to_dict(cookie):
18 cookie_dict = {
19 'name': cookie.name,
20 'value': cookie.value,
21 }
22 if cookie.port_specified:
23 cookie_dict['port'] = cookie.port
24 if cookie.domain_specified:
25 cookie_dict['domain'] = cookie.domain
26 if cookie.path_specified:
27 cookie_dict['path'] = cookie.path
28 if cookie.expires is not None:
29 cookie_dict['expires'] = cookie.expires
30 if cookie.secure is not None:
31 cookie_dict['secure'] = cookie.secure
32 if cookie.discard is not None:
33 cookie_dict['discard'] = cookie.discard
34 with contextlib.suppress(TypeError):
35 if (cookie.has_nonstandard_attr('httpOnly')
36 or cookie.has_nonstandard_attr('httponly')
37 or cookie.has_nonstandard_attr('HttpOnly')):
38 cookie_dict['httponly'] = True
39 return cookie_dict
40
41
42 def cookie_jar_to_list(cookie_jar):
43 return [cookie_to_dict(cookie) for cookie in cookie_jar]
44
45
46 class PhantomJSwrapper:
47 """PhantomJS wrapper class
48
49 This class is experimental.
50 """
51
52 _TEMPLATE = r'''
53 phantom.onError = function(msg, trace) {{
54 var msgStack = ['PHANTOM ERROR: ' + msg];
55 if(trace && trace.length) {{
56 msgStack.push('TRACE:');
57 trace.forEach(function(t) {{
58 msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
59 + (t.function ? ' (in function ' + t.function +')' : ''));
60 }});
61 }}
62 console.error(msgStack.join('\n'));
63 phantom.exit(1);
64 }};
65 var page = require('webpage').create();
66 var fs = require('fs');
67 var read = {{ mode: 'r', charset: 'utf-8' }};
68 var write = {{ mode: 'w', charset: 'utf-8' }};
69 JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
70 phantom.addCookie(x);
71 }});
72 page.settings.resourceTimeout = {timeout};
73 page.settings.userAgent = "{ua}";
74 page.onLoadStarted = function() {{
75 page.evaluate(function() {{
76 delete window._phantom;
77 delete window.callPhantom;
78 }});
79 }};
80 var saveAndExit = function() {{
81 fs.write("{html}", page.content, write);
82 fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
83 phantom.exit();
84 }};
85 page.onLoadFinished = function(status) {{
86 if(page.url === "") {{
87 page.setContent(fs.read("{html}", read), "{url}");
88 }}
89 else {{
90 {jscode}
91 }}
92 }};
93 page.open("");
94 '''
95
96 _TMP_FILE_NAMES = ['script', 'html', 'cookies']
97
98 @staticmethod
99 def _version():
100 return get_exe_version('phantomjs', version_re=r'([0-9.]+)')
101
102 def __init__(self, extractor, required_version=None, timeout=10000):
103 self._TMP_FILES = {}
104
105 self.exe = check_executable('phantomjs', ['-v'])
106 if not self.exe:
107 raise ExtractorError(
108 'PhantomJS not found, Please download it from https://phantomjs.org/download.html', expected=True)
109
110 self.extractor = extractor
111
112 if required_version:
113 version = self._version()
114 if is_outdated_version(version, required_version):
115 self.extractor._downloader.report_warning(
116 'Your copy of PhantomJS is outdated, update it to version '
117 '%s or newer if you encounter any errors.' % required_version)
118
119 self.options = {
120 'timeout': timeout,
121 }
122 for name in self._TMP_FILE_NAMES:
123 tmp = tempfile.NamedTemporaryFile(delete=False)
124 tmp.close()
125 self._TMP_FILES[name] = tmp
126
127 def __del__(self):
128 for name in self._TMP_FILE_NAMES:
129 with contextlib.suppress(OSError, KeyError):
130 os.remove(self._TMP_FILES[name].name)
131
132 def _save_cookies(self, url):
133 cookies = cookie_jar_to_list(self.extractor.cookiejar)
134 for cookie in cookies:
135 if 'path' not in cookie:
136 cookie['path'] = '/'
137 if 'domain' not in cookie:
138 cookie['domain'] = compat_urlparse.urlparse(url).netloc
139 with open(self._TMP_FILES['cookies'].name, 'wb') as f:
140 f.write(json.dumps(cookies).encode('utf-8'))
141
142 def _load_cookies(self):
143 with open(self._TMP_FILES['cookies'].name, 'rb') as f:
144 cookies = json.loads(f.read().decode('utf-8'))
145 for cookie in cookies:
146 if cookie['httponly'] is True:
147 cookie['rest'] = {'httpOnly': None}
148 if 'expiry' in cookie:
149 cookie['expire_time'] = cookie['expiry']
150 self.extractor._set_cookie(**cookie)
151
152 def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
153 """
154 Downloads webpage (if needed) and executes JS
155
156 Params:
157 url: website url
158 html: optional, html code of website
159 video_id: video id
160 note: optional, displayed when downloading webpage
161 note2: optional, displayed when executing JS
162 headers: custom http headers
163 jscode: code to be executed when page is loaded
164
165 Returns tuple with:
166 * downloaded website (after JS execution)
167 * anything you print with `console.log` (but not inside `page.execute`!)
168
169 In most cases you don't need to add any `jscode`.
170 It is executed in `page.onLoadFinished`.
171 `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
172 It is possible to wait for some element on the webpage, e.g.
173 var check = function() {
174 var elementFound = page.evaluate(function() {
175 return document.querySelector('#b.done') !== null;
176 });
177 if(elementFound)
178 saveAndExit();
179 else
180 window.setTimeout(check, 500);
181 }
182
183 page.evaluate(function(){
184 document.querySelector('#a').click();
185 });
186 check();
187 """
188 if 'saveAndExit();' not in jscode:
189 raise ExtractorError('`saveAndExit();` not found in `jscode`')
190 if not html:
191 html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
192 with open(self._TMP_FILES['html'].name, 'wb') as f:
193 f.write(html.encode('utf-8'))
194
195 self._save_cookies(url)
196
197 replaces = self.options
198 replaces['url'] = url
199 user_agent = headers.get('User-Agent') or self.extractor.get_param('http_headers')['User-Agent']
200 replaces['ua'] = user_agent.replace('"', '\\"')
201 replaces['jscode'] = jscode
202
203 for x in self._TMP_FILE_NAMES:
204 replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
205
206 with open(self._TMP_FILES['script'].name, 'wb') as f:
207 f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
208
209 if video_id is None:
210 self.extractor.to_screen(f'{note2}')
211 else:
212 self.extractor.to_screen(f'{video_id}: {note2}')
213
214 stdout, stderr, returncode = Popen.run(
215 [self.exe, '--ssl-protocol=any', self._TMP_FILES['script'].name],
216 text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
217 if returncode:
218 raise ExtractorError(f'Executing JS failed:\n{stderr}')
219 with open(self._TMP_FILES['html'].name, 'rb') as f:
220 html = f.read().decode('utf-8')
221
222 self._load_cookies()
223
224 return html, stdout