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.

806 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. # Working around MAX_PATH limitation on Windows (see
  251. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  252. if os.name == 'nt':
  253. absfilepath = os.path.abspath(filename)
  254. if len(absfilepath) > 259:
  255. filename = '\\\\?\\' + absfilepath
  256. with open(filename, 'wb') as outf:
  257. outf.write(webpage_bytes)
  258. try:
  259. content = webpage_bytes.decode(encoding, 'replace')
  260. except LookupError:
  261. content = webpage_bytes.decode('utf-8', 'replace')
  262. if ('<title>Access to this site is blocked</title>' in content and
  263. 'Websense' in content[:512]):
  264. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  265. blocked_iframe = self._html_search_regex(
  266. r'<iframe src="([^"]+)"', content,
  267. 'Websense information URL', default=None)
  268. if blocked_iframe:
  269. msg += ' Visit %s for more details' % blocked_iframe
  270. raise ExtractorError(msg, expected=True)
  271. return (content, urlh)
  272. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  273. """ Returns the data of the page as a string """
  274. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal)
  275. if res is False:
  276. return res
  277. else:
  278. content, _ = res
  279. return content
  280. def _download_xml(self, url_or_request, video_id,
  281. note='Downloading XML', errnote='Unable to download XML',
  282. transform_source=None, fatal=True):
  283. """Return the xml as an xml.etree.ElementTree.Element"""
  284. xml_string = self._download_webpage(
  285. url_or_request, video_id, note, errnote, fatal=fatal)
  286. if xml_string is False:
  287. return xml_string
  288. if transform_source:
  289. xml_string = transform_source(xml_string)
  290. return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
  291. def _download_json(self, url_or_request, video_id,
  292. note='Downloading JSON metadata',
  293. errnote='Unable to download JSON metadata',
  294. transform_source=None,
  295. fatal=True):
  296. json_string = self._download_webpage(
  297. url_or_request, video_id, note, errnote, fatal=fatal)
  298. if (not fatal) and json_string is False:
  299. return None
  300. if transform_source:
  301. json_string = transform_source(json_string)
  302. try:
  303. return json.loads(json_string)
  304. except ValueError as ve:
  305. errmsg = '%s: Failed to parse JSON ' % video_id
  306. if fatal:
  307. raise ExtractorError(errmsg, cause=ve)
  308. else:
  309. self.report_warning(errmsg + str(ve))
  310. def report_warning(self, msg, video_id=None):
  311. idstr = '' if video_id is None else '%s: ' % video_id
  312. self._downloader.report_warning(
  313. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  314. def to_screen(self, msg):
  315. """Print msg to screen, prefixing it with '[ie_name]'"""
  316. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  317. def report_extraction(self, id_or_name):
  318. """Report information extraction."""
  319. self.to_screen('%s: Extracting information' % id_or_name)
  320. def report_download_webpage(self, video_id):
  321. """Report webpage download."""
  322. self.to_screen('%s: Downloading webpage' % video_id)
  323. def report_age_confirmation(self):
  324. """Report attempt to confirm age."""
  325. self.to_screen('Confirming age')
  326. def report_login(self):
  327. """Report attempt to log in."""
  328. self.to_screen('Logging in')
  329. #Methods for following #608
  330. @staticmethod
  331. def url_result(url, ie=None, video_id=None):
  332. """Returns a url that points to a page that should be processed"""
  333. #TODO: ie should be the class used for getting the info
  334. video_info = {'_type': 'url',
  335. 'url': url,
  336. 'ie_key': ie}
  337. if video_id is not None:
  338. video_info['id'] = video_id
  339. return video_info
  340. @staticmethod
  341. def playlist_result(entries, playlist_id=None, playlist_title=None):
  342. """Returns a playlist"""
  343. video_info = {'_type': 'playlist',
  344. 'entries': entries}
  345. if playlist_id:
  346. video_info['id'] = playlist_id
  347. if playlist_title:
  348. video_info['title'] = playlist_title
  349. return video_info
  350. def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  351. """
  352. Perform a regex search on the given string, using a single or a list of
  353. patterns returning the first matching group.
  354. In case of failure return a default value or raise a WARNING or a
  355. RegexNotFoundError, depending on fatal, specifying the field name.
  356. """
  357. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  358. mobj = re.search(pattern, string, flags)
  359. else:
  360. for p in pattern:
  361. mobj = re.search(p, string, flags)
  362. if mobj:
  363. break
  364. if os.name != 'nt' and sys.stderr.isatty():
  365. _name = '\033[0;34m%s\033[0m' % name
  366. else:
  367. _name = name
  368. if mobj:
  369. # return the first matching group
  370. return next(g for g in mobj.groups() if g is not None)
  371. elif default is not _NO_DEFAULT:
  372. return default
  373. elif fatal:
  374. raise RegexNotFoundError('Unable to extract %s' % _name)
  375. else:
  376. self._downloader.report_warning('unable to extract %s; '
  377. 'please report this issue on http://yt-dl.org/bug' % _name)
  378. return None
  379. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  380. """
  381. Like _search_regex, but strips HTML tags and unescapes entities.
  382. """
  383. res = self._search_regex(pattern, string, name, default, fatal, flags)
  384. if res:
  385. return clean_html(res).strip()
  386. else:
  387. return res
  388. def _get_login_info(self):
  389. """
  390. Get the the login info as (username, password)
  391. It will look in the netrc file using the _NETRC_MACHINE value
  392. If there's no info available, return (None, None)
  393. """
  394. if self._downloader is None:
  395. return (None, None)
  396. username = None
  397. password = None
  398. downloader_params = self._downloader.params
  399. # Attempt to use provided username and password or .netrc data
  400. if downloader_params.get('username', None) is not None:
  401. username = downloader_params['username']
  402. password = downloader_params['password']
  403. elif downloader_params.get('usenetrc', False):
  404. try:
  405. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  406. if info is not None:
  407. username = info[0]
  408. password = info[2]
  409. else:
  410. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  411. except (IOError, netrc.NetrcParseError) as err:
  412. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  413. return (username, password)
  414. def _get_tfa_info(self):
  415. """
  416. Get the two-factor authentication info
  417. TODO - asking the user will be required for sms/phone verify
  418. currently just uses the command line option
  419. If there's no info available, return None
  420. """
  421. if self._downloader is None:
  422. return None
  423. downloader_params = self._downloader.params
  424. if downloader_params.get('twofactor', None) is not None:
  425. return downloader_params['twofactor']
  426. return None
  427. # Helper functions for extracting OpenGraph info
  428. @staticmethod
  429. def _og_regexes(prop):
  430. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  431. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  432. template = r'<meta[^>]+?%s[^>]+?%s'
  433. return [
  434. template % (property_re, content_re),
  435. template % (content_re, property_re),
  436. ]
  437. def _og_search_property(self, prop, html, name=None, **kargs):
  438. if name is None:
  439. name = 'OpenGraph %s' % prop
  440. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  441. if escaped is None:
  442. return None
  443. return unescapeHTML(escaped)
  444. def _og_search_thumbnail(self, html, **kargs):
  445. return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs)
  446. def _og_search_description(self, html, **kargs):
  447. return self._og_search_property('description', html, fatal=False, **kargs)
  448. def _og_search_title(self, html, **kargs):
  449. return self._og_search_property('title', html, **kargs)
  450. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  451. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  452. if secure:
  453. regexes = self._og_regexes('video:secure_url') + regexes
  454. return self._html_search_regex(regexes, html, name, **kargs)
  455. def _og_search_url(self, html, **kargs):
  456. return self._og_search_property('url', html, **kargs)
  457. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  458. if display_name is None:
  459. display_name = name
  460. return self._html_search_regex(
  461. r'''(?ix)<meta
  462. (?=[^>]+(?:itemprop|name|property)=["\']?%s["\']?)
  463. [^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
  464. html, display_name, fatal=fatal, **kwargs)
  465. def _dc_search_uploader(self, html):
  466. return self._html_search_meta('dc.creator', html, 'uploader')
  467. def _rta_search(self, html):
  468. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  469. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  470. r' content="RTA-5042-1996-1400-1577-RTA"',
  471. html):
  472. return 18
  473. return 0
  474. def _media_rating_search(self, html):
  475. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  476. rating = self._html_search_meta('rating', html)
  477. if not rating:
  478. return None
  479. RATING_TABLE = {
  480. 'safe for kids': 0,
  481. 'general': 8,
  482. '14 years': 14,
  483. 'mature': 17,
  484. 'restricted': 19,
  485. }
  486. return RATING_TABLE.get(rating.lower(), None)
  487. def _twitter_search_player(self, html):
  488. return self._html_search_meta('twitter:player', html,
  489. 'twitter card player')
  490. def _sort_formats(self, formats):
  491. if not formats:
  492. raise ExtractorError('No video formats found')
  493. def _formats_key(f):
  494. # TODO remove the following workaround
  495. from ..utils import determine_ext
  496. if not f.get('ext') and 'url' in f:
  497. f['ext'] = determine_ext(f['url'])
  498. preference = f.get('preference')
  499. if preference is None:
  500. proto = f.get('protocol')
  501. if proto is None:
  502. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  503. preference = 0 if proto in ['http', 'https'] else -0.1
  504. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  505. preference -= 0.5
  506. if f.get('vcodec') == 'none': # audio only
  507. if self._downloader.params.get('prefer_free_formats'):
  508. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  509. else:
  510. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  511. ext_preference = 0
  512. try:
  513. audio_ext_preference = ORDER.index(f['ext'])
  514. except ValueError:
  515. audio_ext_preference = -1
  516. else:
  517. if self._downloader.params.get('prefer_free_formats'):
  518. ORDER = ['flv', 'mp4', 'webm']
  519. else:
  520. ORDER = ['webm', 'flv', 'mp4']
  521. try:
  522. ext_preference = ORDER.index(f['ext'])
  523. except ValueError:
  524. ext_preference = -1
  525. audio_ext_preference = 0
  526. return (
  527. preference,
  528. f.get('quality') if f.get('quality') is not None else -1,
  529. f.get('height') if f.get('height') is not None else -1,
  530. f.get('width') if f.get('width') is not None else -1,
  531. ext_preference,
  532. f.get('tbr') if f.get('tbr') is not None else -1,
  533. f.get('vbr') if f.get('vbr') is not None else -1,
  534. f.get('abr') if f.get('abr') is not None else -1,
  535. audio_ext_preference,
  536. f.get('filesize') if f.get('filesize') is not None else -1,
  537. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  538. f.get('format_id'),
  539. )
  540. formats.sort(key=_formats_key)
  541. def http_scheme(self):
  542. """ Either "https:" or "https:", depending on the user's preferences """
  543. return (
  544. 'http:'
  545. if self._downloader.params.get('prefer_insecure', False)
  546. else 'https:')
  547. def _proto_relative_url(self, url, scheme=None):
  548. if url is None:
  549. return url
  550. if url.startswith('//'):
  551. if scheme is None:
  552. scheme = self.http_scheme()
  553. return scheme + url
  554. else:
  555. return url
  556. def _sleep(self, timeout, video_id, msg_template=None):
  557. if msg_template is None:
  558. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  559. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  560. self.to_screen(msg)
  561. time.sleep(timeout)
  562. def _extract_f4m_formats(self, manifest_url, video_id):
  563. manifest = self._download_xml(
  564. manifest_url, video_id, 'Downloading f4m manifest',
  565. 'Unable to download f4m manifest')
  566. formats = []
  567. manifest_version = '1.0'
  568. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  569. if not media_nodes:
  570. manifest_version = '2.0'
  571. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  572. for i, media_el in enumerate(media_nodes):
  573. if manifest_version == '2.0':
  574. manifest_url = '/'.join(manifest_url.split('/')[:-1]) + '/' + media_el.attrib.get('href')
  575. tbr = int_or_none(media_el.attrib.get('bitrate'))
  576. format_id = 'f4m-%d' % (i if tbr is None else tbr)
  577. formats.append({
  578. 'format_id': format_id,
  579. 'url': manifest_url,
  580. 'ext': 'flv',
  581. 'tbr': tbr,
  582. 'width': int_or_none(media_el.attrib.get('width')),
  583. 'height': int_or_none(media_el.attrib.get('height')),
  584. })
  585. self._sort_formats(formats)
  586. return formats
  587. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  588. entry_protocol='m3u8', preference=None):
  589. formats = [{
  590. 'format_id': 'm3u8-meta',
  591. 'url': m3u8_url,
  592. 'ext': ext,
  593. 'protocol': 'm3u8',
  594. 'preference': -1,
  595. 'resolution': 'multiple',
  596. 'format_note': 'Quality selection URL',
  597. }]
  598. format_url = lambda u: (
  599. u
  600. if re.match(r'^https?://', u)
  601. else compat_urlparse.urljoin(m3u8_url, u))
  602. m3u8_doc = self._download_webpage(m3u8_url, video_id)
  603. last_info = None
  604. kv_rex = re.compile(
  605. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  606. for line in m3u8_doc.splitlines():
  607. if line.startswith('#EXT-X-STREAM-INF:'):
  608. last_info = {}
  609. for m in kv_rex.finditer(line):
  610. v = m.group('val')
  611. if v.startswith('"'):
  612. v = v[1:-1]
  613. last_info[m.group('key')] = v
  614. elif line.startswith('#') or not line.strip():
  615. continue
  616. else:
  617. if last_info is None:
  618. formats.append({'url': format_url(line)})
  619. continue
  620. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  621. f = {
  622. 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)),
  623. 'url': format_url(line.strip()),
  624. 'tbr': tbr,
  625. 'ext': ext,
  626. 'protocol': entry_protocol,
  627. 'preference': preference,
  628. }
  629. codecs = last_info.get('CODECS')
  630. if codecs:
  631. # TODO: looks like video codec is not always necessarily goes first
  632. va_codecs = codecs.split(',')
  633. if va_codecs[0]:
  634. f['vcodec'] = va_codecs[0].partition('.')[0]
  635. if len(va_codecs) > 1 and va_codecs[1]:
  636. f['acodec'] = va_codecs[1].partition('.')[0]
  637. resolution = last_info.get('RESOLUTION')
  638. if resolution:
  639. width_str, height_str = resolution.split('x')
  640. f['width'] = int(width_str)
  641. f['height'] = int(height_str)
  642. formats.append(f)
  643. last_info = {}
  644. self._sort_formats(formats)
  645. return formats
  646. def _live_title(self, name):
  647. """ Generate the title for a live video """
  648. now = datetime.datetime.now()
  649. now_str = now.strftime("%Y-%m-%d %H:%M")
  650. return name + ' ' + now_str
  651. def _int(self, v, name, fatal=False, **kwargs):
  652. res = int_or_none(v, **kwargs)
  653. if 'get_attr' in kwargs:
  654. print(getattr(v, kwargs['get_attr']))
  655. if res is None:
  656. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  657. if fatal:
  658. raise ExtractorError(msg)
  659. else:
  660. self._downloader.report_warning(msg)
  661. return res
  662. def _float(self, v, name, fatal=False, **kwargs):
  663. res = float_or_none(v, **kwargs)
  664. if res is None:
  665. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  666. if fatal:
  667. raise ExtractorError(msg)
  668. else:
  669. self._downloader.report_warning(msg)
  670. return res
  671. class SearchInfoExtractor(InfoExtractor):
  672. """
  673. Base class for paged search queries extractors.
  674. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
  675. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  676. """
  677. @classmethod
  678. def _make_valid_url(cls):
  679. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  680. @classmethod
  681. def suitable(cls, url):
  682. return re.match(cls._make_valid_url(), url) is not None
  683. def _real_extract(self, query):
  684. mobj = re.match(self._make_valid_url(), query)
  685. if mobj is None:
  686. raise ExtractorError('Invalid search query "%s"' % query)
  687. prefix = mobj.group('prefix')
  688. query = mobj.group('query')
  689. if prefix == '':
  690. return self._get_n_results(query, 1)
  691. elif prefix == 'all':
  692. return self._get_n_results(query, self._MAX_RESULTS)
  693. else:
  694. n = int(prefix)
  695. if n <= 0:
  696. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  697. elif n > self._MAX_RESULTS:
  698. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  699. n = self._MAX_RESULTS
  700. return self._get_n_results(query, n)
  701. def _get_n_results(self, query, n):
  702. """Get a specified number of results for a query"""
  703. raise NotImplementedError("This method must be implemented by subclasses")
  704. @property
  705. def SEARCH_KEY(self):
  706. return self._SEARCH_KEY