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.

635 lines
26 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. fatal=True):
  269. json_string = self._download_webpage(
  270. url_or_request, video_id, note, errnote, fatal=fatal)
  271. if (not fatal) and json_string is False:
  272. return None
  273. if transform_source:
  274. json_string = transform_source(json_string)
  275. try:
  276. return json.loads(json_string)
  277. except ValueError as ve:
  278. raise ExtractorError('Failed to download JSON', cause=ve)
  279. def report_warning(self, msg, video_id=None):
  280. idstr = u'' if video_id is None else u'%s: ' % video_id
  281. self._downloader.report_warning(
  282. u'[%s] %s%s' % (self.IE_NAME, idstr, msg))
  283. def to_screen(self, msg):
  284. """Print msg to screen, prefixing it with '[ie_name]'"""
  285. self._downloader.to_screen(u'[%s] %s' % (self.IE_NAME, msg))
  286. def report_extraction(self, id_or_name):
  287. """Report information extraction."""
  288. self.to_screen(u'%s: Extracting information' % id_or_name)
  289. def report_download_webpage(self, video_id):
  290. """Report webpage download."""
  291. self.to_screen(u'%s: Downloading webpage' % video_id)
  292. def report_age_confirmation(self):
  293. """Report attempt to confirm age."""
  294. self.to_screen(u'Confirming age')
  295. def report_login(self):
  296. """Report attempt to log in."""
  297. self.to_screen(u'Logging in')
  298. #Methods for following #608
  299. @staticmethod
  300. def url_result(url, ie=None, video_id=None):
  301. """Returns a url that points to a page that should be processed"""
  302. #TODO: ie should be the class used for getting the info
  303. video_info = {'_type': 'url',
  304. 'url': url,
  305. 'ie_key': ie}
  306. if video_id is not None:
  307. video_info['id'] = video_id
  308. return video_info
  309. @staticmethod
  310. def playlist_result(entries, playlist_id=None, playlist_title=None):
  311. """Returns a playlist"""
  312. video_info = {'_type': 'playlist',
  313. 'entries': entries}
  314. if playlist_id:
  315. video_info['id'] = playlist_id
  316. if playlist_title:
  317. video_info['title'] = playlist_title
  318. return video_info
  319. def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  320. """
  321. Perform a regex search on the given string, using a single or a list of
  322. patterns returning the first matching group.
  323. In case of failure return a default value or raise a WARNING or a
  324. RegexNotFoundError, depending on fatal, specifying the field name.
  325. """
  326. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  327. mobj = re.search(pattern, string, flags)
  328. else:
  329. for p in pattern:
  330. mobj = re.search(p, string, flags)
  331. if mobj:
  332. break
  333. if os.name != 'nt' and sys.stderr.isatty():
  334. _name = u'\033[0;34m%s\033[0m' % name
  335. else:
  336. _name = name
  337. if mobj:
  338. # return the first matching group
  339. return next(g for g in mobj.groups() if g is not None)
  340. elif default is not _NO_DEFAULT:
  341. return default
  342. elif fatal:
  343. raise RegexNotFoundError(u'Unable to extract %s' % _name)
  344. else:
  345. self._downloader.report_warning(u'unable to extract %s; '
  346. u'please report this issue on http://yt-dl.org/bug' % _name)
  347. return None
  348. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  349. """
  350. Like _search_regex, but strips HTML tags and unescapes entities.
  351. """
  352. res = self._search_regex(pattern, string, name, default, fatal, flags)
  353. if res:
  354. return clean_html(res).strip()
  355. else:
  356. return res
  357. def _get_login_info(self):
  358. """
  359. Get the the login info as (username, password)
  360. It will look in the netrc file using the _NETRC_MACHINE value
  361. If there's no info available, return (None, None)
  362. """
  363. if self._downloader is None:
  364. return (None, None)
  365. username = None
  366. password = None
  367. downloader_params = self._downloader.params
  368. # Attempt to use provided username and password or .netrc data
  369. if downloader_params.get('username', None) is not None:
  370. username = downloader_params['username']
  371. password = downloader_params['password']
  372. elif downloader_params.get('usenetrc', False):
  373. try:
  374. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  375. if info is not None:
  376. username = info[0]
  377. password = info[2]
  378. else:
  379. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  380. except (IOError, netrc.NetrcParseError) as err:
  381. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  382. return (username, password)
  383. # Helper functions for extracting OpenGraph info
  384. @staticmethod
  385. def _og_regexes(prop):
  386. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  387. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  388. template = r'<meta[^>]+?%s[^>]+?%s'
  389. return [
  390. template % (property_re, content_re),
  391. template % (content_re, property_re),
  392. ]
  393. def _og_search_property(self, prop, html, name=None, **kargs):
  394. if name is None:
  395. name = 'OpenGraph %s' % prop
  396. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  397. if escaped is None:
  398. return None
  399. return unescapeHTML(escaped)
  400. def _og_search_thumbnail(self, html, **kargs):
  401. return self._og_search_property('image', html, u'thumbnail url', fatal=False, **kargs)
  402. def _og_search_description(self, html, **kargs):
  403. return self._og_search_property('description', html, fatal=False, **kargs)
  404. def _og_search_title(self, html, **kargs):
  405. return self._og_search_property('title', html, **kargs)
  406. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  407. regexes = self._og_regexes('video')
  408. if secure: regexes = self._og_regexes('video:secure_url') + regexes
  409. return self._html_search_regex(regexes, html, name, **kargs)
  410. def _og_search_url(self, html, **kargs):
  411. return self._og_search_property('url', html, **kargs)
  412. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  413. if display_name is None:
  414. display_name = name
  415. return self._html_search_regex(
  416. r'''(?ix)<meta
  417. (?=[^>]+(?:itemprop|name|property)=["\']?%s["\']?)
  418. [^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
  419. html, display_name, fatal=fatal, **kwargs)
  420. def _dc_search_uploader(self, html):
  421. return self._html_search_meta('dc.creator', html, 'uploader')
  422. def _rta_search(self, html):
  423. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  424. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  425. r' content="RTA-5042-1996-1400-1577-RTA"',
  426. html):
  427. return 18
  428. return 0
  429. def _media_rating_search(self, html):
  430. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  431. rating = self._html_search_meta('rating', html)
  432. if not rating:
  433. return None
  434. RATING_TABLE = {
  435. 'safe for kids': 0,
  436. 'general': 8,
  437. '14 years': 14,
  438. 'mature': 17,
  439. 'restricted': 19,
  440. }
  441. return RATING_TABLE.get(rating.lower(), None)
  442. def _twitter_search_player(self, html):
  443. return self._html_search_meta('twitter:player', html,
  444. 'twitter card player')
  445. def _sort_formats(self, formats):
  446. if not formats:
  447. raise ExtractorError(u'No video formats found')
  448. def _formats_key(f):
  449. # TODO remove the following workaround
  450. from ..utils import determine_ext
  451. if not f.get('ext') and 'url' in f:
  452. f['ext'] = determine_ext(f['url'])
  453. preference = f.get('preference')
  454. if preference is None:
  455. proto = f.get('protocol')
  456. if proto is None:
  457. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  458. preference = 0 if proto in ['http', 'https'] else -0.1
  459. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  460. preference -= 0.5
  461. if f.get('vcodec') == 'none': # audio only
  462. if self._downloader.params.get('prefer_free_formats'):
  463. ORDER = [u'aac', u'mp3', u'm4a', u'webm', u'ogg', u'opus']
  464. else:
  465. ORDER = [u'webm', u'opus', u'ogg', u'mp3', u'aac', u'm4a']
  466. ext_preference = 0
  467. try:
  468. audio_ext_preference = ORDER.index(f['ext'])
  469. except ValueError:
  470. audio_ext_preference = -1
  471. else:
  472. if self._downloader.params.get('prefer_free_formats'):
  473. ORDER = [u'flv', u'mp4', u'webm']
  474. else:
  475. ORDER = [u'webm', u'flv', u'mp4']
  476. try:
  477. ext_preference = ORDER.index(f['ext'])
  478. except ValueError:
  479. ext_preference = -1
  480. audio_ext_preference = 0
  481. return (
  482. preference,
  483. f.get('quality') if f.get('quality') is not None else -1,
  484. f.get('height') if f.get('height') is not None else -1,
  485. f.get('width') if f.get('width') is not None else -1,
  486. ext_preference,
  487. f.get('tbr') if f.get('tbr') is not None else -1,
  488. f.get('vbr') if f.get('vbr') is not None else -1,
  489. f.get('abr') if f.get('abr') is not None else -1,
  490. audio_ext_preference,
  491. f.get('filesize') if f.get('filesize') is not None else -1,
  492. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  493. f.get('format_id'),
  494. )
  495. formats.sort(key=_formats_key)
  496. def http_scheme(self):
  497. """ Either "https:" or "https:", depending on the user's preferences """
  498. return (
  499. 'http:'
  500. if self._downloader.params.get('prefer_insecure', False)
  501. else 'https:')
  502. def _proto_relative_url(self, url, scheme=None):
  503. if url is None:
  504. return url
  505. if url.startswith('//'):
  506. if scheme is None:
  507. scheme = self.http_scheme()
  508. return scheme + url
  509. else:
  510. return url
  511. def _sleep(self, timeout, video_id, msg_template=None):
  512. if msg_template is None:
  513. msg_template = u'%(video_id)s: Waiting for %(timeout)s seconds'
  514. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  515. self.to_screen(msg)
  516. time.sleep(timeout)
  517. class SearchInfoExtractor(InfoExtractor):
  518. """
  519. Base class for paged search queries extractors.
  520. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
  521. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  522. """
  523. @classmethod
  524. def _make_valid_url(cls):
  525. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  526. @classmethod
  527. def suitable(cls, url):
  528. return re.match(cls._make_valid_url(), url) is not None
  529. def _real_extract(self, query):
  530. mobj = re.match(self._make_valid_url(), query)
  531. if mobj is None:
  532. raise ExtractorError(u'Invalid search query "%s"' % query)
  533. prefix = mobj.group('prefix')
  534. query = mobj.group('query')
  535. if prefix == '':
  536. return self._get_n_results(query, 1)
  537. elif prefix == 'all':
  538. return self._get_n_results(query, self._MAX_RESULTS)
  539. else:
  540. n = int(prefix)
  541. if n <= 0:
  542. raise ExtractorError(u'invalid download number %s for query "%s"' % (n, query))
  543. elif n > self._MAX_RESULTS:
  544. self._downloader.report_warning(u'%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  545. n = self._MAX_RESULTS
  546. return self._get_n_results(query, n)
  547. def _get_n_results(self, query, n):
  548. """Get a specified number of results for a query"""
  549. raise NotImplementedError("This method must be implemented by subclasses")
  550. @property
  551. def SEARCH_KEY(self):
  552. return self._SEARCH_KEY