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.

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