]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/openload.py
2 from __future__
import unicode_literals
22 def cookie_to_dict(cookie
):
25 'value': cookie
.value
,
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
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
49 def cookie_jar_to_list(cookie_jar
):
50 return [cookie_to_dict(cookie
) for cookie
in cookie_jar
]
53 class PhantomJSwrapper(object):
54 """PhantomJS wrapper class
56 This class is experimental.
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 +')' : ''));
69 console.error(msgStack.join('\n'));
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) {{
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;
87 var saveAndExit = function() {{
88 fs.write("{html}", page.content, write);
89 fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
92 page.onLoadFinished = function(status) {{
93 if(page.url === "") {{
94 page.setContent(fs.read("{html}", read), "{url}");
103 _TMP_FILE_NAMES
= ['script', 'html', 'cookies']
107 return get_exe_version('phantomjs', version_re
=r
'([0-9.]+)')
109 def __init__(self
, extractor
, required_version
=None, timeout
=10000):
112 self
.exe
= check_executable('phantomjs', ['-v'])
114 raise ExtractorError('PhantomJS executable not found in PATH, '
115 'download it from http://phantomjs.org',
118 self
.extractor
= extractor
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
)
130 for name
in self
._TMP
_FILE
_NAMES
:
131 tmp
= tempfile
.NamedTemporaryFile(delete
=False)
133 self
._TMP
_FILES
[name
] = tmp
136 for name
in self
._TMP
_FILE
_NAMES
:
138 os
.remove(self
._TMP
_FILES
[name
].name
)
139 except (IOError, OSError, KeyError):
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
:
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'))
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
)
162 def get(self
, url
, html
=None, video_id
=None, note
=None, note2
='Executing JS on webpage', headers
={}, jscode
='saveAndExit();'):
164 Downloads webpage (if needed) and executes JS
168 html: optional, html code of website
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
176 * downloaded website (after JS execution)
177 * anything you print with `console.log` (but not inside `page.execute`!)
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;
190 window.setTimeout(check, 500);
193 page.evaluate(function(){
194 document.querySelector('#a').click();
198 if 'saveAndExit();' not in jscode
:
199 raise ExtractorError('`saveAndExit();` not found in `jscode`')
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'))
205 self
._save
_cookies
(url
)
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
213 for x
in self
._TMP
_FILE
_NAMES
:
214 replaces
[x
] = self
._TMP
_FILES
[x
].name
.replace('\\', '\\\\').replace('"', '\\"')
216 with open(self
._TMP
_FILES
['script'].name
, 'wb') as f
:
217 f
.write(self
._TEMPLATE
.format(**replaces
).encode('utf-8'))
220 self
.extractor
.to_screen('%s' % (note2
,))
222 self
.extractor
.to_screen('%s: %s' % (video_id
, note2
))
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')
236 return (html
, encodeArgument(out
))