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