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.

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