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.

860 lines
35 KiB

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