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.

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