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.

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