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.

792 lines
31 KiB

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