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