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.

376 lines
14 KiB

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