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.

872 lines
35 KiB

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