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.

920 lines
37 KiB

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