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.

976 lines
40 KiB

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