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.

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