You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

264 lines
9.7 KiB

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