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.

750 lines
30 KiB

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