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.

2236 lines
102 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
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
  1. from __future__ import unicode_literals
  2. import base64
  3. import datetime
  4. import hashlib
  5. import json
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import sys
  11. import time
  12. import math
  13. from ..compat import (
  14. compat_cookiejar,
  15. compat_cookies,
  16. compat_etree_fromstring,
  17. compat_getpass,
  18. compat_http_client,
  19. compat_os_name,
  20. compat_str,
  21. compat_urllib_error,
  22. compat_urllib_parse_unquote,
  23. compat_urllib_parse_urlencode,
  24. compat_urllib_request,
  25. compat_urlparse,
  26. )
  27. from ..downloader.f4m import remove_encrypted_media
  28. from ..utils import (
  29. NO_DEFAULT,
  30. age_restricted,
  31. base_url,
  32. bug_reports_message,
  33. clean_html,
  34. compiled_regex_type,
  35. determine_ext,
  36. error_to_compat_str,
  37. ExtractorError,
  38. fix_xml_ampersands,
  39. float_or_none,
  40. int_or_none,
  41. parse_iso8601,
  42. RegexNotFoundError,
  43. sanitize_filename,
  44. sanitized_Request,
  45. unescapeHTML,
  46. unified_strdate,
  47. unified_timestamp,
  48. url_basename,
  49. xpath_element,
  50. xpath_text,
  51. xpath_with_ns,
  52. determine_protocol,
  53. parse_duration,
  54. mimetype2ext,
  55. update_Request,
  56. update_url_query,
  57. parse_m3u8_attributes,
  58. extract_attributes,
  59. parse_codecs,
  60. urljoin,
  61. )
  62. class InfoExtractor(object):
  63. """Information Extractor class.
  64. Information extractors are the classes that, given a URL, extract
  65. information about the video (or videos) the URL refers to. This
  66. information includes the real video URL, the video title, author and
  67. others. The information is stored in a dictionary which is then
  68. passed to the YoutubeDL. The YoutubeDL processes this
  69. information possibly downloading the video to the file system, among
  70. other possible outcomes.
  71. The type field determines the type of the result.
  72. By far the most common value (and the default if _type is missing) is
  73. "video", which indicates a single video.
  74. For a video, the dictionaries must include the following fields:
  75. id: Video identifier.
  76. title: Video title, unescaped.
  77. Additionally, it must contain either a formats entry or a url one:
  78. formats: A list of dictionaries for each format available, ordered
  79. from worst to best quality.
  80. Potential fields:
  81. * url Mandatory. The URL of the video file
  82. * manifest_url
  83. The URL of the manifest file in case of
  84. fragmented media (DASH, hls, hds)
  85. * ext Will be calculated from URL if missing
  86. * format A human-readable description of the format
  87. ("mp4 container with h264/opus").
  88. Calculated from the format_id, width, height.
  89. and format_note fields if missing.
  90. * format_id A short description of the format
  91. ("mp4_h264_opus" or "19").
  92. Technically optional, but strongly recommended.
  93. * format_note Additional info about the format
  94. ("3D" or "DASH video")
  95. * width Width of the video, if known
  96. * height Height of the video, if known
  97. * resolution Textual description of width and height
  98. * tbr Average bitrate of audio and video in KBit/s
  99. * abr Average audio bitrate in KBit/s
  100. * acodec Name of the audio codec in use
  101. * asr Audio sampling rate in Hertz
  102. * vbr Average video bitrate in KBit/s
  103. * fps Frame rate
  104. * vcodec Name of the video codec in use
  105. * container Name of the container format
  106. * filesize The number of bytes, if known in advance
  107. * filesize_approx An estimate for the number of bytes
  108. * player_url SWF Player URL (used for rtmpdump).
  109. * protocol The protocol that will be used for the actual
  110. download, lower-case.
  111. "http", "https", "rtsp", "rtmp", "rtmpe",
  112. "m3u8", "m3u8_native" or "http_dash_segments".
  113. * fragment_base_url
  114. Base URL for fragments. Each fragment's path
  115. value (if present) will be relative to
  116. this URL.
  117. * fragments A list of fragments of a fragmented media.
  118. Each fragment entry must contain either an url
  119. or a path. If an url is present it should be
  120. considered by a client. Otherwise both path and
  121. fragment_base_url must be present. Here is
  122. the list of all potential fields:
  123. * "url" - fragment's URL
  124. * "path" - fragment's path relative to
  125. fragment_base_url
  126. * "duration" (optional, int or float)
  127. * "filesize" (optional, int)
  128. * preference Order number of this format. If this field is
  129. present and not None, the formats get sorted
  130. by this field, regardless of all other values.
  131. -1 for default (order by other properties),
  132. -2 or smaller for less than default.
  133. < -1000 to hide the format (if there is
  134. another one which is strictly better)
  135. * language Language code, e.g. "de" or "en-US".
  136. * language_preference Is this in the language mentioned in
  137. the URL?
  138. 10 if it's what the URL is about,
  139. -1 for default (don't know),
  140. -10 otherwise, other values reserved for now.
  141. * quality Order number of the video quality of this
  142. format, irrespective of the file format.
  143. -1 for default (order by other properties),
  144. -2 or smaller for less than default.
  145. * source_preference Order number for this video source
  146. (quality takes higher priority)
  147. -1 for default (order by other properties),
  148. -2 or smaller for less than default.
  149. * http_headers A dictionary of additional HTTP headers
  150. to add to the request.
  151. * stretched_ratio If given and not 1, indicates that the
  152. video's pixels are not square.
  153. width : height ratio as float.
  154. * no_resume The server does not support resuming the
  155. (HTTP or RTMP) download. Boolean.
  156. url: Final video URL.
  157. ext: Video filename extension.
  158. format: The video format, defaults to ext (used for --get-format)
  159. player_url: SWF Player URL (used for rtmpdump).
  160. The following fields are optional:
  161. alt_title: A secondary title of the video.
  162. display_id An alternative identifier for the video, not necessarily
  163. unique, but available before title. Typically, id is
  164. something like "4234987", title "Dancing naked mole rats",
  165. and display_id "dancing-naked-mole-rats"
  166. thumbnails: A list of dictionaries, with the following entries:
  167. * "id" (optional, string) - Thumbnail format ID
  168. * "url"
  169. * "preference" (optional, int) - quality of the image
  170. * "width" (optional, int)
  171. * "height" (optional, int)
  172. * "resolution" (optional, string "{width}x{height"},
  173. deprecated)
  174. * "filesize" (optional, int)
  175. thumbnail: Full URL to a video thumbnail image.
  176. description: Full video description.
  177. uploader: Full name of the video uploader.
  178. license: License name the video is licensed under.
  179. creator: The creator of the video.
  180. release_date: The date (YYYYMMDD) when the video was released.
  181. timestamp: UNIX timestamp of the moment the video became available.
  182. upload_date: Video upload date (YYYYMMDD).
  183. If not explicitly set, calculated from timestamp.
  184. uploader_id: Nickname or id of the video uploader.
  185. uploader_url: Full URL to a personal webpage of the video uploader.
  186. location: Physical location where the video was filmed.
  187. subtitles: The available subtitles as a dictionary in the format
  188. {tag: subformats}. "tag" is usually a language code, and
  189. "subformats" is a list sorted from lower to higher
  190. preference, each element is a dictionary with the "ext"
  191. entry and one of:
  192. * "data": The subtitles file contents
  193. * "url": A URL pointing to the subtitles file
  194. "ext" will be calculated from URL if missing
  195. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  196. automatically generated captions
  197. duration: Length of the video in seconds, as an integer or float.
  198. view_count: How many users have watched the video on the platform.
  199. like_count: Number of positive ratings of the video
  200. dislike_count: Number of negative ratings of the video
  201. repost_count: Number of reposts of the video
  202. average_rating: Average rating give by users, the scale used depends on the webpage
  203. comment_count: Number of comments on the video
  204. comments: A list of comments, each with one or more of the following
  205. properties (all but one of text or html optional):
  206. * "author" - human-readable name of the comment author
  207. * "author_id" - user ID of the comment author
  208. * "id" - Comment ID
  209. * "html" - Comment as HTML
  210. * "text" - Plain text of the comment
  211. * "timestamp" - UNIX timestamp of comment
  212. * "parent" - ID of the comment this one is replying to.
  213. Set to "root" to indicate that this is a
  214. comment to the original video.
  215. age_limit: Age restriction for the video, as an integer (years)
  216. webpage_url: The URL to the video webpage, if given to youtube-dl it
  217. should allow to get the same result again. (It will be set
  218. by YoutubeDL if it's missing)
  219. categories: A list of categories that the video falls in, for example
  220. ["Sports", "Berlin"]
  221. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  222. is_live: True, False, or None (=unknown). Whether this video is a
  223. live stream that goes on instead of a fixed-length video.
  224. start_time: Time in seconds where the reproduction should start, as
  225. specified in the URL.
  226. end_time: Time in seconds where the reproduction should end, as
  227. specified in the URL.
  228. The following fields should only be used when the video belongs to some logical
  229. chapter or section:
  230. chapter: Name or title of the chapter the video belongs to.
  231. chapter_number: Number of the chapter the video belongs to, as an integer.
  232. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  233. The following fields should only be used when the video is an episode of some
  234. series, programme or podcast:
  235. series: Title of the series or programme the video episode belongs to.
  236. season: Title of the season the video episode belongs to.
  237. season_number: Number of the season the video episode belongs to, as an integer.
  238. season_id: Id of the season the video episode belongs to, as a unicode string.
  239. episode: Title of the video episode. Unlike mandatory video title field,
  240. this field should denote the exact title of the video episode
  241. without any kind of decoration.
  242. episode_number: Number of the video episode within a season, as an integer.
  243. episode_id: Id of the video episode, as a unicode string.
  244. The following fields should only be used when the media is a track or a part of
  245. a music album:
  246. track: Title of the track.
  247. track_number: Number of the track within an album or a disc, as an integer.
  248. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  249. as a unicode string.
  250. artist: Artist(s) of the track.
  251. genre: Genre(s) of the track.
  252. album: Title of the album the track belongs to.
  253. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  254. album_artist: List of all artists appeared on the album (e.g.
  255. "Ash Borer / Fell Voices" or "Various Artists", useful for splits
  256. and compilations).
  257. disc_number: Number of the disc or other physical medium the track belongs to,
  258. as an integer.
  259. release_year: Year (YYYY) when the album was released.
  260. Unless mentioned otherwise, the fields should be Unicode strings.
  261. Unless mentioned otherwise, None is equivalent to absence of information.
  262. _type "playlist" indicates multiple videos.
  263. There must be a key "entries", which is a list, an iterable, or a PagedList
  264. object, each element of which is a valid dictionary by this specification.
  265. Additionally, playlists can have "title", "description" and "id" attributes
  266. with the same semantics as videos (see above).
  267. _type "multi_video" indicates that there are multiple videos that
  268. form a single show, for examples multiple acts of an opera or TV episode.
  269. It must have an entries key like a playlist and contain all the keys
  270. required for a video at the same time.
  271. _type "url" indicates that the video must be extracted from another
  272. location, possibly by a different extractor. Its only required key is:
  273. "url" - the next URL to extract.
  274. The key "ie_key" can be set to the class name (minus the trailing "IE",
  275. e.g. "Youtube") if the extractor class is known in advance.
  276. Additionally, the dictionary may have any properties of the resolved entity
  277. known in advance, for example "title" if the title of the referred video is
  278. known ahead of time.
  279. _type "url_transparent" entities have the same specification as "url", but
  280. indicate that the given additional information is more precise than the one
  281. associated with the resolved URL.
  282. This is useful when a site employs a video service that hosts the video and
  283. its technical metadata, but that video service does not embed a useful
  284. title, description etc.
  285. Subclasses of this one should re-define the _real_initialize() and
  286. _real_extract() methods and define a _VALID_URL regexp.
  287. Probably, they should also be added to the list of extractors.
  288. Finally, the _WORKING attribute should be set to False for broken IEs
  289. in order to warn the users and skip the tests.
  290. """
  291. _ready = False
  292. _downloader = None
  293. _WORKING = True
  294. def __init__(self, downloader=None):
  295. """Constructor. Receives an optional downloader."""
  296. self._ready = False
  297. self.set_downloader(downloader)
  298. @classmethod
  299. def suitable(cls, url):
  300. """Receives a URL and returns True if suitable for this IE."""
  301. # This does not use has/getattr intentionally - we want to know whether
  302. # we have cached the regexp for *this* class, whereas getattr would also
  303. # match the superclass
  304. if '_VALID_URL_RE' not in cls.__dict__:
  305. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  306. return cls._VALID_URL_RE.match(url) is not None
  307. @classmethod
  308. def _match_id(cls, url):
  309. if '_VALID_URL_RE' not in cls.__dict__:
  310. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  311. m = cls._VALID_URL_RE.match(url)
  312. assert m
  313. return m.group('id')
  314. @classmethod
  315. def working(cls):
  316. """Getter method for _WORKING."""
  317. return cls._WORKING
  318. def initialize(self):
  319. """Initializes an instance (authentication, etc)."""
  320. if not self._ready:
  321. self._real_initialize()
  322. self._ready = True
  323. def extract(self, url):
  324. """Extracts URL information and returns it in list of dicts."""
  325. try:
  326. self.initialize()
  327. return self._real_extract(url)
  328. except ExtractorError:
  329. raise
  330. except compat_http_client.IncompleteRead as e:
  331. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  332. except (KeyError, StopIteration) as e:
  333. raise ExtractorError('An extractor error has occurred.', cause=e)
  334. def set_downloader(self, downloader):
  335. """Sets the downloader for this IE."""
  336. self._downloader = downloader
  337. def _real_initialize(self):
  338. """Real initialization process. Redefine in subclasses."""
  339. pass
  340. def _real_extract(self, url):
  341. """Real extraction process. Redefine in subclasses."""
  342. pass
  343. @classmethod
  344. def ie_key(cls):
  345. """A string for getting the InfoExtractor with get_info_extractor"""
  346. return compat_str(cls.__name__[:-2])
  347. @property
  348. def IE_NAME(self):
  349. return compat_str(type(self).__name__[:-2])
  350. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  351. """ Returns the response handle """
  352. if note is None:
  353. self.report_download_webpage(video_id)
  354. elif note is not False:
  355. if video_id is None:
  356. self.to_screen('%s' % (note,))
  357. else:
  358. self.to_screen('%s: %s' % (video_id, note))
  359. if isinstance(url_or_request, compat_urllib_request.Request):
  360. url_or_request = update_Request(
  361. url_or_request, data=data, headers=headers, query=query)
  362. else:
  363. if query:
  364. url_or_request = update_url_query(url_or_request, query)
  365. if data is not None or headers:
  366. url_or_request = sanitized_Request(url_or_request, data, headers)
  367. try:
  368. return self._downloader.urlopen(url_or_request)
  369. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  370. if errnote is False:
  371. return False
  372. if errnote is None:
  373. errnote = 'Unable to download webpage'
  374. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  375. if fatal:
  376. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  377. else:
  378. self._downloader.report_warning(errmsg)
  379. return False
  380. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  381. """ Returns a tuple (page content as string, URL handle) """
  382. # Strip hashes from the URL (#1038)
  383. if isinstance(url_or_request, (compat_str, str)):
  384. url_or_request = url_or_request.partition('#')[0]
  385. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query)
  386. if urlh is False:
  387. assert not fatal
  388. return False
  389. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  390. return (content, urlh)
  391. @staticmethod
  392. def _guess_encoding_from_content(content_type, webpage_bytes):
  393. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  394. if m:
  395. encoding = m.group(1)
  396. else:
  397. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  398. webpage_bytes[:1024])
  399. if m:
  400. encoding = m.group(1).decode('ascii')
  401. elif webpage_bytes.startswith(b'\xff\xfe'):
  402. encoding = 'utf-16'
  403. else:
  404. encoding = 'utf-8'
  405. return encoding
  406. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  407. content_type = urlh.headers.get('Content-Type', '')
  408. webpage_bytes = urlh.read()
  409. if prefix is not None:
  410. webpage_bytes = prefix + webpage_bytes
  411. if not encoding:
  412. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  413. if self._downloader.params.get('dump_intermediate_pages', False):
  414. try:
  415. url = url_or_request.get_full_url()
  416. except AttributeError:
  417. url = url_or_request
  418. self.to_screen('Dumping request to ' + url)
  419. dump = base64.b64encode(webpage_bytes).decode('ascii')
  420. self._downloader.to_screen(dump)
  421. if self._downloader.params.get('write_pages', False):
  422. try:
  423. url = url_or_request.get_full_url()
  424. except AttributeError:
  425. url = url_or_request
  426. basen = '%s_%s' % (video_id, url)
  427. if len(basen) > 240:
  428. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  429. basen = basen[:240 - len(h)] + h
  430. raw_filename = basen + '.dump'
  431. filename = sanitize_filename(raw_filename, restricted=True)
  432. self.to_screen('Saving request to ' + filename)
  433. # Working around MAX_PATH limitation on Windows (see
  434. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  435. if compat_os_name == 'nt':
  436. absfilepath = os.path.abspath(filename)
  437. if len(absfilepath) > 259:
  438. filename = '\\\\?\\' + absfilepath
  439. with open(filename, 'wb') as outf:
  440. outf.write(webpage_bytes)
  441. try:
  442. content = webpage_bytes.decode(encoding, 'replace')
  443. except LookupError:
  444. content = webpage_bytes.decode('utf-8', 'replace')
  445. if ('<title>Access to this site is blocked</title>' in content and
  446. 'Websense' in content[:512]):
  447. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  448. blocked_iframe = self._html_search_regex(
  449. r'<iframe src="([^"]+)"', content,
  450. 'Websense information URL', default=None)
  451. if blocked_iframe:
  452. msg += ' Visit %s for more details' % blocked_iframe
  453. raise ExtractorError(msg, expected=True)
  454. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  455. msg = (
  456. 'Access to this webpage has been blocked by Indian censorship. '
  457. 'Use a VPN or proxy server (with --proxy) to route around it.')
  458. block_msg = self._html_search_regex(
  459. r'</h1><p>(.*?)</p>',
  460. content, 'block message', default=None)
  461. if block_msg:
  462. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  463. raise ExtractorError(msg, expected=True)
  464. return content
  465. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None, data=None, headers={}, query={}):
  466. """ Returns the data of the page as a string """
  467. success = False
  468. try_count = 0
  469. while success is False:
  470. try:
  471. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding, data=data, headers=headers, query=query)
  472. success = True
  473. except compat_http_client.IncompleteRead as e:
  474. try_count += 1
  475. if try_count >= tries:
  476. raise e
  477. self._sleep(timeout, video_id)
  478. if res is False:
  479. return res
  480. else:
  481. content, _ = res
  482. return content
  483. def _download_xml(self, url_or_request, video_id,
  484. note='Downloading XML', errnote='Unable to download XML',
  485. transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  486. """Return the xml as an xml.etree.ElementTree.Element"""
  487. xml_string = self._download_webpage(
  488. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding, data=data, headers=headers, query=query)
  489. if xml_string is False:
  490. return xml_string
  491. if transform_source:
  492. xml_string = transform_source(xml_string)
  493. return compat_etree_fromstring(xml_string.encode('utf-8'))
  494. def _download_json(self, url_or_request, video_id,
  495. note='Downloading JSON metadata',
  496. errnote='Unable to download JSON metadata',
  497. transform_source=None,
  498. fatal=True, encoding=None, data=None, headers={}, query={}):
  499. json_string = self._download_webpage(
  500. url_or_request, video_id, note, errnote, fatal=fatal,
  501. encoding=encoding, data=data, headers=headers, query=query)
  502. if (not fatal) and json_string is False:
  503. return None
  504. return self._parse_json(
  505. json_string, video_id, transform_source=transform_source, fatal=fatal)
  506. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  507. if transform_source:
  508. json_string = transform_source(json_string)
  509. try:
  510. return json.loads(json_string)
  511. except ValueError as ve:
  512. errmsg = '%s: Failed to parse JSON ' % video_id
  513. if fatal:
  514. raise ExtractorError(errmsg, cause=ve)
  515. else:
  516. self.report_warning(errmsg + str(ve))
  517. def report_warning(self, msg, video_id=None):
  518. idstr = '' if video_id is None else '%s: ' % video_id
  519. self._downloader.report_warning(
  520. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  521. def to_screen(self, msg):
  522. """Print msg to screen, prefixing it with '[ie_name]'"""
  523. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  524. def report_extraction(self, id_or_name):
  525. """Report information extraction."""
  526. self.to_screen('%s: Extracting information' % id_or_name)
  527. def report_download_webpage(self, video_id):
  528. """Report webpage download."""
  529. self.to_screen('%s: Downloading webpage' % video_id)
  530. def report_age_confirmation(self):
  531. """Report attempt to confirm age."""
  532. self.to_screen('Confirming age')
  533. def report_login(self):
  534. """Report attempt to log in."""
  535. self.to_screen('Logging in')
  536. @staticmethod
  537. def raise_login_required(msg='This video is only available for registered users'):
  538. raise ExtractorError(
  539. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  540. expected=True)
  541. @staticmethod
  542. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction'):
  543. raise ExtractorError(
  544. '%s. You might want to use --proxy to workaround.' % msg,
  545. expected=True)
  546. # Methods for following #608
  547. @staticmethod
  548. def url_result(url, ie=None, video_id=None, video_title=None):
  549. """Returns a URL that points to a page that should be processed"""
  550. # TODO: ie should be the class used for getting the info
  551. video_info = {'_type': 'url',
  552. 'url': url,
  553. 'ie_key': ie}
  554. if video_id is not None:
  555. video_info['id'] = video_id
  556. if video_title is not None:
  557. video_info['title'] = video_title
  558. return video_info
  559. @staticmethod
  560. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  561. """Returns a playlist"""
  562. video_info = {'_type': 'playlist',
  563. 'entries': entries}
  564. if playlist_id:
  565. video_info['id'] = playlist_id
  566. if playlist_title:
  567. video_info['title'] = playlist_title
  568. if playlist_description:
  569. video_info['description'] = playlist_description
  570. return video_info
  571. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  572. """
  573. Perform a regex search on the given string, using a single or a list of
  574. patterns returning the first matching group.
  575. In case of failure return a default value or raise a WARNING or a
  576. RegexNotFoundError, depending on fatal, specifying the field name.
  577. """
  578. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  579. mobj = re.search(pattern, string, flags)
  580. else:
  581. for p in pattern:
  582. mobj = re.search(p, string, flags)
  583. if mobj:
  584. break
  585. if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  586. _name = '\033[0;34m%s\033[0m' % name
  587. else:
  588. _name = name
  589. if mobj:
  590. if group is None:
  591. # return the first matching group
  592. return next(g for g in mobj.groups() if g is not None)
  593. else:
  594. return mobj.group(group)
  595. elif default is not NO_DEFAULT:
  596. return default
  597. elif fatal:
  598. raise RegexNotFoundError('Unable to extract %s' % _name)
  599. else:
  600. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  601. return None
  602. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  603. """
  604. Like _search_regex, but strips HTML tags and unescapes entities.
  605. """
  606. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  607. if res:
  608. return clean_html(res).strip()
  609. else:
  610. return res
  611. def _get_netrc_login_info(self, netrc_machine=None):
  612. username = None
  613. password = None
  614. netrc_machine = netrc_machine or self._NETRC_MACHINE
  615. if self._downloader.params.get('usenetrc', False):
  616. try:
  617. info = netrc.netrc().authenticators(netrc_machine)
  618. if info is not None:
  619. username = info[0]
  620. password = info[2]
  621. else:
  622. raise netrc.NetrcParseError(
  623. 'No authenticators for %s' % netrc_machine)
  624. except (IOError, netrc.NetrcParseError) as err:
  625. self._downloader.report_warning(
  626. 'parsing .netrc: %s' % error_to_compat_str(err))
  627. return username, password
  628. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  629. """
  630. Get the login info as (username, password)
  631. First look for the manually specified credentials using username_option
  632. and password_option as keys in params dictionary. If no such credentials
  633. available look in the netrc file using the netrc_machine or _NETRC_MACHINE
  634. value.
  635. If there's no info available, return (None, None)
  636. """
  637. if self._downloader is None:
  638. return (None, None)
  639. downloader_params = self._downloader.params
  640. # Attempt to use provided username and password or .netrc data
  641. if downloader_params.get(username_option) is not None:
  642. username = downloader_params[username_option]
  643. password = downloader_params[password_option]
  644. else:
  645. username, password = self._get_netrc_login_info(netrc_machine)
  646. return username, password
  647. def _get_tfa_info(self, note='two-factor verification code'):
  648. """
  649. Get the two-factor authentication info
  650. TODO - asking the user will be required for sms/phone verify
  651. currently just uses the command line option
  652. If there's no info available, return None
  653. """
  654. if self._downloader is None:
  655. return None
  656. downloader_params = self._downloader.params
  657. if downloader_params.get('twofactor') is not None:
  658. return downloader_params['twofactor']
  659. return compat_getpass('Type %s and press [Return]: ' % note)
  660. # Helper functions for extracting OpenGraph info
  661. @staticmethod
  662. def _og_regexes(prop):
  663. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  664. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  665. % {'prop': re.escape(prop)})
  666. template = r'<meta[^>]+?%s[^>]+?%s'
  667. return [
  668. template % (property_re, content_re),
  669. template % (content_re, property_re),
  670. ]
  671. @staticmethod
  672. def _meta_regex(prop):
  673. return r'''(?isx)<meta
  674. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  675. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  676. def _og_search_property(self, prop, html, name=None, **kargs):
  677. if not isinstance(prop, (list, tuple)):
  678. prop = [prop]
  679. if name is None:
  680. name = 'OpenGraph %s' % prop[0]
  681. og_regexes = []
  682. for p in prop:
  683. og_regexes.extend(self._og_regexes(p))
  684. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  685. if escaped is None:
  686. return None
  687. return unescapeHTML(escaped)
  688. def _og_search_thumbnail(self, html, **kargs):
  689. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  690. def _og_search_description(self, html, **kargs):
  691. return self._og_search_property('description', html, fatal=False, **kargs)
  692. def _og_search_title(self, html, **kargs):
  693. return self._og_search_property('title', html, **kargs)
  694. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  695. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  696. if secure:
  697. regexes = self._og_regexes('video:secure_url') + regexes
  698. return self._html_search_regex(regexes, html, name, **kargs)
  699. def _og_search_url(self, html, **kargs):
  700. return self._og_search_property('url', html, **kargs)
  701. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  702. if not isinstance(name, (list, tuple)):
  703. name = [name]
  704. if display_name is None:
  705. display_name = name[0]
  706. return self._html_search_regex(
  707. [self._meta_regex(n) for n in name],
  708. html, display_name, fatal=fatal, group='content', **kwargs)
  709. def _dc_search_uploader(self, html):
  710. return self._html_search_meta('dc.creator', html, 'uploader')
  711. def _rta_search(self, html):
  712. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  713. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  714. r' content="RTA-5042-1996-1400-1577-RTA"',
  715. html):
  716. return 18
  717. return 0
  718. def _media_rating_search(self, html):
  719. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  720. rating = self._html_search_meta('rating', html)
  721. if not rating:
  722. return None
  723. RATING_TABLE = {
  724. 'safe for kids': 0,
  725. 'general': 8,
  726. '14 years': 14,
  727. 'mature': 17,
  728. 'restricted': 19,
  729. }
  730. return RATING_TABLE.get(rating.lower())
  731. def _family_friendly_search(self, html):
  732. # See http://schema.org/VideoObject
  733. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  734. if not family_friendly:
  735. return None
  736. RATING_TABLE = {
  737. '1': 0,
  738. 'true': 0,
  739. '0': 18,
  740. 'false': 18,
  741. }
  742. return RATING_TABLE.get(family_friendly.lower())
  743. def _twitter_search_player(self, html):
  744. return self._html_search_meta('twitter:player', html,
  745. 'twitter card player')
  746. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  747. json_ld = self._search_regex(
  748. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  749. html, 'JSON-LD', group='json_ld', **kwargs)
  750. default = kwargs.get('default', NO_DEFAULT)
  751. if not json_ld:
  752. return default if default is not NO_DEFAULT else {}
  753. # JSON-LD may be malformed and thus `fatal` should be respected.
  754. # At the same time `default` may be passed that assumes `fatal=False`
  755. # for _search_regex. Let's simulate the same behavior here as well.
  756. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  757. return self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  758. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  759. if isinstance(json_ld, compat_str):
  760. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  761. if not json_ld:
  762. return {}
  763. info = {}
  764. if not isinstance(json_ld, (list, tuple, dict)):
  765. return info
  766. if isinstance(json_ld, dict):
  767. json_ld = [json_ld]
  768. for e in json_ld:
  769. if e.get('@context') == 'http://schema.org':
  770. item_type = e.get('@type')
  771. if expected_type is not None and expected_type != item_type:
  772. return info
  773. if item_type == 'TVEpisode':
  774. info.update({
  775. 'episode': unescapeHTML(e.get('name')),
  776. 'episode_number': int_or_none(e.get('episodeNumber')),
  777. 'description': unescapeHTML(e.get('description')),
  778. })
  779. part_of_season = e.get('partOfSeason')
  780. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  781. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  782. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  783. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  784. info['series'] = unescapeHTML(part_of_series.get('name'))
  785. elif item_type == 'Article':
  786. info.update({
  787. 'timestamp': parse_iso8601(e.get('datePublished')),
  788. 'title': unescapeHTML(e.get('headline')),
  789. 'description': unescapeHTML(e.get('articleBody')),
  790. })
  791. elif item_type == 'VideoObject':
  792. info.update({
  793. 'url': e.get('contentUrl'),
  794. 'title': unescapeHTML(e.get('name')),
  795. 'description': unescapeHTML(e.get('description')),
  796. 'thumbnail': e.get('thumbnailUrl') or e.get('thumbnailURL'),
  797. 'duration': parse_duration(e.get('duration')),
  798. 'timestamp': unified_timestamp(e.get('uploadDate')),
  799. 'filesize': float_or_none(e.get('contentSize')),
  800. 'tbr': int_or_none(e.get('bitrate')),
  801. 'width': int_or_none(e.get('width')),
  802. 'height': int_or_none(e.get('height')),
  803. })
  804. break
  805. return dict((k, v) for k, v in info.items() if v is not None)
  806. @staticmethod
  807. def _hidden_inputs(html):
  808. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  809. hidden_inputs = {}
  810. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  811. attrs = extract_attributes(input)
  812. if not input:
  813. continue
  814. if attrs.get('type') not in ('hidden', 'submit'):
  815. continue
  816. name = attrs.get('name') or attrs.get('id')
  817. value = attrs.get('value')
  818. if name and value is not None:
  819. hidden_inputs[name] = value
  820. return hidden_inputs
  821. def _form_hidden_inputs(self, form_id, html):
  822. form = self._search_regex(
  823. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  824. html, '%s form' % form_id, group='form')
  825. return self._hidden_inputs(form)
  826. def _sort_formats(self, formats, field_preference=None):
  827. if not formats:
  828. raise ExtractorError('No video formats found')
  829. for f in formats:
  830. # Automatically determine tbr when missing based on abr and vbr (improves
  831. # formats sorting in some cases)
  832. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  833. f['tbr'] = f['abr'] + f['vbr']
  834. def _formats_key(f):
  835. # TODO remove the following workaround
  836. from ..utils import determine_ext
  837. if not f.get('ext') and 'url' in f:
  838. f['ext'] = determine_ext(f['url'])
  839. if isinstance(field_preference, (list, tuple)):
  840. return tuple(
  841. f.get(field)
  842. if f.get(field) is not None
  843. else ('' if field == 'format_id' else -1)
  844. for field in field_preference)
  845. preference = f.get('preference')
  846. if preference is None:
  847. preference = 0
  848. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  849. preference -= 0.5
  850. protocol = f.get('protocol') or determine_protocol(f)
  851. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  852. if f.get('vcodec') == 'none': # audio only
  853. preference -= 50
  854. if self._downloader.params.get('prefer_free_formats'):
  855. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  856. else:
  857. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  858. ext_preference = 0
  859. try:
  860. audio_ext_preference = ORDER.index(f['ext'])
  861. except ValueError:
  862. audio_ext_preference = -1
  863. else:
  864. if f.get('acodec') == 'none': # video only
  865. preference -= 40
  866. if self._downloader.params.get('prefer_free_formats'):
  867. ORDER = ['flv', 'mp4', 'webm']
  868. else:
  869. ORDER = ['webm', 'flv', 'mp4']
  870. try:
  871. ext_preference = ORDER.index(f['ext'])
  872. except ValueError:
  873. ext_preference = -1
  874. audio_ext_preference = 0
  875. return (
  876. preference,
  877. f.get('language_preference') if f.get('language_preference') is not None else -1,
  878. f.get('quality') if f.get('quality') is not None else -1,
  879. f.get('tbr') if f.get('tbr') is not None else -1,
  880. f.get('filesize') if f.get('filesize') is not None else -1,
  881. f.get('vbr') if f.get('vbr') is not None else -1,
  882. f.get('height') if f.get('height') is not None else -1,
  883. f.get('width') if f.get('width') is not None else -1,
  884. proto_preference,
  885. ext_preference,
  886. f.get('abr') if f.get('abr') is not None else -1,
  887. audio_ext_preference,
  888. f.get('fps') if f.get('fps') is not None else -1,
  889. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  890. f.get('source_preference') if f.get('source_preference') is not None else -1,
  891. f.get('format_id') if f.get('format_id') is not None else '',
  892. )
  893. formats.sort(key=_formats_key)
  894. def _check_formats(self, formats, video_id):
  895. if formats:
  896. formats[:] = filter(
  897. lambda f: self._is_valid_url(
  898. f['url'], video_id,
  899. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  900. formats)
  901. @staticmethod
  902. def _remove_duplicate_formats(formats):
  903. format_urls = set()
  904. unique_formats = []
  905. for f in formats:
  906. if f['url'] not in format_urls:
  907. format_urls.add(f['url'])
  908. unique_formats.append(f)
  909. formats[:] = unique_formats
  910. def _is_valid_url(self, url, video_id, item='video'):
  911. url = self._proto_relative_url(url, scheme='http:')
  912. # For now assume non HTTP(S) URLs always valid
  913. if not (url.startswith('http://') or url.startswith('https://')):
  914. return True
  915. try:
  916. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  917. return True
  918. except ExtractorError as e:
  919. if isinstance(e.cause, compat_urllib_error.URLError):
  920. self.to_screen(
  921. '%s: %s URL is invalid, skipping' % (video_id, item))
  922. return False
  923. raise
  924. def http_scheme(self):
  925. """ Either "http:" or "https:", depending on the user's preferences """
  926. return (
  927. 'http:'
  928. if self._downloader.params.get('prefer_insecure', False)
  929. else 'https:')
  930. def _proto_relative_url(self, url, scheme=None):
  931. if url is None:
  932. return url
  933. if url.startswith('//'):
  934. if scheme is None:
  935. scheme = self.http_scheme()
  936. return scheme + url
  937. else:
  938. return url
  939. def _sleep(self, timeout, video_id, msg_template=None):
  940. if msg_template is None:
  941. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  942. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  943. self.to_screen(msg)
  944. time.sleep(timeout)
  945. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  946. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  947. fatal=True, m3u8_id=None):
  948. manifest = self._download_xml(
  949. manifest_url, video_id, 'Downloading f4m manifest',
  950. 'Unable to download f4m manifest',
  951. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  952. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  953. transform_source=transform_source,
  954. fatal=fatal)
  955. if manifest is False:
  956. return []
  957. return self._parse_f4m_formats(
  958. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  959. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  960. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  961. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  962. fatal=True, m3u8_id=None):
  963. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  964. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  965. if akamai_pv is not None and ';' in akamai_pv.text:
  966. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  967. if playerVerificationChallenge.strip() != '':
  968. return []
  969. formats = []
  970. manifest_version = '1.0'
  971. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  972. if not media_nodes:
  973. manifest_version = '2.0'
  974. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  975. # Remove unsupported DRM protected media from final formats
  976. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  977. media_nodes = remove_encrypted_media(media_nodes)
  978. if not media_nodes:
  979. return formats
  980. base_url = xpath_text(
  981. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  982. 'base URL', default=None)
  983. if base_url:
  984. base_url = base_url.strip()
  985. bootstrap_info = xpath_element(
  986. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  987. 'bootstrap info', default=None)
  988. vcodec = None
  989. mime_type = xpath_text(
  990. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  991. 'base URL', default=None)
  992. if mime_type and mime_type.startswith('audio/'):
  993. vcodec = 'none'
  994. for i, media_el in enumerate(media_nodes):
  995. tbr = int_or_none(media_el.attrib.get('bitrate'))
  996. width = int_or_none(media_el.attrib.get('width'))
  997. height = int_or_none(media_el.attrib.get('height'))
  998. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  999. # If <bootstrapInfo> is present, the specified f4m is a
  1000. # stream-level manifest, and only set-level manifests may refer to
  1001. # external resources. See section 11.4 and section 4 of F4M spec
  1002. if bootstrap_info is None:
  1003. media_url = None
  1004. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1005. if manifest_version == '2.0':
  1006. media_url = media_el.attrib.get('href')
  1007. if media_url is None:
  1008. media_url = media_el.attrib.get('url')
  1009. if not media_url:
  1010. continue
  1011. manifest_url = (
  1012. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1013. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1014. # If media_url is itself a f4m manifest do the recursive extraction
  1015. # since bitrates in parent manifest (this one) and media_url manifest
  1016. # may differ leading to inability to resolve the format by requested
  1017. # bitrate in f4m downloader
  1018. ext = determine_ext(manifest_url)
  1019. if ext == 'f4m':
  1020. f4m_formats = self._extract_f4m_formats(
  1021. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1022. transform_source=transform_source, fatal=fatal)
  1023. # Sometimes stream-level manifest contains single media entry that
  1024. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1025. # At the same time parent's media entry in set-level manifest may
  1026. # contain it. We will copy it from parent in such cases.
  1027. if len(f4m_formats) == 1:
  1028. f = f4m_formats[0]
  1029. f.update({
  1030. 'tbr': f.get('tbr') or tbr,
  1031. 'width': f.get('width') or width,
  1032. 'height': f.get('height') or height,
  1033. 'format_id': f.get('format_id') if not tbr else format_id,
  1034. 'vcodec': vcodec,
  1035. })
  1036. formats.extend(f4m_formats)
  1037. continue
  1038. elif ext == 'm3u8':
  1039. formats.extend(self._extract_m3u8_formats(
  1040. manifest_url, video_id, 'mp4', preference=preference,
  1041. m3u8_id=m3u8_id, fatal=fatal))
  1042. continue
  1043. formats.append({
  1044. 'format_id': format_id,
  1045. 'url': manifest_url,
  1046. 'manifest_url': manifest_url,
  1047. 'ext': 'flv' if bootstrap_info is not None else None,
  1048. 'tbr': tbr,
  1049. 'width': width,
  1050. 'height': height,
  1051. 'vcodec': vcodec,
  1052. 'preference': preference,
  1053. })
  1054. return formats
  1055. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1056. return {
  1057. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1058. 'url': m3u8_url,
  1059. 'ext': ext,
  1060. 'protocol': 'm3u8',
  1061. 'preference': preference - 100 if preference else -100,
  1062. 'resolution': 'multiple',
  1063. 'format_note': 'Quality selection URL',
  1064. }
  1065. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1066. entry_protocol='m3u8', preference=None,
  1067. m3u8_id=None, note=None, errnote=None,
  1068. fatal=True, live=False):
  1069. res = self._download_webpage_handle(
  1070. m3u8_url, video_id,
  1071. note=note or 'Downloading m3u8 information',
  1072. errnote=errnote or 'Failed to download m3u8 information',
  1073. fatal=fatal)
  1074. if res is False:
  1075. return []
  1076. m3u8_doc, urlh = res
  1077. m3u8_url = urlh.geturl()
  1078. formats = [self._m3u8_meta_format(m3u8_url, ext, preference, m3u8_id)]
  1079. format_url = lambda u: (
  1080. u
  1081. if re.match(r'^https?://', u)
  1082. else compat_urlparse.urljoin(m3u8_url, u))
  1083. # We should try extracting formats only from master playlists [1], i.e.
  1084. # playlists that describe available qualities. On the other hand media
  1085. # playlists [2] should be returned as is since they contain just the media
  1086. # without qualities renditions.
  1087. # Fortunately, master playlist can be easily distinguished from media
  1088. # playlist based on particular tags availability. As of [1, 2] master
  1089. # playlist tags MUST NOT appear in a media playist and vice versa.
  1090. # As of [3] #EXT-X-TARGETDURATION tag is REQUIRED for every media playlist
  1091. # and MUST NOT appear in master playlist thus we can clearly detect media
  1092. # playlist with this criterion.
  1093. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.4
  1094. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  1095. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  1096. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1097. return [{
  1098. 'url': m3u8_url,
  1099. 'format_id': m3u8_id,
  1100. 'ext': ext,
  1101. 'protocol': entry_protocol,
  1102. 'preference': preference,
  1103. }]
  1104. audio_in_video_stream = {}
  1105. last_info = {}
  1106. last_media = {}
  1107. for line in m3u8_doc.splitlines():
  1108. if line.startswith('#EXT-X-STREAM-INF:'):
  1109. last_info = parse_m3u8_attributes(line)
  1110. elif line.startswith('#EXT-X-MEDIA:'):
  1111. media = parse_m3u8_attributes(line)
  1112. media_type = media.get('TYPE')
  1113. if media_type in ('VIDEO', 'AUDIO'):
  1114. group_id = media.get('GROUP-ID')
  1115. media_url = media.get('URI')
  1116. if media_url:
  1117. format_id = []
  1118. for v in (group_id, media.get('NAME')):
  1119. if v:
  1120. format_id.append(v)
  1121. f = {
  1122. 'format_id': '-'.join(format_id),
  1123. 'url': format_url(media_url),
  1124. 'language': media.get('LANGUAGE'),
  1125. 'ext': ext,
  1126. 'protocol': entry_protocol,
  1127. 'preference': preference,
  1128. }
  1129. if media_type == 'AUDIO':
  1130. f['vcodec'] = 'none'
  1131. if group_id and not audio_in_video_stream.get(group_id):
  1132. audio_in_video_stream[group_id] = False
  1133. formats.append(f)
  1134. else:
  1135. # When there is no URI in EXT-X-MEDIA let this tag's
  1136. # data be used by regular URI lines below
  1137. last_media = media
  1138. if media_type == 'AUDIO' and group_id:
  1139. audio_in_video_stream[group_id] = True
  1140. elif line.startswith('#') or not line.strip():
  1141. continue
  1142. else:
  1143. tbr = int_or_none(last_info.get('AVERAGE-BANDWIDTH') or last_info.get('BANDWIDTH'), scale=1000)
  1144. format_id = []
  1145. if m3u8_id:
  1146. format_id.append(m3u8_id)
  1147. # Despite specification does not mention NAME attribute for
  1148. # EXT-X-STREAM-INF it still sometimes may be present
  1149. stream_name = last_info.get('NAME') or last_media.get('NAME')
  1150. # Bandwidth of live streams may differ over time thus making
  1151. # format_id unpredictable. So it's better to keep provided
  1152. # format_id intact.
  1153. if not live:
  1154. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1155. manifest_url = format_url(line.strip())
  1156. f = {
  1157. 'format_id': '-'.join(format_id),
  1158. 'url': manifest_url,
  1159. 'manifest_url': manifest_url,
  1160. 'tbr': tbr,
  1161. 'ext': ext,
  1162. 'fps': float_or_none(last_info.get('FRAME-RATE')),
  1163. 'protocol': entry_protocol,
  1164. 'preference': preference,
  1165. }
  1166. resolution = last_info.get('RESOLUTION')
  1167. if resolution:
  1168. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1169. if mobj:
  1170. f['width'] = int(mobj.group('width'))
  1171. f['height'] = int(mobj.group('height'))
  1172. # Unified Streaming Platform
  1173. mobj = re.search(
  1174. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1175. if mobj:
  1176. abr, vbr = mobj.groups()
  1177. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1178. f.update({
  1179. 'vbr': vbr,
  1180. 'abr': abr,
  1181. })
  1182. f.update(parse_codecs(last_info.get('CODECS')))
  1183. if audio_in_video_stream.get(last_info.get('AUDIO')) is False:
  1184. # TODO: update acodec for for audio only formats with the same GROUP-ID
  1185. f['acodec'] = 'none'
  1186. formats.append(f)
  1187. last_info = {}
  1188. last_media = {}
  1189. return formats
  1190. @staticmethod
  1191. def _xpath_ns(path, namespace=None):
  1192. if not namespace:
  1193. return path
  1194. out = []
  1195. for c in path.split('/'):
  1196. if not c or c == '.':
  1197. out.append(c)
  1198. else:
  1199. out.append('{%s}%s' % (namespace, c))
  1200. return '/'.join(out)
  1201. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1202. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1203. if smil is False:
  1204. assert not fatal
  1205. return []
  1206. namespace = self._parse_smil_namespace(smil)
  1207. return self._parse_smil_formats(
  1208. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1209. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1210. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1211. if smil is False:
  1212. return {}
  1213. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1214. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1215. return self._download_xml(
  1216. smil_url, video_id, 'Downloading SMIL file',
  1217. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1218. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1219. namespace = self._parse_smil_namespace(smil)
  1220. formats = self._parse_smil_formats(
  1221. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1222. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1223. video_id = os.path.splitext(url_basename(smil_url))[0]
  1224. title = None
  1225. description = None
  1226. upload_date = None
  1227. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1228. name = meta.attrib.get('name')
  1229. content = meta.attrib.get('content')
  1230. if not name or not content:
  1231. continue
  1232. if not title and name == 'title':
  1233. title = content
  1234. elif not description and name in ('description', 'abstract'):
  1235. description = content
  1236. elif not upload_date and name == 'date':
  1237. upload_date = unified_strdate(content)
  1238. thumbnails = [{
  1239. 'id': image.get('type'),
  1240. 'url': image.get('src'),
  1241. 'width': int_or_none(image.get('width')),
  1242. 'height': int_or_none(image.get('height')),
  1243. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1244. return {
  1245. 'id': video_id,
  1246. 'title': title or video_id,
  1247. 'description': description,
  1248. 'upload_date': upload_date,
  1249. 'thumbnails': thumbnails,
  1250. 'formats': formats,
  1251. 'subtitles': subtitles,
  1252. }
  1253. def _parse_smil_namespace(self, smil):
  1254. return self._search_regex(
  1255. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1256. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1257. base = smil_url
  1258. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1259. b = meta.get('base') or meta.get('httpBase')
  1260. if b:
  1261. base = b
  1262. break
  1263. formats = []
  1264. rtmp_count = 0
  1265. http_count = 0
  1266. m3u8_count = 0
  1267. srcs = []
  1268. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1269. for medium in media:
  1270. src = medium.get('src')
  1271. if not src or src in srcs:
  1272. continue
  1273. srcs.append(src)
  1274. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1275. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1276. width = int_or_none(medium.get('width'))
  1277. height = int_or_none(medium.get('height'))
  1278. proto = medium.get('proto')
  1279. ext = medium.get('ext')
  1280. src_ext = determine_ext(src)
  1281. streamer = medium.get('streamer') or base
  1282. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1283. rtmp_count += 1
  1284. formats.append({
  1285. 'url': streamer,
  1286. 'play_path': src,
  1287. 'ext': 'flv',
  1288. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1289. 'tbr': bitrate,
  1290. 'filesize': filesize,
  1291. 'width': width,
  1292. 'height': height,
  1293. })
  1294. if transform_rtmp_url:
  1295. streamer, src = transform_rtmp_url(streamer, src)
  1296. formats[-1].update({
  1297. 'url': streamer,
  1298. 'play_path': src,
  1299. })
  1300. continue
  1301. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1302. src_url = src_url.strip()
  1303. if proto == 'm3u8' or src_ext == 'm3u8':
  1304. m3u8_formats = self._extract_m3u8_formats(
  1305. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1306. if len(m3u8_formats) == 1:
  1307. m3u8_count += 1
  1308. m3u8_formats[0].update({
  1309. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1310. 'tbr': bitrate,
  1311. 'width': width,
  1312. 'height': height,
  1313. })
  1314. formats.extend(m3u8_formats)
  1315. continue
  1316. if src_ext == 'f4m':
  1317. f4m_url = src_url
  1318. if not f4m_params:
  1319. f4m_params = {
  1320. 'hdcore': '3.2.0',
  1321. 'plugin': 'flowplayer-3.2.0.1',
  1322. }
  1323. f4m_url += '&' if '?' in f4m_url else '?'
  1324. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1325. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1326. continue
  1327. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1328. http_count += 1
  1329. formats.append({
  1330. 'url': src_url,
  1331. 'ext': ext or src_ext or 'flv',
  1332. 'format_id': 'http-%d' % (bitrate or http_count),
  1333. 'tbr': bitrate,
  1334. 'filesize': filesize,
  1335. 'width': width,
  1336. 'height': height,
  1337. })
  1338. continue
  1339. return formats
  1340. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1341. urls = []
  1342. subtitles = {}
  1343. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1344. src = textstream.get('src')
  1345. if not src or src in urls:
  1346. continue
  1347. urls.append(src)
  1348. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1349. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1350. subtitles.setdefault(lang, []).append({
  1351. 'url': src,
  1352. 'ext': ext,
  1353. })
  1354. return subtitles
  1355. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1356. xspf = self._download_xml(
  1357. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1358. 'Unable to download xspf manifest', fatal=fatal)
  1359. if xspf is False:
  1360. return []
  1361. return self._parse_xspf(xspf, playlist_id)
  1362. def _parse_xspf(self, playlist, playlist_id):
  1363. NS_MAP = {
  1364. 'xspf': 'http://xspf.org/ns/0/',
  1365. 's1': 'http://static.streamone.nl/player/ns/0',
  1366. }
  1367. entries = []
  1368. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1369. title = xpath_text(
  1370. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1371. description = xpath_text(
  1372. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1373. thumbnail = xpath_text(
  1374. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1375. duration = float_or_none(
  1376. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1377. formats = [{
  1378. 'url': location.text,
  1379. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1380. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1381. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1382. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1383. self._sort_formats(formats)
  1384. entries.append({
  1385. 'id': playlist_id,
  1386. 'title': title,
  1387. 'description': description,
  1388. 'thumbnail': thumbnail,
  1389. 'duration': duration,
  1390. 'formats': formats,
  1391. })
  1392. return entries
  1393. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1394. res = self._download_webpage_handle(
  1395. mpd_url, video_id,
  1396. note=note or 'Downloading MPD manifest',
  1397. errnote=errnote or 'Failed to download MPD manifest',
  1398. fatal=fatal)
  1399. if res is False:
  1400. return []
  1401. mpd, urlh = res
  1402. mpd_base_url = base_url(urlh.geturl())
  1403. return self._parse_mpd_formats(
  1404. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url,
  1405. formats_dict=formats_dict, mpd_url=mpd_url)
  1406. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}, mpd_url=None):
  1407. """
  1408. Parse formats from MPD manifest.
  1409. References:
  1410. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  1411. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  1412. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  1413. """
  1414. if mpd_doc.get('type') == 'dynamic':
  1415. return []
  1416. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1417. def _add_ns(path):
  1418. return self._xpath_ns(path, namespace)
  1419. def is_drm_protected(element):
  1420. return element.find(_add_ns('ContentProtection')) is not None
  1421. def extract_multisegment_info(element, ms_parent_info):
  1422. ms_info = ms_parent_info.copy()
  1423. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  1424. # common attributes and elements. We will only extract relevant
  1425. # for us.
  1426. def extract_common(source):
  1427. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  1428. if segment_timeline is not None:
  1429. s_e = segment_timeline.findall(_add_ns('S'))
  1430. if s_e:
  1431. ms_info['total_number'] = 0
  1432. ms_info['s'] = []
  1433. for s in s_e:
  1434. r = int(s.get('r', 0))
  1435. ms_info['total_number'] += 1 + r
  1436. ms_info['s'].append({
  1437. 't': int(s.get('t', 0)),
  1438. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  1439. 'd': int(s.attrib['d']),
  1440. 'r': r,
  1441. })
  1442. start_number = source.get('startNumber')
  1443. if start_number:
  1444. ms_info['start_number'] = int(start_number)
  1445. timescale = source.get('timescale')
  1446. if timescale:
  1447. ms_info['timescale'] = int(timescale)
  1448. segment_duration = source.get('duration')
  1449. if segment_duration:
  1450. ms_info['segment_duration'] = int(segment_duration)
  1451. def extract_Initialization(source):
  1452. initialization = source.find(_add_ns('Initialization'))
  1453. if initialization is not None:
  1454. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1455. segment_list = element.find(_add_ns('SegmentList'))
  1456. if segment_list is not None:
  1457. extract_common(segment_list)
  1458. extract_Initialization(segment_list)
  1459. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1460. if segment_urls_e:
  1461. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1462. else:
  1463. segment_template = element.find(_add_ns('SegmentTemplate'))
  1464. if segment_template is not None:
  1465. extract_common(segment_template)
  1466. media = segment_template.get('media')
  1467. if media:
  1468. ms_info['media'] = media
  1469. initialization = segment_template.get('initialization')
  1470. if initialization:
  1471. ms_info['initialization'] = initialization
  1472. else:
  1473. extract_Initialization(segment_template)
  1474. return ms_info
  1475. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1476. formats = []
  1477. for period in mpd_doc.findall(_add_ns('Period')):
  1478. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1479. period_ms_info = extract_multisegment_info(period, {
  1480. 'start_number': 1,
  1481. 'timescale': 1,
  1482. })
  1483. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1484. if is_drm_protected(adaptation_set):
  1485. continue
  1486. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1487. for representation in adaptation_set.findall(_add_ns('Representation')):
  1488. if is_drm_protected(representation):
  1489. continue
  1490. representation_attrib = adaptation_set.attrib.copy()
  1491. representation_attrib.update(representation.attrib)
  1492. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  1493. mime_type = representation_attrib['mimeType']
  1494. content_type = mime_type.split('/')[0]
  1495. if content_type == 'text':
  1496. # TODO implement WebVTT downloading
  1497. pass
  1498. elif content_type == 'video' or content_type == 'audio':
  1499. base_url = ''
  1500. for element in (representation, adaptation_set, period, mpd_doc):
  1501. base_url_e = element.find(_add_ns('BaseURL'))
  1502. if base_url_e is not None:
  1503. base_url = base_url_e.text + base_url
  1504. if re.match(r'^https?://', base_url):
  1505. break
  1506. if mpd_base_url and not re.match(r'^https?://', base_url):
  1507. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1508. mpd_base_url += '/'
  1509. base_url = mpd_base_url + base_url
  1510. representation_id = representation_attrib.get('id')
  1511. lang = representation_attrib.get('lang')
  1512. url_el = representation.find(_add_ns('BaseURL'))
  1513. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1514. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  1515. f = {
  1516. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1517. 'url': base_url,
  1518. 'manifest_url': mpd_url,
  1519. 'ext': mimetype2ext(mime_type),
  1520. 'width': int_or_none(representation_attrib.get('width')),
  1521. 'height': int_or_none(representation_attrib.get('height')),
  1522. 'tbr': int_or_none(bandwidth, 1000),
  1523. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1524. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1525. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1526. 'format_note': 'DASH %s' % content_type,
  1527. 'filesize': filesize,
  1528. }
  1529. f.update(parse_codecs(representation_attrib.get('codecs')))
  1530. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1531. def prepare_template(template_name, identifiers):
  1532. t = representation_ms_info[template_name]
  1533. t = t.replace('$RepresentationID$', representation_id)
  1534. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  1535. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  1536. t.replace('$$', '$')
  1537. return t
  1538. # @initialization is a regular template like @media one
  1539. # so it should be handled just the same way (see
  1540. # https://github.com/rg3/youtube-dl/issues/11605)
  1541. if 'initialization' in representation_ms_info:
  1542. initialization_template = prepare_template(
  1543. 'initialization',
  1544. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  1545. # $Time$ shall not be included for @initialization thus
  1546. # only $Bandwidth$ remains
  1547. ('Bandwidth', ))
  1548. representation_ms_info['initialization_url'] = initialization_template % {
  1549. 'Bandwidth': bandwidth,
  1550. }
  1551. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  1552. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  1553. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  1554. # can't be used at the same time
  1555. if '%(Number' in media_template and 's' not in representation_ms_info:
  1556. segment_duration = None
  1557. if 'total_number' not in representation_ms_info and 'segment_duration':
  1558. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  1559. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1560. representation_ms_info['fragments'] = [{
  1561. 'url': media_template % {
  1562. 'Number': segment_number,
  1563. 'Bandwidth': bandwidth,
  1564. },
  1565. 'duration': segment_duration,
  1566. } for segment_number in range(
  1567. representation_ms_info['start_number'],
  1568. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1569. else:
  1570. # $Number*$ or $Time$ in media template with S list available
  1571. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  1572. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  1573. representation_ms_info['fragments'] = []
  1574. segment_time = 0
  1575. segment_d = None
  1576. segment_number = representation_ms_info['start_number']
  1577. def add_segment_url():
  1578. segment_url = media_template % {
  1579. 'Time': segment_time,
  1580. 'Bandwidth': bandwidth,
  1581. 'Number': segment_number,
  1582. }
  1583. representation_ms_info['fragments'].append({
  1584. 'url': segment_url,
  1585. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  1586. })
  1587. for num, s in enumerate(representation_ms_info['s']):
  1588. segment_time = s.get('t') or segment_time
  1589. segment_d = s['d']
  1590. add_segment_url()
  1591. segment_number += 1
  1592. for r in range(s.get('r', 0)):
  1593. segment_time += segment_d
  1594. add_segment_url()
  1595. segment_number += 1
  1596. segment_time += segment_d
  1597. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  1598. # No media template
  1599. # Example: https://www.youtube.com/watch?v=iXZV5uAYMJI
  1600. # or any YouTube dashsegments video
  1601. fragments = []
  1602. segment_index = 0
  1603. timescale = representation_ms_info['timescale']
  1604. for s in representation_ms_info['s']:
  1605. duration = float_or_none(s['d'], timescale)
  1606. for r in range(s.get('r', 0) + 1):
  1607. fragments.append({
  1608. 'url': representation_ms_info['segment_urls'][segment_index],
  1609. 'duration': duration,
  1610. })
  1611. segment_index += 1
  1612. representation_ms_info['fragments'] = fragments
  1613. # NB: MPD manifest may contain direct URLs to unfragmented media.
  1614. # No fragments key is present in this case.
  1615. if 'fragments' in representation_ms_info:
  1616. f.update({
  1617. 'fragments': [],
  1618. 'protocol': 'http_dash_segments',
  1619. })
  1620. if 'initialization_url' in representation_ms_info:
  1621. initialization_url = representation_ms_info['initialization_url']
  1622. if not f.get('url'):
  1623. f['url'] = initialization_url
  1624. f['fragments'].append({'url': initialization_url})
  1625. f['fragments'].extend(representation_ms_info['fragments'])
  1626. for fragment in f['fragments']:
  1627. fragment['url'] = urljoin(base_url, fragment['url'])
  1628. try:
  1629. existing_format = next(
  1630. fo for fo in formats
  1631. if fo['format_id'] == representation_id)
  1632. except StopIteration:
  1633. full_info = formats_dict.get(representation_id, {}).copy()
  1634. full_info.update(f)
  1635. formats.append(full_info)
  1636. else:
  1637. existing_format.update(f)
  1638. else:
  1639. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1640. return formats
  1641. def _extract_ism_formats(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True):
  1642. res = self._download_webpage_handle(
  1643. ism_url, video_id,
  1644. note=note or 'Downloading ISM manifest',
  1645. errnote=errnote or 'Failed to download ISM manifest',
  1646. fatal=fatal)
  1647. if res is False:
  1648. return []
  1649. ism, urlh = res
  1650. return self._parse_ism_formats(
  1651. compat_etree_fromstring(ism.encode('utf-8')), urlh.geturl(), ism_id)
  1652. def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
  1653. if ism_doc.get('IsLive') == 'TRUE' or ism_doc.find('Protection') is not None:
  1654. return []
  1655. duration = int(ism_doc.attrib['Duration'])
  1656. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  1657. formats = []
  1658. for stream in ism_doc.findall('StreamIndex'):
  1659. stream_type = stream.get('Type')
  1660. if stream_type not in ('video', 'audio'):
  1661. continue
  1662. url_pattern = stream.attrib['Url']
  1663. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  1664. stream_name = stream.get('Name')
  1665. for track in stream.findall('QualityLevel'):
  1666. fourcc = track.get('FourCC')
  1667. # TODO: add support for WVC1 and WMAP
  1668. if fourcc not in ('H264', 'AVC1', 'AACL'):
  1669. self.report_warning('%s is not a supported codec' % fourcc)
  1670. continue
  1671. tbr = int(track.attrib['Bitrate']) // 1000
  1672. width = int_or_none(track.get('MaxWidth'))
  1673. height = int_or_none(track.get('MaxHeight'))
  1674. sampling_rate = int_or_none(track.get('SamplingRate'))
  1675. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  1676. track_url_pattern = compat_urlparse.urljoin(ism_url, track_url_pattern)
  1677. fragments = []
  1678. fragment_ctx = {
  1679. 'time': 0,
  1680. }
  1681. stream_fragments = stream.findall('c')
  1682. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  1683. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  1684. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  1685. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  1686. if not fragment_ctx['duration']:
  1687. try:
  1688. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  1689. except IndexError:
  1690. next_fragment_time = duration
  1691. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  1692. for _ in range(fragment_repeat):
  1693. fragments.append({
  1694. 'url': re.sub(r'{start[ _]time}', compat_str(fragment_ctx['time']), track_url_pattern),
  1695. 'duration': fragment_ctx['duration'] / stream_timescale,
  1696. })
  1697. fragment_ctx['time'] += fragment_ctx['duration']
  1698. format_id = []
  1699. if ism_id:
  1700. format_id.append(ism_id)
  1701. if stream_name:
  1702. format_id.append(stream_name)
  1703. format_id.append(compat_str(tbr))
  1704. formats.append({
  1705. 'format_id': '-'.join(format_id),
  1706. 'url': ism_url,
  1707. 'manifest_url': ism_url,
  1708. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  1709. 'width': width,
  1710. 'height': height,
  1711. 'tbr': tbr,
  1712. 'asr': sampling_rate,
  1713. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  1714. 'acodec': 'none' if stream_type == 'video' else fourcc,
  1715. 'protocol': 'ism',
  1716. 'fragments': fragments,
  1717. '_download_params': {
  1718. 'duration': duration,
  1719. 'timescale': stream_timescale,
  1720. 'width': width or 0,
  1721. 'height': height or 0,
  1722. 'fourcc': fourcc,
  1723. 'codec_private_data': track.get('CodecPrivateData'),
  1724. 'sampling_rate': sampling_rate,
  1725. 'channels': int_or_none(track.get('Channels', 2)),
  1726. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  1727. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  1728. },
  1729. })
  1730. return formats
  1731. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8', mpd_id=None):
  1732. def absolute_url(video_url):
  1733. return compat_urlparse.urljoin(base_url, video_url)
  1734. def parse_content_type(content_type):
  1735. if not content_type:
  1736. return {}
  1737. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  1738. if ctr:
  1739. mimetype, codecs = ctr.groups()
  1740. f = parse_codecs(codecs)
  1741. f['ext'] = mimetype2ext(mimetype)
  1742. return f
  1743. return {}
  1744. def _media_formats(src, cur_media_type):
  1745. full_url = absolute_url(src)
  1746. ext = determine_ext(full_url)
  1747. if ext == 'm3u8':
  1748. is_plain_url = False
  1749. formats = self._extract_m3u8_formats(
  1750. full_url, video_id, ext='mp4',
  1751. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id)
  1752. elif ext == 'mpd':
  1753. is_plain_url = False
  1754. formats = self._extract_mpd_formats(
  1755. full_url, video_id, mpd_id=mpd_id)
  1756. else:
  1757. is_plain_url = True
  1758. formats = [{
  1759. 'url': full_url,
  1760. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  1761. }]
  1762. return is_plain_url, formats
  1763. entries = []
  1764. media_tags = [(media_tag, media_type, '')
  1765. for media_tag, media_type
  1766. in re.findall(r'(?s)(<(video|audio)[^>]*/>)', webpage)]
  1767. media_tags.extend(re.findall(r'(?s)(<(?P<tag>video|audio)[^>]*>)(.*?)</(?P=tag)>', webpage))
  1768. for media_tag, media_type, media_content in media_tags:
  1769. media_info = {
  1770. 'formats': [],
  1771. 'subtitles': {},
  1772. }
  1773. media_attributes = extract_attributes(media_tag)
  1774. src = media_attributes.get('src')
  1775. if src:
  1776. _, formats = _media_formats(src, media_type)
  1777. media_info['formats'].extend(formats)
  1778. media_info['thumbnail'] = media_attributes.get('poster')
  1779. if media_content:
  1780. for source_tag in re.findall(r'<source[^>]+>', media_content):
  1781. source_attributes = extract_attributes(source_tag)
  1782. src = source_attributes.get('src')
  1783. if not src:
  1784. continue
  1785. is_plain_url, formats = _media_formats(src, media_type)
  1786. if is_plain_url:
  1787. f = parse_content_type(source_attributes.get('type'))
  1788. f.update(formats[0])
  1789. media_info['formats'].append(f)
  1790. else:
  1791. media_info['formats'].extend(formats)
  1792. for track_tag in re.findall(r'<track[^>]+>', media_content):
  1793. track_attributes = extract_attributes(track_tag)
  1794. kind = track_attributes.get('kind')
  1795. if not kind or kind in ('subtitles', 'captions'):
  1796. src = track_attributes.get('src')
  1797. if not src:
  1798. continue
  1799. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  1800. media_info['subtitles'].setdefault(lang, []).append({
  1801. 'url': absolute_url(src),
  1802. })
  1803. if media_info['formats'] or media_info['subtitles']:
  1804. entries.append(media_info)
  1805. return entries
  1806. def _extract_akamai_formats(self, manifest_url, video_id, hosts={}):
  1807. formats = []
  1808. hdcore_sign = 'hdcore=3.7.0'
  1809. f4m_url = re.sub(r'(https?://[^/+])/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  1810. hds_host = hosts.get('hds')
  1811. if hds_host:
  1812. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  1813. if 'hdcore=' not in f4m_url:
  1814. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  1815. f4m_formats = self._extract_f4m_formats(
  1816. f4m_url, video_id, f4m_id='hds', fatal=False)
  1817. for entry in f4m_formats:
  1818. entry.update({'extra_param_to_segment_url': hdcore_sign})
  1819. formats.extend(f4m_formats)
  1820. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  1821. hls_host = hosts.get('hls')
  1822. if hls_host:
  1823. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  1824. formats.extend(self._extract_m3u8_formats(
  1825. m3u8_url, video_id, 'mp4', 'm3u8_native',
  1826. m3u8_id='hls', fatal=False))
  1827. return formats
  1828. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  1829. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  1830. url_base = self._search_regex(r'(?:https?|rtmp|rtsp)(://[^?]+)', url, 'format url')
  1831. http_base_url = 'http' + url_base
  1832. formats = []
  1833. if 'm3u8' not in skip_protocols:
  1834. formats.extend(self._extract_m3u8_formats(
  1835. http_base_url + '/playlist.m3u8', video_id, 'mp4',
  1836. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  1837. if 'f4m' not in skip_protocols:
  1838. formats.extend(self._extract_f4m_formats(
  1839. http_base_url + '/manifest.f4m',
  1840. video_id, f4m_id='hds', fatal=False))
  1841. if 'dash' not in skip_protocols:
  1842. formats.extend(self._extract_mpd_formats(
  1843. http_base_url + '/manifest.mpd',
  1844. video_id, mpd_id='dash', fatal=False))
  1845. if re.search(r'(?:/smil:|\.smil)', url_base):
  1846. if 'smil' not in skip_protocols:
  1847. rtmp_formats = self._extract_smil_formats(
  1848. http_base_url + '/jwplayer.smil',
  1849. video_id, fatal=False)
  1850. for rtmp_format in rtmp_formats:
  1851. rtsp_format = rtmp_format.copy()
  1852. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  1853. del rtsp_format['play_path']
  1854. del rtsp_format['ext']
  1855. rtsp_format.update({
  1856. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  1857. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  1858. 'protocol': 'rtsp',
  1859. })
  1860. formats.extend([rtmp_format, rtsp_format])
  1861. else:
  1862. for protocol in ('rtmp', 'rtsp'):
  1863. if protocol not in skip_protocols:
  1864. formats.append({
  1865. 'url': protocol + url_base,
  1866. 'format_id': protocol,
  1867. 'protocol': protocol,
  1868. })
  1869. return formats
  1870. def _live_title(self, name):
  1871. """ Generate the title for a live video """
  1872. now = datetime.datetime.now()
  1873. now_str = now.strftime('%Y-%m-%d %H:%M')
  1874. return name + ' ' + now_str
  1875. def _int(self, v, name, fatal=False, **kwargs):
  1876. res = int_or_none(v, **kwargs)
  1877. if 'get_attr' in kwargs:
  1878. print(getattr(v, kwargs['get_attr']))
  1879. if res is None:
  1880. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1881. if fatal:
  1882. raise ExtractorError(msg)
  1883. else:
  1884. self._downloader.report_warning(msg)
  1885. return res
  1886. def _float(self, v, name, fatal=False, **kwargs):
  1887. res = float_or_none(v, **kwargs)
  1888. if res is None:
  1889. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1890. if fatal:
  1891. raise ExtractorError(msg)
  1892. else:
  1893. self._downloader.report_warning(msg)
  1894. return res
  1895. def _set_cookie(self, domain, name, value, expire_time=None):
  1896. cookie = compat_cookiejar.Cookie(
  1897. 0, name, value, None, None, domain, None,
  1898. None, '/', True, False, expire_time, '', None, None, None)
  1899. self._downloader.cookiejar.set_cookie(cookie)
  1900. def _get_cookies(self, url):
  1901. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1902. req = sanitized_Request(url)
  1903. self._downloader.cookiejar.add_cookie_header(req)
  1904. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1905. def get_testcases(self, include_onlymatching=False):
  1906. t = getattr(self, '_TEST', None)
  1907. if t:
  1908. assert not hasattr(self, '_TESTS'), \
  1909. '%s has _TEST and _TESTS' % type(self).__name__
  1910. tests = [t]
  1911. else:
  1912. tests = getattr(self, '_TESTS', [])
  1913. for t in tests:
  1914. if not include_onlymatching and t.get('only_matching', False):
  1915. continue
  1916. t['name'] = type(self).__name__[:-len('IE')]
  1917. yield t
  1918. def is_suitable(self, age_limit):
  1919. """ Test whether the extractor is generally suitable for the given
  1920. age limit (i.e. pornographic sites are not, all others usually are) """
  1921. any_restricted = False
  1922. for tc in self.get_testcases(include_onlymatching=False):
  1923. if tc.get('playlist', []):
  1924. tc = tc['playlist'][0]
  1925. is_restricted = age_restricted(
  1926. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1927. if not is_restricted:
  1928. return True
  1929. any_restricted = any_restricted or is_restricted
  1930. return not any_restricted
  1931. def extract_subtitles(self, *args, **kwargs):
  1932. if (self._downloader.params.get('writesubtitles', False) or
  1933. self._downloader.params.get('listsubtitles')):
  1934. return self._get_subtitles(*args, **kwargs)
  1935. return {}
  1936. def _get_subtitles(self, *args, **kwargs):
  1937. raise NotImplementedError('This method must be implemented by subclasses')
  1938. @staticmethod
  1939. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1940. """ Merge subtitle items for one language. Items with duplicated URLs
  1941. will be dropped. """
  1942. list1_urls = set([item['url'] for item in subtitle_list1])
  1943. ret = list(subtitle_list1)
  1944. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1945. return ret
  1946. @classmethod
  1947. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1948. """ Merge two subtitle dictionaries, language by language. """
  1949. ret = dict(subtitle_dict1)
  1950. for lang in subtitle_dict2:
  1951. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1952. return ret
  1953. def extract_automatic_captions(self, *args, **kwargs):
  1954. if (self._downloader.params.get('writeautomaticsub', False) or
  1955. self._downloader.params.get('listsubtitles')):
  1956. return self._get_automatic_captions(*args, **kwargs)
  1957. return {}
  1958. def _get_automatic_captions(self, *args, **kwargs):
  1959. raise NotImplementedError('This method must be implemented by subclasses')
  1960. def mark_watched(self, *args, **kwargs):
  1961. if (self._downloader.params.get('mark_watched', False) and
  1962. (self._get_login_info()[0] is not None or
  1963. self._downloader.params.get('cookiefile') is not None)):
  1964. self._mark_watched(*args, **kwargs)
  1965. def _mark_watched(self, *args, **kwargs):
  1966. raise NotImplementedError('This method must be implemented by subclasses')
  1967. def geo_verification_headers(self):
  1968. headers = {}
  1969. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  1970. if geo_verification_proxy:
  1971. headers['Ytdl-request-proxy'] = geo_verification_proxy
  1972. return headers
  1973. def _generic_id(self, url):
  1974. return compat_urllib_parse_unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  1975. def _generic_title(self, url):
  1976. return compat_urllib_parse_unquote(os.path.splitext(url_basename(url))[0])
  1977. class SearchInfoExtractor(InfoExtractor):
  1978. """
  1979. Base class for paged search queries extractors.
  1980. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1981. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1982. """
  1983. @classmethod
  1984. def _make_valid_url(cls):
  1985. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1986. @classmethod
  1987. def suitable(cls, url):
  1988. return re.match(cls._make_valid_url(), url) is not None
  1989. def _real_extract(self, query):
  1990. mobj = re.match(self._make_valid_url(), query)
  1991. if mobj is None:
  1992. raise ExtractorError('Invalid search query "%s"' % query)
  1993. prefix = mobj.group('prefix')
  1994. query = mobj.group('query')
  1995. if prefix == '':
  1996. return self._get_n_results(query, 1)
  1997. elif prefix == 'all':
  1998. return self._get_n_results(query, self._MAX_RESULTS)
  1999. else:
  2000. n = int(prefix)
  2001. if n <= 0:
  2002. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  2003. elif n > self._MAX_RESULTS:
  2004. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  2005. n = self._MAX_RESULTS
  2006. return self._get_n_results(query, n)
  2007. def _get_n_results(self, query, n):
  2008. """Get a specified number of results for a query"""
  2009. raise NotImplementedError('This method must be implemented by subclasses')
  2010. @property
  2011. def SEARCH_KEY(self):
  2012. return self._SEARCH_KEY