]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/generic.py
[utils] Fix url_basename
[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,
9d4660ca
PH
14 smuggle_url,
15 unescapeHTML,
9b122384 16)
cfe50f04 17from .brightcove import BrightcoveIE
9b122384 18
0838239e 19
9b122384 20class GenericIE(InfoExtractor):
0f818663 21 IE_DESC = u'Generic downloader that works on some sites'
9b122384
PH
22 _VALID_URL = r'.*'
23 IE_NAME = u'generic'
cfe50f04
JMF
24 _TESTS = [
25 {
26 u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
27 u'file': u'13601338388002.mp4',
aa929c37 28 u'md5': u'6e15c93721d7ec9e9ca3fdbf07982cfd',
cfe50f04 29 u'info_dict': {
0838239e 30 u"uploader": u"www.hodiho.fr",
cfe50f04
JMF
31 u"title": u"R\u00e9gis plante sa Jeep"
32 }
33 },
9d4660ca
PH
34 # embedded vimeo video
35 {
9ee2b5f6 36 u'add_ie': ['Vimeo'],
9d4660ca
PH
37 u'url': u'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
38 u'file': u'22444065.mp4',
39 u'md5': u'2903896e23df39722c33f015af0666e2',
40 u'info_dict': {
41 u'title': u'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
42 u"uploader_id": u"skillsmatter",
43 u"uploader": u"Skills Matter",
44 }
c19f7764
JMF
45 },
46 # bandcamp page with custom domain
47 {
9ee2b5f6 48 u'add_ie': ['Bandcamp'],
c19f7764
JMF
49 u'url': u'http://bronyrock.com/track/the-pony-mash',
50 u'file': u'3235767654.mp3',
51 u'info_dict': {
52 u'title': u'The Pony Mash',
53 u'uploader': u'M_Pallante',
54 },
55 u'skip': u'There is a limit of 200 free downloads / month for the test song',
56 },
eeb165e6 57 # embedded brightcove video
dd5bcdc4
JMF
58 # it also tests brightcove videos that need to set the 'Referer' in the
59 # http requests
eeb165e6
JMF
60 {
61 u'add_ie': ['Brightcove'],
dd5bcdc4 62 u'url': u'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
eeb165e6 63 u'info_dict': {
dd5bcdc4 64 u'id': u'2765128793001',
eeb165e6 65 u'ext': u'mp4',
dd5bcdc4
JMF
66 u'title': u'Le cours de bourse : l’analyse technique',
67 u'description': u'md5:7e9ad046e968cb2d1114004aba466fd9',
68 u'uploader': u'BFM BUSINESS',
eeb165e6
JMF
69 },
70 u'params': {
71 u'skip_download': True,
72 },
73 },
cfe50f04 74 ]
9b122384
PH
75
76 def report_download_webpage(self, video_id):
77 """Report webpage download."""
78 if not self._downloader.params.get('test', False):
79 self._downloader.report_warning(u'Falling back on generic information extractor.')
80 super(GenericIE, self).report_download_webpage(video_id)
81
82 def report_following_redirect(self, new_url):
83 """Report information extraction."""
84 self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
85
86 def _test_redirect(self, url):
87 """Check if it is a redirect, like url shorteners, in case return the new url."""
88 class HeadRequest(compat_urllib_request.Request):
89 def get_method(self):
90 return "HEAD"
91
92 class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
93 """
94 Subclass the HTTPRedirectHandler to make it use our
95 HeadRequest also on the redirected URL
96 """
97 def redirect_request(self, req, fp, code, msg, headers, newurl):
98 if code in (301, 302, 303, 307):
99 newurl = newurl.replace(' ', '%20')
100 newheaders = dict((k,v) for k,v in req.headers.items()
101 if k.lower() not in ("content-length", "content-type"))
102 return HeadRequest(newurl,
103 headers=newheaders,
104 origin_req_host=req.get_origin_req_host(),
105 unverifiable=True)
106 else:
107 raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
108
109 class HTTPMethodFallback(compat_urllib_request.BaseHandler):
110 """
111 Fallback to GET if HEAD is not allowed (405 HTTP error)
112 """
113 def http_error_405(self, req, fp, code, msg, headers):
114 fp.read()
115 fp.close()
116
117 newheaders = dict((k,v) for k,v in req.headers.items()
118 if k.lower() not in ("content-length", "content-type"))
119 return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
120 headers=newheaders,
121 origin_req_host=req.get_origin_req_host(),
122 unverifiable=True))
123
124 # Build our opener
125 opener = compat_urllib_request.OpenerDirector()
126 for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
127 HTTPMethodFallback, HEADRedirectHandler,
128 compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
129 opener.add_handler(handler())
130
131 response = opener.open(HeadRequest(url))
132 if response is None:
133 raise ExtractorError(u'Invalid URL protocol')
134 new_url = response.geturl()
135
136 if url == new_url:
137 return False
138
139 self.report_following_redirect(new_url)
140 return new_url
141
142 def _real_extract(self, url):
a7130543
JMF
143 parsed_url = compat_urlparse.urlparse(url)
144 if not parsed_url.scheme:
145 self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
146 return self.url_result('http://' + url)
147
30934689
PH
148 try:
149 new_url = self._test_redirect(url)
150 if new_url:
cecaaf3f 151 return self.url_result(new_url)
30934689
PH
152 except compat_urllib_error.HTTPError:
153 # This may be a stupid server that doesn't like HEAD, our UA, or so
154 pass
9b122384
PH
155
156 video_id = url.split('/')[-1]
157 try:
158 webpage = self._download_webpage(url, video_id)
159 except ValueError:
160 # since this is the last-resort InfoExtractor, if
161 # this error is thrown, it'll be thrown here
e484c81f 162 raise ExtractorError(u'Failed to download URL: %s' % url)
9b122384
PH
163
164 self.report_extraction(video_id)
887c6acd
PH
165
166 # it's tempting to parse this further, but you would
167 # have to take into account all the variations like
168 # Video Title - Site Name
169 # Site Name | Video Title
170 # Video Title - Tagline | Site Name
171 # and so on and so forth; it's just not practical
ef4fd848
PH
172 video_title = self._html_search_regex(
173 r'(?s)<title>(.*?)</title>', webpage, u'video title',
174 default=u'video')
175
176 # video uploader is domain name
177 video_uploader = self._search_regex(
178 r'^(?:https?://)?([^/]*)/.*', url, u'video uploader')
887c6acd 179
627a91a9 180 # Look for BrightCove:
eeb165e6
JMF
181 bc_url = BrightcoveIE._extract_brightcove_url(webpage)
182 if bc_url is not None:
cfe50f04 183 self.to_screen(u'Brightcove video detected.')
cfe50f04
JMF
184 return self.url_result(bc_url, 'Brightcove')
185
9d4660ca
PH
186 # Look for embedded Vimeo player
187 mobj = re.search(
53c1d3ef 188 r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
9d4660ca
PH
189 if mobj:
190 player_url = unescapeHTML(mobj.group(1))
191 surl = smuggle_url(player_url, {'Referer': url})
192 return self.url_result(surl, 'Vimeo')
193
53c1d3ef 194 # Look for embedded YouTube player
887c6acd 195 matches = re.findall(
ef4fd848 196 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/embed/.+?)\1', webpage)
887c6acd
PH
197 if matches:
198 urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
199 for tuppl in matches]
200 return self.playlist_result(
201 urlrs, playlist_id=video_id, playlist_title=video_title)
53c1d3ef 202
355e4fd0
PH
203 # Look for embedded Dailymotion player
204 matches = re.findall(
ef4fd848 205 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
355e4fd0
PH
206 if matches:
207 urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
208 for tuppl in matches]
209 return self.playlist_result(
210 urlrs, playlist_id=video_id, playlist_title=video_title)
211
ef4fd848
PH
212 # Look for embedded Wistia player
213 match = re.search(
214 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
215 if match:
216 return {
217 '_type': 'url_transparent',
218 'url': unescapeHTML(match.group('url')),
219 'ie_key': 'Wistia',
220 'uploader': video_uploader,
221 'title': video_title,
222 'id': video_id,
223 }
224
ee3e63e4 225 # Look for embedded blip.tv player
226 mobj = re.search(r'<meta\s[^>]*https?://api.blip.tv/\w+/redirect/\w+/(\d+)', webpage)
227 if mobj:
228 return self.url_result('http://blip.tv/seo/-'+mobj.group(1), 'BlipTV')
229 mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*https?://(?:\w+\.)?blip.tv/(?:play/|api\.swf#)([a-zA-Z0-9]+)', webpage)
230 if mobj:
231 player_url = 'http://blip.tv/play/%s.x?p=1' % mobj.group(1)
232 player_page = self._download_webpage(player_url, mobj.group(1))
233 blip_video_id = self._search_regex(r'data-episode-id="(\d+)', player_page, u'blip_video_id', fatal=False)
234 if blip_video_id:
235 return self.url_result('http://blip.tv/seo/-'+blip_video_id, 'BlipTV')
236
c19f7764
JMF
237 # Look for Bandcamp pages with custom domain
238 mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
239 if mobj is not None:
240 burl = unescapeHTML(mobj.group(1))
09804265
JMF
241 # Don't set the extractor because it can be a track url or an album
242 return self.url_result(burl)
c19f7764 243
f25571ff
PH
244 # Look for embedded Vevo player
245 mobj = re.search(
246 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
247 if mobj is not None:
248 return self.url_result(mobj.group('url'))
249
9b122384
PH
250 # Start with something easy: JW Player in SWFObject
251 mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
252 if mobj is None:
253 # Broaden the search a little bit
254 mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
255 if mobj is None:
256 # Broaden the search a little bit: JWPlayer JS loader
113577e1 257 mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"]*)', webpage)
9b122384
PH
258 if mobj is None:
259 # Try to find twitter cards info
260 mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
261 if mobj is None:
262 # We look for Open Graph info:
263 # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
264 m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
265 # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
266 if m_video_type is not None:
267 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
7fea7156
PH
268 if mobj is None:
269 # HTML5 video
08e291b5 270 mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
9b122384 271 if mobj is None:
e484c81f 272 raise ExtractorError(u'Unsupported URL: %s' % url)
9b122384
PH
273
274 # It's possible that one of the regexes
275 # matched, but returned an empty group:
276 if mobj.group(1) is None:
e484c81f 277 raise ExtractorError(u'Did not find a valid video URL at %s' % url)
9b122384 278
08e291b5 279 video_url = mobj.group(1)
a5caba1e 280 video_url = compat_urlparse.urljoin(url, video_url)
08e291b5 281 video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
9b122384
PH
282
283 # here's a fun little line of code for you:
9b122384
PH
284 video_id = os.path.splitext(video_id)[0]
285
113577e1 286 return {
9b122384
PH
287 'id': video_id,
288 'url': video_url,
289 'uploader': video_uploader,
9b122384 290 'title': video_title,
113577e1 291 }