3 from __future__ import unicode_literals
7 import xml.etree.ElementTree
9 from .common import InfoExtractor
10 from .youtube import YoutubeIE
14 compat_urllib_request,
16 compat_xml_parse_error,
25 from .brightcove import BrightcoveIE
26 from .ooyala import OoyalaIE
29 class GenericIE(InfoExtractor):
30 IE_DESC = 'Generic downloader that works on some sites'
35 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
36 'file': '13601338388002.mp4',
37 'md5': '6e15c93721d7ec9e9ca3fdbf07982cfd',
39 'uploader': 'www.hodiho.fr',
40 'title': 'R\u00e9gis plante sa Jeep',
43 # bandcamp page with custom domain
45 'add_ie': ['Bandcamp'],
46 'url': 'http://bronyrock.com/track/the-pony-mash',
47 'file': '3235767654.mp3',
49 'title': 'The Pony Mash',
50 'uploader': 'M_Pallante',
52 'skip': 'There is a limit of 200 free downloads / month for the test song',
54 # embedded brightcove video
55 # it also tests brightcove videos that need to set the 'Referer' in the
58 'add_ie': ['Brightcove'],
59 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
61 'id': '2765128793001',
63 'title': 'Le cours de bourse : l’analyse technique',
64 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
65 'uploader': 'BFM BUSINESS',
68 'skip_download': True,
72 # https://github.com/rg3/youtube-dl/issues/2253
73 'url': 'http://bcove.me/i6nfkrc3',
74 'file': '3101154703001.mp4',
75 'md5': '0ba9446db037002366bab3b3eb30c88c',
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.',
81 'add_ie': ['Brightcove'],
83 # Direct link to a video
85 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
86 'file': 'trailer.mp4',
87 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
91 'upload_date': '20100513',
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',
100 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
102 'title': '2cc213299525360.mov', # that's what we get
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)
113 def report_following_redirect(self, new_url):
114 """Report information extraction."""
115 self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
117 def _send_head(self, url):
118 """Check if it is a redirect, like url shorteners, in case return the new url."""
120 class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
122 Subclass the HTTPRedirectHandler to make it use our
123 HEADRequest also on the redirected URL
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,
132 origin_req_host=req.get_origin_req_host(),
135 raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
137 class HTTPMethodFallback(compat_urllib_request.BaseHandler):
139 Fallback to GET if HEAD is not allowed (405 HTTP error)
141 def http_error_405(self, req, fp, code, msg, headers):
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(),
149 origin_req_host=req.get_origin_req_host(),
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())
159 response = opener.open(HEADRequest(url))
161 raise ExtractorError('Invalid URL protocol')
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
171 'url': e.find('link').text,
172 'title': e.find('title').text,
173 } for e in doc.findall('./channel/item')]
178 'title': playlist_title,
179 'description': playlist_desc,
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'
190 if default_search == 'auto':
192 self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
193 return self.url_result('http://' + url)
195 return self.url_result('ytsearch:' + url)
197 assert ':' in default_search
198 return self.url_result(default_search + url)
199 video_id = os.path.splitext(url.split('/')[-1])[0]
201 self.to_screen('%s: Requesting header' % video_id)
204 response = self._send_head(url)
207 new_url = response.geturl()
209 self.report_following_redirect(new_url)
210 return self.url_result(new_url)
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)
216 upload_date = response.headers.get('Last-Modified')
218 upload_date = unified_strdate(upload_date)
221 'title': os.path.splitext(url_basename(url))[0],
223 'format_id': m.group('format_id'),
225 'vcodec': 'none' if m.group('type') == 'audio' else None
227 'upload_date': upload_date,
230 except compat_urllib_error.HTTPError:
231 # This may be a stupid server that doesn't like HEAD, our UA, or so
235 webpage = self._download_webpage(url, video_id)
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)
241 self.report_extraction(video_id)
245 doc = xml.etree.ElementTree.fromstring(webpage.encode('utf-8'))
247 return self._extract_rss(url, video_id, doc)
248 except compat_xml_parse_error:
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',
261 # video uploader is domain name
262 video_uploader = self._search_regex(
263 r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
265 # Look for BrightCove:
266 bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
268 self.to_screen('Brightcove video detected.')
271 'url': smuggle_url(bc_url, {'Referer': url}),
272 'ie_key': 'Brightcove'
273 } for bc_url in bc_urls]
277 'title': video_title,
282 # Look for embedded (iframe) Vimeo player
284 r'<iframe[^>]+?src="((?:https?:)?//player\.vimeo\.com/video/.+?)"', webpage)
286 player_url = unescapeHTML(mobj.group(1))
287 surl = smuggle_url(player_url, {'Referer': url})
288 return self.url_result(surl, 'Vimeo')
290 # Look for embedded (swf embed) Vimeo player
292 r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
294 return self.url_result(mobj.group(1), 'Vimeo')
296 # Look for embedded YouTube player
297 matches = re.findall(r'''(?x)
298 (?:<iframe[^>]+?src=|embedSWF\(\s*)
299 (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
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)
308 # Look for embedded Dailymotion player
309 matches = re.findall(
310 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
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)
317 # Look for embedded Wistia player
319 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
322 '_type': 'url_transparent',
323 'url': unescapeHTML(match.group('url')),
325 'uploader': video_uploader,
326 'title': video_title,
330 # Look for embedded blip.tv player
331 mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
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)
336 return self.url_result(mobj.group(1), 'BlipTV')
338 # Look for Bandcamp pages with custom domain
339 mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
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)
345 # Look for embedded Vevo player
347 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
349 return self.url_result(mobj.group('url'))
351 # Look for Ooyala videos
352 mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
354 return OoyalaIE._build_url_result(mobj.group(1))
356 # Look for Aparat videos
357 mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
359 return self.url_result(mobj.group(1), 'Aparat')
361 # Look for MPORA videos
362 mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
364 return self.url_result(mobj.group(1), 'Mpora')
366 # Look for embedded Novamov player
368 r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
370 return self.url_result(mobj.group('url'), 'Novamov')
372 # Look for embedded Facebook player
374 r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
376 return self.url_result(mobj.group('url'), 'Facebook')
378 # Look for embedded Huffington Post player
380 r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
382 return self.url_result(mobj.group('url'), 'HuffPost')
384 # Start with something easy: JW Player in SWFObject
385 mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
387 # Look for gorilla-vid style embedding
388 mobj = re.search(r'(?s)(?:jw_plugins|JWPlayerOptions).*?file\s*:\s*["\'](.*?)["\']', webpage)
390 # Broaden the search a little bit
391 mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
393 # Broaden the search a little bit: JWPlayer JS loader
394 mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
396 # Try to find twitter cards info
397 mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
399 # We look for Open Graph info:
400 # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
401 m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
402 # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
403 if m_video_type is not None:
404 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
407 mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
409 raise ExtractorError('Unsupported URL: %s' % url)
411 # It's possible that one of the regexes
412 # matched, but returned an empty group:
413 if mobj.group(1) is None:
414 raise ExtractorError('Did not find a valid video URL at %s' % url)
416 video_url = mobj.group(1)
417 video_url = compat_urlparse.urljoin(url, video_url)
418 video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
420 # Sometimes, jwplayer extraction will result in a YouTube URL
421 if YoutubeIE.suitable(video_url):
422 return self.url_result(video_url, 'Youtube')
424 # here's a fun little line of code for you:
425 video_id = os.path.splitext(video_id)[0]
430 'uploader': video_uploader,
431 'title': video_title,