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