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.

1556 lines
66 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 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. from ..compat import (
  13. compat_cookiejar,
  14. compat_cookies,
  15. compat_getpass,
  16. compat_http_client,
  17. compat_urllib_error,
  18. compat_urllib_parse,
  19. compat_urlparse,
  20. compat_str,
  21. compat_etree_fromstring,
  22. )
  23. from ..utils import (
  24. NO_DEFAULT,
  25. age_restricted,
  26. bug_reports_message,
  27. clean_html,
  28. compiled_regex_type,
  29. determine_ext,
  30. error_to_compat_str,
  31. ExtractorError,
  32. fix_xml_ampersands,
  33. float_or_none,
  34. int_or_none,
  35. parse_iso8601,
  36. RegexNotFoundError,
  37. sanitize_filename,
  38. sanitized_Request,
  39. unescapeHTML,
  40. unified_strdate,
  41. url_basename,
  42. xpath_text,
  43. xpath_with_ns,
  44. determine_protocol,
  45. )
  46. class InfoExtractor(object):
  47. """Information Extractor class.
  48. Information extractors are the classes that, given a URL, extract
  49. information about the video (or videos) the URL refers to. This
  50. information includes the real video URL, the video title, author and
  51. others. The information is stored in a dictionary which is then
  52. passed to the YoutubeDL. The YoutubeDL processes this
  53. information possibly downloading the video to the file system, among
  54. other possible outcomes.
  55. The type field determines the type of the result.
  56. By far the most common value (and the default if _type is missing) is
  57. "video", which indicates a single video.
  58. For a video, the dictionaries must include the following fields:
  59. id: Video identifier.
  60. title: Video title, unescaped.
  61. Additionally, it must contain either a formats entry or a url one:
  62. formats: A list of dictionaries for each format available, ordered
  63. from worst to best quality.
  64. Potential fields:
  65. * url Mandatory. The URL of the video file
  66. * ext Will be calculated from URL if missing
  67. * format A human-readable description of the format
  68. ("mp4 container with h264/opus").
  69. Calculated from the format_id, width, height.
  70. and format_note fields if missing.
  71. * format_id A short description of the format
  72. ("mp4_h264_opus" or "19").
  73. Technically optional, but strongly recommended.
  74. * format_note Additional info about the format
  75. ("3D" or "DASH video")
  76. * width Width of the video, if known
  77. * height Height of the video, if known
  78. * resolution Textual description of width and height
  79. * tbr Average bitrate of audio and video in KBit/s
  80. * abr Average audio bitrate in KBit/s
  81. * acodec Name of the audio codec in use
  82. * asr Audio sampling rate in Hertz
  83. * vbr Average video bitrate in KBit/s
  84. * fps Frame rate
  85. * vcodec Name of the video codec in use
  86. * container Name of the container format
  87. * filesize The number of bytes, if known in advance
  88. * filesize_approx An estimate for the number of bytes
  89. * player_url SWF Player URL (used for rtmpdump).
  90. * protocol The protocol that will be used for the actual
  91. download, lower-case.
  92. "http", "https", "rtsp", "rtmp", "rtmpe",
  93. "m3u8", or "m3u8_native".
  94. * preference Order number of this format. If this field is
  95. present and not None, the formats get sorted
  96. by this field, regardless of all other values.
  97. -1 for default (order by other properties),
  98. -2 or smaller for less than default.
  99. < -1000 to hide the format (if there is
  100. another one which is strictly better)
  101. * language Language code, e.g. "de" or "en-US".
  102. * language_preference Is this in the language mentioned in
  103. the URL?
  104. 10 if it's what the URL is about,
  105. -1 for default (don't know),
  106. -10 otherwise, other values reserved for now.
  107. * quality Order number of the video quality of this
  108. format, irrespective of the file format.
  109. -1 for default (order by other properties),
  110. -2 or smaller for less than default.
  111. * source_preference Order number for this video source
  112. (quality takes higher priority)
  113. -1 for default (order by other properties),
  114. -2 or smaller for less than default.
  115. * http_headers A dictionary of additional HTTP headers
  116. to add to the request.
  117. * stretched_ratio If given and not 1, indicates that the
  118. video's pixels are not square.
  119. width : height ratio as float.
  120. * no_resume The server does not support resuming the
  121. (HTTP or RTMP) download. Boolean.
  122. url: Final video URL.
  123. ext: Video filename extension.
  124. format: The video format, defaults to ext (used for --get-format)
  125. player_url: SWF Player URL (used for rtmpdump).
  126. The following fields are optional:
  127. alt_title: A secondary title of the video.
  128. display_id An alternative identifier for the video, not necessarily
  129. unique, but available before title. Typically, id is
  130. something like "4234987", title "Dancing naked mole rats",
  131. and display_id "dancing-naked-mole-rats"
  132. thumbnails: A list of dictionaries, with the following entries:
  133. * "id" (optional, string) - Thumbnail format ID
  134. * "url"
  135. * "preference" (optional, int) - quality of the image
  136. * "width" (optional, int)
  137. * "height" (optional, int)
  138. * "resolution" (optional, string "{width}x{height"},
  139. deprecated)
  140. thumbnail: Full URL to a video thumbnail image.
  141. description: Full video description.
  142. uploader: Full name of the video uploader.
  143. creator: The main artist who created the video.
  144. release_date: The date (YYYYMMDD) when the video was released.
  145. timestamp: UNIX timestamp of the moment the video became available.
  146. upload_date: Video upload date (YYYYMMDD).
  147. If not explicitly set, calculated from timestamp.
  148. uploader_id: Nickname or id of the video uploader.
  149. location: Physical location where the video was filmed.
  150. subtitles: The available subtitles as a dictionary in the format
  151. {language: subformats}. "subformats" is a list sorted from
  152. lower to higher preference, each element is a dictionary
  153. with the "ext" entry and one of:
  154. * "data": The subtitles file contents
  155. * "url": A URL pointing to the subtitles file
  156. "ext" will be calculated from URL if missing
  157. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  158. automatically generated captions
  159. duration: Length of the video in seconds, as an integer or float.
  160. view_count: How many users have watched the video on the platform.
  161. like_count: Number of positive ratings of the video
  162. dislike_count: Number of negative ratings of the video
  163. repost_count: Number of reposts of the video
  164. average_rating: Average rating give by users, the scale used depends on the webpage
  165. comment_count: Number of comments on the video
  166. comments: A list of comments, each with one or more of the following
  167. properties (all but one of text or html optional):
  168. * "author" - human-readable name of the comment author
  169. * "author_id" - user ID of the comment author
  170. * "id" - Comment ID
  171. * "html" - Comment as HTML
  172. * "text" - Plain text of the comment
  173. * "timestamp" - UNIX timestamp of comment
  174. * "parent" - ID of the comment this one is replying to.
  175. Set to "root" to indicate that this is a
  176. comment to the original video.
  177. age_limit: Age restriction for the video, as an integer (years)
  178. webpage_url: The URL to the video webpage, if given to youtube-dl it
  179. should allow to get the same result again. (It will be set
  180. by YoutubeDL if it's missing)
  181. categories: A list of categories that the video falls in, for example
  182. ["Sports", "Berlin"]
  183. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  184. is_live: True, False, or None (=unknown). Whether this video is a
  185. live stream that goes on instead of a fixed-length video.
  186. start_time: Time in seconds where the reproduction should start, as
  187. specified in the URL.
  188. end_time: Time in seconds where the reproduction should end, as
  189. specified in the URL.
  190. The following fields should only be used when the video belongs to some logical
  191. chapter or section:
  192. chapter: Name or title of the chapter the video belongs to.
  193. chapter_number: Number of the chapter the video belongs to, as an integer.
  194. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  195. The following fields should only be used when the video is an episode of some
  196. series or programme:
  197. series: Title of the series or programme the video episode belongs to.
  198. season: Title of the season the video episode belongs to.
  199. season_number: Number of the season the video episode belongs to, as an integer.
  200. season_id: Id of the season the video episode belongs to, as a unicode string.
  201. episode: Title of the video episode. Unlike mandatory video title field,
  202. this field should denote the exact title of the video episode
  203. without any kind of decoration.
  204. episode_number: Number of the video episode within a season, as an integer.
  205. episode_id: Id of the video episode, as a unicode string.
  206. Unless mentioned otherwise, the fields should be Unicode strings.
  207. Unless mentioned otherwise, None is equivalent to absence of information.
  208. _type "playlist" indicates multiple videos.
  209. There must be a key "entries", which is a list, an iterable, or a PagedList
  210. object, each element of which is a valid dictionary by this specification.
  211. Additionally, playlists can have "title", "description" and "id" attributes
  212. with the same semantics as videos (see above).
  213. _type "multi_video" indicates that there are multiple videos that
  214. form a single show, for examples multiple acts of an opera or TV episode.
  215. It must have an entries key like a playlist and contain all the keys
  216. required for a video at the same time.
  217. _type "url" indicates that the video must be extracted from another
  218. location, possibly by a different extractor. Its only required key is:
  219. "url" - the next URL to extract.
  220. The key "ie_key" can be set to the class name (minus the trailing "IE",
  221. e.g. "Youtube") if the extractor class is known in advance.
  222. Additionally, the dictionary may have any properties of the resolved entity
  223. known in advance, for example "title" if the title of the referred video is
  224. known ahead of time.
  225. _type "url_transparent" entities have the same specification as "url", but
  226. indicate that the given additional information is more precise than the one
  227. associated with the resolved URL.
  228. This is useful when a site employs a video service that hosts the video and
  229. its technical metadata, but that video service does not embed a useful
  230. title, description etc.
  231. Subclasses of this one should re-define the _real_initialize() and
  232. _real_extract() methods and define a _VALID_URL regexp.
  233. Probably, they should also be added to the list of extractors.
  234. Finally, the _WORKING attribute should be set to False for broken IEs
  235. in order to warn the users and skip the tests.
  236. """
  237. _ready = False
  238. _downloader = None
  239. _WORKING = True
  240. def __init__(self, downloader=None):
  241. """Constructor. Receives an optional downloader."""
  242. self._ready = False
  243. self.set_downloader(downloader)
  244. @classmethod
  245. def suitable(cls, url):
  246. """Receives a URL and returns True if suitable for this IE."""
  247. # This does not use has/getattr intentionally - we want to know whether
  248. # we have cached the regexp for *this* class, whereas getattr would also
  249. # match the superclass
  250. if '_VALID_URL_RE' not in cls.__dict__:
  251. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  252. return cls._VALID_URL_RE.match(url) is not None
  253. @classmethod
  254. def _match_id(cls, url):
  255. if '_VALID_URL_RE' not in cls.__dict__:
  256. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  257. m = cls._VALID_URL_RE.match(url)
  258. assert m
  259. return m.group('id')
  260. @classmethod
  261. def working(cls):
  262. """Getter method for _WORKING."""
  263. return cls._WORKING
  264. def initialize(self):
  265. """Initializes an instance (authentication, etc)."""
  266. if not self._ready:
  267. self._real_initialize()
  268. self._ready = True
  269. def extract(self, url):
  270. """Extracts URL information and returns it in list of dicts."""
  271. try:
  272. self.initialize()
  273. return self._real_extract(url)
  274. except ExtractorError:
  275. raise
  276. except compat_http_client.IncompleteRead as e:
  277. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  278. except (KeyError, StopIteration) as e:
  279. raise ExtractorError('An extractor error has occurred.', cause=e)
  280. def set_downloader(self, downloader):
  281. """Sets the downloader for this IE."""
  282. self._downloader = downloader
  283. def _real_initialize(self):
  284. """Real initialization process. Redefine in subclasses."""
  285. pass
  286. def _real_extract(self, url):
  287. """Real extraction process. Redefine in subclasses."""
  288. pass
  289. @classmethod
  290. def ie_key(cls):
  291. """A string for getting the InfoExtractor with get_info_extractor"""
  292. return compat_str(cls.__name__[:-2])
  293. @property
  294. def IE_NAME(self):
  295. return compat_str(type(self).__name__[:-2])
  296. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  297. """ Returns the response handle """
  298. if note is None:
  299. self.report_download_webpage(video_id)
  300. elif note is not False:
  301. if video_id is None:
  302. self.to_screen('%s' % (note,))
  303. else:
  304. self.to_screen('%s: %s' % (video_id, note))
  305. try:
  306. return self._downloader.urlopen(url_or_request)
  307. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  308. if errnote is False:
  309. return False
  310. if errnote is None:
  311. errnote = 'Unable to download webpage'
  312. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  313. if fatal:
  314. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  315. else:
  316. self._downloader.report_warning(errmsg)
  317. return False
  318. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None):
  319. """ Returns a tuple (page content as string, URL handle) """
  320. # Strip hashes from the URL (#1038)
  321. if isinstance(url_or_request, (compat_str, str)):
  322. url_or_request = url_or_request.partition('#')[0]
  323. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
  324. if urlh is False:
  325. assert not fatal
  326. return False
  327. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  328. return (content, urlh)
  329. @staticmethod
  330. def _guess_encoding_from_content(content_type, webpage_bytes):
  331. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  332. if m:
  333. encoding = m.group(1)
  334. else:
  335. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  336. webpage_bytes[:1024])
  337. if m:
  338. encoding = m.group(1).decode('ascii')
  339. elif webpage_bytes.startswith(b'\xff\xfe'):
  340. encoding = 'utf-16'
  341. else:
  342. encoding = 'utf-8'
  343. return encoding
  344. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  345. content_type = urlh.headers.get('Content-Type', '')
  346. webpage_bytes = urlh.read()
  347. if prefix is not None:
  348. webpage_bytes = prefix + webpage_bytes
  349. if not encoding:
  350. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  351. if self._downloader.params.get('dump_intermediate_pages', False):
  352. try:
  353. url = url_or_request.get_full_url()
  354. except AttributeError:
  355. url = url_or_request
  356. self.to_screen('Dumping request to ' + url)
  357. dump = base64.b64encode(webpage_bytes).decode('ascii')
  358. self._downloader.to_screen(dump)
  359. if self._downloader.params.get('write_pages', False):
  360. try:
  361. url = url_or_request.get_full_url()
  362. except AttributeError:
  363. url = url_or_request
  364. basen = '%s_%s' % (video_id, url)
  365. if len(basen) > 240:
  366. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  367. basen = basen[:240 - len(h)] + h
  368. raw_filename = basen + '.dump'
  369. filename = sanitize_filename(raw_filename, restricted=True)
  370. self.to_screen('Saving request to ' + filename)
  371. # Working around MAX_PATH limitation on Windows (see
  372. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  373. if os.name == 'nt':
  374. absfilepath = os.path.abspath(filename)
  375. if len(absfilepath) > 259:
  376. filename = '\\\\?\\' + absfilepath
  377. with open(filename, 'wb') as outf:
  378. outf.write(webpage_bytes)
  379. try:
  380. content = webpage_bytes.decode(encoding, 'replace')
  381. except LookupError:
  382. content = webpage_bytes.decode('utf-8', 'replace')
  383. if ('<title>Access to this site is blocked</title>' in content and
  384. 'Websense' in content[:512]):
  385. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  386. blocked_iframe = self._html_search_regex(
  387. r'<iframe src="([^"]+)"', content,
  388. 'Websense information URL', default=None)
  389. if blocked_iframe:
  390. msg += ' Visit %s for more details' % blocked_iframe
  391. raise ExtractorError(msg, expected=True)
  392. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  393. msg = (
  394. 'Access to this webpage has been blocked by Indian censorship. '
  395. 'Use a VPN or proxy server (with --proxy) to route around it.')
  396. block_msg = self._html_search_regex(
  397. r'</h1><p>(.*?)</p>',
  398. content, 'block message', default=None)
  399. if block_msg:
  400. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  401. raise ExtractorError(msg, expected=True)
  402. return content
  403. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
  404. """ Returns the data of the page as a string """
  405. success = False
  406. try_count = 0
  407. while success is False:
  408. try:
  409. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  410. success = True
  411. except compat_http_client.IncompleteRead as e:
  412. try_count += 1
  413. if try_count >= tries:
  414. raise e
  415. self._sleep(timeout, video_id)
  416. if res is False:
  417. return res
  418. else:
  419. content, _ = res
  420. return content
  421. def _download_xml(self, url_or_request, video_id,
  422. note='Downloading XML', errnote='Unable to download XML',
  423. transform_source=None, fatal=True, encoding=None):
  424. """Return the xml as an xml.etree.ElementTree.Element"""
  425. xml_string = self._download_webpage(
  426. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding)
  427. if xml_string is False:
  428. return xml_string
  429. if transform_source:
  430. xml_string = transform_source(xml_string)
  431. return compat_etree_fromstring(xml_string.encode('utf-8'))
  432. def _download_json(self, url_or_request, video_id,
  433. note='Downloading JSON metadata',
  434. errnote='Unable to download JSON metadata',
  435. transform_source=None,
  436. fatal=True, encoding=None):
  437. json_string = self._download_webpage(
  438. url_or_request, video_id, note, errnote, fatal=fatal,
  439. encoding=encoding)
  440. if (not fatal) and json_string is False:
  441. return None
  442. return self._parse_json(
  443. json_string, video_id, transform_source=transform_source, fatal=fatal)
  444. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  445. if transform_source:
  446. json_string = transform_source(json_string)
  447. try:
  448. return json.loads(json_string)
  449. except ValueError as ve:
  450. errmsg = '%s: Failed to parse JSON ' % video_id
  451. if fatal:
  452. raise ExtractorError(errmsg, cause=ve)
  453. else:
  454. self.report_warning(errmsg + str(ve))
  455. def report_warning(self, msg, video_id=None):
  456. idstr = '' if video_id is None else '%s: ' % video_id
  457. self._downloader.report_warning(
  458. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  459. def to_screen(self, msg):
  460. """Print msg to screen, prefixing it with '[ie_name]'"""
  461. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  462. def report_extraction(self, id_or_name):
  463. """Report information extraction."""
  464. self.to_screen('%s: Extracting information' % id_or_name)
  465. def report_download_webpage(self, video_id):
  466. """Report webpage download."""
  467. self.to_screen('%s: Downloading webpage' % video_id)
  468. def report_age_confirmation(self):
  469. """Report attempt to confirm age."""
  470. self.to_screen('Confirming age')
  471. def report_login(self):
  472. """Report attempt to log in."""
  473. self.to_screen('Logging in')
  474. @staticmethod
  475. def raise_login_required(msg='This video is only available for registered users'):
  476. raise ExtractorError(
  477. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  478. expected=True)
  479. @staticmethod
  480. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction'):
  481. raise ExtractorError(
  482. '%s. You might want to use --proxy to workaround.' % msg,
  483. expected=True)
  484. # Methods for following #608
  485. @staticmethod
  486. def url_result(url, ie=None, video_id=None, video_title=None):
  487. """Returns a URL that points to a page that should be processed"""
  488. # TODO: ie should be the class used for getting the info
  489. video_info = {'_type': 'url',
  490. 'url': url,
  491. 'ie_key': ie}
  492. if video_id is not None:
  493. video_info['id'] = video_id
  494. if video_title is not None:
  495. video_info['title'] = video_title
  496. return video_info
  497. @staticmethod
  498. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  499. """Returns a playlist"""
  500. video_info = {'_type': 'playlist',
  501. 'entries': entries}
  502. if playlist_id:
  503. video_info['id'] = playlist_id
  504. if playlist_title:
  505. video_info['title'] = playlist_title
  506. if playlist_description:
  507. video_info['description'] = playlist_description
  508. return video_info
  509. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  510. """
  511. Perform a regex search on the given string, using a single or a list of
  512. patterns returning the first matching group.
  513. In case of failure return a default value or raise a WARNING or a
  514. RegexNotFoundError, depending on fatal, specifying the field name.
  515. """
  516. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  517. mobj = re.search(pattern, string, flags)
  518. else:
  519. for p in pattern:
  520. mobj = re.search(p, string, flags)
  521. if mobj:
  522. break
  523. if not self._downloader.params.get('no_color') and os.name != 'nt' and sys.stderr.isatty():
  524. _name = '\033[0;34m%s\033[0m' % name
  525. else:
  526. _name = name
  527. if mobj:
  528. if group is None:
  529. # return the first matching group
  530. return next(g for g in mobj.groups() if g is not None)
  531. else:
  532. return mobj.group(group)
  533. elif default is not NO_DEFAULT:
  534. return default
  535. elif fatal:
  536. raise RegexNotFoundError('Unable to extract %s' % _name)
  537. else:
  538. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  539. return None
  540. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  541. """
  542. Like _search_regex, but strips HTML tags and unescapes entities.
  543. """
  544. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  545. if res:
  546. return clean_html(res).strip()
  547. else:
  548. return res
  549. def _get_login_info(self):
  550. """
  551. Get the login info as (username, password)
  552. It will look in the netrc file using the _NETRC_MACHINE value
  553. If there's no info available, return (None, None)
  554. """
  555. if self._downloader is None:
  556. return (None, None)
  557. username = None
  558. password = None
  559. downloader_params = self._downloader.params
  560. # Attempt to use provided username and password or .netrc data
  561. if downloader_params.get('username', None) is not None:
  562. username = downloader_params['username']
  563. password = downloader_params['password']
  564. elif downloader_params.get('usenetrc', False):
  565. try:
  566. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  567. if info is not None:
  568. username = info[0]
  569. password = info[2]
  570. else:
  571. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  572. except (IOError, netrc.NetrcParseError) as err:
  573. self._downloader.report_warning('parsing .netrc: %s' % error_to_compat_str(err))
  574. return (username, password)
  575. def _get_tfa_info(self, note='two-factor verification code'):
  576. """
  577. Get the two-factor authentication info
  578. TODO - asking the user will be required for sms/phone verify
  579. currently just uses the command line option
  580. If there's no info available, return None
  581. """
  582. if self._downloader is None:
  583. return None
  584. downloader_params = self._downloader.params
  585. if downloader_params.get('twofactor', None) is not None:
  586. return downloader_params['twofactor']
  587. return compat_getpass('Type %s and press [Return]: ' % note)
  588. # Helper functions for extracting OpenGraph info
  589. @staticmethod
  590. def _og_regexes(prop):
  591. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  592. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  593. % {'prop': re.escape(prop)})
  594. template = r'<meta[^>]+?%s[^>]+?%s'
  595. return [
  596. template % (property_re, content_re),
  597. template % (content_re, property_re),
  598. ]
  599. @staticmethod
  600. def _meta_regex(prop):
  601. return r'''(?isx)<meta
  602. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  603. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  604. def _og_search_property(self, prop, html, name=None, **kargs):
  605. if name is None:
  606. name = 'OpenGraph %s' % prop
  607. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  608. if escaped is None:
  609. return None
  610. return unescapeHTML(escaped)
  611. def _og_search_thumbnail(self, html, **kargs):
  612. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  613. def _og_search_description(self, html, **kargs):
  614. return self._og_search_property('description', html, fatal=False, **kargs)
  615. def _og_search_title(self, html, **kargs):
  616. return self._og_search_property('title', html, **kargs)
  617. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  618. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  619. if secure:
  620. regexes = self._og_regexes('video:secure_url') + regexes
  621. return self._html_search_regex(regexes, html, name, **kargs)
  622. def _og_search_url(self, html, **kargs):
  623. return self._og_search_property('url', html, **kargs)
  624. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  625. if display_name is None:
  626. display_name = name
  627. return self._html_search_regex(
  628. self._meta_regex(name),
  629. html, display_name, fatal=fatal, group='content', **kwargs)
  630. def _dc_search_uploader(self, html):
  631. return self._html_search_meta('dc.creator', html, 'uploader')
  632. def _rta_search(self, html):
  633. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  634. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  635. r' content="RTA-5042-1996-1400-1577-RTA"',
  636. html):
  637. return 18
  638. return 0
  639. def _media_rating_search(self, html):
  640. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  641. rating = self._html_search_meta('rating', html)
  642. if not rating:
  643. return None
  644. RATING_TABLE = {
  645. 'safe for kids': 0,
  646. 'general': 8,
  647. '14 years': 14,
  648. 'mature': 17,
  649. 'restricted': 19,
  650. }
  651. return RATING_TABLE.get(rating.lower(), None)
  652. def _family_friendly_search(self, html):
  653. # See http://schema.org/VideoObject
  654. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  655. if not family_friendly:
  656. return None
  657. RATING_TABLE = {
  658. '1': 0,
  659. 'true': 0,
  660. '0': 18,
  661. 'false': 18,
  662. }
  663. return RATING_TABLE.get(family_friendly.lower(), None)
  664. def _twitter_search_player(self, html):
  665. return self._html_search_meta('twitter:player', html,
  666. 'twitter card player')
  667. def _search_json_ld(self, html, video_id, **kwargs):
  668. json_ld = self._search_regex(
  669. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  670. html, 'JSON-LD', group='json_ld', **kwargs)
  671. if not json_ld:
  672. return {}
  673. return self._json_ld(json_ld, video_id, fatal=kwargs.get('fatal', True))
  674. def _json_ld(self, json_ld, video_id, fatal=True):
  675. if isinstance(json_ld, compat_str):
  676. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  677. if not json_ld:
  678. return {}
  679. info = {}
  680. if json_ld.get('@context') == 'http://schema.org':
  681. item_type = json_ld.get('@type')
  682. if item_type == 'TVEpisode':
  683. info.update({
  684. 'episode': unescapeHTML(json_ld.get('name')),
  685. 'episode_number': int_or_none(json_ld.get('episodeNumber')),
  686. 'description': unescapeHTML(json_ld.get('description')),
  687. })
  688. part_of_season = json_ld.get('partOfSeason')
  689. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  690. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  691. part_of_series = json_ld.get('partOfSeries')
  692. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  693. info['series'] = unescapeHTML(part_of_series.get('name'))
  694. elif item_type == 'Article':
  695. info.update({
  696. 'timestamp': parse_iso8601(json_ld.get('datePublished')),
  697. 'title': unescapeHTML(json_ld.get('headline')),
  698. 'description': unescapeHTML(json_ld.get('articleBody')),
  699. })
  700. return dict((k, v) for k, v in info.items() if v is not None)
  701. @staticmethod
  702. def _hidden_inputs(html):
  703. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  704. hidden_inputs = {}
  705. for input in re.findall(r'(?i)<input([^>]+)>', html):
  706. if not re.search(r'type=(["\'])(?:hidden|submit)\1', input):
  707. continue
  708. name = re.search(r'name=(["\'])(?P<value>.+?)\1', input)
  709. if not name:
  710. continue
  711. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  712. if not value:
  713. continue
  714. hidden_inputs[name.group('value')] = value.group('value')
  715. return hidden_inputs
  716. def _form_hidden_inputs(self, form_id, html):
  717. form = self._search_regex(
  718. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  719. html, '%s form' % form_id, group='form')
  720. return self._hidden_inputs(form)
  721. def _sort_formats(self, formats, field_preference=None):
  722. if not formats:
  723. raise ExtractorError('No video formats found')
  724. for f in formats:
  725. # Automatically determine tbr when missing based on abr and vbr (improves
  726. # formats sorting in some cases)
  727. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  728. f['tbr'] = f['abr'] + f['vbr']
  729. def _formats_key(f):
  730. # TODO remove the following workaround
  731. from ..utils import determine_ext
  732. if not f.get('ext') and 'url' in f:
  733. f['ext'] = determine_ext(f['url'])
  734. if isinstance(field_preference, (list, tuple)):
  735. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  736. preference = f.get('preference')
  737. if preference is None:
  738. preference = 0
  739. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  740. preference -= 0.5
  741. proto_preference = 0 if determine_protocol(f) in ['http', 'https'] else -0.1
  742. if f.get('vcodec') == 'none': # audio only
  743. if self._downloader.params.get('prefer_free_formats'):
  744. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  745. else:
  746. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  747. ext_preference = 0
  748. try:
  749. audio_ext_preference = ORDER.index(f['ext'])
  750. except ValueError:
  751. audio_ext_preference = -1
  752. else:
  753. if self._downloader.params.get('prefer_free_formats'):
  754. ORDER = ['flv', 'mp4', 'webm']
  755. else:
  756. ORDER = ['webm', 'flv', 'mp4']
  757. try:
  758. ext_preference = ORDER.index(f['ext'])
  759. except ValueError:
  760. ext_preference = -1
  761. audio_ext_preference = 0
  762. return (
  763. preference,
  764. f.get('language_preference') if f.get('language_preference') is not None else -1,
  765. f.get('quality') if f.get('quality') is not None else -1,
  766. f.get('tbr') if f.get('tbr') is not None else -1,
  767. f.get('filesize') if f.get('filesize') is not None else -1,
  768. f.get('vbr') if f.get('vbr') is not None else -1,
  769. f.get('height') if f.get('height') is not None else -1,
  770. f.get('width') if f.get('width') is not None else -1,
  771. proto_preference,
  772. ext_preference,
  773. f.get('abr') if f.get('abr') is not None else -1,
  774. audio_ext_preference,
  775. f.get('fps') if f.get('fps') is not None else -1,
  776. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  777. f.get('source_preference') if f.get('source_preference') is not None else -1,
  778. f.get('format_id') if f.get('format_id') is not None else '',
  779. )
  780. formats.sort(key=_formats_key)
  781. def _check_formats(self, formats, video_id):
  782. if formats:
  783. formats[:] = filter(
  784. lambda f: self._is_valid_url(
  785. f['url'], video_id,
  786. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  787. formats)
  788. def _is_valid_url(self, url, video_id, item='video'):
  789. url = self._proto_relative_url(url, scheme='http:')
  790. # For now assume non HTTP(S) URLs always valid
  791. if not (url.startswith('http://') or url.startswith('https://')):
  792. return True
  793. try:
  794. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  795. return True
  796. except ExtractorError as e:
  797. if isinstance(e.cause, compat_urllib_error.URLError):
  798. self.to_screen(
  799. '%s: %s URL is invalid, skipping' % (video_id, item))
  800. return False
  801. raise
  802. def http_scheme(self):
  803. """ Either "http:" or "https:", depending on the user's preferences """
  804. return (
  805. 'http:'
  806. if self._downloader.params.get('prefer_insecure', False)
  807. else 'https:')
  808. def _proto_relative_url(self, url, scheme=None):
  809. if url is None:
  810. return url
  811. if url.startswith('//'):
  812. if scheme is None:
  813. scheme = self.http_scheme()
  814. return scheme + url
  815. else:
  816. return url
  817. def _sleep(self, timeout, video_id, msg_template=None):
  818. if msg_template is None:
  819. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  820. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  821. self.to_screen(msg)
  822. time.sleep(timeout)
  823. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  824. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  825. fatal=True):
  826. manifest = self._download_xml(
  827. manifest_url, video_id, 'Downloading f4m manifest',
  828. 'Unable to download f4m manifest',
  829. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  830. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  831. transform_source=transform_source,
  832. fatal=fatal)
  833. if manifest is False:
  834. return []
  835. formats = []
  836. manifest_version = '1.0'
  837. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  838. if not media_nodes:
  839. manifest_version = '2.0'
  840. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  841. base_url = xpath_text(
  842. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  843. 'base URL', default=None)
  844. if base_url:
  845. base_url = base_url.strip()
  846. for i, media_el in enumerate(media_nodes):
  847. if manifest_version == '2.0':
  848. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  849. if not media_url:
  850. continue
  851. manifest_url = (
  852. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  853. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  854. # If media_url is itself a f4m manifest do the recursive extraction
  855. # since bitrates in parent manifest (this one) and media_url manifest
  856. # may differ leading to inability to resolve the format by requested
  857. # bitrate in f4m downloader
  858. if determine_ext(manifest_url) == 'f4m':
  859. formats.extend(self._extract_f4m_formats(
  860. manifest_url, video_id, preference, f4m_id, fatal=fatal))
  861. continue
  862. tbr = int_or_none(media_el.attrib.get('bitrate'))
  863. formats.append({
  864. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  865. 'url': manifest_url,
  866. 'ext': 'flv',
  867. 'tbr': tbr,
  868. 'width': int_or_none(media_el.attrib.get('width')),
  869. 'height': int_or_none(media_el.attrib.get('height')),
  870. 'preference': preference,
  871. })
  872. self._sort_formats(formats)
  873. return formats
  874. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  875. entry_protocol='m3u8', preference=None,
  876. m3u8_id=None, note=None, errnote=None,
  877. fatal=True):
  878. formats = [{
  879. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  880. 'url': m3u8_url,
  881. 'ext': ext,
  882. 'protocol': 'm3u8',
  883. 'preference': preference - 1 if preference else -1,
  884. 'resolution': 'multiple',
  885. 'format_note': 'Quality selection URL',
  886. }]
  887. format_url = lambda u: (
  888. u
  889. if re.match(r'^https?://', u)
  890. else compat_urlparse.urljoin(m3u8_url, u))
  891. res = self._download_webpage_handle(
  892. m3u8_url, video_id,
  893. note=note or 'Downloading m3u8 information',
  894. errnote=errnote or 'Failed to download m3u8 information',
  895. fatal=fatal)
  896. if res is False:
  897. return []
  898. m3u8_doc, urlh = res
  899. m3u8_url = urlh.geturl()
  900. # A Media Playlist Tag MUST NOT appear in a Master Playlist
  901. # https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  902. # The EXT-X-TARGETDURATION tag is REQUIRED for every M3U8 Media Playlists
  903. # https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  904. if '#EXT-X-TARGETDURATION' in m3u8_doc:
  905. return [{
  906. 'url': m3u8_url,
  907. 'format_id': m3u8_id,
  908. 'ext': ext,
  909. 'protocol': entry_protocol,
  910. 'preference': preference,
  911. }]
  912. last_info = None
  913. last_media = None
  914. kv_rex = re.compile(
  915. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  916. for line in m3u8_doc.splitlines():
  917. if line.startswith('#EXT-X-STREAM-INF:'):
  918. last_info = {}
  919. for m in kv_rex.finditer(line):
  920. v = m.group('val')
  921. if v.startswith('"'):
  922. v = v[1:-1]
  923. last_info[m.group('key')] = v
  924. elif line.startswith('#EXT-X-MEDIA:'):
  925. last_media = {}
  926. for m in kv_rex.finditer(line):
  927. v = m.group('val')
  928. if v.startswith('"'):
  929. v = v[1:-1]
  930. last_media[m.group('key')] = v
  931. elif line.startswith('#') or not line.strip():
  932. continue
  933. else:
  934. if last_info is None:
  935. formats.append({'url': format_url(line)})
  936. continue
  937. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  938. format_id = []
  939. if m3u8_id:
  940. format_id.append(m3u8_id)
  941. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  942. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  943. f = {
  944. 'format_id': '-'.join(format_id),
  945. 'url': format_url(line.strip()),
  946. 'tbr': tbr,
  947. 'ext': ext,
  948. 'protocol': entry_protocol,
  949. 'preference': preference,
  950. }
  951. codecs = last_info.get('CODECS')
  952. if codecs:
  953. # TODO: looks like video codec is not always necessarily goes first
  954. va_codecs = codecs.split(',')
  955. if va_codecs[0]:
  956. f['vcodec'] = va_codecs[0]
  957. if len(va_codecs) > 1 and va_codecs[1]:
  958. f['acodec'] = va_codecs[1]
  959. resolution = last_info.get('RESOLUTION')
  960. if resolution:
  961. width_str, height_str = resolution.split('x')
  962. f['width'] = int(width_str)
  963. f['height'] = int(height_str)
  964. if last_media is not None:
  965. f['m3u8_media'] = last_media
  966. last_media = None
  967. formats.append(f)
  968. last_info = {}
  969. self._sort_formats(formats)
  970. return formats
  971. @staticmethod
  972. def _xpath_ns(path, namespace=None):
  973. if not namespace:
  974. return path
  975. out = []
  976. for c in path.split('/'):
  977. if not c or c == '.':
  978. out.append(c)
  979. else:
  980. out.append('{%s}%s' % (namespace, c))
  981. return '/'.join(out)
  982. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  983. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  984. if smil is False:
  985. assert not fatal
  986. return []
  987. namespace = self._parse_smil_namespace(smil)
  988. return self._parse_smil_formats(
  989. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  990. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  991. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  992. if smil is False:
  993. return {}
  994. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  995. def _download_smil(self, smil_url, video_id, fatal=True):
  996. return self._download_xml(
  997. smil_url, video_id, 'Downloading SMIL file',
  998. 'Unable to download SMIL file', fatal=fatal)
  999. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1000. namespace = self._parse_smil_namespace(smil)
  1001. formats = self._parse_smil_formats(
  1002. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1003. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1004. video_id = os.path.splitext(url_basename(smil_url))[0]
  1005. title = None
  1006. description = None
  1007. upload_date = None
  1008. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1009. name = meta.attrib.get('name')
  1010. content = meta.attrib.get('content')
  1011. if not name or not content:
  1012. continue
  1013. if not title and name == 'title':
  1014. title = content
  1015. elif not description and name in ('description', 'abstract'):
  1016. description = content
  1017. elif not upload_date and name == 'date':
  1018. upload_date = unified_strdate(content)
  1019. thumbnails = [{
  1020. 'id': image.get('type'),
  1021. 'url': image.get('src'),
  1022. 'width': int_or_none(image.get('width')),
  1023. 'height': int_or_none(image.get('height')),
  1024. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1025. return {
  1026. 'id': video_id,
  1027. 'title': title or video_id,
  1028. 'description': description,
  1029. 'upload_date': upload_date,
  1030. 'thumbnails': thumbnails,
  1031. 'formats': formats,
  1032. 'subtitles': subtitles,
  1033. }
  1034. def _parse_smil_namespace(self, smil):
  1035. return self._search_regex(
  1036. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1037. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1038. base = smil_url
  1039. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1040. b = meta.get('base') or meta.get('httpBase')
  1041. if b:
  1042. base = b
  1043. break
  1044. formats = []
  1045. rtmp_count = 0
  1046. http_count = 0
  1047. m3u8_count = 0
  1048. videos = smil.findall(self._xpath_ns('.//video', namespace))
  1049. for video in videos:
  1050. src = video.get('src')
  1051. if not src:
  1052. continue
  1053. bitrate = float_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  1054. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  1055. width = int_or_none(video.get('width'))
  1056. height = int_or_none(video.get('height'))
  1057. proto = video.get('proto')
  1058. ext = video.get('ext')
  1059. src_ext = determine_ext(src)
  1060. streamer = video.get('streamer') or base
  1061. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1062. rtmp_count += 1
  1063. formats.append({
  1064. 'url': streamer,
  1065. 'play_path': src,
  1066. 'ext': 'flv',
  1067. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1068. 'tbr': bitrate,
  1069. 'filesize': filesize,
  1070. 'width': width,
  1071. 'height': height,
  1072. })
  1073. if transform_rtmp_url:
  1074. streamer, src = transform_rtmp_url(streamer, src)
  1075. formats[-1].update({
  1076. 'url': streamer,
  1077. 'play_path': src,
  1078. })
  1079. continue
  1080. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1081. if proto == 'm3u8' or src_ext == 'm3u8':
  1082. m3u8_formats = self._extract_m3u8_formats(
  1083. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1084. if len(m3u8_formats) == 1:
  1085. m3u8_count += 1
  1086. m3u8_formats[0].update({
  1087. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1088. 'tbr': bitrate,
  1089. 'width': width,
  1090. 'height': height,
  1091. })
  1092. formats.extend(m3u8_formats)
  1093. continue
  1094. if src_ext == 'f4m':
  1095. f4m_url = src_url
  1096. if not f4m_params:
  1097. f4m_params = {
  1098. 'hdcore': '3.2.0',
  1099. 'plugin': 'flowplayer-3.2.0.1',
  1100. }
  1101. f4m_url += '&' if '?' in f4m_url else '?'
  1102. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  1103. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1104. continue
  1105. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1106. http_count += 1
  1107. formats.append({
  1108. 'url': src_url,
  1109. 'ext': ext or src_ext or 'flv',
  1110. 'format_id': 'http-%d' % (bitrate or http_count),
  1111. 'tbr': bitrate,
  1112. 'filesize': filesize,
  1113. 'width': width,
  1114. 'height': height,
  1115. })
  1116. continue
  1117. self._sort_formats(formats)
  1118. return formats
  1119. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1120. subtitles = {}
  1121. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1122. src = textstream.get('src')
  1123. if not src:
  1124. continue
  1125. ext = textstream.get('ext') or determine_ext(src)
  1126. if not ext:
  1127. type_ = textstream.get('type')
  1128. SUBTITLES_TYPES = {
  1129. 'text/vtt': 'vtt',
  1130. 'text/srt': 'srt',
  1131. 'application/smptett+xml': 'tt',
  1132. }
  1133. if type_ in SUBTITLES_TYPES:
  1134. ext = SUBTITLES_TYPES[type_]
  1135. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1136. subtitles.setdefault(lang, []).append({
  1137. 'url': src,
  1138. 'ext': ext,
  1139. })
  1140. return subtitles
  1141. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1142. xspf = self._download_xml(
  1143. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1144. 'Unable to download xspf manifest', fatal=fatal)
  1145. if xspf is False:
  1146. return []
  1147. return self._parse_xspf(xspf, playlist_id)
  1148. def _parse_xspf(self, playlist, playlist_id):
  1149. NS_MAP = {
  1150. 'xspf': 'http://xspf.org/ns/0/',
  1151. 's1': 'http://static.streamone.nl/player/ns/0',
  1152. }
  1153. entries = []
  1154. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1155. title = xpath_text(
  1156. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1157. description = xpath_text(
  1158. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1159. thumbnail = xpath_text(
  1160. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1161. duration = float_or_none(
  1162. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1163. formats = [{
  1164. 'url': location.text,
  1165. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1166. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1167. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1168. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1169. self._sort_formats(formats)
  1170. entries.append({
  1171. 'id': playlist_id,
  1172. 'title': title,
  1173. 'description': description,
  1174. 'thumbnail': thumbnail,
  1175. 'duration': duration,
  1176. 'formats': formats,
  1177. })
  1178. return entries
  1179. def _download_dash_manifest(self, dash_manifest_url, video_id, fatal=True):
  1180. return self._download_xml(
  1181. dash_manifest_url, video_id,
  1182. note='Downloading DASH manifest',
  1183. errnote='Could not download DASH manifest',
  1184. fatal=fatal)
  1185. def _extract_dash_manifest_formats(self, dash_manifest_url, video_id, fatal=True, namespace=None, formats_dict={}):
  1186. dash_doc = self._download_dash_manifest(dash_manifest_url, video_id, fatal)
  1187. if dash_doc is False:
  1188. return []
  1189. return self._parse_dash_manifest(
  1190. dash_doc, namespace=namespace, formats_dict=formats_dict)
  1191. def _parse_dash_manifest(self, dash_doc, namespace=None, formats_dict={}):
  1192. def _add_ns(path):
  1193. return self._xpath_ns(path, namespace)
  1194. formats = []
  1195. for a in dash_doc.findall('.//' + _add_ns('AdaptationSet')):
  1196. mime_type = a.attrib.get('mimeType')
  1197. for r in a.findall(_add_ns('Representation')):
  1198. mime_type = r.attrib.get('mimeType') or mime_type
  1199. url_el = r.find(_add_ns('BaseURL'))
  1200. if mime_type == 'text/vtt':
  1201. # TODO implement WebVTT downloading
  1202. pass
  1203. elif mime_type.startswith('audio/') or mime_type.startswith('video/'):
  1204. segment_list = r.find(_add_ns('SegmentList'))
  1205. format_id = r.attrib['id']
  1206. video_url = url_el.text if url_el is not None else None
  1207. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1208. f = {
  1209. 'format_id': format_id,
  1210. 'url': video_url,
  1211. 'width': int_or_none(r.attrib.get('width')),
  1212. 'height': int_or_none(r.attrib.get('height')),
  1213. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  1214. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  1215. 'filesize': filesize,
  1216. 'fps': int_or_none(r.attrib.get('frameRate')),
  1217. }
  1218. if segment_list is not None:
  1219. initialization_url = segment_list.find(_add_ns('Initialization')).attrib['sourceURL']
  1220. f.update({
  1221. 'initialization_url': initialization_url,
  1222. 'segment_urls': [segment.attrib.get('media') for segment in segment_list.findall(_add_ns('SegmentURL'))],
  1223. 'protocol': 'http_dash_segments',
  1224. })
  1225. if not f.get('url'):
  1226. f['url'] = initialization_url
  1227. try:
  1228. existing_format = next(
  1229. fo for fo in formats
  1230. if fo['format_id'] == format_id)
  1231. except StopIteration:
  1232. full_info = formats_dict.get(format_id, {}).copy()
  1233. full_info.update(f)
  1234. codecs = r.attrib.get('codecs')
  1235. if codecs:
  1236. if mime_type.startswith('video/'):
  1237. vcodec, acodec = codecs, 'none'
  1238. else: # mime_type.startswith('audio/')
  1239. vcodec, acodec = 'none', codecs
  1240. full_info.update({
  1241. 'vcodec': vcodec,
  1242. 'acodec': acodec,
  1243. })
  1244. formats.append(full_info)
  1245. else:
  1246. existing_format.update(f)
  1247. else:
  1248. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1249. return formats
  1250. def _live_title(self, name):
  1251. """ Generate the title for a live video """
  1252. now = datetime.datetime.now()
  1253. now_str = now.strftime("%Y-%m-%d %H:%M")
  1254. return name + ' ' + now_str
  1255. def _int(self, v, name, fatal=False, **kwargs):
  1256. res = int_or_none(v, **kwargs)
  1257. if 'get_attr' in kwargs:
  1258. print(getattr(v, kwargs['get_attr']))
  1259. if res is None:
  1260. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1261. if fatal:
  1262. raise ExtractorError(msg)
  1263. else:
  1264. self._downloader.report_warning(msg)
  1265. return res
  1266. def _float(self, v, name, fatal=False, **kwargs):
  1267. res = float_or_none(v, **kwargs)
  1268. if res is None:
  1269. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1270. if fatal:
  1271. raise ExtractorError(msg)
  1272. else:
  1273. self._downloader.report_warning(msg)
  1274. return res
  1275. def _set_cookie(self, domain, name, value, expire_time=None):
  1276. cookie = compat_cookiejar.Cookie(
  1277. 0, name, value, None, None, domain, None,
  1278. None, '/', True, False, expire_time, '', None, None, None)
  1279. self._downloader.cookiejar.set_cookie(cookie)
  1280. def _get_cookies(self, url):
  1281. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1282. req = sanitized_Request(url)
  1283. self._downloader.cookiejar.add_cookie_header(req)
  1284. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1285. def get_testcases(self, include_onlymatching=False):
  1286. t = getattr(self, '_TEST', None)
  1287. if t:
  1288. assert not hasattr(self, '_TESTS'), \
  1289. '%s has _TEST and _TESTS' % type(self).__name__
  1290. tests = [t]
  1291. else:
  1292. tests = getattr(self, '_TESTS', [])
  1293. for t in tests:
  1294. if not include_onlymatching and t.get('only_matching', False):
  1295. continue
  1296. t['name'] = type(self).__name__[:-len('IE')]
  1297. yield t
  1298. def is_suitable(self, age_limit):
  1299. """ Test whether the extractor is generally suitable for the given
  1300. age limit (i.e. pornographic sites are not, all others usually are) """
  1301. any_restricted = False
  1302. for tc in self.get_testcases(include_onlymatching=False):
  1303. if 'playlist' in tc:
  1304. tc = tc['playlist'][0]
  1305. is_restricted = age_restricted(
  1306. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1307. if not is_restricted:
  1308. return True
  1309. any_restricted = any_restricted or is_restricted
  1310. return not any_restricted
  1311. def extract_subtitles(self, *args, **kwargs):
  1312. if (self._downloader.params.get('writesubtitles', False) or
  1313. self._downloader.params.get('listsubtitles')):
  1314. return self._get_subtitles(*args, **kwargs)
  1315. return {}
  1316. def _get_subtitles(self, *args, **kwargs):
  1317. raise NotImplementedError("This method must be implemented by subclasses")
  1318. @staticmethod
  1319. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1320. """ Merge subtitle items for one language. Items with duplicated URLs
  1321. will be dropped. """
  1322. list1_urls = set([item['url'] for item in subtitle_list1])
  1323. ret = list(subtitle_list1)
  1324. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1325. return ret
  1326. @classmethod
  1327. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1328. """ Merge two subtitle dictionaries, language by language. """
  1329. ret = dict(subtitle_dict1)
  1330. for lang in subtitle_dict2:
  1331. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1332. return ret
  1333. def extract_automatic_captions(self, *args, **kwargs):
  1334. if (self._downloader.params.get('writeautomaticsub', False) or
  1335. self._downloader.params.get('listsubtitles')):
  1336. return self._get_automatic_captions(*args, **kwargs)
  1337. return {}
  1338. def _get_automatic_captions(self, *args, **kwargs):
  1339. raise NotImplementedError("This method must be implemented by subclasses")
  1340. class SearchInfoExtractor(InfoExtractor):
  1341. """
  1342. Base class for paged search queries extractors.
  1343. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1344. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1345. """
  1346. @classmethod
  1347. def _make_valid_url(cls):
  1348. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1349. @classmethod
  1350. def suitable(cls, url):
  1351. return re.match(cls._make_valid_url(), url) is not None
  1352. def _real_extract(self, query):
  1353. mobj = re.match(self._make_valid_url(), query)
  1354. if mobj is None:
  1355. raise ExtractorError('Invalid search query "%s"' % query)
  1356. prefix = mobj.group('prefix')
  1357. query = mobj.group('query')
  1358. if prefix == '':
  1359. return self._get_n_results(query, 1)
  1360. elif prefix == 'all':
  1361. return self._get_n_results(query, self._MAX_RESULTS)
  1362. else:
  1363. n = int(prefix)
  1364. if n <= 0:
  1365. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1366. elif n > self._MAX_RESULTS:
  1367. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1368. n = self._MAX_RESULTS
  1369. return self._get_n_results(query, n)
  1370. def _get_n_results(self, query, n):
  1371. """Get a specified number of results for a query"""
  1372. raise NotImplementedError("This method must be implemented by subclasses")
  1373. @property
  1374. def SEARCH_KEY(self):
  1375. return self._SEARCH_KEY