]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/openload.py
Prepare new version
[youtubedl] / youtube_dl / extractor / openload.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import os
6 import re
7 import subprocess
8 import tempfile
9
10 from .common import InfoExtractor
11 from ..compat import (
12 compat_urlparse,
13 compat_kwargs,
14 )
15 from ..utils import (
16 check_executable,
17 determine_ext,
18 encodeArgument,
19 ExtractorError,
20 get_element_by_id,
21 get_exe_version,
22 is_outdated_version,
23 std_headers,
24 )
25
26
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')
46 or cookie.has_nonstandard_attr('httponly')
47 or 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._TMP_FILES = {}
116
117 self.exe = check_executable('phantomjs', ['-v'])
118 if not self.exe:
119 raise ExtractorError('PhantomJS executable not found in PATH, '
120 'download it from http://phantomjs.org',
121 expected=True)
122
123 self.extractor = extractor
124
125 if required_version:
126 version = self._version()
127 if is_outdated_version(version, required_version):
128 self.extractor._downloader.report_warning(
129 'Your copy of PhantomJS is outdated, update it to version '
130 '%s or newer if you encounter any errors.' % required_version)
131
132 self.options = {
133 'timeout': timeout,
134 }
135 for name in self._TMP_FILE_NAMES:
136 tmp = tempfile.NamedTemporaryFile(delete=False)
137 tmp.close()
138 self._TMP_FILES[name] = tmp
139
140 def __del__(self):
141 for name in self._TMP_FILE_NAMES:
142 try:
143 os.remove(self._TMP_FILES[name].name)
144 except (IOError, OSError, KeyError):
145 pass
146
147 def _save_cookies(self, url):
148 cookies = cookie_jar_to_list(self.extractor._downloader.cookiejar)
149 for cookie in cookies:
150 if 'path' not in cookie:
151 cookie['path'] = '/'
152 if 'domain' not in cookie:
153 cookie['domain'] = compat_urlparse.urlparse(url).netloc
154 with open(self._TMP_FILES['cookies'].name, 'wb') as f:
155 f.write(json.dumps(cookies).encode('utf-8'))
156
157 def _load_cookies(self):
158 with open(self._TMP_FILES['cookies'].name, 'rb') as f:
159 cookies = json.loads(f.read().decode('utf-8'))
160 for cookie in cookies:
161 if cookie['httponly'] is True:
162 cookie['rest'] = {'httpOnly': None}
163 if 'expiry' in cookie:
164 cookie['expire_time'] = cookie['expiry']
165 self.extractor._set_cookie(**compat_kwargs(cookie))
166
167 def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
168 """
169 Downloads webpage (if needed) and executes JS
170
171 Params:
172 url: website url
173 html: optional, html code of website
174 video_id: video id
175 note: optional, displayed when downloading webpage
176 note2: optional, displayed when executing JS
177 headers: custom http headers
178 jscode: code to be executed when page is loaded
179
180 Returns tuple with:
181 * downloaded website (after JS execution)
182 * anything you print with `console.log` (but not inside `page.execute`!)
183
184 In most cases you don't need to add any `jscode`.
185 It is executed in `page.onLoadFinished`.
186 `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
187 It is possible to wait for some element on the webpage, for example:
188 var check = function() {
189 var elementFound = page.evaluate(function() {
190 return document.querySelector('#b.done') !== null;
191 });
192 if(elementFound)
193 saveAndExit();
194 else
195 window.setTimeout(check, 500);
196 }
197
198 page.evaluate(function(){
199 document.querySelector('#a').click();
200 });
201 check();
202 """
203 if 'saveAndExit();' not in jscode:
204 raise ExtractorError('`saveAndExit();` not found in `jscode`')
205 if not html:
206 html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
207 with open(self._TMP_FILES['html'].name, 'wb') as f:
208 f.write(html.encode('utf-8'))
209
210 self._save_cookies(url)
211
212 replaces = self.options
213 replaces['url'] = url
214 user_agent = headers.get('User-Agent') or std_headers['User-Agent']
215 replaces['ua'] = user_agent.replace('"', '\\"')
216 replaces['jscode'] = jscode
217
218 for x in self._TMP_FILE_NAMES:
219 replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
220
221 with open(self._TMP_FILES['script'].name, 'wb') as f:
222 f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
223
224 if video_id is None:
225 self.extractor.to_screen('%s' % (note2,))
226 else:
227 self.extractor.to_screen('%s: %s' % (video_id, note2))
228
229 p = subprocess.Popen([
230 self.exe, '--ssl-protocol=any',
231 self._TMP_FILES['script'].name
232 ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
233 out, err = p.communicate()
234 if p.returncode != 0:
235 raise ExtractorError(
236 'Executing JS failed\n:' + encodeArgument(err))
237 with open(self._TMP_FILES['html'].name, 'rb') as f:
238 html = f.read().decode('utf-8')
239
240 self._load_cookies()
241
242 return (html, encodeArgument(out))
243
244
245 class OpenloadIE(InfoExtractor):
246 _DOMAINS = r'''
247 (?:
248 openload\.(?:co|io|link|pw)|
249 oload\.(?:tv|best|biz|stream|site|xyz|win|download|cloud|cc|icu|fun|club|info|online|press|pw|life|live|space|services|website|vip)|
250 oladblock\.(?:services|xyz|me)|openloed\.co
251 )
252 '''
253 _VALID_URL = r'''(?x)
254 https?://
255 (?P<host>
256 (?:www\.)?
257 %s
258 )/
259 (?:f|embed)/
260 (?P<id>[a-zA-Z0-9-_]+)
261 ''' % _DOMAINS
262 _EMBED_WORD = 'embed'
263 _STREAM_WORD = 'f'
264 _REDIR_WORD = 'stream'
265 _URL_IDS = ('streamurl', 'streamuri', 'streamurj')
266 _TESTS = [{
267 'url': 'https://openload.co/f/kUEfGclsU9o',
268 'md5': 'bf1c059b004ebc7a256f89408e65c36e',
269 'info_dict': {
270 'id': 'kUEfGclsU9o',
271 'ext': 'mp4',
272 'title': 'skyrim_no-audio_1080.mp4',
273 'thumbnail': r're:^https?://.*\.jpg$',
274 },
275 }, {
276 'url': 'https://openload.co/embed/rjC09fkPLYs',
277 'info_dict': {
278 'id': 'rjC09fkPLYs',
279 'ext': 'mp4',
280 'title': 'movie.mp4',
281 'thumbnail': r're:^https?://.*\.jpg$',
282 'subtitles': {
283 'en': [{
284 'ext': 'vtt',
285 }],
286 },
287 },
288 'params': {
289 'skip_download': True, # test subtitles only
290 },
291 }, {
292 'url': 'https://openload.co/embed/kUEfGclsU9o/skyrim_no-audio_1080.mp4',
293 'only_matching': True,
294 }, {
295 'url': 'https://openload.io/f/ZAn6oz-VZGE/',
296 'only_matching': True,
297 }, {
298 'url': 'https://openload.co/f/_-ztPaZtMhM/',
299 'only_matching': True,
300 }, {
301 # unavailable via https://openload.co/f/Sxz5sADo82g/, different layout
302 # for title and ext
303 'url': 'https://openload.co/embed/Sxz5sADo82g/',
304 'only_matching': True,
305 }, {
306 # unavailable via https://openload.co/embed/e-Ixz9ZR5L0/ but available
307 # via https://openload.co/f/e-Ixz9ZR5L0/
308 'url': 'https://openload.co/f/e-Ixz9ZR5L0/',
309 'only_matching': True,
310 }, {
311 'url': 'https://oload.tv/embed/KnG-kKZdcfY/',
312 'only_matching': True,
313 }, {
314 'url': 'http://www.openload.link/f/KnG-kKZdcfY',
315 'only_matching': True,
316 }, {
317 'url': 'https://oload.stream/f/KnG-kKZdcfY',
318 'only_matching': True,
319 }, {
320 'url': 'https://oload.xyz/f/WwRBpzW8Wtk',
321 'only_matching': True,
322 }, {
323 'url': 'https://oload.win/f/kUEfGclsU9o',
324 'only_matching': True,
325 }, {
326 'url': 'https://oload.download/f/kUEfGclsU9o',
327 'only_matching': True,
328 }, {
329 'url': 'https://oload.cloud/f/4ZDnBXRWiB8',
330 'only_matching': True,
331 }, {
332 # Its title has not got its extension but url has it
333 'url': 'https://oload.download/f/N4Otkw39VCw/Tomb.Raider.2018.HDRip.XviD.AC3-EVO.avi.mp4',
334 'only_matching': True,
335 }, {
336 'url': 'https://oload.cc/embed/5NEAbI2BDSk',
337 'only_matching': True,
338 }, {
339 'url': 'https://oload.icu/f/-_i4y_F_Hs8',
340 'only_matching': True,
341 }, {
342 'url': 'https://oload.fun/f/gb6G1H4sHXY',
343 'only_matching': True,
344 }, {
345 'url': 'https://oload.club/f/Nr1L-aZ2dbQ',
346 'only_matching': True,
347 }, {
348 'url': 'https://oload.info/f/5NEAbI2BDSk',
349 'only_matching': True,
350 }, {
351 'url': 'https://openload.pw/f/WyKgK8s94N0',
352 'only_matching': True,
353 }, {
354 'url': 'https://oload.pw/f/WyKgK8s94N0',
355 'only_matching': True,
356 }, {
357 'url': 'https://oload.live/f/-Z58UZ-GR4M',
358 'only_matching': True,
359 }, {
360 'url': 'https://oload.space/f/IY4eZSst3u8/',
361 'only_matching': True,
362 }, {
363 'url': 'https://oload.services/embed/bs1NWj1dCag/',
364 'only_matching': True,
365 }, {
366 'url': 'https://oload.online/f/W8o2UfN1vNY/',
367 'only_matching': True,
368 }, {
369 'url': 'https://oload.press/embed/drTBl1aOTvk/',
370 'only_matching': True,
371 }, {
372 'url': 'https://oload.website/embed/drTBl1aOTvk/',
373 'only_matching': True,
374 }, {
375 'url': 'https://oload.life/embed/oOzZjNPw9Dc/',
376 'only_matching': True,
377 }, {
378 'url': 'https://oload.biz/f/bEk3Gp8ARr4/',
379 'only_matching': True,
380 }, {
381 'url': 'https://oload.best/embed/kkz9JgVZeWc/',
382 'only_matching': True,
383 }, {
384 'url': 'https://oladblock.services/f/b8NWEgkqNLI/',
385 'only_matching': True,
386 }, {
387 'url': 'https://oladblock.xyz/f/b8NWEgkqNLI/',
388 'only_matching': True,
389 }, {
390 'url': 'https://oladblock.me/f/b8NWEgkqNLI/',
391 'only_matching': True,
392 }, {
393 'url': 'https://openloed.co/f/b8NWEgkqNLI/',
394 'only_matching': True,
395 }, {
396 'url': 'https://oload.vip/f/kUEfGclsU9o',
397 'only_matching': True,
398 }]
399
400 @classmethod
401 def _extract_urls(cls, webpage):
402 return re.findall(
403 r'(?x)<iframe[^>]+src=["\']((?:https?://)?%s/%s/[a-zA-Z0-9-_]+)'
404 % (cls._DOMAINS, cls._EMBED_WORD), webpage)
405
406 def _extract_decrypted_page(self, page_url, webpage, video_id):
407 phantom = PhantomJSwrapper(self, required_version='2.0')
408 webpage, _ = phantom.get(page_url, html=webpage, video_id=video_id)
409 return webpage
410
411 def _real_extract(self, url):
412 mobj = re.match(self._VALID_URL, url)
413 host = mobj.group('host')
414 video_id = mobj.group('id')
415
416 url_pattern = 'https://%s/%%s/%s/' % (host, video_id)
417
418 for path in (self._EMBED_WORD, self._STREAM_WORD):
419 page_url = url_pattern % path
420 last = path == self._STREAM_WORD
421 webpage = self._download_webpage(
422 page_url, video_id, 'Downloading %s webpage' % path,
423 fatal=last)
424 if not webpage:
425 continue
426 if 'File not found' in webpage or 'deleted by the owner' in webpage:
427 if not last:
428 continue
429 raise ExtractorError('File not found', expected=True, video_id=video_id)
430 break
431
432 webpage = self._extract_decrypted_page(page_url, webpage, video_id)
433 for element_id in self._URL_IDS:
434 decoded_id = get_element_by_id(element_id, webpage)
435 if decoded_id:
436 break
437 if not decoded_id:
438 decoded_id = self._search_regex(
439 (r'>\s*([\w-]+~\d{10,}~\d+\.\d+\.0\.0~[\w-]+)\s*<',
440 r'>\s*([\w~-]+~\d+\.\d+\.\d+\.\d+~[\w~-]+)',
441 r'>\s*([\w-]+~\d{10,}~(?:[a-f\d]+:){2}:~[\w-]+)\s*<',
442 r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)\s*<',
443 r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)'), webpage,
444 'stream URL')
445 video_url = 'https://%s/%s/%s?mime=true' % (host, self._REDIR_WORD, decoded_id)
446
447 title = self._og_search_title(webpage, default=None) or self._search_regex(
448 r'<span[^>]+class=["\']title["\'][^>]*>([^<]+)', webpage,
449 'title', default=None) or self._html_search_meta(
450 'description', webpage, 'title', fatal=True)
451
452 entries = self._parse_html5_media_entries(page_url, webpage, video_id)
453 entry = entries[0] if entries else {}
454 subtitles = entry.get('subtitles')
455
456 return {
457 'id': video_id,
458 'title': title,
459 'thumbnail': entry.get('thumbnail') or self._og_search_thumbnail(webpage, default=None),
460 'url': video_url,
461 'ext': determine_ext(title, None) or determine_ext(url, 'mp4'),
462 'subtitles': subtitles,
463 }
464
465
466 class VerystreamIE(OpenloadIE):
467 IE_NAME = 'verystream'
468
469 _DOMAINS = r'(?:verystream\.com|woof\.tube)'
470 _VALID_URL = r'''(?x)
471 https?://
472 (?P<host>
473 (?:www\.)?
474 %s
475 )/
476 (?:stream|e)/
477 (?P<id>[a-zA-Z0-9-_]+)
478 ''' % _DOMAINS
479 _EMBED_WORD = 'e'
480 _STREAM_WORD = 'stream'
481 _REDIR_WORD = 'gettoken'
482 _URL_IDS = ('videolink', )
483 _TESTS = [{
484 'url': 'https://verystream.com/stream/c1GWQ9ngBBx/',
485 'md5': 'd3e8c5628ccb9970b65fd65269886795',
486 'info_dict': {
487 'id': 'c1GWQ9ngBBx',
488 'ext': 'mp4',
489 'title': 'Big Buck Bunny.mp4',
490 'thumbnail': r're:^https?://.*\.jpg$',
491 },
492 }, {
493 'url': 'https://verystream.com/e/c1GWQ9ngBBx/',
494 'only_matching': True,
495 }]
496
497 def _extract_decrypted_page(self, page_url, webpage, video_id):
498 return webpage # for Verystream, the webpage is already decrypted