Improve some regexes for embedded players
[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_error,
12     compat_urllib_parse,
13     compat_urllib_request,
14     compat_urlparse,
15
16     ExtractorError,
17     HEADRequest,
18     smuggle_url,
19     unescapeHTML,
20     unified_strdate,
21     url_basename,
22 )
23 from .brightcove import BrightcoveIE
24 from .ooyala import OoyalaIE
25
26
27 class GenericIE(InfoExtractor):
28     IE_DESC = 'Generic downloader that works on some sites'
29     _VALID_URL = r'.*'
30     IE_NAME = 'generic'
31     _TESTS = [
32         {
33             'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
34             'file': '13601338388002.mp4',
35             'md5': '6e15c93721d7ec9e9ca3fdbf07982cfd',
36             'info_dict': {
37                 'uploader': 'www.hodiho.fr',
38                 'title': 'R\u00e9gis plante sa Jeep',
39             }
40         },
41         # embedded vimeo video
42         {
43             'add_ie': ['Vimeo'],
44             'url': 'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
45             'file': '22444065.mp4',
46             'md5': '2903896e23df39722c33f015af0666e2',
47             'info_dict': {
48                 'title': 'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
49                 'uploader_id': 'skillsmatter',
50                 'uploader': 'Skills Matter',
51             }
52         },
53         # bandcamp page with custom domain
54         {
55             'add_ie': ['Bandcamp'],
56             'url': 'http://bronyrock.com/track/the-pony-mash',
57             'file': '3235767654.mp3',
58             'info_dict': {
59                 'title': 'The Pony Mash',
60                 'uploader': 'M_Pallante',
61             },
62             'skip': 'There is a limit of 200 free downloads / month for the test song',
63         },
64         # embedded brightcove video
65         # it also tests brightcove videos that need to set the 'Referer' in the
66         # http requests
67         {
68             'add_ie': ['Brightcove'],
69             'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
70             'info_dict': {
71                 'id': '2765128793001',
72                 'ext': 'mp4',
73                 'title': 'Le cours de bourse : l’analyse technique',
74                 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
75                 'uploader': 'BFM BUSINESS',
76             },
77             'params': {
78                 'skip_download': True,
79             },
80         },
81         {
82             # https://github.com/rg3/youtube-dl/issues/2253
83             'url': 'http://bcove.me/i6nfkrc3',
84             'file': '3101154703001.mp4',
85             'md5': '0ba9446db037002366bab3b3eb30c88c',
86             'info_dict': {
87                 'title': 'Still no power',
88                 'uploader': 'thestar.com',
89                 '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.',
90             },
91             'add_ie': ['Brightcove'],
92         },
93         # Direct link to a video
94         {
95             'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
96             'file': 'trailer.mp4',
97             'md5': '67d406c2bcb6af27fa886f31aa934bbe',
98             'info_dict': {
99                 'id': 'trailer',
100                 'title': 'trailer',
101                 'upload_date': '20100513',
102             }
103         },
104         # ooyala video
105         {
106             'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
107             'file': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ.mp4',
108             'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
109             'info_dict': {
110                 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
111                 'ext': 'mp4',
112                 'title': '2cc213299525360.mov',  # that's what we get
113             },
114         },
115     ]
116
117     def report_download_webpage(self, video_id):
118         """Report webpage download."""
119         if not self._downloader.params.get('test', False):
120             self._downloader.report_warning('Falling back on generic information extractor.')
121         super(GenericIE, self).report_download_webpage(video_id)
122
123     def report_following_redirect(self, new_url):
124         """Report information extraction."""
125         self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
126
127     def _send_head(self, url):
128         """Check if it is a redirect, like url shorteners, in case return the new url."""
129
130         class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
131             """
132             Subclass the HTTPRedirectHandler to make it use our
133             HEADRequest also on the redirected URL
134             """
135             def redirect_request(self, req, fp, code, msg, headers, newurl):
136                 if code in (301, 302, 303, 307):
137                     newurl = newurl.replace(' ', '%20')
138                     newheaders = dict((k,v) for k,v in req.headers.items()
139                                       if k.lower() not in ("content-length", "content-type"))
140                     return HEADRequest(newurl,
141                                        headers=newheaders,
142                                        origin_req_host=req.get_origin_req_host(),
143                                        unverifiable=True)
144                 else:
145                     raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
146
147         class HTTPMethodFallback(compat_urllib_request.BaseHandler):
148             """
149             Fallback to GET if HEAD is not allowed (405 HTTP error)
150             """
151             def http_error_405(self, req, fp, code, msg, headers):
152                 fp.read()
153                 fp.close()
154
155                 newheaders = dict((k,v) for k,v in req.headers.items()
156                                   if k.lower() not in ("content-length", "content-type"))
157                 return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
158                                                  headers=newheaders,
159                                                  origin_req_host=req.get_origin_req_host(),
160                                                  unverifiable=True))
161
162         # Build our opener
163         opener = compat_urllib_request.OpenerDirector()
164         for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
165                         HTTPMethodFallback, HEADRedirectHandler,
166                         compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
167             opener.add_handler(handler())
168
169         response = opener.open(HEADRequest(url))
170         if response is None:
171             raise ExtractorError('Invalid URL protocol')
172         return response
173
174     def _real_extract(self, url):
175         parsed_url = compat_urlparse.urlparse(url)
176         if not parsed_url.scheme:
177             default_search = self._downloader.params.get('default_search')
178             if default_search is None:
179                 default_search = 'auto'
180
181             if default_search == 'auto':
182                 if '/' in url:
183                     self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
184                     return self.url_result('http://' + url)
185                 else:
186                     return self.url_result('ytsearch:' + url)
187             else:
188                 assert ':' in default_search
189                 return self.url_result(default_search + url)
190         video_id = os.path.splitext(url.split('/')[-1])[0]
191
192         self.to_screen('%s: Requesting header' % video_id)
193
194         try:
195             response = self._send_head(url)
196
197             # Check for redirect
198             new_url = response.geturl()
199             if url != new_url:
200                 self.report_following_redirect(new_url)
201                 return self.url_result(new_url)
202
203             # Check for direct link to a video
204             content_type = response.headers.get('Content-Type', '')
205             m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
206             if m:
207                 upload_date = response.headers.get('Last-Modified')
208                 if upload_date:
209                     upload_date = unified_strdate(upload_date)
210                 return {
211                     'id': video_id,
212                     'title': os.path.splitext(url_basename(url))[0],
213                     'formats': [{
214                         'format_id': m.group('format_id'),
215                         'url': url,
216                         'vcodec': 'none' if m.group('type') == 'audio' else None
217                     }],
218                     'upload_date': upload_date,
219                 }
220
221         except compat_urllib_error.HTTPError:
222             # This may be a stupid server that doesn't like HEAD, our UA, or so
223             pass
224
225         try:
226             webpage = self._download_webpage(url, video_id)
227         except ValueError:
228             # since this is the last-resort InfoExtractor, if
229             # this error is thrown, it'll be thrown here
230             raise ExtractorError('Failed to download URL: %s' % url)
231
232         self.report_extraction(video_id)
233
234         # it's tempting to parse this further, but you would
235         # have to take into account all the variations like
236         #   Video Title - Site Name
237         #   Site Name | Video Title
238         #   Video Title - Tagline | Site Name
239         # and so on and so forth; it's just not practical
240         video_title = self._html_search_regex(
241             r'(?s)<title>(.*?)</title>', webpage, 'video title',
242             default='video')
243
244         # video uploader is domain name
245         video_uploader = self._search_regex(
246             r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
247
248         # Look for BrightCove:
249         bc_url = BrightcoveIE._extract_brightcove_url(webpage)
250         if bc_url is not None:
251             self.to_screen('Brightcove video detected.')
252             surl = smuggle_url(bc_url, {'Referer': url})
253             return self.url_result(surl, 'Brightcove')
254
255         # Look for embedded (iframe) Vimeo player
256         mobj = re.search(
257             r'<iframe[^>]+?src="((?:https?:)?//player\.vimeo\.com/video/.+?)"', webpage)
258         if mobj:
259             player_url = unescapeHTML(mobj.group(1))
260             surl = smuggle_url(player_url, {'Referer': url})
261             return self.url_result(surl, 'Vimeo')
262
263         # Look for embedded (swf embed) Vimeo player
264         mobj = re.search(
265             r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
266         if mobj:
267             return self.url_result(mobj.group(1), 'Vimeo')
268
269         # Look for embedded YouTube player
270         matches = re.findall(r'''(?x)
271             (?:<iframe[^>]+?src=|embedSWF\(\s*)
272             (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
273                 (?:embed|v)/.+?)
274             \1''', webpage)
275         if matches:
276             urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
277                      for tuppl in matches]
278             return self.playlist_result(
279                 urlrs, playlist_id=video_id, playlist_title=video_title)
280
281         # Look for embedded Dailymotion player
282         matches = re.findall(
283             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
284         if matches:
285             urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
286                      for tuppl in matches]
287             return self.playlist_result(
288                 urlrs, playlist_id=video_id, playlist_title=video_title)
289
290         # Look for embedded Wistia player
291         match = re.search(
292             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
293         if match:
294             return {
295                 '_type': 'url_transparent',
296                 'url': unescapeHTML(match.group('url')),
297                 'ie_key': 'Wistia',
298                 'uploader': video_uploader,
299                 'title': video_title,
300                 'id': video_id,
301             }
302
303         # Look for embedded blip.tv player
304         mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
305         if mobj:
306             return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
307         mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
308         if mobj:
309             return self.url_result(mobj.group(1), 'BlipTV')
310
311         # Look for Bandcamp pages with custom domain
312         mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
313         if mobj is not None:
314             burl = unescapeHTML(mobj.group(1))
315             # Don't set the extractor because it can be a track url or an album
316             return self.url_result(burl)
317
318         # Look for embedded Vevo player
319         mobj = re.search(
320             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
321         if mobj is not None:
322             return self.url_result(mobj.group('url'))
323
324         # Look for Ooyala videos
325         mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
326         if mobj is not None:
327             return OoyalaIE._build_url_result(mobj.group(1))
328
329         # Look for Aparat videos
330         mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
331         if mobj is not None:
332             return self.url_result(mobj.group(1), 'Aparat')
333
334         # Look for MPORA videos
335         mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
336         if mobj is not None:
337             return self.url_result(mobj.group(1), 'Mpora')
338
339         # Look for embedded Novamov player
340         mobj = re.search(
341             r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
342         if mobj is not None:
343             return self.url_result(mobj.group('url'), 'Novamov')
344
345         # Look for embedded Facebook player
346         mobj = re.search(
347             r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
348         if mobj is not None:
349             return self.url_result(mobj.group('url'), 'Facebook')
350
351         # Look for embedded Huffington Post player
352         mobj = re.search(
353             r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
354         if mobj is not None:
355             return self.url_result(mobj.group('url'), 'HuffPost')
356
357         # Start with something easy: JW Player in SWFObject
358         mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
359         if mobj is None:
360             # Look for gorilla-vid style embedding
361             mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
362         if mobj is None:
363             # Broaden the search a little bit
364             mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
365         if mobj is None:
366             # Broaden the search a little bit: JWPlayer JS loader
367             mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
368         if mobj is None:
369             # Try to find twitter cards info
370             mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
371         if mobj is None:
372             # We look for Open Graph info:
373             # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
374             m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
375             # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
376             if m_video_type is not None:
377                 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
378         if mobj is None:
379             # HTML5 video
380             mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
381         if mobj is None:
382             raise ExtractorError('Unsupported URL: %s' % url)
383
384         # It's possible that one of the regexes
385         # matched, but returned an empty group:
386         if mobj.group(1) is None:
387             raise ExtractorError('Did not find a valid video URL at %s' % url)
388
389         video_url = mobj.group(1)
390         video_url = compat_urlparse.urljoin(url, video_url)
391         video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
392
393         # Sometimes, jwplayer extraction will result in a YouTube URL
394         if YoutubeIE.suitable(video_url):
395             return self.url_result(video_url, 'Youtube')
396
397         # here's a fun little line of code for you:
398         video_id = os.path.splitext(video_id)[0]
399
400         return {
401             'id': video_id,
402             'url': video_url,
403             'uploader': video_uploader,
404             'title': video_title,
405         }