2
0

common.py 17 KB

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