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