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.

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