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.

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