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.

1906 lines
86 KiB

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