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