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.

808 lines
32 KiB

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