[generic] Improve testcase
[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         # Direct link to a video
82         {
83             'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
84             'file': 'trailer.mp4',
85             'md5': '67d406c2bcb6af27fa886f31aa934bbe',
86             'info_dict': {
87                 'id': 'trailer',
88                 'title': 'trailer',
89                 'upload_date': '20100513',
90             }
91         },
92         # ooyala video
93         {
94             'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
95             'file': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ.mp4',
96             'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
97             'info_dict': {
98                 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
99                 'ext': 'mp4',
100                 'title': '2cc213299525360.mov',  # that's what we get
101             },
102         },
103     ]
104
105     def report_download_webpage(self, video_id):
106         """Report webpage download."""
107         if not self._downloader.params.get('test', False):
108             self._downloader.report_warning('Falling back on generic information extractor.')
109         super(GenericIE, self).report_download_webpage(video_id)
110
111     def report_following_redirect(self, new_url):
112         """Report information extraction."""
113         self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
114
115     def _send_head(self, url):
116         """Check if it is a redirect, like url shorteners, in case return the new url."""
117
118         class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
119             """
120             Subclass the HTTPRedirectHandler to make it use our
121             HEADRequest also on the redirected URL
122             """
123             def redirect_request(self, req, fp, code, msg, headers, newurl):
124                 if code in (301, 302, 303, 307):
125                     newurl = newurl.replace(' ', '%20')
126                     newheaders = dict((k,v) for k,v in req.headers.items()
127                                       if k.lower() not in ("content-length", "content-type"))
128                     return HEADRequest(newurl,
129                                        headers=newheaders,
130                                        origin_req_host=req.get_origin_req_host(),
131                                        unverifiable=True)
132                 else:
133                     raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
134
135         class HTTPMethodFallback(compat_urllib_request.BaseHandler):
136             """
137             Fallback to GET if HEAD is not allowed (405 HTTP error)
138             """
139             def http_error_405(self, req, fp, code, msg, headers):
140                 fp.read()
141                 fp.close()
142
143                 newheaders = dict((k,v) for k,v in req.headers.items()
144                                   if k.lower() not in ("content-length", "content-type"))
145                 return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
146                                                  headers=newheaders,
147                                                  origin_req_host=req.get_origin_req_host(),
148                                                  unverifiable=True))
149
150         # Build our opener
151         opener = compat_urllib_request.OpenerDirector()
152         for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
153                         HTTPMethodFallback, HEADRedirectHandler,
154                         compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
155             opener.add_handler(handler())
156
157         response = opener.open(HEADRequest(url))
158         if response is None:
159             raise ExtractorError('Invalid URL protocol')
160         return response
161
162     def _real_extract(self, url):
163         parsed_url = compat_urlparse.urlparse(url)
164         if not parsed_url.scheme:
165             self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
166             return self.url_result('http://' + url)
167         video_id = os.path.splitext(url.split('/')[-1])[0]
168
169         self.to_screen('%s: Requesting header' % video_id)
170
171         try:
172             response = self._send_head(url)
173
174             # Check for redirect
175             new_url = response.geturl()
176             if url != new_url:
177                 self.report_following_redirect(new_url)
178                 return self.url_result(new_url)
179
180             # Check for direct link to a video
181             content_type = response.headers.get('Content-Type', '')
182             m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
183             if m:
184                 upload_date = response.headers.get('Last-Modified')
185                 if upload_date:
186                     upload_date = unified_strdate(upload_date)
187                 return {
188                     'id': video_id,
189                     'title': os.path.splitext(url_basename(url))[0],
190                     'formats': [{
191                         'format_id': m.group('format_id'),
192                         'url': url,
193                         'vcodec': 'none' if m.group('type') == 'audio' else None
194                     }],
195                     'upload_date': upload_date,
196                 }
197
198         except compat_urllib_error.HTTPError:
199             # This may be a stupid server that doesn't like HEAD, our UA, or so
200             pass
201
202         try:
203             webpage = self._download_webpage(url, video_id)
204         except ValueError:
205             # since this is the last-resort InfoExtractor, if
206             # this error is thrown, it'll be thrown here
207             raise ExtractorError('Failed to download URL: %s' % url)
208
209         self.report_extraction(video_id)
210
211         # it's tempting to parse this further, but you would
212         # have to take into account all the variations like
213         #   Video Title - Site Name
214         #   Site Name | Video Title
215         #   Video Title - Tagline | Site Name
216         # and so on and so forth; it's just not practical
217         video_title = self._html_search_regex(
218             r'(?s)<title>(.*?)</title>', webpage, 'video title',
219             default='video')
220
221         # video uploader is domain name
222         video_uploader = self._search_regex(
223             r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
224
225         # Look for BrightCove:
226         bc_url = BrightcoveIE._extract_brightcove_url(webpage)
227         if bc_url is not None:
228             self.to_screen('Brightcove video detected.')
229             surl = smuggle_url(bc_url, {'Referer': url})
230             return self.url_result(surl, 'Brightcove')
231
232         # Look for embedded (iframe) Vimeo player
233         mobj = re.search(
234             r'<iframe[^>]+?src="((?:https?:)?//player.vimeo.com/video/.+?)"', webpage)
235         if mobj:
236             player_url = unescapeHTML(mobj.group(1))
237             surl = smuggle_url(player_url, {'Referer': url})
238             return self.url_result(surl, 'Vimeo')
239
240         # Look for embedded (swf embed) Vimeo player
241         mobj = re.search(
242             r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
243         if mobj:
244             return self.url_result(mobj.group(1), 'Vimeo')
245
246         # Look for embedded YouTube player
247         matches = re.findall(r'''(?x)
248             (?:<iframe[^>]+?src=|embedSWF\(\s*)
249             (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
250                 (?:embed|v)/.+?)
251             \1''', webpage)
252         if matches:
253             urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
254                      for tuppl in matches]
255             return self.playlist_result(
256                 urlrs, playlist_id=video_id, playlist_title=video_title)
257
258         # Look for embedded Dailymotion player
259         matches = re.findall(
260             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
261         if matches:
262             urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
263                      for tuppl in matches]
264             return self.playlist_result(
265                 urlrs, playlist_id=video_id, playlist_title=video_title)
266
267         # Look for embedded Wistia player
268         match = re.search(
269             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
270         if match:
271             return {
272                 '_type': 'url_transparent',
273                 'url': unescapeHTML(match.group('url')),
274                 'ie_key': 'Wistia',
275                 'uploader': video_uploader,
276                 'title': video_title,
277                 'id': video_id,
278             }
279
280         # Look for embedded blip.tv player
281         mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
282         if mobj:
283             return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
284         mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
285         if mobj:
286             return self.url_result(mobj.group(1), 'BlipTV')
287
288         # Look for Bandcamp pages with custom domain
289         mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
290         if mobj is not None:
291             burl = unescapeHTML(mobj.group(1))
292             # Don't set the extractor because it can be a track url or an album
293             return self.url_result(burl)
294
295         # Look for embedded Vevo player
296         mobj = re.search(
297             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
298         if mobj is not None:
299             return self.url_result(mobj.group('url'))
300
301         # Look for Ooyala videos
302         mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
303         if mobj is not None:
304             return OoyalaIE._build_url_result(mobj.group(1))
305
306         # Look for Aparat videos
307         mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
308         if mobj is not None:
309             return self.url_result(mobj.group(1), 'Aparat')
310
311         # Look for MPORA videos
312         mobj = re.search(r'<iframe .*?src="(http://mpora\.com/videos/[^"]+)"', webpage)
313         if mobj is not None:
314             return self.url_result(mobj.group(1), 'Mpora')
315
316         # Look for embedded Novamov player
317         mobj = re.search(
318             r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
319         if mobj is not None:
320             return self.url_result(mobj.group('url'), 'Novamov')
321
322         # Start with something easy: JW Player in SWFObject
323         mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
324         if mobj is None:
325             # Look for gorilla-vid style embedding
326             mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
327         if mobj is None:
328             # Broaden the search a little bit
329             mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
330         if mobj is None:
331             # Broaden the search a little bit: JWPlayer JS loader
332             mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
333         if mobj is None:
334             # Try to find twitter cards info
335             mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
336         if mobj is None:
337             # We look for Open Graph info:
338             # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
339             m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
340             # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
341             if m_video_type is not None:
342                 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
343         if mobj is None:
344             # HTML5 video
345             mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
346         if mobj is None:
347             raise ExtractorError('Unsupported URL: %s' % url)
348
349         # It's possible that one of the regexes
350         # matched, but returned an empty group:
351         if mobj.group(1) is None:
352             raise ExtractorError('Did not find a valid video URL at %s' % url)
353
354         video_url = mobj.group(1)
355         video_url = compat_urlparse.urljoin(url, video_url)
356         video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
357
358         # Sometimes, jwplayer extraction will result in a YouTube URL
359         if YoutubeIE.suitable(video_url):
360             return self.url_result(video_url, 'Youtube')
361
362         # here's a fun little line of code for you:
363         video_id = os.path.splitext(video_id)[0]
364
365         return {
366             'id': video_id,
367             'url': video_url,
368             'uploader': video_uploader,
369             'title': video_title,
370         }