Merge pull request #3865 from diffycat/jpopsuki
[youtube-dl] / youtube_dl / extractor / generic.py
1 # encoding: utf-8
2
3 from __future__ import unicode_literals
4
5 import os
6 import re
7
8 from .common import InfoExtractor
9 from .youtube import YoutubeIE
10 from ..utils import (
11     compat_urllib_parse,
12     compat_urlparse,
13     compat_xml_parse_error,
14
15     determine_ext,
16     ExtractorError,
17     float_or_none,
18     HEADRequest,
19     orderedSet,
20     parse_xml,
21     smuggle_url,
22     unescapeHTML,
23     unified_strdate,
24     unsmuggle_url,
25     url_basename,
26 )
27 from .brightcove import BrightcoveIE
28 from .ooyala import OoyalaIE
29 from .rutv import RUTVIE
30 from .smotri import SmotriIE
31
32
33 class GenericIE(InfoExtractor):
34     IE_DESC = 'Generic downloader that works on some sites'
35     _VALID_URL = r'.*'
36     IE_NAME = 'generic'
37     _TESTS = [
38         {
39             'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
40             'md5': '85b90ccc9d73b4acd9138d3af4c27f89',
41             'info_dict': {
42                 'id': '13601338388002',
43                 'ext': 'mp4',
44                 'uploader': 'www.hodiho.fr',
45                 'title': 'R\u00e9gis plante sa Jeep',
46             }
47         },
48         # bandcamp page with custom domain
49         {
50             'add_ie': ['Bandcamp'],
51             'url': 'http://bronyrock.com/track/the-pony-mash',
52             'info_dict': {
53                 'id': '3235767654',
54                 'ext': 'mp3',
55                 'title': 'The Pony Mash',
56                 'uploader': 'M_Pallante',
57             },
58             'skip': 'There is a limit of 200 free downloads / month for the test song',
59         },
60         # embedded brightcove video
61         # it also tests brightcove videos that need to set the 'Referer' in the
62         # http requests
63         {
64             'add_ie': ['Brightcove'],
65             'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
66             'info_dict': {
67                 'id': '2765128793001',
68                 'ext': 'mp4',
69                 'title': 'Le cours de bourse : l’analyse technique',
70                 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
71                 'uploader': 'BFM BUSINESS',
72             },
73             'params': {
74                 'skip_download': True,
75             },
76         },
77         {
78             # https://github.com/rg3/youtube-dl/issues/2253
79             'url': 'http://bcove.me/i6nfkrc3',
80             'md5': '0ba9446db037002366bab3b3eb30c88c',
81             'info_dict': {
82                 'id': '3101154703001',
83                 'ext': 'mp4',
84                 'title': 'Still no power',
85                 'uploader': 'thestar.com',
86                 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
87             },
88             'add_ie': ['Brightcove'],
89         },
90         {
91             'url': 'http://www.championat.com/video/football/v/87/87499.html',
92             'md5': 'fb973ecf6e4a78a67453647444222983',
93             'info_dict': {
94                 'id': '3414141473001',
95                 'ext': 'mp4',
96                 'title': 'Видео. Удаление Дзагоева (ЦСКА)',
97                 'description': 'Онлайн-трансляция матча ЦСКА - "Волга"',
98                 'uploader': 'Championat',
99             },
100         },
101         # Direct link to a video
102         {
103             'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
104             'md5': '67d406c2bcb6af27fa886f31aa934bbe',
105             'info_dict': {
106                 'id': 'trailer',
107                 'ext': 'mp4',
108                 'title': 'trailer',
109                 'upload_date': '20100513',
110             }
111         },
112         # ooyala video
113         {
114             'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
115             'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
116             'info_dict': {
117                 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
118                 'ext': 'mp4',
119                 'title': '2cc213299525360.mov',  # that's what we get
120             },
121         },
122         # google redirect
123         {
124             'url': 'http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CCUQtwIwAA&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcmQHVoWB5FY&ei=F-sNU-LLCaXk4QT52ICQBQ&usg=AFQjCNEw4hL29zgOohLXvpJ-Bdh2bils1Q&bvm=bv.61965928,d.bGE',
125             'info_dict': {
126                 'id': 'cmQHVoWB5FY',
127                 'ext': 'mp4',
128                 'upload_date': '20130224',
129                 'uploader_id': 'TheVerge',
130                 'description': 'Chris Ziegler takes a look at the Alcatel OneTouch Fire and the ZTE Open; two of the first Firefox OS handsets to be officially announced.',
131                 'uploader': 'The Verge',
132                 'title': 'First Firefox OS phones side-by-side',
133             },
134             'params': {
135                 'skip_download': False,
136             }
137         },
138         # embed.ly video
139         {
140             'url': 'http://www.tested.com/science/weird/460206-tested-grinding-coffee-2000-frames-second/',
141             'info_dict': {
142                 'id': '9ODmcdjQcHQ',
143                 'ext': 'mp4',
144                 'title': 'Tested: Grinding Coffee at 2000 Frames Per Second',
145                 'upload_date': '20140225',
146                 'description': 'md5:06a40fbf30b220468f1e0957c0f558ff',
147                 'uploader': 'Tested',
148                 'uploader_id': 'testedcom',
149             },
150             # No need to test YoutubeIE here
151             'params': {
152                 'skip_download': True,
153             },
154         },
155         # funnyordie embed
156         {
157             'url': 'http://www.theguardian.com/world/2014/mar/11/obama-zach-galifianakis-between-two-ferns',
158             'info_dict': {
159                 'id': '18e820ec3f',
160                 'ext': 'mp4',
161                 'title': 'Between Two Ferns with Zach Galifianakis: President Barack Obama',
162                 'description': 'Episode 18: President Barack Obama sits down with Zach Galifianakis for his most memorable interview yet.',
163             },
164         },
165         # RUTV embed
166         {
167             'url': 'http://www.rg.ru/2014/03/15/reg-dfo/anklav-anons.html',
168             'info_dict': {
169                 'id': '776940',
170                 'ext': 'mp4',
171                 'title': 'Охотское море стало целиком российским',
172                 'description': 'md5:5ed62483b14663e2a95ebbe115eb8f43',
173             },
174             'params': {
175                 # m3u8 download
176                 'skip_download': True,
177             },
178         },
179         # Embedded TED video
180         {
181             'url': 'http://en.support.wordpress.com/videos/ted-talks/',
182             'md5': '65fdff94098e4a607385a60c5177c638',
183             'info_dict': {
184                 'id': '1969',
185                 'ext': 'mp4',
186                 'title': 'Hidden miracles of the natural world',
187                 'uploader': 'Louie Schwartzberg',
188                 'description': 'md5:8145d19d320ff3e52f28401f4c4283b9',
189             }
190         },
191         # Embeded Ustream video
192         {
193             'url': 'http://www.american.edu/spa/pti/nsa-privacy-janus-2014.cfm',
194             'md5': '27b99cdb639c9b12a79bca876a073417',
195             'info_dict': {
196                 'id': '45734260',
197                 'ext': 'flv',
198                 'uploader': 'AU SPA:  The NSA and Privacy',
199                 'title': 'NSA and Privacy Forum Debate featuring General Hayden and Barton Gellman'
200             }
201         },
202         # nowvideo embed hidden behind percent encoding
203         {
204             'url': 'http://www.waoanime.tv/the-super-dimension-fortress-macross-episode-1/',
205             'md5': '2baf4ddd70f697d94b1c18cf796d5107',
206             'info_dict': {
207                 'id': '06e53103ca9aa',
208                 'ext': 'flv',
209                 'title': 'Macross Episode 001  Watch Macross Episode 001 onl',
210                 'description': 'No description',
211             },
212         },
213         # arte embed
214         {
215             'url': 'http://www.tv-replay.fr/redirection/20-03-14/x-enius-arte-10753389.html',
216             'md5': '7653032cbb25bf6c80d80f217055fa43',
217             'info_dict': {
218                 'id': '048195-004_PLUS7-F',
219                 'ext': 'flv',
220                 'title': 'X:enius',
221                 'description': 'md5:d5fdf32ef6613cdbfd516ae658abf168',
222                 'upload_date': '20140320',
223             },
224             'params': {
225                 'skip_download': 'Requires rtmpdump'
226             }
227         },
228         # Condé Nast embed
229         {
230             'url': 'http://www.wired.com/2014/04/honda-asimo/',
231             'md5': 'ba0dfe966fa007657bd1443ee672db0f',
232             'info_dict': {
233                 'id': '53501be369702d3275860000',
234                 'ext': 'mp4',
235                 'title': 'Honda’s  New Asimo Robot Is More Human Than Ever',
236             }
237         },
238         # Dailymotion embed
239         {
240             'url': 'http://www.spi0n.com/zap-spi0n-com-n216/',
241             'md5': '441aeeb82eb72c422c7f14ec533999cd',
242             'info_dict': {
243                 'id': 'k2mm4bCdJ6CQ2i7c8o2',
244                 'ext': 'mp4',
245                 'title': 'Le Zap de Spi0n n°216 - Zapping du Web',
246                 'uploader': 'Spi0n',
247             },
248             'add_ie': ['Dailymotion'],
249         },
250         # YouTube embed
251         {
252             'url': 'http://www.badzine.de/ansicht/datum/2014/06/09/so-funktioniert-die-neue-englische-badminton-liga.html',
253             'info_dict': {
254                 'id': 'FXRb4ykk4S0',
255                 'ext': 'mp4',
256                 'title': 'The NBL Auction 2014',
257                 'uploader': 'BADMINTON England',
258                 'uploader_id': 'BADMINTONEvents',
259                 'upload_date': '20140603',
260                 'description': 'md5:9ef128a69f1e262a700ed83edb163a73',
261             },
262             'add_ie': ['Youtube'],
263             'params': {
264                 'skip_download': True,
265             }
266         },
267         # MTVSercices embed
268         {
269             'url': 'http://www.gametrailers.com/news-post/76093/north-america-europe-is-getting-that-mario-kart-8-mercedes-dlc-too',
270             'md5': '35727f82f58c76d996fc188f9755b0d5',
271             'info_dict': {
272                 'id': '0306a69b-8adf-4fb5-aace-75f8e8cbfca9',
273                 'ext': 'mp4',
274                 'title': 'Review',
275                 'description': 'Mario\'s life in the fast lane has never looked so good.',
276             },
277         },
278         # YouTube embed via <data-embed-url="">
279         {
280             'url': 'https://play.google.com/store/apps/details?id=com.gameloft.android.ANMP.GloftA8HM',
281             'info_dict': {
282                 'id': '4vAffPZIT44',
283                 'ext': 'mp4',
284                 'title': 'Asphalt 8: Airborne - Update - Welcome to Dubai!',
285                 'uploader': 'Gameloft',
286                 'uploader_id': 'gameloft',
287                 'upload_date': '20140828',
288                 'description': 'md5:c80da9ed3d83ae6d1876c834de03e1c4',
289             },
290             'params': {
291                 'skip_download': True,
292             }
293         },
294         # Camtasia studio
295         {
296             'url': 'http://www.ll.mit.edu/workshops/education/videocourses/antennas/lecture1/video/',
297             'playlist': [{
298                 'md5': '0c5e352edabf715d762b0ad4e6d9ee67',
299                 'info_dict': {
300                     'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
301                     'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - video1',
302                     'ext': 'flv',
303                     'duration': 2235.90,
304                 }
305             }, {
306                 'md5': '10e4bb3aaca9fd630e273ff92d9f3c63',
307                 'info_dict': {
308                     'id': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final_PIP',
309                     'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final - pip',
310                     'ext': 'flv',
311                     'duration': 2235.93,
312                 }
313             }],
314             'info_dict': {
315                 'title': 'Fenn-AA_PA_Radar_Course_Lecture_1c_Final',
316             }
317         },
318         # Flowplayer
319         {
320             'url': 'http://www.handjobhub.com/video/busty-blonde-siri-tit-fuck-while-wank-6313.html',
321             'md5': '9d65602bf31c6e20014319c7d07fba27',
322             'info_dict': {
323                 'id': '5123ea6d5e5a7',
324                 'ext': 'mp4',
325                 'age_limit': 18,
326                 'uploader': 'www.handjobhub.com',
327                 'title': 'Busty Blonde Siri Tit Fuck While Wank at Handjob Hub',
328             }
329         },
330         # RSS feed
331         {
332             'url': 'http://phihag.de/2014/youtube-dl/rss2.xml',
333             'info_dict': {
334                 'id': 'http://phihag.de/2014/youtube-dl/rss2.xml',
335                 'title': 'Zero Punctuation',
336                 'description': 're:'
337             },
338             'playlist_mincount': 11,
339         },
340         # Multiple brightcove videos
341         # https://github.com/rg3/youtube-dl/issues/2283
342         {
343             'url': 'http://www.newyorker.com/online/blogs/newsdesk/2014/01/always-never-nuclear-command-and-control.html',
344             'info_dict': {
345                 'id': 'always-never',
346                 'title': 'Always / Never - The New Yorker',
347             },
348             'playlist_count': 3,
349             'params': {
350                 'extract_flat': False,
351                 'skip_download': True,
352             }
353         },
354         # MLB embed
355         {
356             'url': 'http://umpire-empire.com/index.php/topic/58125-laz-decides-no-thats-low/',
357             'md5': '96f09a37e44da40dd083e12d9a683327',
358             'info_dict': {
359                 'id': '33322633',
360                 'ext': 'mp4',
361                 'title': 'Ump changes call to ball',
362                 'description': 'md5:71c11215384298a172a6dcb4c2e20685',
363                 'duration': 48,
364                 'timestamp': 1401537900,
365                 'upload_date': '20140531',
366                 'thumbnail': 're:^https?://.*\.jpg$',
367             },
368         },
369         # Wistia embed
370         {
371             'url': 'http://education-portal.com/academy/lesson/north-american-exploration-failed-colonies-of-spain-france-england.html#lesson',
372             'md5': '8788b683c777a5cf25621eaf286d0c23',
373             'info_dict': {
374                 'id': '1cfaf6b7ea',
375                 'ext': 'mov',
376                 'title': 'md5:51364a8d3d009997ba99656004b5e20d',
377                 'duration': 643.0,
378                 'filesize': 182808282,
379                 'uploader': 'education-portal.com',
380             },
381         },
382     ]
383
384     def report_following_redirect(self, new_url):
385         """Report information extraction."""
386         self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
387
388     def _extract_rss(self, url, video_id, doc):
389         playlist_title = doc.find('./channel/title').text
390         playlist_desc_el = doc.find('./channel/description')
391         playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
392
393         entries = [{
394             '_type': 'url',
395             'url': e.find('link').text,
396             'title': e.find('title').text,
397         } for e in doc.findall('./channel/item')]
398
399         return {
400             '_type': 'playlist',
401             'id': url,
402             'title': playlist_title,
403             'description': playlist_desc,
404             'entries': entries,
405         }
406
407     def _extract_camtasia(self, url, video_id, webpage):
408         """ Returns None if no camtasia video can be found. """
409
410         camtasia_cfg = self._search_regex(
411             r'fo\.addVariable\(\s*"csConfigFile",\s*"([^"]+)"\s*\);',
412             webpage, 'camtasia configuration file', default=None)
413         if camtasia_cfg is None:
414             return None
415
416         title = self._html_search_meta('DC.title', webpage, fatal=True)
417
418         camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
419         camtasia_cfg = self._download_xml(
420             camtasia_url, video_id,
421             note='Downloading camtasia configuration',
422             errnote='Failed to download camtasia configuration')
423         fileset_node = camtasia_cfg.find('./playlist/array/fileset')
424
425         entries = []
426         for n in fileset_node.getchildren():
427             url_n = n.find('./uri')
428             if url_n is None:
429                 continue
430
431             entries.append({
432                 'id': os.path.splitext(url_n.text.rpartition('/')[2])[0],
433                 'title': '%s - %s' % (title, n.tag),
434                 'url': compat_urlparse.urljoin(url, url_n.text),
435                 'duration': float_or_none(n.find('./duration').text),
436             })
437
438         return {
439             '_type': 'playlist',
440             'entries': entries,
441             'title': title,
442         }
443
444     def _real_extract(self, url):
445         if url.startswith('//'):
446             return {
447                 '_type': 'url',
448                 'url': self.http_scheme() + url,
449             }
450
451         parsed_url = compat_urlparse.urlparse(url)
452         if not parsed_url.scheme:
453             default_search = self._downloader.params.get('default_search')
454             if default_search is None:
455                 default_search = 'fixup_error'
456
457             if default_search in ('auto', 'auto_warning', 'fixup_error'):
458                 if '/' in url:
459                     self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
460                     return self.url_result('http://' + url)
461                 elif default_search != 'fixup_error':
462                     if default_search == 'auto_warning':
463                         if re.match(r'^(?:url|URL)$', url):
464                             raise ExtractorError(
465                                 'Invalid URL:  %r . Call youtube-dl like this:  youtube-dl -v "https://www.youtube.com/watch?v=BaW_jenozKc"  ' % url,
466                                 expected=True)
467                         else:
468                             self._downloader.report_warning(
469                                 'Falling back to youtube search for  %s . Set --default-search "auto" to suppress this warning.' % url)
470                     return self.url_result('ytsearch:' + url)
471
472             if default_search in ('error', 'fixup_error'):
473                 raise ExtractorError(
474                     ('%r is not a valid URL. '
475                      'Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:%s" ) to search YouTube'
476                     ) % (url, url), expected=True)
477             else:
478                 assert ':' in default_search
479                 return self.url_result(default_search + url)
480
481         url, smuggled_data = unsmuggle_url(url)
482         force_videoid = None
483         is_intentional = smuggled_data and smuggled_data.get('to_generic')
484         if smuggled_data and 'force_videoid' in smuggled_data:
485             force_videoid = smuggled_data['force_videoid']
486             video_id = force_videoid
487         else:
488             video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
489
490         self.to_screen('%s: Requesting header' % video_id)
491
492         head_req = HEADRequest(url)
493         response = self._request_webpage(
494             head_req, video_id,
495             note=False, errnote='Could not send HEAD request to %s' % url,
496             fatal=False)
497
498         if response is not False:
499             # Check for redirect
500             new_url = response.geturl()
501             if url != new_url:
502                 self.report_following_redirect(new_url)
503                 if force_videoid:
504                     new_url = smuggle_url(
505                         new_url, {'force_videoid': force_videoid})
506                 return self.url_result(new_url)
507
508             # Check for direct link to a video
509             content_type = response.headers.get('Content-Type', '')
510             m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
511             if m:
512                 upload_date = response.headers.get('Last-Modified')
513                 if upload_date:
514                     upload_date = unified_strdate(upload_date)
515                 return {
516                     'id': video_id,
517                     'title': os.path.splitext(url_basename(url))[0],
518                     'formats': [{
519                         'format_id': m.group('format_id'),
520                         'url': url,
521                         'vcodec': 'none' if m.group('type') == 'audio' else None
522                     }],
523                     'upload_date': upload_date,
524                 }
525
526         if not self._downloader.params.get('test', False) and not is_intentional:
527             self._downloader.report_warning('Falling back on generic information extractor.')
528
529         try:
530             webpage = self._download_webpage(url, video_id)
531         except ValueError:
532             # since this is the last-resort InfoExtractor, if
533             # this error is thrown, it'll be thrown here
534             raise ExtractorError('Failed to download URL: %s' % url)
535
536         self.report_extraction(video_id)
537
538         # Is it an RSS feed?
539         try:
540             doc = parse_xml(webpage)
541             if doc.tag == 'rss':
542                 return self._extract_rss(url, video_id, doc)
543         except compat_xml_parse_error:
544             pass
545
546         # Is it a Camtasia project?
547         camtasia_res = self._extract_camtasia(url, video_id, webpage)
548         if camtasia_res is not None:
549             return camtasia_res
550
551         # Sometimes embedded video player is hidden behind percent encoding
552         # (e.g. https://github.com/rg3/youtube-dl/issues/2448)
553         # Unescaping the whole page allows to handle those cases in a generic way
554         webpage = compat_urllib_parse.unquote(webpage)
555
556         # it's tempting to parse this further, but you would
557         # have to take into account all the variations like
558         #   Video Title - Site Name
559         #   Site Name | Video Title
560         #   Video Title - Tagline | Site Name
561         # and so on and so forth; it's just not practical
562         video_title = self._html_search_regex(
563             r'(?s)<title>(.*?)</title>', webpage, 'video title',
564             default='video')
565
566         # Try to detect age limit automatically
567         age_limit = self._rta_search(webpage)
568         # And then there are the jokers who advertise that they use RTA,
569         # but actually don't.
570         AGE_LIMIT_MARKERS = [
571             r'Proudly Labeled <a href="http://www.rtalabel.org/" title="Restricted to Adults">RTA</a>',
572         ]
573         if any(re.search(marker, webpage) for marker in AGE_LIMIT_MARKERS):
574             age_limit = 18
575
576         # video uploader is domain name
577         video_uploader = self._search_regex(
578             r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
579
580         # Helper method
581         def _playlist_from_matches(matches, getter, ie=None):
582             urlrs = orderedSet(
583                 self.url_result(self._proto_relative_url(getter(m)), ie)
584                 for m in matches)
585             return self.playlist_result(
586                 urlrs, playlist_id=video_id, playlist_title=video_title)
587
588         # Look for BrightCove:
589         bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
590         if bc_urls:
591             self.to_screen('Brightcove video detected.')
592             entries = [{
593                 '_type': 'url',
594                 'url': smuggle_url(bc_url, {'Referer': url}),
595                 'ie_key': 'Brightcove'
596             } for bc_url in bc_urls]
597
598             return {
599                 '_type': 'playlist',
600                 'title': video_title,
601                 'id': video_id,
602                 'entries': entries,
603             }
604
605         # Look for embedded (iframe) Vimeo player
606         mobj = re.search(
607             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
608         if mobj:
609             player_url = unescapeHTML(mobj.group('url'))
610             surl = smuggle_url(player_url, {'Referer': url})
611             return self.url_result(surl, 'Vimeo')
612
613         # Look for embedded (swf embed) Vimeo player
614         mobj = re.search(
615             r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
616         if mobj:
617             return self.url_result(mobj.group(1), 'Vimeo')
618
619         # Look for embedded YouTube player
620         matches = re.findall(r'''(?x)
621             (?:
622                 <iframe[^>]+?src=|
623                 data-video-url=|
624                 <embed[^>]+?src=|
625                 embedSWF\(?:\s*
626             )
627             (["\'])
628                 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
629                 (?:embed|v|p)/.+?)
630             \1''', webpage)
631         if matches:
632             return _playlist_from_matches(
633                 matches, lambda m: unescapeHTML(m[1]))
634
635         # Look for embedded Dailymotion player
636         matches = re.findall(
637             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
638         if matches:
639             return _playlist_from_matches(
640                 matches, lambda m: unescapeHTML(m[1]))
641
642         # Look for embedded Wistia player
643         match = re.search(
644             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
645         if match:
646             return {
647                 '_type': 'url_transparent',
648                 'url': unescapeHTML(match.group('url')),
649                 'ie_key': 'Wistia',
650                 'uploader': video_uploader,
651                 'title': video_title,
652                 'id': video_id,
653             }
654         match = re.search(r'(?:id=["\']wistia_|data-wistiaid=["\']|Wistia\.embed\(["\'])(?P<id>[^"\']+)', webpage)
655         if match:
656             return {
657                 '_type': 'url_transparent',
658                 'url': 'http://fast.wistia.net/embed/iframe/{0:}'.format(match.group('id')),
659                 'ie_key': 'Wistia',
660                 'uploader': video_uploader,
661                 'title': video_title,
662                 'id': match.group('id')
663             }
664
665         # Look for embedded blip.tv player
666         mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
667         if mobj:
668             return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
669         mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9_]+)', webpage)
670         if mobj:
671             return self.url_result(mobj.group(1), 'BlipTV')
672
673         # Look for embedded condenast player
674         matches = re.findall(
675             r'<iframe\s+(?:[a-zA-Z-]+="[^"]+"\s+)*?src="(https?://player\.cnevids\.com/embed/[^"]+")',
676             webpage)
677         if matches:
678             return {
679                 '_type': 'playlist',
680                 'entries': [{
681                     '_type': 'url',
682                     'ie_key': 'CondeNast',
683                     'url': ma,
684                 } for ma in matches],
685                 'title': video_title,
686                 'id': video_id,
687             }
688
689         # Look for Bandcamp pages with custom domain
690         mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
691         if mobj is not None:
692             burl = unescapeHTML(mobj.group(1))
693             # Don't set the extractor because it can be a track url or an album
694             return self.url_result(burl)
695
696         # Look for embedded Vevo player
697         mobj = re.search(
698             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
699         if mobj is not None:
700             return self.url_result(mobj.group('url'))
701
702         # Look for Ooyala videos
703         mobj = (re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=(?P<ec>[^"&]+)', webpage) or
704              re.search(r'OO.Player.create\([\'"].*?[\'"],\s*[\'"](?P<ec>.{32})[\'"]', webpage))
705         if mobj is not None:
706             return OoyalaIE._build_url_result(mobj.group('ec'))
707
708         # Look for Aparat videos
709         mobj = re.search(r'<iframe .*?src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
710         if mobj is not None:
711             return self.url_result(mobj.group(1), 'Aparat')
712
713         # Look for MPORA videos
714         mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
715         if mobj is not None:
716             return self.url_result(mobj.group(1), 'Mpora')
717
718         # Look for embedded NovaMov-based player
719         mobj = re.search(
720             r'''(?x)<(?:pagespeed_)?iframe[^>]+?src=(["\'])
721                     (?P<url>http://(?:(?:embed|www)\.)?
722                         (?:novamov\.com|
723                            nowvideo\.(?:ch|sx|eu|at|ag|co)|
724                            videoweed\.(?:es|com)|
725                            movshare\.(?:net|sx|ag)|
726                            divxstage\.(?:eu|net|ch|co|at|ag))
727                         /embed\.php.+?)\1''', webpage)
728         if mobj is not None:
729             return self.url_result(mobj.group('url'))
730
731         # Look for embedded Facebook player
732         mobj = re.search(
733             r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
734         if mobj is not None:
735             return self.url_result(mobj.group('url'), 'Facebook')
736
737         # Look for embedded VK player
738         mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
739         if mobj is not None:
740             return self.url_result(mobj.group('url'), 'VK')
741
742         # Look for embedded ivi player
743         mobj = re.search(r'<embed[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?ivi\.ru/video/player.+?)\1', webpage)
744         if mobj is not None:
745             return self.url_result(mobj.group('url'), 'Ivi')
746
747         # Look for embedded Huffington Post player
748         mobj = re.search(
749             r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
750         if mobj is not None:
751             return self.url_result(mobj.group('url'), 'HuffPost')
752
753         # Look for embed.ly
754         mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
755         if mobj is not None:
756             return self.url_result(mobj.group('url'))
757         mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
758         if mobj is not None:
759             return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
760
761         # Look for funnyordie embed
762         matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
763         if matches:
764             return _playlist_from_matches(
765                 matches, getter=unescapeHTML, ie='FunnyOrDie')
766
767         # Look for embedded RUTV player
768         rutv_url = RUTVIE._extract_url(webpage)
769         if rutv_url:
770             return self.url_result(rutv_url, 'RUTV')
771
772         # Look for embedded TED player
773         mobj = re.search(
774             r'<iframe[^>]+?src=(["\'])(?P<url>http://embed\.ted\.com/.+?)\1', webpage)
775         if mobj is not None:
776             return self.url_result(mobj.group('url'), 'TED')
777
778         # Look for embedded Ustream videos
779         mobj = re.search(
780             r'<iframe[^>]+?src=(["\'])(?P<url>http://www\.ustream\.tv/embed/.+?)\1', webpage)
781         if mobj is not None:
782             return self.url_result(mobj.group('url'), 'Ustream')
783
784         # Look for embedded arte.tv player
785         mobj = re.search(
786             r'<script [^>]*?src="(?P<url>http://www\.arte\.tv/playerv2/embed[^"]+)"',
787             webpage)
788         if mobj is not None:
789             return self.url_result(mobj.group('url'), 'ArteTVEmbed')
790
791         # Look for embedded smotri.com player
792         smotri_url = SmotriIE._extract_url(webpage)
793         if smotri_url:
794             return self.url_result(smotri_url, 'Smotri')
795
796         # Look for embeded soundcloud player
797         mobj = re.search(
798             r'<iframe src="(?P<url>https?://(?:w\.)?soundcloud\.com/player[^"]+)"',
799             webpage)
800         if mobj is not None:
801             url = unescapeHTML(mobj.group('url'))
802             return self.url_result(url)
803
804         # Look for embedded vulture.com player
805         mobj = re.search(
806             r'<iframe src="(?P<url>https?://video\.vulture\.com/[^"]+)"',
807             webpage)
808         if mobj is not None:
809             url = unescapeHTML(mobj.group('url'))
810             return self.url_result(url, ie='Vulture')
811
812         # Look for embedded mtvservices player
813         mobj = re.search(
814             r'<iframe src="(?P<url>https?://media\.mtvnservices\.com/embed/[^"]+)"',
815             webpage)
816         if mobj is not None:
817             url = unescapeHTML(mobj.group('url'))
818             return self.url_result(url, ie='MTVServicesEmbedded')
819
820         # Look for embedded yahoo player
821         mobj = re.search(
822             r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1',
823             webpage)
824         if mobj is not None:
825             return self.url_result(mobj.group('url'), 'Yahoo')
826
827         # Look for embedded sbs.com.au player
828         mobj = re.search(
829             r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:www\.)sbs\.com\.au/ondemand/video/single/.+?)\1',
830             webpage)
831         if mobj is not None:
832             return self.url_result(mobj.group('url'), 'SBS')
833
834         mobj = re.search(
835             r'<iframe[^>]+?src=(["\'])(?P<url>https?://m\.mlb\.com/shared/video/embed/embed\.html\?.+?)\1',
836             webpage)
837         if mobj is not None:
838             return self.url_result(mobj.group('url'), 'MLB')
839
840         # Start with something easy: JW Player in SWFObject
841         found = re.findall(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
842         if not found:
843             # Look for gorilla-vid style embedding
844             found = re.findall(r'''(?sx)
845                 (?:
846                     jw_plugins|
847                     JWPlayerOptions|
848                     jwplayer\s*\(\s*["'][^'"]+["']\s*\)\s*\.setup
849                 )
850                 .*?file\s*:\s*["\'](.*?)["\']''', webpage)
851         if not found:
852             # Broaden the search a little bit
853             found = re.findall(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
854         if not found:
855             # Broaden the findall a little bit: JWPlayer JS loader
856             found = re.findall(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
857         if not found:
858             # Flow player
859             found = re.findall(r'''(?xs)
860                 flowplayer\("[^"]+",\s*
861                     \{[^}]+?\}\s*,
862                     \s*{[^}]+? ["']?clip["']?\s*:\s*\{\s*
863                         ["']?url["']?\s*:\s*["']([^"']+)["']
864             ''', webpage)
865         if not found:
866             # Try to find twitter cards info
867             found = re.findall(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
868         if not found:
869             # We look for Open Graph info:
870             # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
871             m_video_type = re.findall(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
872             # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
873             if m_video_type is not None:
874                 def check_video(vurl):
875                     vpath = compat_urlparse.urlparse(vurl).path
876                     vext = determine_ext(vpath)
877                     return '.' in vpath and vext not in ('swf', 'png', 'jpg')
878                 found = list(filter(
879                     check_video,
880                     re.findall(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)))
881         if not found:
882             # HTML5 video
883             found = re.findall(r'(?s)<video[^<]*(?:>.*?<source[^>]+)? src="([^"]+)"', webpage)
884         if not found:
885             found = re.search(
886                 r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
887                 r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'?([^\'"]+)',
888                 webpage)
889             if found:
890                 new_url = found.group(1)
891                 self.report_following_redirect(new_url)
892                 return {
893                     '_type': 'url',
894                     'url': new_url,
895                 }
896         if not found:
897             raise ExtractorError('Unsupported URL: %s' % url)
898
899         entries = []
900         for video_url in found:
901             video_url = compat_urlparse.urljoin(url, video_url)
902             video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
903
904             # Sometimes, jwplayer extraction will result in a YouTube URL
905             if YoutubeIE.suitable(video_url):
906                 entries.append(self.url_result(video_url, 'Youtube'))
907                 continue
908
909             # here's a fun little line of code for you:
910             video_id = os.path.splitext(video_id)[0]
911
912             entries.append({
913                 'id': video_id,
914                 'url': video_url,
915                 'uploader': video_uploader,
916                 'title': video_title,
917                 'age_limit': age_limit,
918             })
919
920         if len(entries) == 1:
921             return entries[0]
922         else:
923             for num, e in enumerate(entries, start=1):
924                 e['title'] = '%s (%d)' % (e['title'], num)
925             return {
926                 '_type': 'playlist',
927                 'entries': entries,
928             }
929