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.

952 lines
38 KiB

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