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.

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