]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/openload.py
2 from __future__
import unicode_literals
24 def cookie_to_dict(cookie
):
27 'value': cookie
.value
,
29 if cookie
.port_specified
:
30 cookie_dict
['port'] = cookie
.port
31 if cookie
.domain_specified
:
32 cookie_dict
['domain'] = cookie
.domain
33 if cookie
.path_specified
:
34 cookie_dict
['path'] = cookie
.path
35 if cookie
.expires
is not None:
36 cookie_dict
['expires'] = cookie
.expires
37 if cookie
.secure
is not None:
38 cookie_dict
['secure'] = cookie
.secure
39 if cookie
.discard
is not None:
40 cookie_dict
['discard'] = cookie
.discard
42 if (cookie
.has_nonstandard_attr('httpOnly')
43 or cookie
.has_nonstandard_attr('httponly')
44 or cookie
.has_nonstandard_attr('HttpOnly')):
45 cookie_dict
['httponly'] = True
51 def cookie_jar_to_list(cookie_jar
):
52 return [cookie_to_dict(cookie
) for cookie
in cookie_jar
]
55 class PhantomJSwrapper(object):
56 """PhantomJS wrapper class
58 This class is experimental.
62 phantom.onError = function(msg, trace) {{
63 var msgStack = ['PHANTOM ERROR: ' + msg];
64 if(trace && trace.length) {{
65 msgStack.push('TRACE:');
66 trace.forEach(function(t) {{
67 msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
68 + (t.function ? ' (in function ' + t.function +')' : ''));
71 console.error(msgStack.join('\n'));
74 var page = require('webpage').create();
75 var fs = require('fs');
76 var read = {{ mode: 'r', charset: 'utf-8' }};
77 var write = {{ mode: 'w', charset: 'utf-8' }};
78 JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
81 page.settings.resourceTimeout = {timeout};
82 page.settings.userAgent = "{ua}";
83 page.onLoadStarted = function() {{
84 page.evaluate(function() {{
85 delete window._phantom;
86 delete window.callPhantom;
89 var saveAndExit = function() {{
90 fs.write("{html}", page.content, write);
91 fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
94 page.onLoadFinished = function(status) {{
95 if(page.url === "") {{
96 page.setContent(fs.read("{html}", read), "{url}");
105 _TMP_FILE_NAMES
= ['script', 'html', 'cookies']
109 return get_exe_version('phantomjs', version_re
=r
'([0-9.]+)')
111 def __init__(self
, extractor
, required_version
=None, timeout
=10000):
114 self
.exe
= check_executable('phantomjs', ['-v'])
116 raise ExtractorError('PhantomJS executable not found in PATH, '
117 'download it from http://phantomjs.org',
120 self
.extractor
= extractor
123 version
= self
._version
()
124 if is_outdated_version(version
, required_version
):
125 self
.extractor
._downloader
.report_warning(
126 'Your copy of PhantomJS is outdated, update it to version '
127 '%s or newer if you encounter any errors.' % required_version
)
132 for name
in self
._TMP
_FILE
_NAMES
:
133 tmp
= tempfile
.NamedTemporaryFile(delete
=False)
135 self
._TMP
_FILES
[name
] = tmp
138 for name
in self
._TMP
_FILE
_NAMES
:
140 os
.remove(self
._TMP
_FILES
[name
].name
)
141 except (IOError, OSError, KeyError):
144 def _save_cookies(self
, url
):
145 cookies
= cookie_jar_to_list(self
.extractor
._downloader
.cookiejar
)
146 for cookie
in cookies
:
147 if 'path' not in cookie
:
149 if 'domain' not in cookie
:
150 cookie
['domain'] = compat_urlparse
.urlparse(url
).netloc
151 with open(self
._TMP
_FILES
['cookies'].name
, 'wb') as f
:
152 f
.write(json
.dumps(cookies
).encode('utf-8'))
154 def _load_cookies(self
):
155 with open(self
._TMP
_FILES
['cookies'].name
, 'rb') as f
:
156 cookies
= json
.loads(f
.read().decode('utf-8'))
157 for cookie
in cookies
:
158 if cookie
['httponly'] is True:
159 cookie
['rest'] = {'httpOnly': None}
160 if 'expiry' in cookie
:
161 cookie
['expire_time'] = cookie
['expiry']
162 self
.extractor
._set
_cookie
(**compat_kwargs(cookie
))
164 def get(self
, url
, html
=None, video_id
=None, note
=None, note2
='Executing JS on webpage', headers
={}, jscode
='saveAndExit();'):
166 Downloads webpage (if needed) and executes JS
170 html: optional, html code of website
172 note: optional, displayed when downloading webpage
173 note2: optional, displayed when executing JS
174 headers: custom http headers
175 jscode: code to be executed when page is loaded
178 * downloaded website (after JS execution)
179 * anything you print with `console.log` (but not inside `page.execute`!)
181 In most cases you don't need to add any `jscode`.
182 It is executed in `page.onLoadFinished`.
183 `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
184 It is possible to wait for some element on the webpage, for example:
185 var check = function() {
186 var elementFound = page.evaluate(function() {
187 return document.querySelector('#b.done') !== null;
192 window.setTimeout(check, 500);
195 page.evaluate(function(){
196 document.querySelector('#a').click();
200 if 'saveAndExit();' not in jscode
:
201 raise ExtractorError('`saveAndExit();` not found in `jscode`')
203 html
= self
.extractor
._download
_webpage
(url
, video_id
, note
=note
, headers
=headers
)
204 with open(self
._TMP
_FILES
['html'].name
, 'wb') as f
:
205 f
.write(html
.encode('utf-8'))
207 self
._save
_cookies
(url
)
209 replaces
= self
.options
210 replaces
['url'] = url
211 user_agent
= headers
.get('User-Agent') or std_headers
['User-Agent']
212 replaces
['ua'] = user_agent
.replace('"', '\\"')
213 replaces
['jscode'] = jscode
215 for x
in self
._TMP
_FILE
_NAMES
:
216 replaces
[x
] = self
._TMP
_FILES
[x
].name
.replace('\\', '\\\\').replace('"', '\\"')
218 with open(self
._TMP
_FILES
['script'].name
, 'wb') as f
:
219 f
.write(self
._TEMPLATE
.format(**replaces
).encode('utf-8'))
222 self
.extractor
.to_screen('%s' % (note2
,))
224 self
.extractor
.to_screen('%s: %s' % (video_id
, note2
))
227 [self
.exe
, '--ssl-protocol=any', self
._TMP
_FILES
['script'].name
],
228 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
229 out
, err
= p
.communicate_or_kill()
230 if p
.returncode
!= 0:
231 raise ExtractorError(
232 'Executing JS failed\n:' + encodeArgument(err
))
233 with open(self
._TMP
_FILES
['html'].name
, 'rb') as f
:
234 html
= f
.read().decode('utf-8')
238 return (html
, encodeArgument(out
))