YoutubeIE: reuse instances of InfoExtractors (closes #998)
[youtube-dl] / youtube_dl / extractor / common.py
1 import base64
2 import os
3 import re
4 import socket
5 import sys
6 import netrc
7
8 from ..utils import (
9     compat_http_client,
10     compat_urllib_error,
11     compat_urllib_request,
12     compat_str,
13
14     clean_html,
15     compiled_regex_type,
16     ExtractorError,
17 )
18
19 class InfoExtractor(object):
20     """Information Extractor class.
21
22     Information extractors are the classes that, given a URL, extract
23     information about the video (or videos) the URL refers to. This
24     information includes the real video URL, the video title, author and
25     others. The information is stored in a dictionary which is then
26     passed to the FileDownloader. The FileDownloader processes this
27     information possibly downloading the video to the file system, among
28     other possible outcomes.
29
30     The dictionaries must include the following fields:
31
32     id:             Video identifier.
33     url:            Final video URL.
34     title:          Video title, unescaped.
35     ext:            Video filename extension.
36
37     The following fields are optional:
38
39     format:         The video format, defaults to ext (used for --get-format)
40     thumbnails:     A list of dictionaries (with the entries "resolution" and
41                     "url") for the varying thumbnails
42     thumbnail:      Full URL to a video thumbnail image.
43     description:    One-line video description.
44     uploader:       Full name of the video uploader.
45     upload_date:    Video upload date (YYYYMMDD).
46     uploader_id:    Nickname or id of the video uploader.
47     location:       Physical location of the video.
48     player_url:     SWF Player URL (used for rtmpdump).
49     subtitles:      The subtitle file contents.
50     view_count:     How many users have watched the video on the platform.
51     urlhandle:      [internal] The urlHandle to be used to download the file,
52                     like returned by urllib.request.urlopen
53
54     The fields should all be Unicode strings.
55
56     Subclasses of this one should re-define the _real_initialize() and
57     _real_extract() methods and define a _VALID_URL regexp.
58     Probably, they should also be added to the list of extractors.
59
60     _real_extract() must return a *list* of information dictionaries as
61     described above.
62
63     Finally, the _WORKING attribute should be set to False for broken IEs
64     in order to warn the users and skip the tests.
65     """
66
67     _ready = False
68     _downloader = None
69     _WORKING = True
70
71     def __init__(self, downloader=None):
72         """Constructor. Receives an optional downloader."""
73         self._ready = False
74         self.set_downloader(downloader)
75
76     @classmethod
77     def suitable(cls, url):
78         """Receives a URL and returns True if suitable for this IE."""
79         return re.match(cls._VALID_URL, url) is not None
80
81     @classmethod
82     def working(cls):
83         """Getter method for _WORKING."""
84         return cls._WORKING
85
86     def initialize(self):
87         """Initializes an instance (authentication, etc)."""
88         if not self._ready:
89             self._real_initialize()
90             self._ready = True
91
92     def extract(self, url):
93         """Extracts URL information and returns it in list of dicts."""
94         self.initialize()
95         return self._real_extract(url)
96
97     def set_downloader(self, downloader):
98         """Sets the downloader for this IE."""
99         self._downloader = downloader
100
101     def _real_initialize(self):
102         """Real initialization process. Redefine in subclasses."""
103         pass
104
105     def _real_extract(self, url):
106         """Real extraction process. Redefine in subclasses."""
107         pass
108
109     @classmethod
110     def ie_key(cls):
111         """A string for getting the InfoExtractor with get_info_extractor"""
112         return cls.__name__[:-2]
113
114     @property
115     def IE_NAME(self):
116         return type(self).__name__[:-2]
117
118     def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
119         """ Returns the response handle """
120         if note is None:
121             self.report_download_webpage(video_id)
122         elif note is not False:
123             self.to_screen(u'%s: %s' % (video_id, note))
124         try:
125             return compat_urllib_request.urlopen(url_or_request)
126         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
127             if errnote is None:
128                 errnote = u'Unable to download webpage'
129             raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2])
130
131     def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None):
132         """ Returns a tuple (page content as string, URL handle) """
133         urlh = self._request_webpage(url_or_request, video_id, note, errnote)
134         content_type = urlh.headers.get('Content-Type', '')
135         m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
136         if m:
137             encoding = m.group(1)
138         else:
139             encoding = 'utf-8'
140         webpage_bytes = urlh.read()
141         if self._downloader.params.get('dump_intermediate_pages', False):
142             try:
143                 url = url_or_request.get_full_url()
144             except AttributeError:
145                 url = url_or_request
146             self.to_screen(u'Dumping request to ' + url)
147             dump = base64.b64encode(webpage_bytes).decode('ascii')
148             self._downloader.to_screen(dump)
149         content = webpage_bytes.decode(encoding, 'replace')
150         return (content, urlh)
151
152     def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
153         """ Returns the data of the page as a string """
154         return self._download_webpage_handle(url_or_request, video_id, note, errnote)[0]
155
156     def to_screen(self, msg):
157         """Print msg to screen, prefixing it with '[ie_name]'"""
158         self._downloader.to_screen(u'[%s] %s' % (self.IE_NAME, msg))
159
160     def report_extraction(self, id_or_name):
161         """Report information extraction."""
162         self.to_screen(u'%s: Extracting information' % id_or_name)
163
164     def report_download_webpage(self, video_id):
165         """Report webpage download."""
166         self.to_screen(u'%s: Downloading webpage' % video_id)
167
168     def report_age_confirmation(self):
169         """Report attempt to confirm age."""
170         self.to_screen(u'Confirming age')
171
172     def report_login(self):
173         """Report attempt to log in."""
174         self.to_screen(u'Logging in')
175
176     #Methods for following #608
177     #They set the correct value of the '_type' key
178     def video_result(self, video_info):
179         """Returns a video"""
180         video_info['_type'] = 'video'
181         return video_info
182     def url_result(self, url, ie=None):
183         """Returns a url that points to a page that should be processed"""
184         #TODO: ie should be the class used for getting the info
185         video_info = {'_type': 'url',
186                       'url': url,
187                       'ie_key': ie}
188         return video_info
189     def playlist_result(self, entries, playlist_id=None, playlist_title=None):
190         """Returns a playlist"""
191         video_info = {'_type': 'playlist',
192                       'entries': entries}
193         if playlist_id:
194             video_info['id'] = playlist_id
195         if playlist_title:
196             video_info['title'] = playlist_title
197         return video_info
198
199     def _search_regex(self, pattern, string, name, default=None, fatal=True, flags=0):
200         """
201         Perform a regex search on the given string, using a single or a list of
202         patterns returning the first matching group.
203         In case of failure return a default value or raise a WARNING or a
204         ExtractorError, depending on fatal, specifying the field name.
205         """
206         if isinstance(pattern, (str, compat_str, compiled_regex_type)):
207             mobj = re.search(pattern, string, flags)
208         else:
209             for p in pattern:
210                 mobj = re.search(p, string, flags)
211                 if mobj: break
212
213         if sys.stderr.isatty() and os.name != 'nt':
214             _name = u'\033[0;34m%s\033[0m' % name
215         else:
216             _name = name
217
218         if mobj:
219             # return the first matching group
220             return next(g for g in mobj.groups() if g is not None)
221         elif default is not None:
222             return default
223         elif fatal:
224             raise ExtractorError(u'Unable to extract %s' % _name)
225         else:
226             self._downloader.report_warning(u'unable to extract %s; '
227                 u'please report this issue on http://yt-dl.org/bug' % _name)
228             return None
229
230     def _html_search_regex(self, pattern, string, name, default=None, fatal=True, flags=0):
231         """
232         Like _search_regex, but strips HTML tags and unescapes entities.
233         """
234         res = self._search_regex(pattern, string, name, default, fatal, flags)
235         if res:
236             return clean_html(res).strip()
237         else:
238             return res
239
240     def _get_login_info(self):
241         """
242         Get the the login info as (username, password)
243         It will look in the netrc file using the _NETRC_MACHINE value
244         If there's no info available, return (None, None)
245         """
246         if self._downloader is None:
247             return (None, None)
248
249         username = None
250         password = None
251         downloader_params = self._downloader.params
252
253         # Attempt to use provided username and password or .netrc data
254         if downloader_params.get('username', None) is not None:
255             username = downloader_params['username']
256             password = downloader_params['password']
257         elif downloader_params.get('usenetrc', False):
258             try:
259                 info = netrc.netrc().authenticators(self._NETRC_MACHINE)
260                 if info is not None:
261                     username = info[0]
262                     password = info[2]
263                 else:
264                     raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
265             except (IOError, netrc.NetrcParseError) as err:
266                 self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
267         
268         return (username, password)
269
270 class SearchInfoExtractor(InfoExtractor):
271     """
272     Base class for paged search queries extractors.
273     They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
274     Instances should define _SEARCH_KEY and _MAX_RESULTS.
275     """
276
277     @classmethod
278     def _make_valid_url(cls):
279         return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
280
281     @classmethod
282     def suitable(cls, url):
283         return re.match(cls._make_valid_url(), url) is not None
284
285     def _real_extract(self, query):
286         mobj = re.match(self._make_valid_url(), query)
287         if mobj is None:
288             raise ExtractorError(u'Invalid search query "%s"' % query)
289
290         prefix = mobj.group('prefix')
291         query = mobj.group('query')
292         if prefix == '':
293             return self._get_n_results(query, 1)
294         elif prefix == 'all':
295             return self._get_n_results(query, self._MAX_RESULTS)
296         else:
297             n = int(prefix)
298             if n <= 0:
299                 raise ExtractorError(u'invalid download number %s for query "%s"' % (n, query))
300             elif n > self._MAX_RESULTS:
301                 self._downloader.report_warning(u'%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
302                 n = self._MAX_RESULTS
303             return self._get_n_results(query, n)
304
305     def _get_n_results(self, query, n):
306         """Get a specified number of results for a query"""
307         raise NotImplementedError("This method must be implemented by sublclasses")
308
309     @property
310     def SEARCH_KEY(self):
311         return self._SEARCH_KEY