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