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