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