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.

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