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.

523 lines
20 KiB

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