]>
Commit | Line | Data |
---|---|---|
2bfeee69 | 1 | # coding: utf-8 |
6c20a0bb | 2 | from __future__ import unicode_literals |
95ad9ce5 | 3 | |
4c54b89e S |
4 | import json |
5 | import os | |
17f8deeb | 6 | import re |
4c54b89e S |
7 | import subprocess |
8 | import tempfile | |
17f8deeb | 9 | |
2bfeee69 | 10 | from .common import InfoExtractor |
011da618 S |
11 | from ..compat import ( |
12 | compat_urlparse, | |
13 | compat_kwargs, | |
14 | ) | |
9e3c2f1d | 15 | from ..utils import ( |
4c54b89e | 16 | check_executable, |
594b0c4c | 17 | determine_ext, |
4c54b89e | 18 | encodeArgument, |
9e3c2f1d | 19 | ExtractorError, |
da57ebaf | 20 | get_element_by_id, |
4c54b89e S |
21 | get_exe_version, |
22 | is_outdated_version, | |
23 | std_headers, | |
9e3c2f1d | 24 | ) |
2bfeee69 YCH |
25 | |
26 | ||
4c54b89e S |
27 | def cookie_to_dict(cookie): |
28 | cookie_dict = { | |
29 | 'name': cookie.name, | |
30 | 'value': cookie.value, | |
31 | } | |
32 | if cookie.port_specified: | |
33 | cookie_dict['port'] = cookie.port | |
34 | if cookie.domain_specified: | |
35 | cookie_dict['domain'] = cookie.domain | |
36 | if cookie.path_specified: | |
37 | cookie_dict['path'] = cookie.path | |
38 | if cookie.expires is not None: | |
39 | cookie_dict['expires'] = cookie.expires | |
40 | if cookie.secure is not None: | |
41 | cookie_dict['secure'] = cookie.secure | |
42 | if cookie.discard is not None: | |
43 | cookie_dict['discard'] = cookie.discard | |
44 | try: | |
45 | if (cookie.has_nonstandard_attr('httpOnly') or | |
46 | cookie.has_nonstandard_attr('httponly') or | |
47 | cookie.has_nonstandard_attr('HttpOnly')): | |
48 | cookie_dict['httponly'] = True | |
49 | except TypeError: | |
50 | pass | |
51 | return cookie_dict | |
52 | ||
53 | ||
54 | def cookie_jar_to_list(cookie_jar): | |
55 | return [cookie_to_dict(cookie) for cookie in cookie_jar] | |
56 | ||
57 | ||
58 | class PhantomJSwrapper(object): | |
59 | """PhantomJS wrapper class | |
60 | ||
61 | This class is experimental. | |
62 | """ | |
63 | ||
64 | _TEMPLATE = r''' | |
65 | phantom.onError = function(msg, trace) {{ | |
66 | var msgStack = ['PHANTOM ERROR: ' + msg]; | |
67 | if(trace && trace.length) {{ | |
68 | msgStack.push('TRACE:'); | |
69 | trace.forEach(function(t) {{ | |
70 | msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line | |
71 | + (t.function ? ' (in function ' + t.function +')' : '')); | |
72 | }}); | |
73 | }} | |
74 | console.error(msgStack.join('\n')); | |
75 | phantom.exit(1); | |
76 | }}; | |
77 | var page = require('webpage').create(); | |
78 | var fs = require('fs'); | |
79 | var read = {{ mode: 'r', charset: 'utf-8' }}; | |
80 | var write = {{ mode: 'w', charset: 'utf-8' }}; | |
81 | JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{ | |
82 | phantom.addCookie(x); | |
83 | }}); | |
84 | page.settings.resourceTimeout = {timeout}; | |
85 | page.settings.userAgent = "{ua}"; | |
86 | page.onLoadStarted = function() {{ | |
87 | page.evaluate(function() {{ | |
88 | delete window._phantom; | |
89 | delete window.callPhantom; | |
90 | }}); | |
91 | }}; | |
92 | var saveAndExit = function() {{ | |
93 | fs.write("{html}", page.content, write); | |
94 | fs.write("{cookies}", JSON.stringify(phantom.cookies), write); | |
95 | phantom.exit(); | |
96 | }}; | |
97 | page.onLoadFinished = function(status) {{ | |
98 | if(page.url === "") {{ | |
99 | page.setContent(fs.read("{html}", read), "{url}"); | |
100 | }} | |
101 | else {{ | |
102 | {jscode} | |
103 | }} | |
104 | }}; | |
105 | page.open(""); | |
106 | ''' | |
107 | ||
108 | _TMP_FILE_NAMES = ['script', 'html', 'cookies'] | |
109 | ||
110 | @staticmethod | |
111 | def _version(): | |
112 | return get_exe_version('phantomjs', version_re=r'([0-9.]+)') | |
113 | ||
114 | def __init__(self, extractor, required_version=None, timeout=10000): | |
115 | self.exe = check_executable('phantomjs', ['-v']) | |
116 | if not self.exe: | |
117 | raise ExtractorError('PhantomJS executable not found in PATH, ' | |
118 | 'download it from http://phantomjs.org', | |
119 | expected=True) | |
120 | ||
121 | self.extractor = extractor | |
122 | ||
123 | if required_version: | |
124 | version = self._version() | |
125 | if is_outdated_version(version, required_version): | |
126 | self.extractor._downloader.report_warning( | |
127 | 'Your copy of PhantomJS is outdated, update it to version ' | |
128 | '%s or newer if you encounter any errors.' % required_version) | |
129 | ||
130 | self.options = { | |
131 | 'timeout': timeout, | |
132 | } | |
133 | self._TMP_FILES = {} | |
134 | for name in self._TMP_FILE_NAMES: | |
135 | tmp = tempfile.NamedTemporaryFile(delete=False) | |
136 | tmp.close() | |
137 | self._TMP_FILES[name] = tmp | |
138 | ||
139 | def __del__(self): | |
140 | for name in self._TMP_FILE_NAMES: | |
141 | try: | |
142 | os.remove(self._TMP_FILES[name].name) | |
6ff27b8d | 143 | except (IOError, OSError): |
4c54b89e S |
144 | pass |
145 | ||
146 | def _save_cookies(self, url): | |
147 | cookies = cookie_jar_to_list(self.extractor._downloader.cookiejar) | |
148 | for cookie in cookies: | |
149 | if 'path' not in cookie: | |
150 | cookie['path'] = '/' | |
151 | if 'domain' not in cookie: | |
152 | cookie['domain'] = compat_urlparse.urlparse(url).netloc | |
153 | with open(self._TMP_FILES['cookies'].name, 'wb') as f: | |
154 | f.write(json.dumps(cookies).encode('utf-8')) | |
155 | ||
156 | def _load_cookies(self): | |
157 | with open(self._TMP_FILES['cookies'].name, 'rb') as f: | |
158 | cookies = json.loads(f.read().decode('utf-8')) | |
159 | for cookie in cookies: | |
160 | if cookie['httponly'] is True: | |
161 | cookie['rest'] = {'httpOnly': None} | |
162 | if 'expiry' in cookie: | |
163 | cookie['expire_time'] = cookie['expiry'] | |
011da618 | 164 | self.extractor._set_cookie(**compat_kwargs(cookie)) |
4c54b89e S |
165 | |
166 | def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'): | |
167 | """ | |
168 | Downloads webpage (if needed) and executes JS | |
169 | ||
170 | Params: | |
171 | url: website url | |
172 | html: optional, html code of website | |
173 | video_id: video id | |
174 | note: optional, displayed when downloading webpage | |
175 | note2: optional, displayed when executing JS | |
176 | headers: custom http headers | |
177 | jscode: code to be executed when page is loaded | |
178 | ||
179 | Returns tuple with: | |
180 | * downloaded website (after JS execution) | |
181 | * anything you print with `console.log` (but not inside `page.execute`!) | |
182 | ||
183 | In most cases you don't need to add any `jscode`. | |
184 | It is executed in `page.onLoadFinished`. | |
185 | `saveAndExit();` is mandatory, use it instead of `phantom.exit()` | |
186 | It is possible to wait for some element on the webpage, for example: | |
187 | var check = function() { | |
188 | var elementFound = page.evaluate(function() { | |
189 | return document.querySelector('#b.done') !== null; | |
190 | }); | |
191 | if(elementFound) | |
192 | saveAndExit(); | |
193 | else | |
194 | window.setTimeout(check, 500); | |
195 | } | |
196 | ||
197 | page.evaluate(function(){ | |
198 | document.querySelector('#a').click(); | |
199 | }); | |
200 | check(); | |
201 | """ | |
202 | if 'saveAndExit();' not in jscode: | |
203 | raise ExtractorError('`saveAndExit();` not found in `jscode`') | |
204 | if not html: | |
205 | html = self.extractor._download_webpage(url, video_id, note=note, headers=headers) | |
206 | with open(self._TMP_FILES['html'].name, 'wb') as f: | |
207 | f.write(html.encode('utf-8')) | |
208 | ||
209 | self._save_cookies(url) | |
210 | ||
211 | replaces = self.options | |
212 | replaces['url'] = url | |
213 | user_agent = headers.get('User-Agent') or std_headers['User-Agent'] | |
214 | replaces['ua'] = user_agent.replace('"', '\\"') | |
215 | replaces['jscode'] = jscode | |
216 | ||
217 | for x in self._TMP_FILE_NAMES: | |
218 | replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"') | |
219 | ||
220 | with open(self._TMP_FILES['script'].name, 'wb') as f: | |
221 | f.write(self._TEMPLATE.format(**replaces).encode('utf-8')) | |
222 | ||
223 | if video_id is None: | |
224 | self.extractor.to_screen('%s' % (note2,)) | |
225 | else: | |
226 | self.extractor.to_screen('%s: %s' % (video_id, note2)) | |
227 | ||
228 | p = subprocess.Popen([ | |
229 | self.exe, '--ssl-protocol=any', | |
230 | self._TMP_FILES['script'].name | |
231 | ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
232 | out, err = p.communicate() | |
233 | if p.returncode != 0: | |
234 | raise ExtractorError( | |
235 | 'Executing JS failed\n:' + encodeArgument(err)) | |
236 | with open(self._TMP_FILES['html'].name, 'rb') as f: | |
237 | html = f.read().decode('utf-8') | |
238 | ||
239 | self._load_cookies() | |
240 | ||
241 | return (html, encodeArgument(out)) | |
242 | ||
243 | ||
2bfeee69 | 244 | class OpenloadIE(InfoExtractor): |
9ef909f2 | 245 | _VALID_URL = r'https?://(?:www\.)?(?:openload\.(?:co|io|link)|oload\.tv)/(?:f|embed)/(?P<id>[a-zA-Z0-9-_]+)' |
2bfeee69 | 246 | |
9e3c2f1d | 247 | _TESTS = [{ |
2bfeee69 YCH |
248 | 'url': 'https://openload.co/f/kUEfGclsU9o', |
249 | 'md5': 'bf1c059b004ebc7a256f89408e65c36e', | |
250 | 'info_dict': { | |
251 | 'id': 'kUEfGclsU9o', | |
252 | 'ext': 'mp4', | |
253 | 'title': 'skyrim_no-audio_1080.mp4', | |
ec85ded8 | 254 | 'thumbnail': r're:^https?://.*\.jpg$', |
2bfeee69 | 255 | }, |
0711995b YCH |
256 | }, { |
257 | 'url': 'https://openload.co/embed/rjC09fkPLYs', | |
258 | 'info_dict': { | |
259 | 'id': 'rjC09fkPLYs', | |
260 | 'ext': 'mp4', | |
261 | 'title': 'movie.mp4', | |
ec85ded8 | 262 | 'thumbnail': r're:^https?://.*\.jpg$', |
0711995b YCH |
263 | 'subtitles': { |
264 | 'en': [{ | |
265 | 'ext': 'vtt', | |
266 | }], | |
267 | }, | |
268 | }, | |
269 | 'params': { | |
270 | 'skip_download': True, # test subtitles only | |
271 | }, | |
9e3c2f1d YCH |
272 | }, { |
273 | 'url': 'https://openload.co/embed/kUEfGclsU9o/skyrim_no-audio_1080.mp4', | |
274 | 'only_matching': True, | |
275 | }, { | |
276 | 'url': 'https://openload.io/f/ZAn6oz-VZGE/', | |
277 | 'only_matching': True, | |
21efee5f N |
278 | }, { |
279 | 'url': 'https://openload.co/f/_-ztPaZtMhM/', | |
280 | 'only_matching': True, | |
e9063b5d S |
281 | }, { |
282 | # unavailable via https://openload.co/f/Sxz5sADo82g/, different layout | |
283 | # for title and ext | |
284 | 'url': 'https://openload.co/embed/Sxz5sADo82g/', | |
285 | 'only_matching': True, | |
5c32a5be YCH |
286 | }, { |
287 | 'url': 'https://oload.tv/embed/KnG-kKZdcfY/', | |
288 | 'only_matching': True, | |
9ef909f2 | 289 | }, { |
290 | 'url': 'http://www.openload.link/f/KnG-kKZdcfY', | |
291 | 'only_matching': True, | |
9e3c2f1d | 292 | }] |
2bfeee69 | 293 | |
da57ebaf | 294 | _USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' |
47e0cef4 | 295 | |
17f8deeb S |
296 | @staticmethod |
297 | def _extract_urls(webpage): | |
298 | return re.findall( | |
299 | r'<iframe[^>]+src=["\']((?:https?://)?(?:openload\.(?:co|io)|oload\.tv)/embed/[a-zA-Z0-9-_]+)', | |
300 | webpage) | |
301 | ||
2bfeee69 YCH |
302 | def _real_extract(self, url): |
303 | video_id = self._match_id(url) | |
47e0cef4 | 304 | url = 'https://openload.co/embed/%s/' % video_id |
da57ebaf TF |
305 | headers = { |
306 | 'User-Agent': self._USER_AGENT, | |
307 | } | |
308 | ||
fcace2d1 | 309 | webpage = self._download_webpage(url, video_id, headers=headers) |
9e3c2f1d | 310 | |
18b62161 | 311 | if 'File not found' in webpage or 'deleted by the owner' in webpage: |
47e0cef4 TF |
312 | raise ExtractorError('File not found', expected=True, video_id=video_id) |
313 | ||
7552f963 | 314 | phantom = PhantomJSwrapper(self, required_version='2.0') |
fcace2d1 TF |
315 | webpage, _ = phantom.get(url, html=webpage, video_id=video_id, headers=headers) |
316 | ||
da57ebaf | 317 | decoded_id = get_element_by_id('streamurl', webpage) |
47e0cef4 TF |
318 | |
319 | video_url = 'https://openload.co/stream/%s?mime=true' % decoded_id | |
a1394b82 | 320 | |
da57ebaf TF |
321 | title = self._og_search_title(webpage, default=None) or self._search_regex( |
322 | r'<span[^>]+class=["\']title["\'][^>]*>([^<]+)', webpage, | |
323 | 'title', default=None) or self._html_search_meta( | |
324 | 'description', webpage, 'title', fatal=True) | |
325 | ||
0711995b | 326 | entries = self._parse_html5_media_entries(url, webpage, video_id) |
47e0cef4 TF |
327 | entry = entries[0] if entries else {} |
328 | subtitles = entry.get('subtitles') | |
0711995b YCH |
329 | |
330 | info_dict = { | |
2bfeee69 | 331 | 'id': video_id, |
a1394b82 | 332 | 'title': title, |
47e0cef4 | 333 | 'thumbnail': entry.get('thumbnail') or self._og_search_thumbnail(webpage, default=None), |
2bfeee69 | 334 | 'url': video_url, |
c1decda5 | 335 | # Seems all videos have extensions in their titles |
c1fa3f46 | 336 | 'ext': determine_ext(title, 'mp4'), |
0711995b | 337 | 'subtitles': subtitles, |
da57ebaf | 338 | 'http_headers': headers, |
2bfeee69 | 339 | } |
0711995b | 340 | return info_dict |