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