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.

555 lines
22 KiB

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