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