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.

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