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.

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