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.

1451 lines
61 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. def _formats_key(f):
  725. # TODO remove the following workaround
  726. from ..utils import determine_ext
  727. if not f.get('ext') and 'url' in f:
  728. f['ext'] = determine_ext(f['url'])
  729. if isinstance(field_preference, (list, tuple)):
  730. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  731. preference = f.get('preference')
  732. if preference is None:
  733. preference = 0
  734. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  735. preference -= 0.5
  736. proto_preference = 0 if determine_protocol(f) in ['http', 'https'] else -0.1
  737. if f.get('vcodec') == 'none': # audio only
  738. if self._downloader.params.get('prefer_free_formats'):
  739. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  740. else:
  741. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  742. ext_preference = 0
  743. try:
  744. audio_ext_preference = ORDER.index(f['ext'])
  745. except ValueError:
  746. audio_ext_preference = -1
  747. else:
  748. if self._downloader.params.get('prefer_free_formats'):
  749. ORDER = ['flv', 'mp4', 'webm']
  750. else:
  751. ORDER = ['webm', 'flv', 'mp4']
  752. try:
  753. ext_preference = ORDER.index(f['ext'])
  754. except ValueError:
  755. ext_preference = -1
  756. audio_ext_preference = 0
  757. return (
  758. preference,
  759. f.get('language_preference') if f.get('language_preference') is not None else -1,
  760. f.get('quality') if f.get('quality') is not None else -1,
  761. f.get('tbr') if f.get('tbr') is not None else -1,
  762. f.get('filesize') if f.get('filesize') is not None else -1,
  763. f.get('vbr') if f.get('vbr') is not None else -1,
  764. f.get('height') if f.get('height') is not None else -1,
  765. f.get('width') if f.get('width') is not None else -1,
  766. proto_preference,
  767. ext_preference,
  768. f.get('abr') if f.get('abr') is not None else -1,
  769. audio_ext_preference,
  770. f.get('fps') if f.get('fps') is not None else -1,
  771. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  772. f.get('source_preference') if f.get('source_preference') is not None else -1,
  773. f.get('format_id') if f.get('format_id') is not None else '',
  774. )
  775. formats.sort(key=_formats_key)
  776. def _check_formats(self, formats, video_id):
  777. if formats:
  778. formats[:] = filter(
  779. lambda f: self._is_valid_url(
  780. f['url'], video_id,
  781. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  782. formats)
  783. def _is_valid_url(self, url, video_id, item='video'):
  784. url = self._proto_relative_url(url, scheme='http:')
  785. # For now assume non HTTP(S) URLs always valid
  786. if not (url.startswith('http://') or url.startswith('https://')):
  787. return True
  788. try:
  789. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  790. return True
  791. except ExtractorError as e:
  792. if isinstance(e.cause, compat_urllib_error.URLError):
  793. self.to_screen(
  794. '%s: %s URL is invalid, skipping' % (video_id, item))
  795. return False
  796. raise
  797. def http_scheme(self):
  798. """ Either "http:" or "https:", depending on the user's preferences """
  799. return (
  800. 'http:'
  801. if self._downloader.params.get('prefer_insecure', False)
  802. else 'https:')
  803. def _proto_relative_url(self, url, scheme=None):
  804. if url is None:
  805. return url
  806. if url.startswith('//'):
  807. if scheme is None:
  808. scheme = self.http_scheme()
  809. return scheme + url
  810. else:
  811. return url
  812. def _sleep(self, timeout, video_id, msg_template=None):
  813. if msg_template is None:
  814. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  815. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  816. self.to_screen(msg)
  817. time.sleep(timeout)
  818. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  819. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  820. fatal=True):
  821. manifest = self._download_xml(
  822. manifest_url, video_id, 'Downloading f4m manifest',
  823. 'Unable to download f4m manifest',
  824. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  825. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  826. transform_source=transform_source,
  827. fatal=fatal)
  828. if manifest is False:
  829. return []
  830. formats = []
  831. manifest_version = '1.0'
  832. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  833. if not media_nodes:
  834. manifest_version = '2.0'
  835. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  836. base_url = xpath_text(
  837. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  838. 'base URL', default=None)
  839. if base_url:
  840. base_url = base_url.strip()
  841. for i, media_el in enumerate(media_nodes):
  842. if manifest_version == '2.0':
  843. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  844. if not media_url:
  845. continue
  846. manifest_url = (
  847. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  848. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  849. # If media_url is itself a f4m manifest do the recursive extraction
  850. # since bitrates in parent manifest (this one) and media_url manifest
  851. # may differ leading to inability to resolve the format by requested
  852. # bitrate in f4m downloader
  853. if determine_ext(manifest_url) == 'f4m':
  854. formats.extend(self._extract_f4m_formats(
  855. manifest_url, video_id, preference, f4m_id, fatal=fatal))
  856. continue
  857. tbr = int_or_none(media_el.attrib.get('bitrate'))
  858. formats.append({
  859. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  860. 'url': manifest_url,
  861. 'ext': 'flv',
  862. 'tbr': tbr,
  863. 'width': int_or_none(media_el.attrib.get('width')),
  864. 'height': int_or_none(media_el.attrib.get('height')),
  865. 'preference': preference,
  866. })
  867. self._sort_formats(formats)
  868. return formats
  869. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  870. entry_protocol='m3u8', preference=None,
  871. m3u8_id=None, note=None, errnote=None,
  872. fatal=True):
  873. formats = [{
  874. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  875. 'url': m3u8_url,
  876. 'ext': ext,
  877. 'protocol': 'm3u8',
  878. 'preference': preference - 1 if preference else -1,
  879. 'resolution': 'multiple',
  880. 'format_note': 'Quality selection URL',
  881. }]
  882. format_url = lambda u: (
  883. u
  884. if re.match(r'^https?://', u)
  885. else compat_urlparse.urljoin(m3u8_url, u))
  886. res = self._download_webpage_handle(
  887. m3u8_url, video_id,
  888. note=note or 'Downloading m3u8 information',
  889. errnote=errnote or 'Failed to download m3u8 information',
  890. fatal=fatal)
  891. if res is False:
  892. return []
  893. m3u8_doc, urlh = res
  894. m3u8_url = urlh.geturl()
  895. last_info = None
  896. last_media = None
  897. kv_rex = re.compile(
  898. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  899. for line in m3u8_doc.splitlines():
  900. if line.startswith('#EXT-X-STREAM-INF:'):
  901. last_info = {}
  902. for m in kv_rex.finditer(line):
  903. v = m.group('val')
  904. if v.startswith('"'):
  905. v = v[1:-1]
  906. last_info[m.group('key')] = v
  907. elif line.startswith('#EXT-X-MEDIA:'):
  908. last_media = {}
  909. for m in kv_rex.finditer(line):
  910. v = m.group('val')
  911. if v.startswith('"'):
  912. v = v[1:-1]
  913. last_media[m.group('key')] = v
  914. elif line.startswith('#') or not line.strip():
  915. continue
  916. else:
  917. if last_info is None:
  918. formats.append({'url': format_url(line)})
  919. continue
  920. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  921. format_id = []
  922. if m3u8_id:
  923. format_id.append(m3u8_id)
  924. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  925. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  926. f = {
  927. 'format_id': '-'.join(format_id),
  928. 'url': format_url(line.strip()),
  929. 'tbr': tbr,
  930. 'ext': ext,
  931. 'protocol': entry_protocol,
  932. 'preference': preference,
  933. }
  934. codecs = last_info.get('CODECS')
  935. if codecs:
  936. # TODO: looks like video codec is not always necessarily goes first
  937. va_codecs = codecs.split(',')
  938. if va_codecs[0]:
  939. f['vcodec'] = va_codecs[0].partition('.')[0]
  940. if len(va_codecs) > 1 and va_codecs[1]:
  941. f['acodec'] = va_codecs[1].partition('.')[0]
  942. resolution = last_info.get('RESOLUTION')
  943. if resolution:
  944. width_str, height_str = resolution.split('x')
  945. f['width'] = int(width_str)
  946. f['height'] = int(height_str)
  947. if last_media is not None:
  948. f['m3u8_media'] = last_media
  949. last_media = None
  950. formats.append(f)
  951. last_info = {}
  952. self._sort_formats(formats)
  953. return formats
  954. @staticmethod
  955. def _xpath_ns(path, namespace=None):
  956. if not namespace:
  957. return path
  958. out = []
  959. for c in path.split('/'):
  960. if not c or c == '.':
  961. out.append(c)
  962. else:
  963. out.append('{%s}%s' % (namespace, c))
  964. return '/'.join(out)
  965. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  966. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  967. if smil is False:
  968. assert not fatal
  969. return []
  970. namespace = self._parse_smil_namespace(smil)
  971. return self._parse_smil_formats(
  972. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  973. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  974. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  975. if smil is False:
  976. return {}
  977. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  978. def _download_smil(self, smil_url, video_id, fatal=True):
  979. return self._download_xml(
  980. smil_url, video_id, 'Downloading SMIL file',
  981. 'Unable to download SMIL file', fatal=fatal)
  982. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  983. namespace = self._parse_smil_namespace(smil)
  984. formats = self._parse_smil_formats(
  985. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  986. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  987. video_id = os.path.splitext(url_basename(smil_url))[0]
  988. title = None
  989. description = None
  990. upload_date = None
  991. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  992. name = meta.attrib.get('name')
  993. content = meta.attrib.get('content')
  994. if not name or not content:
  995. continue
  996. if not title and name == 'title':
  997. title = content
  998. elif not description and name in ('description', 'abstract'):
  999. description = content
  1000. elif not upload_date and name == 'date':
  1001. upload_date = unified_strdate(content)
  1002. thumbnails = [{
  1003. 'id': image.get('type'),
  1004. 'url': image.get('src'),
  1005. 'width': int_or_none(image.get('width')),
  1006. 'height': int_or_none(image.get('height')),
  1007. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1008. return {
  1009. 'id': video_id,
  1010. 'title': title or video_id,
  1011. 'description': description,
  1012. 'upload_date': upload_date,
  1013. 'thumbnails': thumbnails,
  1014. 'formats': formats,
  1015. 'subtitles': subtitles,
  1016. }
  1017. def _parse_smil_namespace(self, smil):
  1018. return self._search_regex(
  1019. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1020. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1021. base = smil_url
  1022. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1023. b = meta.get('base') or meta.get('httpBase')
  1024. if b:
  1025. base = b
  1026. break
  1027. formats = []
  1028. rtmp_count = 0
  1029. http_count = 0
  1030. videos = smil.findall(self._xpath_ns('.//video', namespace))
  1031. for video in videos:
  1032. src = video.get('src')
  1033. if not src:
  1034. continue
  1035. bitrate = float_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  1036. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  1037. width = int_or_none(video.get('width'))
  1038. height = int_or_none(video.get('height'))
  1039. proto = video.get('proto')
  1040. ext = video.get('ext')
  1041. src_ext = determine_ext(src)
  1042. streamer = video.get('streamer') or base
  1043. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1044. rtmp_count += 1
  1045. formats.append({
  1046. 'url': streamer,
  1047. 'play_path': src,
  1048. 'ext': 'flv',
  1049. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1050. 'tbr': bitrate,
  1051. 'filesize': filesize,
  1052. 'width': width,
  1053. 'height': height,
  1054. })
  1055. if transform_rtmp_url:
  1056. streamer, src = transform_rtmp_url(streamer, src)
  1057. formats[-1].update({
  1058. 'url': streamer,
  1059. 'play_path': src,
  1060. })
  1061. continue
  1062. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1063. if proto == 'm3u8' or src_ext == 'm3u8':
  1064. formats.extend(self._extract_m3u8_formats(
  1065. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False))
  1066. continue
  1067. if src_ext == 'f4m':
  1068. f4m_url = src_url
  1069. if not f4m_params:
  1070. f4m_params = {
  1071. 'hdcore': '3.2.0',
  1072. 'plugin': 'flowplayer-3.2.0.1',
  1073. }
  1074. f4m_url += '&' if '?' in f4m_url else '?'
  1075. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  1076. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1077. continue
  1078. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1079. http_count += 1
  1080. formats.append({
  1081. 'url': src_url,
  1082. 'ext': ext or src_ext or 'flv',
  1083. 'format_id': 'http-%d' % (bitrate or http_count),
  1084. 'tbr': bitrate,
  1085. 'filesize': filesize,
  1086. 'width': width,
  1087. 'height': height,
  1088. })
  1089. continue
  1090. self._sort_formats(formats)
  1091. return formats
  1092. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1093. subtitles = {}
  1094. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1095. src = textstream.get('src')
  1096. if not src:
  1097. continue
  1098. ext = textstream.get('ext') or determine_ext(src)
  1099. if not ext:
  1100. type_ = textstream.get('type')
  1101. SUBTITLES_TYPES = {
  1102. 'text/vtt': 'vtt',
  1103. 'text/srt': 'srt',
  1104. 'application/smptett+xml': 'tt',
  1105. }
  1106. if type_ in SUBTITLES_TYPES:
  1107. ext = SUBTITLES_TYPES[type_]
  1108. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1109. subtitles.setdefault(lang, []).append({
  1110. 'url': src,
  1111. 'ext': ext,
  1112. })
  1113. return subtitles
  1114. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1115. xspf = self._download_xml(
  1116. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1117. 'Unable to download xspf manifest', fatal=fatal)
  1118. if xspf is False:
  1119. return []
  1120. return self._parse_xspf(xspf, playlist_id)
  1121. def _parse_xspf(self, playlist, playlist_id):
  1122. NS_MAP = {
  1123. 'xspf': 'http://xspf.org/ns/0/',
  1124. 's1': 'http://static.streamone.nl/player/ns/0',
  1125. }
  1126. entries = []
  1127. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1128. title = xpath_text(
  1129. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1130. description = xpath_text(
  1131. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1132. thumbnail = xpath_text(
  1133. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1134. duration = float_or_none(
  1135. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1136. formats = [{
  1137. 'url': location.text,
  1138. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1139. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1140. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1141. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1142. self._sort_formats(formats)
  1143. entries.append({
  1144. 'id': playlist_id,
  1145. 'title': title,
  1146. 'description': description,
  1147. 'thumbnail': thumbnail,
  1148. 'duration': duration,
  1149. 'formats': formats,
  1150. })
  1151. return entries
  1152. def _live_title(self, name):
  1153. """ Generate the title for a live video """
  1154. now = datetime.datetime.now()
  1155. now_str = now.strftime("%Y-%m-%d %H:%M")
  1156. return name + ' ' + now_str
  1157. def _int(self, v, name, fatal=False, **kwargs):
  1158. res = int_or_none(v, **kwargs)
  1159. if 'get_attr' in kwargs:
  1160. print(getattr(v, kwargs['get_attr']))
  1161. if res is None:
  1162. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1163. if fatal:
  1164. raise ExtractorError(msg)
  1165. else:
  1166. self._downloader.report_warning(msg)
  1167. return res
  1168. def _float(self, v, name, fatal=False, **kwargs):
  1169. res = float_or_none(v, **kwargs)
  1170. if res is None:
  1171. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1172. if fatal:
  1173. raise ExtractorError(msg)
  1174. else:
  1175. self._downloader.report_warning(msg)
  1176. return res
  1177. def _set_cookie(self, domain, name, value, expire_time=None):
  1178. cookie = compat_cookiejar.Cookie(
  1179. 0, name, value, None, None, domain, None,
  1180. None, '/', True, False, expire_time, '', None, None, None)
  1181. self._downloader.cookiejar.set_cookie(cookie)
  1182. def _get_cookies(self, url):
  1183. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1184. req = sanitized_Request(url)
  1185. self._downloader.cookiejar.add_cookie_header(req)
  1186. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1187. def get_testcases(self, include_onlymatching=False):
  1188. t = getattr(self, '_TEST', None)
  1189. if t:
  1190. assert not hasattr(self, '_TESTS'), \
  1191. '%s has _TEST and _TESTS' % type(self).__name__
  1192. tests = [t]
  1193. else:
  1194. tests = getattr(self, '_TESTS', [])
  1195. for t in tests:
  1196. if not include_onlymatching and t.get('only_matching', False):
  1197. continue
  1198. t['name'] = type(self).__name__[:-len('IE')]
  1199. yield t
  1200. def is_suitable(self, age_limit):
  1201. """ Test whether the extractor is generally suitable for the given
  1202. age limit (i.e. pornographic sites are not, all others usually are) """
  1203. any_restricted = False
  1204. for tc in self.get_testcases(include_onlymatching=False):
  1205. if 'playlist' in tc:
  1206. tc = tc['playlist'][0]
  1207. is_restricted = age_restricted(
  1208. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1209. if not is_restricted:
  1210. return True
  1211. any_restricted = any_restricted or is_restricted
  1212. return not any_restricted
  1213. def extract_subtitles(self, *args, **kwargs):
  1214. if (self._downloader.params.get('writesubtitles', False) or
  1215. self._downloader.params.get('listsubtitles')):
  1216. return self._get_subtitles(*args, **kwargs)
  1217. return {}
  1218. def _get_subtitles(self, *args, **kwargs):
  1219. raise NotImplementedError("This method must be implemented by subclasses")
  1220. @staticmethod
  1221. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1222. """ Merge subtitle items for one language. Items with duplicated URLs
  1223. will be dropped. """
  1224. list1_urls = set([item['url'] for item in subtitle_list1])
  1225. ret = list(subtitle_list1)
  1226. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1227. return ret
  1228. @classmethod
  1229. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1230. """ Merge two subtitle dictionaries, language by language. """
  1231. ret = dict(subtitle_dict1)
  1232. for lang in subtitle_dict2:
  1233. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1234. return ret
  1235. def extract_automatic_captions(self, *args, **kwargs):
  1236. if (self._downloader.params.get('writeautomaticsub', False) or
  1237. self._downloader.params.get('listsubtitles')):
  1238. return self._get_automatic_captions(*args, **kwargs)
  1239. return {}
  1240. def _get_automatic_captions(self, *args, **kwargs):
  1241. raise NotImplementedError("This method must be implemented by subclasses")
  1242. class SearchInfoExtractor(InfoExtractor):
  1243. """
  1244. Base class for paged search queries extractors.
  1245. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1246. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1247. """
  1248. @classmethod
  1249. def _make_valid_url(cls):
  1250. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1251. @classmethod
  1252. def suitable(cls, url):
  1253. return re.match(cls._make_valid_url(), url) is not None
  1254. def _real_extract(self, query):
  1255. mobj = re.match(self._make_valid_url(), query)
  1256. if mobj is None:
  1257. raise ExtractorError('Invalid search query "%s"' % query)
  1258. prefix = mobj.group('prefix')
  1259. query = mobj.group('query')
  1260. if prefix == '':
  1261. return self._get_n_results(query, 1)
  1262. elif prefix == 'all':
  1263. return self._get_n_results(query, self._MAX_RESULTS)
  1264. else:
  1265. n = int(prefix)
  1266. if n <= 0:
  1267. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1268. elif n > self._MAX_RESULTS:
  1269. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1270. n = self._MAX_RESULTS
  1271. return self._get_n_results(query, n)
  1272. def _get_n_results(self, query, n):
  1273. """Get a specified number of results for a query"""
  1274. raise NotImplementedError("This method must be implemented by subclasses")
  1275. @property
  1276. def SEARCH_KEY(self):
  1277. return self._SEARCH_KEY