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.

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