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.

1274 lines
52 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
  1. from __future__ import unicode_literals
  2. import base64
  3. import datetime
  4. import hashlib
  5. import json
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import sys
  11. import time
  12. import xml.etree.ElementTree
  13. from ..compat import (
  14. compat_cookiejar,
  15. compat_cookies,
  16. compat_HTTPError,
  17. compat_http_client,
  18. compat_urllib_error,
  19. compat_urllib_parse,
  20. compat_urllib_parse_urlparse,
  21. compat_urllib_request,
  22. compat_urlparse,
  23. compat_str,
  24. )
  25. from ..utils import (
  26. NO_DEFAULT,
  27. age_restricted,
  28. bug_reports_message,
  29. clean_html,
  30. compiled_regex_type,
  31. determine_ext,
  32. ExtractorError,
  33. fix_xml_ampersands,
  34. float_or_none,
  35. int_or_none,
  36. RegexNotFoundError,
  37. sanitize_filename,
  38. unescapeHTML,
  39. url_basename,
  40. )
  41. class InfoExtractor(object):
  42. """Information Extractor class.
  43. Information extractors are the classes that, given a URL, extract
  44. information about the video (or videos) the URL refers to. This
  45. information includes the real video URL, the video title, author and
  46. others. The information is stored in a dictionary which is then
  47. passed to the YoutubeDL. The YoutubeDL processes this
  48. information possibly downloading the video to the file system, among
  49. other possible outcomes.
  50. The type field determines the type of the result.
  51. By far the most common value (and the default if _type is missing) is
  52. "video", which indicates a single video.
  53. For a video, the dictionaries must include the following fields:
  54. id: Video identifier.
  55. title: Video title, unescaped.
  56. Additionally, it must contain either a formats entry or a url one:
  57. formats: A list of dictionaries for each format available, ordered
  58. from worst to best quality.
  59. Potential fields:
  60. * url Mandatory. The URL of the video file
  61. * ext Will be calculated from URL if missing
  62. * format A human-readable description of the format
  63. ("mp4 container with h264/opus").
  64. Calculated from the format_id, width, height.
  65. and format_note fields if missing.
  66. * format_id A short description of the format
  67. ("mp4_h264_opus" or "19").
  68. Technically optional, but strongly recommended.
  69. * format_note Additional info about the format
  70. ("3D" or "DASH video")
  71. * width Width of the video, if known
  72. * height Height of the video, if known
  73. * resolution Textual description of width and height
  74. * tbr Average bitrate of audio and video in KBit/s
  75. * abr Average audio bitrate in KBit/s
  76. * acodec Name of the audio codec in use
  77. * asr Audio sampling rate in Hertz
  78. * vbr Average video bitrate in KBit/s
  79. * fps Frame rate
  80. * vcodec Name of the video codec in use
  81. * container Name of the container format
  82. * filesize The number of bytes, if known in advance
  83. * filesize_approx An estimate for the number of bytes
  84. * player_url SWF Player URL (used for rtmpdump).
  85. * protocol The protocol that will be used for the actual
  86. download, lower-case.
  87. "http", "https", "rtsp", "rtmp", "rtmpe",
  88. "m3u8", or "m3u8_native".
  89. * preference Order number of this format. If this field is
  90. present and not None, the formats get sorted
  91. by this field, regardless of all other values.
  92. -1 for default (order by other properties),
  93. -2 or smaller for less than default.
  94. < -1000 to hide the format (if there is
  95. another one which is strictly better)
  96. * language_preference Is this in the correct requested
  97. language?
  98. 10 if it's what the URL is about,
  99. -1 for default (don't know),
  100. -10 otherwise, other values reserved for now.
  101. * quality Order number of the video quality of this
  102. format, irrespective of the file format.
  103. -1 for default (order by other properties),
  104. -2 or smaller for less than default.
  105. * source_preference Order number for this video source
  106. (quality takes higher priority)
  107. -1 for default (order by other properties),
  108. -2 or smaller for less than default.
  109. * http_headers A dictionary of additional HTTP headers
  110. to add to the request.
  111. * stretched_ratio If given and not 1, indicates that the
  112. video's pixels are not square.
  113. width : height ratio as float.
  114. * no_resume The server does not support resuming the
  115. (HTTP or RTMP) download. Boolean.
  116. url: Final video URL.
  117. ext: Video filename extension.
  118. format: The video format, defaults to ext (used for --get-format)
  119. player_url: SWF Player URL (used for rtmpdump).
  120. The following fields are optional:
  121. alt_title: A secondary title of the video.
  122. display_id An alternative identifier for the video, not necessarily
  123. unique, but available before title. Typically, id is
  124. something like "4234987", title "Dancing naked mole rats",
  125. and display_id "dancing-naked-mole-rats"
  126. thumbnails: A list of dictionaries, with the following entries:
  127. * "id" (optional, string) - Thumbnail format ID
  128. * "url"
  129. * "preference" (optional, int) - quality of the image
  130. * "width" (optional, int)
  131. * "height" (optional, int)
  132. * "resolution" (optional, string "{width}x{height"},
  133. deprecated)
  134. thumbnail: Full URL to a video thumbnail image.
  135. description: Full video description.
  136. uploader: Full name of the video uploader.
  137. creator: The main artist who created the video.
  138. timestamp: UNIX timestamp of the moment the video became available.
  139. upload_date: Video upload date (YYYYMMDD).
  140. If not explicitly set, calculated from timestamp.
  141. uploader_id: Nickname or id of the video uploader.
  142. location: Physical location where the video was filmed.
  143. subtitles: The available subtitles as a dictionary in the format
  144. {language: subformats}. "subformats" is a list sorted from
  145. lower to higher preference, each element is a dictionary
  146. with the "ext" entry and one of:
  147. * "data": The subtitles file contents
  148. * "url": A URL pointing to the subtitles file
  149. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  150. automatically generated captions
  151. duration: Length of the video in seconds, as an integer.
  152. view_count: How many users have watched the video on the platform.
  153. like_count: Number of positive ratings of the video
  154. dislike_count: Number of negative ratings of the video
  155. average_rating: Average rating give by users, the scale used depends on the webpage
  156. comment_count: Number of comments on the video
  157. comments: A list of comments, each with one or more of the following
  158. properties (all but one of text or html optional):
  159. * "author" - human-readable name of the comment author
  160. * "author_id" - user ID of the comment author
  161. * "id" - Comment ID
  162. * "html" - Comment as HTML
  163. * "text" - Plain text of the comment
  164. * "timestamp" - UNIX timestamp of comment
  165. * "parent" - ID of the comment this one is replying to.
  166. Set to "root" to indicate that this is a
  167. comment to the original video.
  168. age_limit: Age restriction for the video, as an integer (years)
  169. webpage_url: The URL to the video webpage, if given to youtube-dl it
  170. should allow to get the same result again. (It will be set
  171. by YoutubeDL if it's missing)
  172. categories: A list of categories that the video falls in, for example
  173. ["Sports", "Berlin"]
  174. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  175. is_live: True, False, or None (=unknown). Whether this video is a
  176. live stream that goes on instead of a fixed-length video.
  177. start_time: Time in seconds where the reproduction should start, as
  178. specified in the URL.
  179. end_time: Time in seconds where the reproduction should end, as
  180. specified in the URL.
  181. Unless mentioned otherwise, the fields should be Unicode strings.
  182. Unless mentioned otherwise, None is equivalent to absence of information.
  183. _type "playlist" indicates multiple videos.
  184. There must be a key "entries", which is a list, an iterable, or a PagedList
  185. object, each element of which is a valid dictionary by this specification.
  186. Additionally, playlists can have "title" and "id" attributes with the same
  187. semantics as videos (see above).
  188. _type "multi_video" indicates that there are multiple videos that
  189. form a single show, for examples multiple acts of an opera or TV episode.
  190. It must have an entries key like a playlist and contain all the keys
  191. required for a video at the same time.
  192. _type "url" indicates that the video must be extracted from another
  193. location, possibly by a different extractor. Its only required key is:
  194. "url" - the next URL to extract.
  195. The key "ie_key" can be set to the class name (minus the trailing "IE",
  196. e.g. "Youtube") if the extractor class is known in advance.
  197. Additionally, the dictionary may have any properties of the resolved entity
  198. known in advance, for example "title" if the title of the referred video is
  199. known ahead of time.
  200. _type "url_transparent" entities have the same specification as "url", but
  201. indicate that the given additional information is more precise than the one
  202. associated with the resolved URL.
  203. This is useful when a site employs a video service that hosts the video and
  204. its technical metadata, but that video service does not embed a useful
  205. title, description etc.
  206. Subclasses of this one should re-define the _real_initialize() and
  207. _real_extract() methods and define a _VALID_URL regexp.
  208. Probably, they should also be added to the list of extractors.
  209. Finally, the _WORKING attribute should be set to False for broken IEs
  210. in order to warn the users and skip the tests.
  211. """
  212. _ready = False
  213. _downloader = None
  214. _WORKING = True
  215. def __init__(self, downloader=None):
  216. """Constructor. Receives an optional downloader."""
  217. self._ready = False
  218. self.set_downloader(downloader)
  219. @classmethod
  220. def suitable(cls, url):
  221. """Receives a URL and returns True if suitable for this IE."""
  222. # This does not use has/getattr intentionally - we want to know whether
  223. # we have cached the regexp for *this* class, whereas getattr would also
  224. # match the superclass
  225. if '_VALID_URL_RE' not in cls.__dict__:
  226. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  227. return cls._VALID_URL_RE.match(url) is not None
  228. @classmethod
  229. def _match_id(cls, url):
  230. if '_VALID_URL_RE' not in cls.__dict__:
  231. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  232. m = cls._VALID_URL_RE.match(url)
  233. assert m
  234. return m.group('id')
  235. @classmethod
  236. def working(cls):
  237. """Getter method for _WORKING."""
  238. return cls._WORKING
  239. def initialize(self):
  240. """Initializes an instance (authentication, etc)."""
  241. if not self._ready:
  242. self._real_initialize()
  243. self._ready = True
  244. def extract(self, url):
  245. """Extracts URL information and returns it in list of dicts."""
  246. try:
  247. self.initialize()
  248. return self._real_extract(url)
  249. except ExtractorError:
  250. raise
  251. except compat_http_client.IncompleteRead as e:
  252. raise ExtractorError('A network error has occured.', cause=e, expected=True)
  253. except (KeyError, StopIteration) as e:
  254. raise ExtractorError('An extractor error has occured.', cause=e)
  255. def set_downloader(self, downloader):
  256. """Sets the downloader for this IE."""
  257. self._downloader = downloader
  258. def _real_initialize(self):
  259. """Real initialization process. Redefine in subclasses."""
  260. pass
  261. def _real_extract(self, url):
  262. """Real extraction process. Redefine in subclasses."""
  263. pass
  264. @classmethod
  265. def ie_key(cls):
  266. """A string for getting the InfoExtractor with get_info_extractor"""
  267. return cls.__name__[:-2]
  268. @property
  269. def IE_NAME(self):
  270. return type(self).__name__[:-2]
  271. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  272. """ Returns the response handle """
  273. if note is None:
  274. self.report_download_webpage(video_id)
  275. elif note is not False:
  276. if video_id is None:
  277. self.to_screen('%s' % (note,))
  278. else:
  279. self.to_screen('%s: %s' % (video_id, note))
  280. try:
  281. return self._downloader.urlopen(url_or_request)
  282. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  283. if errnote is False:
  284. return False
  285. if errnote is None:
  286. errnote = 'Unable to download webpage'
  287. errmsg = '%s: %s' % (errnote, compat_str(err))
  288. if fatal:
  289. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  290. else:
  291. self._downloader.report_warning(errmsg)
  292. return False
  293. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None):
  294. """ Returns a tuple (page content as string, URL handle) """
  295. # Strip hashes from the URL (#1038)
  296. if isinstance(url_or_request, (compat_str, str)):
  297. url_or_request = url_or_request.partition('#')[0]
  298. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
  299. if urlh is False:
  300. assert not fatal
  301. return False
  302. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  303. return (content, urlh)
  304. @staticmethod
  305. def _guess_encoding_from_content(content_type, webpage_bytes):
  306. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  307. if m:
  308. encoding = m.group(1)
  309. else:
  310. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  311. webpage_bytes[:1024])
  312. if m:
  313. encoding = m.group(1).decode('ascii')
  314. elif webpage_bytes.startswith(b'\xff\xfe'):
  315. encoding = 'utf-16'
  316. else:
  317. encoding = 'utf-8'
  318. return encoding
  319. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  320. content_type = urlh.headers.get('Content-Type', '')
  321. webpage_bytes = urlh.read()
  322. if prefix is not None:
  323. webpage_bytes = prefix + webpage_bytes
  324. if not encoding:
  325. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  326. if self._downloader.params.get('dump_intermediate_pages', False):
  327. try:
  328. url = url_or_request.get_full_url()
  329. except AttributeError:
  330. url = url_or_request
  331. self.to_screen('Dumping request to ' + url)
  332. dump = base64.b64encode(webpage_bytes).decode('ascii')
  333. self._downloader.to_screen(dump)
  334. if self._downloader.params.get('write_pages', False):
  335. try:
  336. url = url_or_request.get_full_url()
  337. except AttributeError:
  338. url = url_or_request
  339. basen = '%s_%s' % (video_id, url)
  340. if len(basen) > 240:
  341. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  342. basen = basen[:240 - len(h)] + h
  343. raw_filename = basen + '.dump'
  344. filename = sanitize_filename(raw_filename, restricted=True)
  345. self.to_screen('Saving request to ' + filename)
  346. # Working around MAX_PATH limitation on Windows (see
  347. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  348. if os.name == 'nt':
  349. absfilepath = os.path.abspath(filename)
  350. if len(absfilepath) > 259:
  351. filename = '\\\\?\\' + absfilepath
  352. with open(filename, 'wb') as outf:
  353. outf.write(webpage_bytes)
  354. try:
  355. content = webpage_bytes.decode(encoding, 'replace')
  356. except LookupError:
  357. content = webpage_bytes.decode('utf-8', 'replace')
  358. if ('<title>Access to this site is blocked</title>' in content and
  359. 'Websense' in content[:512]):
  360. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  361. blocked_iframe = self._html_search_regex(
  362. r'<iframe src="([^"]+)"', content,
  363. 'Websense information URL', default=None)
  364. if blocked_iframe:
  365. msg += ' Visit %s for more details' % blocked_iframe
  366. raise ExtractorError(msg, expected=True)
  367. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  368. msg = (
  369. 'Access to this webpage has been blocked by Indian censorship. '
  370. 'Use a VPN or proxy server (with --proxy) to route around it.')
  371. block_msg = self._html_search_regex(
  372. r'</h1><p>(.*?)</p>',
  373. content, 'block message', default=None)
  374. if block_msg:
  375. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  376. raise ExtractorError(msg, expected=True)
  377. return content
  378. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
  379. """ Returns the data of the page as a string """
  380. success = False
  381. try_count = 0
  382. while success is False:
  383. try:
  384. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  385. success = True
  386. except compat_http_client.IncompleteRead as e:
  387. try_count += 1
  388. if try_count >= tries:
  389. raise e
  390. self._sleep(timeout, video_id)
  391. if res is False:
  392. return res
  393. else:
  394. content, _ = res
  395. return content
  396. def _download_xml(self, url_or_request, video_id,
  397. note='Downloading XML', errnote='Unable to download XML',
  398. transform_source=None, fatal=True, encoding=None):
  399. """Return the xml as an xml.etree.ElementTree.Element"""
  400. xml_string = self._download_webpage(
  401. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding)
  402. if xml_string is False:
  403. return xml_string
  404. if transform_source:
  405. xml_string = transform_source(xml_string)
  406. return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
  407. def _download_json(self, url_or_request, video_id,
  408. note='Downloading JSON metadata',
  409. errnote='Unable to download JSON metadata',
  410. transform_source=None,
  411. fatal=True, encoding=None):
  412. json_string = self._download_webpage(
  413. url_or_request, video_id, note, errnote, fatal=fatal,
  414. encoding=encoding)
  415. if (not fatal) and json_string is False:
  416. return None
  417. return self._parse_json(
  418. json_string, video_id, transform_source=transform_source, fatal=fatal)
  419. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  420. if transform_source:
  421. json_string = transform_source(json_string)
  422. try:
  423. return json.loads(json_string)
  424. except ValueError as ve:
  425. errmsg = '%s: Failed to parse JSON ' % video_id
  426. if fatal:
  427. raise ExtractorError(errmsg, cause=ve)
  428. else:
  429. self.report_warning(errmsg + str(ve))
  430. def report_warning(self, msg, video_id=None):
  431. idstr = '' if video_id is None else '%s: ' % video_id
  432. self._downloader.report_warning(
  433. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  434. def to_screen(self, msg):
  435. """Print msg to screen, prefixing it with '[ie_name]'"""
  436. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  437. def report_extraction(self, id_or_name):
  438. """Report information extraction."""
  439. self.to_screen('%s: Extracting information' % id_or_name)
  440. def report_download_webpage(self, video_id):
  441. """Report webpage download."""
  442. self.to_screen('%s: Downloading webpage' % video_id)
  443. def report_age_confirmation(self):
  444. """Report attempt to confirm age."""
  445. self.to_screen('Confirming age')
  446. def report_login(self):
  447. """Report attempt to log in."""
  448. self.to_screen('Logging in')
  449. # Methods for following #608
  450. @staticmethod
  451. def url_result(url, ie=None, video_id=None, video_title=None):
  452. """Returns a URL that points to a page that should be processed"""
  453. # TODO: ie should be the class used for getting the info
  454. video_info = {'_type': 'url',
  455. 'url': url,
  456. 'ie_key': ie}
  457. if video_id is not None:
  458. video_info['id'] = video_id
  459. if video_title is not None:
  460. video_info['title'] = video_title
  461. return video_info
  462. @staticmethod
  463. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  464. """Returns a playlist"""
  465. video_info = {'_type': 'playlist',
  466. 'entries': entries}
  467. if playlist_id:
  468. video_info['id'] = playlist_id
  469. if playlist_title:
  470. video_info['title'] = playlist_title
  471. if playlist_description:
  472. video_info['description'] = playlist_description
  473. return video_info
  474. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  475. """
  476. Perform a regex search on the given string, using a single or a list of
  477. patterns returning the first matching group.
  478. In case of failure return a default value or raise a WARNING or a
  479. RegexNotFoundError, depending on fatal, specifying the field name.
  480. """
  481. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  482. mobj = re.search(pattern, string, flags)
  483. else:
  484. for p in pattern:
  485. mobj = re.search(p, string, flags)
  486. if mobj:
  487. break
  488. if not self._downloader.params.get('no_color') and os.name != 'nt' and sys.stderr.isatty():
  489. _name = '\033[0;34m%s\033[0m' % name
  490. else:
  491. _name = name
  492. if mobj:
  493. if group is None:
  494. # return the first matching group
  495. return next(g for g in mobj.groups() if g is not None)
  496. else:
  497. return mobj.group(group)
  498. elif default is not NO_DEFAULT:
  499. return default
  500. elif fatal:
  501. raise RegexNotFoundError('Unable to extract %s' % _name)
  502. else:
  503. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  504. return None
  505. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  506. """
  507. Like _search_regex, but strips HTML tags and unescapes entities.
  508. """
  509. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  510. if res:
  511. return clean_html(res).strip()
  512. else:
  513. return res
  514. def _get_login_info(self):
  515. """
  516. Get the login info as (username, password)
  517. It will look in the netrc file using the _NETRC_MACHINE value
  518. If there's no info available, return (None, None)
  519. """
  520. if self._downloader is None:
  521. return (None, None)
  522. username = None
  523. password = None
  524. downloader_params = self._downloader.params
  525. # Attempt to use provided username and password or .netrc data
  526. if downloader_params.get('username', None) is not None:
  527. username = downloader_params['username']
  528. password = downloader_params['password']
  529. elif downloader_params.get('usenetrc', False):
  530. try:
  531. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  532. if info is not None:
  533. username = info[0]
  534. password = info[2]
  535. else:
  536. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  537. except (IOError, netrc.NetrcParseError) as err:
  538. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  539. return (username, password)
  540. def _get_tfa_info(self):
  541. """
  542. Get the two-factor authentication info
  543. TODO - asking the user will be required for sms/phone verify
  544. currently just uses the command line option
  545. If there's no info available, return None
  546. """
  547. if self._downloader is None:
  548. return None
  549. downloader_params = self._downloader.params
  550. if downloader_params.get('twofactor', None) is not None:
  551. return downloader_params['twofactor']
  552. return None
  553. # Helper functions for extracting OpenGraph info
  554. @staticmethod
  555. def _og_regexes(prop):
  556. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  557. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  558. template = r'<meta[^>]+?%s[^>]+?%s'
  559. return [
  560. template % (property_re, content_re),
  561. template % (content_re, property_re),
  562. ]
  563. @staticmethod
  564. def _meta_regex(prop):
  565. return r'''(?isx)<meta
  566. (?=[^>]+(?:itemprop|name|property|id)=(["\']?)%s\1)
  567. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  568. def _og_search_property(self, prop, html, name=None, **kargs):
  569. if name is None:
  570. name = 'OpenGraph %s' % prop
  571. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  572. if escaped is None:
  573. return None
  574. return unescapeHTML(escaped)
  575. def _og_search_thumbnail(self, html, **kargs):
  576. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  577. def _og_search_description(self, html, **kargs):
  578. return self._og_search_property('description', html, fatal=False, **kargs)
  579. def _og_search_title(self, html, **kargs):
  580. return self._og_search_property('title', html, **kargs)
  581. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  582. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  583. if secure:
  584. regexes = self._og_regexes('video:secure_url') + regexes
  585. return self._html_search_regex(regexes, html, name, **kargs)
  586. def _og_search_url(self, html, **kargs):
  587. return self._og_search_property('url', html, **kargs)
  588. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  589. if display_name is None:
  590. display_name = name
  591. return self._html_search_regex(
  592. self._meta_regex(name),
  593. html, display_name, fatal=fatal, group='content', **kwargs)
  594. def _dc_search_uploader(self, html):
  595. return self._html_search_meta('dc.creator', html, 'uploader')
  596. def _rta_search(self, html):
  597. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  598. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  599. r' content="RTA-5042-1996-1400-1577-RTA"',
  600. html):
  601. return 18
  602. return 0
  603. def _media_rating_search(self, html):
  604. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  605. rating = self._html_search_meta('rating', html)
  606. if not rating:
  607. return None
  608. RATING_TABLE = {
  609. 'safe for kids': 0,
  610. 'general': 8,
  611. '14 years': 14,
  612. 'mature': 17,
  613. 'restricted': 19,
  614. }
  615. return RATING_TABLE.get(rating.lower(), None)
  616. def _family_friendly_search(self, html):
  617. # See http://schema.org/VideoObject
  618. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  619. if not family_friendly:
  620. return None
  621. RATING_TABLE = {
  622. '1': 0,
  623. 'true': 0,
  624. '0': 18,
  625. 'false': 18,
  626. }
  627. return RATING_TABLE.get(family_friendly.lower(), None)
  628. def _twitter_search_player(self, html):
  629. return self._html_search_meta('twitter:player', html,
  630. 'twitter card player')
  631. @staticmethod
  632. def _hidden_inputs(html):
  633. return dict([
  634. (input.group('name'), input.group('value')) for input in re.finditer(
  635. r'''(?x)
  636. <input\s+
  637. type=(?P<q_hidden>["\'])hidden(?P=q_hidden)\s+
  638. name=(?P<q_name>["\'])(?P<name>.+?)(?P=q_name)\s+
  639. (?:id=(?P<q_id>["\']).+?(?P=q_id)\s+)?
  640. value=(?P<q_value>["\'])(?P<value>.*?)(?P=q_value)
  641. ''', html)
  642. ])
  643. def _form_hidden_inputs(self, form_id, html):
  644. form = self._search_regex(
  645. r'(?s)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  646. html, '%s form' % form_id, group='form')
  647. return self._hidden_inputs(form)
  648. def _sort_formats(self, formats, field_preference=None):
  649. if not formats:
  650. raise ExtractorError('No video formats found')
  651. def _formats_key(f):
  652. # TODO remove the following workaround
  653. from ..utils import determine_ext
  654. if not f.get('ext') and 'url' in f:
  655. f['ext'] = determine_ext(f['url'])
  656. if isinstance(field_preference, (list, tuple)):
  657. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  658. preference = f.get('preference')
  659. if preference is None:
  660. proto = f.get('protocol')
  661. if proto is None:
  662. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  663. preference = 0 if proto in ['http', 'https'] else -0.1
  664. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  665. preference -= 0.5
  666. if f.get('vcodec') == 'none': # audio only
  667. if self._downloader.params.get('prefer_free_formats'):
  668. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  669. else:
  670. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  671. ext_preference = 0
  672. try:
  673. audio_ext_preference = ORDER.index(f['ext'])
  674. except ValueError:
  675. audio_ext_preference = -1
  676. else:
  677. if self._downloader.params.get('prefer_free_formats'):
  678. ORDER = ['flv', 'mp4', 'webm']
  679. else:
  680. ORDER = ['webm', 'flv', 'mp4']
  681. try:
  682. ext_preference = ORDER.index(f['ext'])
  683. except ValueError:
  684. ext_preference = -1
  685. audio_ext_preference = 0
  686. return (
  687. preference,
  688. f.get('language_preference') if f.get('language_preference') is not None else -1,
  689. f.get('quality') if f.get('quality') is not None else -1,
  690. f.get('tbr') if f.get('tbr') is not None else -1,
  691. f.get('filesize') if f.get('filesize') is not None else -1,
  692. f.get('vbr') if f.get('vbr') is not None else -1,
  693. f.get('height') if f.get('height') is not None else -1,
  694. f.get('width') if f.get('width') is not None else -1,
  695. ext_preference,
  696. f.get('abr') if f.get('abr') is not None else -1,
  697. audio_ext_preference,
  698. f.get('fps') if f.get('fps') is not None else -1,
  699. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  700. f.get('source_preference') if f.get('source_preference') is not None else -1,
  701. f.get('format_id') if f.get('format_id') is not None else '',
  702. )
  703. formats.sort(key=_formats_key)
  704. def _check_formats(self, formats, video_id):
  705. if formats:
  706. formats[:] = filter(
  707. lambda f: self._is_valid_url(
  708. f['url'], video_id,
  709. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  710. formats)
  711. def _is_valid_url(self, url, video_id, item='video'):
  712. url = self._proto_relative_url(url, scheme='http:')
  713. # For now assume non HTTP(S) URLs always valid
  714. if not (url.startswith('http://') or url.startswith('https://')):
  715. return True
  716. try:
  717. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  718. return True
  719. except ExtractorError as e:
  720. if isinstance(e.cause, compat_HTTPError):
  721. self.to_screen(
  722. '%s: %s URL is invalid, skipping' % (video_id, item))
  723. return False
  724. raise
  725. def http_scheme(self):
  726. """ Either "http:" or "https:", depending on the user's preferences """
  727. return (
  728. 'http:'
  729. if self._downloader.params.get('prefer_insecure', False)
  730. else 'https:')
  731. def _proto_relative_url(self, url, scheme=None):
  732. if url is None:
  733. return url
  734. if url.startswith('//'):
  735. if scheme is None:
  736. scheme = self.http_scheme()
  737. return scheme + url
  738. else:
  739. return url
  740. def _sleep(self, timeout, video_id, msg_template=None):
  741. if msg_template is None:
  742. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  743. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  744. self.to_screen(msg)
  745. time.sleep(timeout)
  746. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  747. transform_source=lambda s: fix_xml_ampersands(s).strip()):
  748. manifest = self._download_xml(
  749. manifest_url, video_id, 'Downloading f4m manifest',
  750. 'Unable to download f4m manifest',
  751. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  752. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  753. transform_source=transform_source)
  754. formats = []
  755. manifest_version = '1.0'
  756. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  757. if not media_nodes:
  758. manifest_version = '2.0'
  759. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  760. for i, media_el in enumerate(media_nodes):
  761. if manifest_version == '2.0':
  762. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  763. if not media_url:
  764. continue
  765. manifest_url = (
  766. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  767. else ('/'.join(manifest_url.split('/')[:-1]) + '/' + media_url))
  768. # If media_url is itself a f4m manifest do the recursive extraction
  769. # since bitrates in parent manifest (this one) and media_url manifest
  770. # may differ leading to inability to resolve the format by requested
  771. # bitrate in f4m downloader
  772. if determine_ext(manifest_url) == 'f4m':
  773. formats.extend(self._extract_f4m_formats(manifest_url, video_id, preference, f4m_id))
  774. continue
  775. tbr = int_or_none(media_el.attrib.get('bitrate'))
  776. formats.append({
  777. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  778. 'url': manifest_url,
  779. 'ext': 'flv',
  780. 'tbr': tbr,
  781. 'width': int_or_none(media_el.attrib.get('width')),
  782. 'height': int_or_none(media_el.attrib.get('height')),
  783. 'preference': preference,
  784. })
  785. self._sort_formats(formats)
  786. return formats
  787. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  788. entry_protocol='m3u8', preference=None,
  789. m3u8_id=None, note=None, errnote=None,
  790. fatal=True):
  791. formats = [{
  792. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  793. 'url': m3u8_url,
  794. 'ext': ext,
  795. 'protocol': 'm3u8',
  796. 'preference': preference - 1 if preference else -1,
  797. 'resolution': 'multiple',
  798. 'format_note': 'Quality selection URL',
  799. }]
  800. format_url = lambda u: (
  801. u
  802. if re.match(r'^https?://', u)
  803. else compat_urlparse.urljoin(m3u8_url, u))
  804. m3u8_doc = self._download_webpage(
  805. m3u8_url, video_id,
  806. note=note or 'Downloading m3u8 information',
  807. errnote=errnote or 'Failed to download m3u8 information',
  808. fatal=fatal)
  809. if m3u8_doc is False:
  810. return m3u8_doc
  811. last_info = None
  812. last_media = None
  813. kv_rex = re.compile(
  814. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  815. for line in m3u8_doc.splitlines():
  816. if line.startswith('#EXT-X-STREAM-INF:'):
  817. last_info = {}
  818. for m in kv_rex.finditer(line):
  819. v = m.group('val')
  820. if v.startswith('"'):
  821. v = v[1:-1]
  822. last_info[m.group('key')] = v
  823. elif line.startswith('#EXT-X-MEDIA:'):
  824. last_media = {}
  825. for m in kv_rex.finditer(line):
  826. v = m.group('val')
  827. if v.startswith('"'):
  828. v = v[1:-1]
  829. last_media[m.group('key')] = v
  830. elif line.startswith('#') or not line.strip():
  831. continue
  832. else:
  833. if last_info is None:
  834. formats.append({'url': format_url(line)})
  835. continue
  836. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  837. format_id = []
  838. if m3u8_id:
  839. format_id.append(m3u8_id)
  840. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  841. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  842. f = {
  843. 'format_id': '-'.join(format_id),
  844. 'url': format_url(line.strip()),
  845. 'tbr': tbr,
  846. 'ext': ext,
  847. 'protocol': entry_protocol,
  848. 'preference': preference,
  849. }
  850. codecs = last_info.get('CODECS')
  851. if codecs:
  852. # TODO: looks like video codec is not always necessarily goes first
  853. va_codecs = codecs.split(',')
  854. if va_codecs[0]:
  855. f['vcodec'] = va_codecs[0].partition('.')[0]
  856. if len(va_codecs) > 1 and va_codecs[1]:
  857. f['acodec'] = va_codecs[1].partition('.')[0]
  858. resolution = last_info.get('RESOLUTION')
  859. if resolution:
  860. width_str, height_str = resolution.split('x')
  861. f['width'] = int(width_str)
  862. f['height'] = int(height_str)
  863. if last_media is not None:
  864. f['m3u8_media'] = last_media
  865. last_media = None
  866. formats.append(f)
  867. last_info = {}
  868. self._sort_formats(formats)
  869. return formats
  870. @staticmethod
  871. def _xpath_ns(path, namespace=None):
  872. if not namespace:
  873. return path
  874. out = []
  875. for c in path.split('/'):
  876. if not c or c == '.':
  877. out.append(c)
  878. else:
  879. out.append('{%s}%s' % (namespace, c))
  880. return '/'.join(out)
  881. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  882. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  883. if smil is False:
  884. assert not fatal
  885. return []
  886. namespace = self._parse_smil_namespace(smil)
  887. return self._parse_smil_formats(
  888. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  889. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  890. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  891. if smil is False:
  892. return {}
  893. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  894. def _download_smil(self, smil_url, video_id, fatal=True):
  895. return self._download_xml(
  896. smil_url, video_id, 'Downloading SMIL file',
  897. 'Unable to download SMIL file', fatal=fatal)
  898. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  899. namespace = self._parse_smil_namespace(smil)
  900. formats = self._parse_smil_formats(
  901. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  902. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  903. video_id = os.path.splitext(url_basename(smil_url))[0]
  904. title = None
  905. description = None
  906. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  907. name = meta.attrib.get('name')
  908. content = meta.attrib.get('content')
  909. if not name or not content:
  910. continue
  911. if not title and name == 'title':
  912. title = content
  913. elif not description and name in ('description', 'abstract'):
  914. description = content
  915. return {
  916. 'id': video_id,
  917. 'title': title or video_id,
  918. 'description': description,
  919. 'formats': formats,
  920. 'subtitles': subtitles,
  921. }
  922. def _parse_smil_namespace(self, smil):
  923. return self._search_regex(
  924. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  925. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None):
  926. base = smil_url
  927. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  928. b = meta.get('base') or meta.get('httpBase')
  929. if b:
  930. base = b
  931. break
  932. formats = []
  933. rtmp_count = 0
  934. http_count = 0
  935. videos = smil.findall(self._xpath_ns('.//video', namespace))
  936. for video in videos:
  937. src = video.get('src')
  938. if not src:
  939. continue
  940. bitrate = int_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  941. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  942. width = int_or_none(video.get('width'))
  943. height = int_or_none(video.get('height'))
  944. proto = video.get('proto')
  945. ext = video.get('ext')
  946. src_ext = determine_ext(src)
  947. streamer = video.get('streamer') or base
  948. if proto == 'rtmp' or streamer.startswith('rtmp'):
  949. rtmp_count += 1
  950. formats.append({
  951. 'url': streamer,
  952. 'play_path': src,
  953. 'ext': 'flv',
  954. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  955. 'tbr': bitrate,
  956. 'filesize': filesize,
  957. 'width': width,
  958. 'height': height,
  959. })
  960. continue
  961. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  962. if proto == 'm3u8' or src_ext == 'm3u8':
  963. formats.extend(self._extract_m3u8_formats(
  964. src_url, video_id, ext or 'mp4', m3u8_id='hls'))
  965. continue
  966. if src_ext == 'f4m':
  967. f4m_url = src_url
  968. if not f4m_params:
  969. f4m_params = {
  970. 'hdcore': '3.2.0',
  971. 'plugin': 'flowplayer-3.2.0.1',
  972. }
  973. f4m_url += '&' if '?' in f4m_url else '?'
  974. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  975. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds'))
  976. continue
  977. if src_url.startswith('http'):
  978. http_count += 1
  979. formats.append({
  980. 'url': src_url,
  981. 'ext': ext or src_ext or 'flv',
  982. 'format_id': 'http-%d' % (bitrate or http_count),
  983. 'tbr': bitrate,
  984. 'filesize': filesize,
  985. 'width': width,
  986. 'height': height,
  987. })
  988. continue
  989. self._sort_formats(formats)
  990. return formats
  991. def _parse_smil_subtitles(self, smil, namespace=None):
  992. subtitles = {}
  993. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  994. src = textstream.get('src')
  995. if not src:
  996. continue
  997. ext = textstream.get('ext') or determine_ext(src)
  998. if not ext:
  999. type_ = textstream.get('type')
  1000. if type_ == 'text/srt':
  1001. ext = 'srt'
  1002. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName')
  1003. subtitles.setdefault(lang, []).append({
  1004. 'url': src,
  1005. 'ext': ext,
  1006. })
  1007. return subtitles
  1008. def _live_title(self, name):
  1009. """ Generate the title for a live video """
  1010. now = datetime.datetime.now()
  1011. now_str = now.strftime("%Y-%m-%d %H:%M")
  1012. return name + ' ' + now_str
  1013. def _int(self, v, name, fatal=False, **kwargs):
  1014. res = int_or_none(v, **kwargs)
  1015. if 'get_attr' in kwargs:
  1016. print(getattr(v, kwargs['get_attr']))
  1017. if res is None:
  1018. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1019. if fatal:
  1020. raise ExtractorError(msg)
  1021. else:
  1022. self._downloader.report_warning(msg)
  1023. return res
  1024. def _float(self, v, name, fatal=False, **kwargs):
  1025. res = float_or_none(v, **kwargs)
  1026. if res is None:
  1027. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1028. if fatal:
  1029. raise ExtractorError(msg)
  1030. else:
  1031. self._downloader.report_warning(msg)
  1032. return res
  1033. def _set_cookie(self, domain, name, value, expire_time=None):
  1034. cookie = compat_cookiejar.Cookie(
  1035. 0, name, value, None, None, domain, None,
  1036. None, '/', True, False, expire_time, '', None, None, None)
  1037. self._downloader.cookiejar.set_cookie(cookie)
  1038. def _get_cookies(self, url):
  1039. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1040. req = compat_urllib_request.Request(url)
  1041. self._downloader.cookiejar.add_cookie_header(req)
  1042. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1043. def get_testcases(self, include_onlymatching=False):
  1044. t = getattr(self, '_TEST', None)
  1045. if t:
  1046. assert not hasattr(self, '_TESTS'), \
  1047. '%s has _TEST and _TESTS' % type(self).__name__
  1048. tests = [t]
  1049. else:
  1050. tests = getattr(self, '_TESTS', [])
  1051. for t in tests:
  1052. if not include_onlymatching and t.get('only_matching', False):
  1053. continue
  1054. t['name'] = type(self).__name__[:-len('IE')]
  1055. yield t
  1056. def is_suitable(self, age_limit):
  1057. """ Test whether the extractor is generally suitable for the given
  1058. age limit (i.e. pornographic sites are not, all others usually are) """
  1059. any_restricted = False
  1060. for tc in self.get_testcases(include_onlymatching=False):
  1061. if 'playlist' in tc:
  1062. tc = tc['playlist'][0]
  1063. is_restricted = age_restricted(
  1064. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1065. if not is_restricted:
  1066. return True
  1067. any_restricted = any_restricted or is_restricted
  1068. return not any_restricted
  1069. def extract_subtitles(self, *args, **kwargs):
  1070. if (self._downloader.params.get('writesubtitles', False) or
  1071. self._downloader.params.get('listsubtitles')):
  1072. return self._get_subtitles(*args, **kwargs)
  1073. return {}
  1074. def _get_subtitles(self, *args, **kwargs):
  1075. raise NotImplementedError("This method must be implemented by subclasses")
  1076. def extract_automatic_captions(self, *args, **kwargs):
  1077. if (self._downloader.params.get('writeautomaticsub', False) or
  1078. self._downloader.params.get('listsubtitles')):
  1079. return self._get_automatic_captions(*args, **kwargs)
  1080. return {}
  1081. def _get_automatic_captions(self, *args, **kwargs):
  1082. raise NotImplementedError("This method must be implemented by subclasses")
  1083. class SearchInfoExtractor(InfoExtractor):
  1084. """
  1085. Base class for paged search queries extractors.
  1086. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1087. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1088. """
  1089. @classmethod
  1090. def _make_valid_url(cls):
  1091. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1092. @classmethod
  1093. def suitable(cls, url):
  1094. return re.match(cls._make_valid_url(), url) is not None
  1095. def _real_extract(self, query):
  1096. mobj = re.match(self._make_valid_url(), query)
  1097. if mobj is None:
  1098. raise ExtractorError('Invalid search query "%s"' % query)
  1099. prefix = mobj.group('prefix')
  1100. query = mobj.group('query')
  1101. if prefix == '':
  1102. return self._get_n_results(query, 1)
  1103. elif prefix == 'all':
  1104. return self._get_n_results(query, self._MAX_RESULTS)
  1105. else:
  1106. n = int(prefix)
  1107. if n <= 0:
  1108. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1109. elif n > self._MAX_RESULTS:
  1110. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1111. n = self._MAX_RESULTS
  1112. return self._get_n_results(query, n)
  1113. def _get_n_results(self, query, n):
  1114. """Get a specified number of results for a query"""
  1115. raise NotImplementedError("This method must be implemented by subclasses")
  1116. @property
  1117. def SEARCH_KEY(self):
  1118. return self._SEARCH_KEY