]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/generic.py
Update changelog.
[youtubedl] / youtube_dl / extractor / generic.py
1 # encoding: utf-8
2
3 import os
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8 compat_urllib_error,
9 compat_urllib_parse,
10 compat_urllib_request,
11 compat_urlparse,
12
13 ExtractorError,
14 smuggle_url,
15 unescapeHTML,
16 )
17 from .brightcove import BrightcoveIE
18
19
20 class GenericIE(InfoExtractor):
21 IE_DESC = u'Generic downloader that works on some sites'
22 _VALID_URL = r'.*'
23 IE_NAME = u'generic'
24 _TESTS = [
25 {
26 u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
27 u'file': u'13601338388002.mp4',
28 u'md5': u'6e15c93721d7ec9e9ca3fdbf07982cfd',
29 u'info_dict': {
30 u"uploader": u"www.hodiho.fr",
31 u"title": u"R\u00e9gis plante sa Jeep"
32 }
33 },
34 # embedded vimeo video
35 {
36 u'add_ie': ['Vimeo'],
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 }
45 },
46 # bandcamp page with custom domain
47 {
48 u'add_ie': ['Bandcamp'],
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 },
57 # embedded brightcove video
58 # it also tests brightcove videos that need to set the 'Referer' in the
59 # http requests
60 {
61 u'add_ie': ['Brightcove'],
62 u'url': u'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
63 u'info_dict': {
64 u'id': u'2765128793001',
65 u'ext': u'mp4',
66 u'title': u'Le cours de bourse : l’analyse technique',
67 u'description': u'md5:7e9ad046e968cb2d1114004aba466fd9',
68 u'uploader': u'BFM BUSINESS',
69 },
70 u'params': {
71 u'skip_download': True,
72 },
73 },
74 ]
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):
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
148 try:
149 new_url = self._test_redirect(url)
150 if new_url:
151 return [self.url_result(new_url)]
152 except compat_urllib_error.HTTPError:
153 # This may be a stupid server that doesn't like HEAD, our UA, or so
154 pass
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
162 raise ExtractorError(u'Failed to download URL: %s' % url)
163
164 self.report_extraction(video_id)
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
172 video_title = self._html_search_regex(r'<title>(.*)</title>',
173 webpage, u'video title', default=u'video', flags=re.DOTALL)
174
175 # Look for BrightCove:
176 bc_url = BrightcoveIE._extract_brightcove_url(webpage)
177 if bc_url is not None:
178 self.to_screen(u'Brightcove video detected.')
179 return self.url_result(bc_url, 'Brightcove')
180
181 # Look for embedded Vimeo player
182 mobj = re.search(
183 r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
184 if mobj:
185 player_url = unescapeHTML(mobj.group(1))
186 surl = smuggle_url(player_url, {'Referer': url})
187 return self.url_result(surl, 'Vimeo')
188
189 # Look for embedded YouTube player
190 matches = re.findall(
191 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube.com/embed/.+?)\1', webpage)
192 if matches:
193 urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
194 for tuppl in matches]
195 return self.playlist_result(
196 urlrs, playlist_id=video_id, playlist_title=video_title)
197
198 # Look for embedded Dailymotion player
199 matches = re.findall(
200 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion.com/embed/video/.+?)\1', webpage)
201 if matches:
202 urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
203 for tuppl in matches]
204 return self.playlist_result(
205 urlrs, playlist_id=video_id, playlist_title=video_title)
206
207 # Look for Bandcamp pages with custom domain
208 mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
209 if mobj is not None:
210 burl = unescapeHTML(mobj.group(1))
211 # Don't set the extractor because it can be a track url or an album
212 return self.url_result(burl)
213
214 # Start with something easy: JW Player in SWFObject
215 mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
216 if mobj is None:
217 # Broaden the search a little bit
218 mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
219 if mobj is None:
220 # Broaden the search a little bit: JWPlayer JS loader
221 mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"]*)', webpage)
222 if mobj is None:
223 # Try to find twitter cards info
224 mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
225 if mobj is None:
226 # We look for Open Graph info:
227 # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
228 m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
229 # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
230 if m_video_type is not None:
231 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
232 if mobj is None:
233 # HTML5 video
234 mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
235 if mobj is None:
236 raise ExtractorError(u'Unsupported URL: %s' % url)
237
238 # It's possible that one of the regexes
239 # matched, but returned an empty group:
240 if mobj.group(1) is None:
241 raise ExtractorError(u'Did not find a valid video URL at %s' % url)
242
243 video_url = mobj.group(1)
244 video_url = compat_urlparse.urljoin(url, video_url)
245 video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
246
247 # here's a fun little line of code for you:
248 video_id = os.path.splitext(video_id)[0]
249
250 # video uploader is domain name
251 video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
252 url, u'video uploader')
253
254 return {
255 'id': video_id,
256 'url': video_url,
257 'uploader': video_uploader,
258 'upload_date': None,
259 'title': video_title,
260 }