]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/generic.py
69e0a7bd271dd0965f5c1f6f9c3a7cdce7a3da0b
[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'85b90ccc9d73b4acd9138d3af4c27f89',
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'url': u'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
37 u'file': u'22444065.mp4',
38 u'md5': u'2903896e23df39722c33f015af0666e2',
39 u'info_dict': {
40 u'title': u'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
41 u"uploader_id": u"skillsmatter",
42 u"uploader": u"Skills Matter",
43 }
44 }
45 ]
46
47 def report_download_webpage(self, video_id):
48 """Report webpage download."""
49 if not self._downloader.params.get('test', False):
50 self._downloader.report_warning(u'Falling back on generic information extractor.')
51 super(GenericIE, self).report_download_webpage(video_id)
52
53 def report_following_redirect(self, new_url):
54 """Report information extraction."""
55 self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
56
57 def _test_redirect(self, url):
58 """Check if it is a redirect, like url shorteners, in case return the new url."""
59 class HeadRequest(compat_urllib_request.Request):
60 def get_method(self):
61 return "HEAD"
62
63 class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
64 """
65 Subclass the HTTPRedirectHandler to make it use our
66 HeadRequest also on the redirected URL
67 """
68 def redirect_request(self, req, fp, code, msg, headers, newurl):
69 if code in (301, 302, 303, 307):
70 newurl = newurl.replace(' ', '%20')
71 newheaders = dict((k,v) for k,v in req.headers.items()
72 if k.lower() not in ("content-length", "content-type"))
73 return HeadRequest(newurl,
74 headers=newheaders,
75 origin_req_host=req.get_origin_req_host(),
76 unverifiable=True)
77 else:
78 raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
79
80 class HTTPMethodFallback(compat_urllib_request.BaseHandler):
81 """
82 Fallback to GET if HEAD is not allowed (405 HTTP error)
83 """
84 def http_error_405(self, req, fp, code, msg, headers):
85 fp.read()
86 fp.close()
87
88 newheaders = dict((k,v) for k,v in req.headers.items()
89 if k.lower() not in ("content-length", "content-type"))
90 return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
91 headers=newheaders,
92 origin_req_host=req.get_origin_req_host(),
93 unverifiable=True))
94
95 # Build our opener
96 opener = compat_urllib_request.OpenerDirector()
97 for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
98 HTTPMethodFallback, HEADRedirectHandler,
99 compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
100 opener.add_handler(handler())
101
102 response = opener.open(HeadRequest(url))
103 if response is None:
104 raise ExtractorError(u'Invalid URL protocol')
105 new_url = response.geturl()
106
107 if url == new_url:
108 return False
109
110 self.report_following_redirect(new_url)
111 return new_url
112
113 def _real_extract(self, url):
114 parsed_url = compat_urlparse.urlparse(url)
115 if not parsed_url.scheme:
116 self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
117 return self.url_result('http://' + url)
118
119 try:
120 new_url = self._test_redirect(url)
121 if new_url:
122 return [self.url_result(new_url)]
123 except compat_urllib_error.HTTPError:
124 # This may be a stupid server that doesn't like HEAD, our UA, or so
125 pass
126
127 video_id = url.split('/')[-1]
128 try:
129 webpage = self._download_webpage(url, video_id)
130 except ValueError:
131 # since this is the last-resort InfoExtractor, if
132 # this error is thrown, it'll be thrown here
133 raise ExtractorError(u'Failed to download URL: %s' % url)
134
135 self.report_extraction(video_id)
136 # Look for BrightCove:
137 m_brightcove = re.search(r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>', webpage, re.DOTALL)
138 if m_brightcove is not None:
139 self.to_screen(u'Brightcove video detected.')
140 bc_url = BrightcoveIE._build_brighcove_url(m_brightcove.group())
141 return self.url_result(bc_url, 'Brightcove')
142
143 # Look for embedded Vimeo player
144 mobj = re.search(
145 r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
146 if mobj:
147 player_url = unescapeHTML(mobj.group(1))
148 surl = smuggle_url(player_url, {'Referer': url})
149 return self.url_result(surl, 'Vimeo')
150
151 # Look for embedded YouTube player
152 mobj = re.search(
153 r'<iframe[^>]+?src="(https?://(?:www\.)?youtube.com/embed/.+?)"', webpage)
154 if mobj:
155 surl = unescapeHTML(mobj.group(1))
156 return self.url_result(surl, 'Youtube')
157
158 # Start with something easy: JW Player in SWFObject
159 mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
160 if mobj is None:
161 # Broaden the search a little bit
162 mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
163 if mobj is None:
164 # Broaden the search a little bit: JWPlayer JS loader
165 mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
166 if mobj is None:
167 # Try to find twitter cards info
168 mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
169 if mobj is None:
170 # We look for Open Graph info:
171 # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
172 m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
173 # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
174 if m_video_type is not None:
175 mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
176 if mobj is None:
177 # HTML5 video
178 mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
179 if mobj is None:
180 raise ExtractorError(u'Unsupported URL: %s' % url)
181
182 # It's possible that one of the regexes
183 # matched, but returned an empty group:
184 if mobj.group(1) is None:
185 raise ExtractorError(u'Did not find a valid video URL at %s' % url)
186
187 video_url = mobj.group(1)
188 video_url = compat_urlparse.urljoin(url, video_url)
189 video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
190
191 # here's a fun little line of code for you:
192 video_extension = os.path.splitext(video_id)[1][1:]
193 video_id = os.path.splitext(video_id)[0]
194
195 # it's tempting to parse this further, but you would
196 # have to take into account all the variations like
197 # Video Title - Site Name
198 # Site Name | Video Title
199 # Video Title - Tagline | Site Name
200 # and so on and so forth; it's just not practical
201 video_title = self._html_search_regex(r'<title>(.*)</title>',
202 webpage, u'video title', default=u'video', flags=re.DOTALL)
203
204 # video uploader is domain name
205 video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
206 url, u'video uploader')
207
208 return [{
209 'id': video_id,
210 'url': video_url,
211 'uploader': video_uploader,
212 'upload_date': None,
213 'title': video_title,
214 'ext': video_extension,
215 }]