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.

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