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.

814 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):
  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. # return the first matching group
  380. return next(g for g in mobj.groups() if g is not None)
  381. elif default is not _NO_DEFAULT:
  382. return default
  383. elif fatal:
  384. raise RegexNotFoundError('Unable to extract %s' % _name)
  385. else:
  386. self._downloader.report_warning('unable to extract %s; '
  387. 'please report this issue on http://yt-dl.org/bug' % _name)
  388. return None
  389. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  390. """
  391. Like _search_regex, but strips HTML tags and unescapes entities.
  392. """
  393. res = self._search_regex(pattern, string, name, default, fatal, flags)
  394. if res:
  395. return clean_html(res).strip()
  396. else:
  397. return res
  398. def _get_login_info(self):
  399. """
  400. Get the the login info as (username, password)
  401. It will look in the netrc file using the _NETRC_MACHINE value
  402. If there's no info available, return (None, None)
  403. """
  404. if self._downloader is None:
  405. return (None, None)
  406. username = None
  407. password = None
  408. downloader_params = self._downloader.params
  409. # Attempt to use provided username and password or .netrc data
  410. if downloader_params.get('username', None) is not None:
  411. username = downloader_params['username']
  412. password = downloader_params['password']
  413. elif downloader_params.get('usenetrc', False):
  414. try:
  415. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  416. if info is not None:
  417. username = info[0]
  418. password = info[2]
  419. else:
  420. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  421. except (IOError, netrc.NetrcParseError) as err:
  422. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  423. return (username, password)
  424. def _get_tfa_info(self):
  425. """
  426. Get the two-factor authentication info
  427. TODO - asking the user will be required for sms/phone verify
  428. currently just uses the command line option
  429. If there's no info available, return None
  430. """
  431. if self._downloader is None:
  432. return None
  433. downloader_params = self._downloader.params
  434. if downloader_params.get('twofactor', None) is not None:
  435. return downloader_params['twofactor']
  436. return None
  437. # Helper functions for extracting OpenGraph info
  438. @staticmethod
  439. def _og_regexes(prop):
  440. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  441. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  442. template = r'<meta[^>]+?%s[^>]+?%s'
  443. return [
  444. template % (property_re, content_re),
  445. template % (content_re, property_re),
  446. ]
  447. def _og_search_property(self, prop, html, name=None, **kargs):
  448. if name is None:
  449. name = 'OpenGraph %s' % prop
  450. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  451. if escaped is None:
  452. return None
  453. return unescapeHTML(escaped)
  454. def _og_search_thumbnail(self, html, **kargs):
  455. return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs)
  456. def _og_search_description(self, html, **kargs):
  457. return self._og_search_property('description', html, fatal=False, **kargs)
  458. def _og_search_title(self, html, **kargs):
  459. return self._og_search_property('title', html, **kargs)
  460. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  461. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  462. if secure:
  463. regexes = self._og_regexes('video:secure_url') + regexes
  464. return self._html_search_regex(regexes, html, name, **kargs)
  465. def _og_search_url(self, html, **kargs):
  466. return self._og_search_property('url', html, **kargs)
  467. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  468. if display_name is None:
  469. display_name = name
  470. return self._html_search_regex(
  471. r'''(?ix)<meta
  472. (?=[^>]+(?:itemprop|name|property)=["\']?%s["\']?)
  473. [^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
  474. html, display_name, fatal=fatal, **kwargs)
  475. def _dc_search_uploader(self, html):
  476. return self._html_search_meta('dc.creator', html, 'uploader')
  477. def _rta_search(self, html):
  478. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  479. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  480. r' content="RTA-5042-1996-1400-1577-RTA"',
  481. html):
  482. return 18
  483. return 0
  484. def _media_rating_search(self, html):
  485. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  486. rating = self._html_search_meta('rating', html)
  487. if not rating:
  488. return None
  489. RATING_TABLE = {
  490. 'safe for kids': 0,
  491. 'general': 8,
  492. '14 years': 14,
  493. 'mature': 17,
  494. 'restricted': 19,
  495. }
  496. return RATING_TABLE.get(rating.lower(), None)
  497. def _twitter_search_player(self, html):
  498. return self._html_search_meta('twitter:player', html,
  499. 'twitter card player')
  500. def _sort_formats(self, formats):
  501. if not formats:
  502. raise ExtractorError('No video formats found')
  503. def _formats_key(f):
  504. # TODO remove the following workaround
  505. from ..utils import determine_ext
  506. if not f.get('ext') and 'url' in f:
  507. f['ext'] = determine_ext(f['url'])
  508. preference = f.get('preference')
  509. if preference is None:
  510. proto = f.get('protocol')
  511. if proto is None:
  512. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  513. preference = 0 if proto in ['http', 'https'] else -0.1
  514. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  515. preference -= 0.5
  516. if f.get('vcodec') == 'none': # audio only
  517. if self._downloader.params.get('prefer_free_formats'):
  518. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  519. else:
  520. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  521. ext_preference = 0
  522. try:
  523. audio_ext_preference = ORDER.index(f['ext'])
  524. except ValueError:
  525. audio_ext_preference = -1
  526. else:
  527. if self._downloader.params.get('prefer_free_formats'):
  528. ORDER = ['flv', 'mp4', 'webm']
  529. else:
  530. ORDER = ['webm', 'flv', 'mp4']
  531. try:
  532. ext_preference = ORDER.index(f['ext'])
  533. except ValueError:
  534. ext_preference = -1
  535. audio_ext_preference = 0
  536. return (
  537. preference,
  538. f.get('quality') if f.get('quality') is not None else -1,
  539. f.get('height') if f.get('height') is not None else -1,
  540. f.get('width') if f.get('width') is not None else -1,
  541. ext_preference,
  542. f.get('tbr') if f.get('tbr') is not None else -1,
  543. f.get('vbr') if f.get('vbr') is not None else -1,
  544. f.get('abr') if f.get('abr') is not None else -1,
  545. audio_ext_preference,
  546. f.get('fps') if f.get('fps') is not None else -1,
  547. f.get('filesize') if f.get('filesize') is not None else -1,
  548. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  549. f.get('source_preference') if f.get('source_preference') is not None else -1,
  550. f.get('format_id'),
  551. )
  552. formats.sort(key=_formats_key)
  553. def http_scheme(self):
  554. """ Either "http:" or "https:", depending on the user's preferences """
  555. return (
  556. 'http:'
  557. if self._downloader.params.get('prefer_insecure', False)
  558. else 'https:')
  559. def _proto_relative_url(self, url, scheme=None):
  560. if url is None:
  561. return url
  562. if url.startswith('//'):
  563. if scheme is None:
  564. scheme = self.http_scheme()
  565. return scheme + url
  566. else:
  567. return url
  568. def _sleep(self, timeout, video_id, msg_template=None):
  569. if msg_template is None:
  570. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  571. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  572. self.to_screen(msg)
  573. time.sleep(timeout)
  574. def _extract_f4m_formats(self, manifest_url, video_id):
  575. manifest = self._download_xml(
  576. manifest_url, video_id, 'Downloading f4m manifest',
  577. 'Unable to download f4m manifest')
  578. formats = []
  579. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  580. for i, media_el in enumerate(media_nodes):
  581. tbr = int_or_none(media_el.attrib.get('bitrate'))
  582. format_id = 'f4m-%d' % (i if tbr is None else tbr)
  583. formats.append({
  584. 'format_id': format_id,
  585. 'url': manifest_url,
  586. 'ext': 'flv',
  587. 'tbr': tbr,
  588. 'width': int_or_none(media_el.attrib.get('width')),
  589. 'height': int_or_none(media_el.attrib.get('height')),
  590. })
  591. self._sort_formats(formats)
  592. return formats
  593. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  594. entry_protocol='m3u8', preference=None):
  595. formats = [{
  596. 'format_id': 'm3u8-meta',
  597. 'url': m3u8_url,
  598. 'ext': ext,
  599. 'protocol': 'm3u8',
  600. 'preference': -1,
  601. 'resolution': 'multiple',
  602. 'format_note': 'Quality selection URL',
  603. }]
  604. format_url = lambda u: (
  605. u
  606. if re.match(r'^https?://', u)
  607. else compat_urlparse.urljoin(m3u8_url, u))
  608. m3u8_doc = self._download_webpage(
  609. m3u8_url, video_id,
  610. note='Downloading m3u8 information',
  611. errnote='Failed to download m3u8 information')
  612. last_info = None
  613. kv_rex = re.compile(
  614. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  615. for line in m3u8_doc.splitlines():
  616. if line.startswith('#EXT-X-STREAM-INF:'):
  617. last_info = {}
  618. for m in kv_rex.finditer(line):
  619. v = m.group('val')
  620. if v.startswith('"'):
  621. v = v[1:-1]
  622. last_info[m.group('key')] = v
  623. elif line.startswith('#') or not line.strip():
  624. continue
  625. else:
  626. if last_info is None:
  627. formats.append({'url': format_url(line)})
  628. continue
  629. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  630. f = {
  631. 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)),
  632. 'url': format_url(line.strip()),
  633. 'tbr': tbr,
  634. 'ext': ext,
  635. 'protocol': entry_protocol,
  636. 'preference': preference,
  637. }
  638. codecs = last_info.get('CODECS')
  639. if codecs:
  640. # TODO: looks like video codec is not always necessarily goes first
  641. va_codecs = codecs.split(',')
  642. if va_codecs[0]:
  643. f['vcodec'] = va_codecs[0].partition('.')[0]
  644. if len(va_codecs) > 1 and va_codecs[1]:
  645. f['acodec'] = va_codecs[1].partition('.')[0]
  646. resolution = last_info.get('RESOLUTION')
  647. if resolution:
  648. width_str, height_str = resolution.split('x')
  649. f['width'] = int(width_str)
  650. f['height'] = int(height_str)
  651. formats.append(f)
  652. last_info = {}
  653. self._sort_formats(formats)
  654. return formats
  655. def _live_title(self, name):
  656. """ Generate the title for a live video """
  657. now = datetime.datetime.now()
  658. now_str = now.strftime("%Y-%m-%d %H:%M")
  659. return name + ' ' + now_str
  660. def _int(self, v, name, fatal=False, **kwargs):
  661. res = int_or_none(v, **kwargs)
  662. if 'get_attr' in kwargs:
  663. print(getattr(v, kwargs['get_attr']))
  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. def _float(self, v, name, fatal=False, **kwargs):
  672. res = float_or_none(v, **kwargs)
  673. if res is None:
  674. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  675. if fatal:
  676. raise ExtractorError(msg)
  677. else:
  678. self._downloader.report_warning(msg)
  679. return res
  680. class SearchInfoExtractor(InfoExtractor):
  681. """
  682. Base class for paged search queries extractors.
  683. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
  684. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  685. """
  686. @classmethod
  687. def _make_valid_url(cls):
  688. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  689. @classmethod
  690. def suitable(cls, url):
  691. return re.match(cls._make_valid_url(), url) is not None
  692. def _real_extract(self, query):
  693. mobj = re.match(self._make_valid_url(), query)
  694. if mobj is None:
  695. raise ExtractorError('Invalid search query "%s"' % query)
  696. prefix = mobj.group('prefix')
  697. query = mobj.group('query')
  698. if prefix == '':
  699. return self._get_n_results(query, 1)
  700. elif prefix == 'all':
  701. return self._get_n_results(query, self._MAX_RESULTS)
  702. else:
  703. n = int(prefix)
  704. if n <= 0:
  705. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  706. elif n > self._MAX_RESULTS:
  707. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  708. n = self._MAX_RESULTS
  709. return self._get_n_results(query, n)
  710. def _get_n_results(self, query, n):
  711. """Get a specified number of results for a query"""
  712. raise NotImplementedError("This method must be implemented by subclasses")
  713. @property
  714. def SEARCH_KEY(self):
  715. return self._SEARCH_KEY