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.

869 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. if transform_source:
  343. json_string = transform_source(json_string)
  344. try:
  345. return json.loads(json_string)
  346. except ValueError as ve:
  347. errmsg = '%s: Failed to parse JSON ' % video_id
  348. if fatal:
  349. raise ExtractorError(errmsg, cause=ve)
  350. else:
  351. self.report_warning(errmsg + str(ve))
  352. def report_warning(self, msg, video_id=None):
  353. idstr = '' if video_id is None else '%s: ' % video_id
  354. self._downloader.report_warning(
  355. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  356. def to_screen(self, msg):
  357. """Print msg to screen, prefixing it with '[ie_name]'"""
  358. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  359. def report_extraction(self, id_or_name):
  360. """Report information extraction."""
  361. self.to_screen('%s: Extracting information' % id_or_name)
  362. def report_download_webpage(self, video_id):
  363. """Report webpage download."""
  364. self.to_screen('%s: Downloading webpage' % video_id)
  365. def report_age_confirmation(self):
  366. """Report attempt to confirm age."""
  367. self.to_screen('Confirming age')
  368. def report_login(self):
  369. """Report attempt to log in."""
  370. self.to_screen('Logging in')
  371. # Methods for following #608
  372. @staticmethod
  373. def url_result(url, ie=None, video_id=None):
  374. """Returns a url that points to a page that should be processed"""
  375. # TODO: ie should be the class used for getting the info
  376. video_info = {'_type': 'url',
  377. 'url': url,
  378. 'ie_key': ie}
  379. if video_id is not None:
  380. video_info['id'] = video_id
  381. return video_info
  382. @staticmethod
  383. def playlist_result(entries, playlist_id=None, playlist_title=None):
  384. """Returns a playlist"""
  385. video_info = {'_type': 'playlist',
  386. 'entries': entries}
  387. if playlist_id:
  388. video_info['id'] = playlist_id
  389. if playlist_title:
  390. video_info['title'] = playlist_title
  391. return video_info
  392. def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None):
  393. """
  394. Perform a regex search on the given string, using a single or a list of
  395. patterns returning the first matching group.
  396. In case of failure return a default value or raise a WARNING or a
  397. RegexNotFoundError, depending on fatal, specifying the field name.
  398. """
  399. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  400. mobj = re.search(pattern, string, flags)
  401. else:
  402. for p in pattern:
  403. mobj = re.search(p, string, flags)
  404. if mobj:
  405. break
  406. if os.name != 'nt' and sys.stderr.isatty():
  407. _name = '\033[0;34m%s\033[0m' % name
  408. else:
  409. _name = name
  410. if mobj:
  411. if group is None:
  412. # return the first matching group
  413. return next(g for g in mobj.groups() if g is not None)
  414. else:
  415. return mobj.group(group)
  416. elif default is not _NO_DEFAULT:
  417. return default
  418. elif fatal:
  419. raise RegexNotFoundError('Unable to extract %s' % _name)
  420. else:
  421. self._downloader.report_warning('unable to extract %s; '
  422. 'please report this issue on http://yt-dl.org/bug' % _name)
  423. return None
  424. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None):
  425. """
  426. Like _search_regex, but strips HTML tags and unescapes entities.
  427. """
  428. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  429. if res:
  430. return clean_html(res).strip()
  431. else:
  432. return res
  433. def _get_login_info(self):
  434. """
  435. Get the the login info as (username, password)
  436. It will look in the netrc file using the _NETRC_MACHINE value
  437. If there's no info available, return (None, None)
  438. """
  439. if self._downloader is None:
  440. return (None, None)
  441. username = None
  442. password = None
  443. downloader_params = self._downloader.params
  444. # Attempt to use provided username and password or .netrc data
  445. if downloader_params.get('username', None) is not None:
  446. username = downloader_params['username']
  447. password = downloader_params['password']
  448. elif downloader_params.get('usenetrc', False):
  449. try:
  450. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  451. if info is not None:
  452. username = info[0]
  453. password = info[2]
  454. else:
  455. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  456. except (IOError, netrc.NetrcParseError) as err:
  457. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  458. return (username, password)
  459. def _get_tfa_info(self):
  460. """
  461. Get the two-factor authentication info
  462. TODO - asking the user will be required for sms/phone verify
  463. currently just uses the command line option
  464. If there's no info available, return None
  465. """
  466. if self._downloader is None:
  467. return None
  468. downloader_params = self._downloader.params
  469. if downloader_params.get('twofactor', None) is not None:
  470. return downloader_params['twofactor']
  471. return None
  472. # Helper functions for extracting OpenGraph info
  473. @staticmethod
  474. def _og_regexes(prop):
  475. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  476. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  477. template = r'<meta[^>]+?%s[^>]+?%s'
  478. return [
  479. template % (property_re, content_re),
  480. template % (content_re, property_re),
  481. ]
  482. def _og_search_property(self, prop, html, name=None, **kargs):
  483. if name is None:
  484. name = 'OpenGraph %s' % prop
  485. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  486. if escaped is None:
  487. return None
  488. return unescapeHTML(escaped)
  489. def _og_search_thumbnail(self, html, **kargs):
  490. return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs)
  491. def _og_search_description(self, html, **kargs):
  492. return self._og_search_property('description', html, fatal=False, **kargs)
  493. def _og_search_title(self, html, **kargs):
  494. return self._og_search_property('title', html, **kargs)
  495. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  496. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  497. if secure:
  498. regexes = self._og_regexes('video:secure_url') + regexes
  499. return self._html_search_regex(regexes, html, name, **kargs)
  500. def _og_search_url(self, html, **kargs):
  501. return self._og_search_property('url', html, **kargs)
  502. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  503. if display_name is None:
  504. display_name = name
  505. return self._html_search_regex(
  506. r'''(?ix)<meta
  507. (?=[^>]+(?:itemprop|name|property)=(["\']?)%s\1)
  508. [^>]+content=(["\'])(?P<content>.*?)\1''' % re.escape(name),
  509. html, display_name, fatal=fatal, group='content', **kwargs)
  510. def _dc_search_uploader(self, html):
  511. return self._html_search_meta('dc.creator', html, 'uploader')
  512. def _rta_search(self, html):
  513. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  514. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  515. r' content="RTA-5042-1996-1400-1577-RTA"',
  516. html):
  517. return 18
  518. return 0
  519. def _media_rating_search(self, html):
  520. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  521. rating = self._html_search_meta('rating', html)
  522. if not rating:
  523. return None
  524. RATING_TABLE = {
  525. 'safe for kids': 0,
  526. 'general': 8,
  527. '14 years': 14,
  528. 'mature': 17,
  529. 'restricted': 19,
  530. }
  531. return RATING_TABLE.get(rating.lower(), None)
  532. def _twitter_search_player(self, html):
  533. return self._html_search_meta('twitter:player', html,
  534. 'twitter card player')
  535. def _sort_formats(self, formats):
  536. if not formats:
  537. raise ExtractorError('No video formats found')
  538. def _formats_key(f):
  539. # TODO remove the following workaround
  540. from ..utils import determine_ext
  541. if not f.get('ext') and 'url' in f:
  542. f['ext'] = determine_ext(f['url'])
  543. preference = f.get('preference')
  544. if preference is None:
  545. proto = f.get('protocol')
  546. if proto is None:
  547. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  548. preference = 0 if proto in ['http', 'https'] else -0.1
  549. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  550. preference -= 0.5
  551. if f.get('vcodec') == 'none': # audio only
  552. if self._downloader.params.get('prefer_free_formats'):
  553. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  554. else:
  555. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  556. ext_preference = 0
  557. try:
  558. audio_ext_preference = ORDER.index(f['ext'])
  559. except ValueError:
  560. audio_ext_preference = -1
  561. else:
  562. if self._downloader.params.get('prefer_free_formats'):
  563. ORDER = ['flv', 'mp4', 'webm']
  564. else:
  565. ORDER = ['webm', 'flv', 'mp4']
  566. try:
  567. ext_preference = ORDER.index(f['ext'])
  568. except ValueError:
  569. ext_preference = -1
  570. audio_ext_preference = 0
  571. return (
  572. preference,
  573. f.get('language_preference') if f.get('language_preference') is not None else -1,
  574. f.get('quality') if f.get('quality') is not None else -1,
  575. f.get('height') if f.get('height') is not None else -1,
  576. f.get('width') if f.get('width') is not None else -1,
  577. ext_preference,
  578. f.get('tbr') if f.get('tbr') is not None else -1,
  579. f.get('vbr') if f.get('vbr') is not None else -1,
  580. f.get('abr') if f.get('abr') is not None else -1,
  581. audio_ext_preference,
  582. f.get('fps') if f.get('fps') is not None else -1,
  583. f.get('filesize') if f.get('filesize') is not None else -1,
  584. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  585. f.get('source_preference') if f.get('source_preference') is not None else -1,
  586. f.get('format_id'),
  587. )
  588. formats.sort(key=_formats_key)
  589. def http_scheme(self):
  590. """ Either "http:" or "https:", depending on the user's preferences """
  591. return (
  592. 'http:'
  593. if self._downloader.params.get('prefer_insecure', False)
  594. else 'https:')
  595. def _proto_relative_url(self, url, scheme=None):
  596. if url is None:
  597. return url
  598. if url.startswith('//'):
  599. if scheme is None:
  600. scheme = self.http_scheme()
  601. return scheme + url
  602. else:
  603. return url
  604. def _sleep(self, timeout, video_id, msg_template=None):
  605. if msg_template is None:
  606. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  607. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  608. self.to_screen(msg)
  609. time.sleep(timeout)
  610. def _extract_f4m_formats(self, manifest_url, video_id):
  611. manifest = self._download_xml(
  612. manifest_url, video_id, 'Downloading f4m manifest',
  613. 'Unable to download f4m manifest')
  614. formats = []
  615. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  616. for i, media_el in enumerate(media_nodes):
  617. tbr = int_or_none(media_el.attrib.get('bitrate'))
  618. format_id = 'f4m-%d' % (i if tbr is None else tbr)
  619. formats.append({
  620. 'format_id': format_id,
  621. 'url': manifest_url,
  622. 'ext': 'flv',
  623. 'tbr': tbr,
  624. 'width': int_or_none(media_el.attrib.get('width')),
  625. 'height': int_or_none(media_el.attrib.get('height')),
  626. })
  627. self._sort_formats(formats)
  628. return formats
  629. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  630. entry_protocol='m3u8', preference=None):
  631. formats = [{
  632. 'format_id': 'm3u8-meta',
  633. 'url': m3u8_url,
  634. 'ext': ext,
  635. 'protocol': 'm3u8',
  636. 'preference': -1,
  637. 'resolution': 'multiple',
  638. 'format_note': 'Quality selection URL',
  639. }]
  640. format_url = lambda u: (
  641. u
  642. if re.match(r'^https?://', u)
  643. else compat_urlparse.urljoin(m3u8_url, u))
  644. m3u8_doc = self._download_webpage(
  645. m3u8_url, video_id,
  646. note='Downloading m3u8 information',
  647. errnote='Failed to download m3u8 information')
  648. last_info = None
  649. kv_rex = re.compile(
  650. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  651. for line in m3u8_doc.splitlines():
  652. if line.startswith('#EXT-X-STREAM-INF:'):
  653. last_info = {}
  654. for m in kv_rex.finditer(line):
  655. v = m.group('val')
  656. if v.startswith('"'):
  657. v = v[1:-1]
  658. last_info[m.group('key')] = v
  659. elif line.startswith('#') or not line.strip():
  660. continue
  661. else:
  662. if last_info is None:
  663. formats.append({'url': format_url(line)})
  664. continue
  665. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  666. f = {
  667. 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)),
  668. 'url': format_url(line.strip()),
  669. 'tbr': tbr,
  670. 'ext': ext,
  671. 'protocol': entry_protocol,
  672. 'preference': preference,
  673. }
  674. codecs = last_info.get('CODECS')
  675. if codecs:
  676. # TODO: looks like video codec is not always necessarily goes first
  677. va_codecs = codecs.split(',')
  678. if va_codecs[0]:
  679. f['vcodec'] = va_codecs[0].partition('.')[0]
  680. if len(va_codecs) > 1 and va_codecs[1]:
  681. f['acodec'] = va_codecs[1].partition('.')[0]
  682. resolution = last_info.get('RESOLUTION')
  683. if resolution:
  684. width_str, height_str = resolution.split('x')
  685. f['width'] = int(width_str)
  686. f['height'] = int(height_str)
  687. formats.append(f)
  688. last_info = {}
  689. self._sort_formats(formats)
  690. return formats
  691. def _live_title(self, name):
  692. """ Generate the title for a live video """
  693. now = datetime.datetime.now()
  694. now_str = now.strftime("%Y-%m-%d %H:%M")
  695. return name + ' ' + now_str
  696. def _int(self, v, name, fatal=False, **kwargs):
  697. res = int_or_none(v, **kwargs)
  698. if 'get_attr' in kwargs:
  699. print(getattr(v, kwargs['get_attr']))
  700. if res is None:
  701. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  702. if fatal:
  703. raise ExtractorError(msg)
  704. else:
  705. self._downloader.report_warning(msg)
  706. return res
  707. def _float(self, v, name, fatal=False, **kwargs):
  708. res = float_or_none(v, **kwargs)
  709. if res is None:
  710. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  711. if fatal:
  712. raise ExtractorError(msg)
  713. else:
  714. self._downloader.report_warning(msg)
  715. return res
  716. def _set_cookie(self, domain, name, value, expire_time=None):
  717. cookie = compat_cookiejar.Cookie(
  718. 0, name, value, None, None, domain, None,
  719. None, '/', True, False, expire_time, '', None, None, None)
  720. self._downloader.cookiejar.set_cookie(cookie)
  721. class SearchInfoExtractor(InfoExtractor):
  722. """
  723. Base class for paged search queries extractors.
  724. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
  725. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  726. """
  727. @classmethod
  728. def _make_valid_url(cls):
  729. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  730. @classmethod
  731. def suitable(cls, url):
  732. return re.match(cls._make_valid_url(), url) is not None
  733. def _real_extract(self, query):
  734. mobj = re.match(self._make_valid_url(), query)
  735. if mobj is None:
  736. raise ExtractorError('Invalid search query "%s"' % query)
  737. prefix = mobj.group('prefix')
  738. query = mobj.group('query')
  739. if prefix == '':
  740. return self._get_n_results(query, 1)
  741. elif prefix == 'all':
  742. return self._get_n_results(query, self._MAX_RESULTS)
  743. else:
  744. n = int(prefix)
  745. if n <= 0:
  746. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  747. elif n > self._MAX_RESULTS:
  748. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  749. n = self._MAX_RESULTS
  750. return self._get_n_results(query, n)
  751. def _get_n_results(self, query, n):
  752. """Get a specified number of results for a query"""
  753. raise NotImplementedError("This method must be implemented by subclasses")
  754. @property
  755. def SEARCH_KEY(self):
  756. return self._SEARCH_KEY