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.

630 lines
25 KiB

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