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.

362 lines
14 KiB

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