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