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.

871 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, an iterable, or a PagedList
  145. object, each element of which is a valid dictionary by this specification.
  146. Additionally, playlists can have "title" and "id" attributes with the same
  147. semantics as videos (see above).
  148. _type "multi_video" indicates that there are multiple videos that
  149. form a single show, for examples multiple acts of an opera or TV episode.
  150. It must have an entries key like a playlist and contain all the keys
  151. required for a video at the same time.
  152. _type "url" indicates that the video must be extracted from another
  153. location, possibly by a different extractor. Its only required key is:
  154. "url" - the next URL to extract.
  155. 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, playlist_description=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. if playlist_description:
  392. video_info['description'] = playlist_description
  393. return video_info
  394. def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None):
  395. """
  396. Perform a regex search on the given string, using a single or a list of
  397. patterns returning the first matching group.
  398. In case of failure return a default value or raise a WARNING or a
  399. RegexNotFoundError, depending on fatal, specifying the field name.
  400. """
  401. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  402. mobj = re.search(pattern, string, flags)
  403. else:
  404. for p in pattern:
  405. mobj = re.search(p, string, flags)
  406. if mobj:
  407. break
  408. if os.name != 'nt' and sys.stderr.isatty():
  409. _name = '\033[0;34m%s\033[0m' % name
  410. else:
  411. _name = name
  412. if mobj:
  413. if group is None:
  414. # return the first matching group
  415. return next(g for g in mobj.groups() if g is not None)
  416. else:
  417. return mobj.group(group)
  418. elif default is not _NO_DEFAULT:
  419. return default
  420. elif fatal:
  421. raise RegexNotFoundError('Unable to extract %s' % _name)
  422. else:
  423. self._downloader.report_warning('unable to extract %s; '
  424. 'please report this issue on http://yt-dl.org/bug' % _name)
  425. return None
  426. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None):
  427. """
  428. Like _search_regex, but strips HTML tags and unescapes entities.
  429. """
  430. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  431. if res:
  432. return clean_html(res).strip()
  433. else:
  434. return res
  435. def _get_login_info(self):
  436. """
  437. Get the the login info as (username, password)
  438. It will look in the netrc file using the _NETRC_MACHINE value
  439. If there's no info available, return (None, None)
  440. """
  441. if self._downloader is None:
  442. return (None, None)
  443. username = None
  444. password = None
  445. downloader_params = self._downloader.params
  446. # Attempt to use provided username and password or .netrc data
  447. if downloader_params.get('username', None) is not None:
  448. username = downloader_params['username']
  449. password = downloader_params['password']
  450. elif downloader_params.get('usenetrc', False):
  451. try:
  452. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  453. if info is not None:
  454. username = info[0]
  455. password = info[2]
  456. else:
  457. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  458. except (IOError, netrc.NetrcParseError) as err:
  459. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  460. return (username, password)
  461. def _get_tfa_info(self):
  462. """
  463. Get the two-factor authentication info
  464. TODO - asking the user will be required for sms/phone verify
  465. currently just uses the command line option
  466. If there's no info available, return None
  467. """
  468. if self._downloader is None:
  469. return None
  470. downloader_params = self._downloader.params
  471. if downloader_params.get('twofactor', None) is not None:
  472. return downloader_params['twofactor']
  473. return None
  474. # Helper functions for extracting OpenGraph info
  475. @staticmethod
  476. def _og_regexes(prop):
  477. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  478. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  479. template = r'<meta[^>]+?%s[^>]+?%s'
  480. return [
  481. template % (property_re, content_re),
  482. template % (content_re, property_re),
  483. ]
  484. def _og_search_property(self, prop, html, name=None, **kargs):
  485. if name is None:
  486. name = 'OpenGraph %s' % prop
  487. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  488. if escaped is None:
  489. return None
  490. return unescapeHTML(escaped)
  491. def _og_search_thumbnail(self, html, **kargs):
  492. return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs)
  493. def _og_search_description(self, html, **kargs):
  494. return self._og_search_property('description', html, fatal=False, **kargs)
  495. def _og_search_title(self, html, **kargs):
  496. return self._og_search_property('title', html, **kargs)
  497. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  498. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  499. if secure:
  500. regexes = self._og_regexes('video:secure_url') + regexes
  501. return self._html_search_regex(regexes, html, name, **kargs)
  502. def _og_search_url(self, html, **kargs):
  503. return self._og_search_property('url', html, **kargs)
  504. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  505. if display_name is None:
  506. display_name = name
  507. return self._html_search_regex(
  508. r'''(?ix)<meta
  509. (?=[^>]+(?:itemprop|name|property)=(["\']?)%s\1)
  510. [^>]+content=(["\'])(?P<content>.*?)\1''' % re.escape(name),
  511. html, display_name, fatal=fatal, group='content', **kwargs)
  512. def _dc_search_uploader(self, html):
  513. return self._html_search_meta('dc.creator', html, 'uploader')
  514. def _rta_search(self, html):
  515. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  516. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  517. r' content="RTA-5042-1996-1400-1577-RTA"',
  518. html):
  519. return 18
  520. return 0
  521. def _media_rating_search(self, html):
  522. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  523. rating = self._html_search_meta('rating', html)
  524. if not rating:
  525. return None
  526. RATING_TABLE = {
  527. 'safe for kids': 0,
  528. 'general': 8,
  529. '14 years': 14,
  530. 'mature': 17,
  531. 'restricted': 19,
  532. }
  533. return RATING_TABLE.get(rating.lower(), None)
  534. def _twitter_search_player(self, html):
  535. return self._html_search_meta('twitter:player', html,
  536. 'twitter card player')
  537. def _sort_formats(self, formats):
  538. if not formats:
  539. raise ExtractorError('No video formats found')
  540. def _formats_key(f):
  541. # TODO remove the following workaround
  542. from ..utils import determine_ext
  543. if not f.get('ext') and 'url' in f:
  544. f['ext'] = determine_ext(f['url'])
  545. preference = f.get('preference')
  546. if preference is None:
  547. proto = f.get('protocol')
  548. if proto is None:
  549. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  550. preference = 0 if proto in ['http', 'https'] else -0.1
  551. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  552. preference -= 0.5
  553. if f.get('vcodec') == 'none': # audio only
  554. if self._downloader.params.get('prefer_free_formats'):
  555. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  556. else:
  557. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  558. ext_preference = 0
  559. try:
  560. audio_ext_preference = ORDER.index(f['ext'])
  561. except ValueError:
  562. audio_ext_preference = -1
  563. else:
  564. if self._downloader.params.get('prefer_free_formats'):
  565. ORDER = ['flv', 'mp4', 'webm']
  566. else:
  567. ORDER = ['webm', 'flv', 'mp4']
  568. try:
  569. ext_preference = ORDER.index(f['ext'])
  570. except ValueError:
  571. ext_preference = -1
  572. audio_ext_preference = 0
  573. return (
  574. preference,
  575. f.get('language_preference') if f.get('language_preference') is not None else -1,
  576. f.get('quality') if f.get('quality') is not None else -1,
  577. f.get('height') if f.get('height') is not None else -1,
  578. f.get('width') if f.get('width') is not None else -1,
  579. ext_preference,
  580. f.get('tbr') if f.get('tbr') is not None else -1,
  581. f.get('vbr') if f.get('vbr') is not None else -1,
  582. f.get('abr') if f.get('abr') is not None else -1,
  583. audio_ext_preference,
  584. f.get('fps') if f.get('fps') is not None else -1,
  585. f.get('filesize') if f.get('filesize') is not None else -1,
  586. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  587. f.get('source_preference') if f.get('source_preference') is not None else -1,
  588. f.get('format_id'),
  589. )
  590. formats.sort(key=_formats_key)
  591. def http_scheme(self):
  592. """ Either "http:" or "https:", depending on the user's preferences """
  593. return (
  594. 'http:'
  595. if self._downloader.params.get('prefer_insecure', False)
  596. else 'https:')
  597. def _proto_relative_url(self, url, scheme=None):
  598. if url is None:
  599. return url
  600. if url.startswith('//'):
  601. if scheme is None:
  602. scheme = self.http_scheme()
  603. return scheme + url
  604. else:
  605. return url
  606. def _sleep(self, timeout, video_id, msg_template=None):
  607. if msg_template is None:
  608. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  609. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  610. self.to_screen(msg)
  611. time.sleep(timeout)
  612. def _extract_f4m_formats(self, manifest_url, video_id):
  613. manifest = self._download_xml(
  614. manifest_url, video_id, 'Downloading f4m manifest',
  615. 'Unable to download f4m manifest')
  616. formats = []
  617. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  618. for i, media_el in enumerate(media_nodes):
  619. tbr = int_or_none(media_el.attrib.get('bitrate'))
  620. format_id = 'f4m-%d' % (i if tbr is None else tbr)
  621. formats.append({
  622. 'format_id': format_id,
  623. 'url': manifest_url,
  624. 'ext': 'flv',
  625. 'tbr': tbr,
  626. 'width': int_or_none(media_el.attrib.get('width')),
  627. 'height': int_or_none(media_el.attrib.get('height')),
  628. })
  629. self._sort_formats(formats)
  630. return formats
  631. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  632. entry_protocol='m3u8', preference=None):
  633. formats = [{
  634. 'format_id': 'm3u8-meta',
  635. 'url': m3u8_url,
  636. 'ext': ext,
  637. 'protocol': 'm3u8',
  638. 'preference': -1,
  639. 'resolution': 'multiple',
  640. 'format_note': 'Quality selection URL',
  641. }]
  642. format_url = lambda u: (
  643. u
  644. if re.match(r'^https?://', u)
  645. else compat_urlparse.urljoin(m3u8_url, u))
  646. m3u8_doc = self._download_webpage(
  647. m3u8_url, video_id,
  648. note='Downloading m3u8 information',
  649. errnote='Failed to download m3u8 information')
  650. last_info = None
  651. kv_rex = re.compile(
  652. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  653. for line in m3u8_doc.splitlines():
  654. if line.startswith('#EXT-X-STREAM-INF:'):
  655. last_info = {}
  656. for m in kv_rex.finditer(line):
  657. v = m.group('val')
  658. if v.startswith('"'):
  659. v = v[1:-1]
  660. last_info[m.group('key')] = v
  661. elif line.startswith('#') or not line.strip():
  662. continue
  663. else:
  664. if last_info is None:
  665. formats.append({'url': format_url(line)})
  666. continue
  667. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  668. f = {
  669. 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)),
  670. 'url': format_url(line.strip()),
  671. 'tbr': tbr,
  672. 'ext': ext,
  673. 'protocol': entry_protocol,
  674. 'preference': preference,
  675. }
  676. codecs = last_info.get('CODECS')
  677. if codecs:
  678. # TODO: looks like video codec is not always necessarily goes first
  679. va_codecs = codecs.split(',')
  680. if va_codecs[0]:
  681. f['vcodec'] = va_codecs[0].partition('.')[0]
  682. if len(va_codecs) > 1 and va_codecs[1]:
  683. f['acodec'] = va_codecs[1].partition('.')[0]
  684. resolution = last_info.get('RESOLUTION')
  685. if resolution:
  686. width_str, height_str = resolution.split('x')
  687. f['width'] = int(width_str)
  688. f['height'] = int(height_str)
  689. formats.append(f)
  690. last_info = {}
  691. self._sort_formats(formats)
  692. return formats
  693. def _live_title(self, name):
  694. """ Generate the title for a live video """
  695. now = datetime.datetime.now()
  696. now_str = now.strftime("%Y-%m-%d %H:%M")
  697. return name + ' ' + now_str
  698. def _int(self, v, name, fatal=False, **kwargs):
  699. res = int_or_none(v, **kwargs)
  700. if 'get_attr' in kwargs:
  701. print(getattr(v, kwargs['get_attr']))
  702. if res is None:
  703. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  704. if fatal:
  705. raise ExtractorError(msg)
  706. else:
  707. self._downloader.report_warning(msg)
  708. return res
  709. def _float(self, v, name, fatal=False, **kwargs):
  710. res = float_or_none(v, **kwargs)
  711. if res is None:
  712. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  713. if fatal:
  714. raise ExtractorError(msg)
  715. else:
  716. self._downloader.report_warning(msg)
  717. return res
  718. def _set_cookie(self, domain, name, value, expire_time=None):
  719. cookie = compat_cookiejar.Cookie(
  720. 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