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.

537 lines
21 KiB

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