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.

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