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.

1930 lines
87 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_netrc_login_info(self, netrc_machine=None):
  590. username = None
  591. password = None
  592. netrc_machine = netrc_machine or self._NETRC_MACHINE
  593. if self._downloader.params.get('usenetrc', False):
  594. try:
  595. info = netrc.netrc().authenticators(netrc_machine)
  596. if info is not None:
  597. username = info[0]
  598. password = info[2]
  599. else:
  600. raise netrc.NetrcParseError('No authenticators for %s' % netrc_machine)
  601. except (IOError, netrc.NetrcParseError) as err:
  602. self._downloader.report_warning('parsing .netrc: %s' % error_to_compat_str(err))
  603. return (username, password)
  604. def _get_login_info(self):
  605. """
  606. Get the login info as (username, password)
  607. It will look in the netrc file using the _NETRC_MACHINE value
  608. If there's no info available, return (None, None)
  609. """
  610. if self._downloader is None:
  611. return (None, None)
  612. username = None
  613. password = None
  614. downloader_params = self._downloader.params
  615. # Attempt to use provided username and password or .netrc data
  616. if downloader_params.get('username') is not None:
  617. username = downloader_params['username']
  618. password = downloader_params['password']
  619. else:
  620. username, password = self._get_netrc_login_info()
  621. return (username, password)
  622. def _get_tfa_info(self, note='two-factor verification code'):
  623. """
  624. Get the two-factor authentication info
  625. TODO - asking the user will be required for sms/phone verify
  626. currently just uses the command line option
  627. If there's no info available, return None
  628. """
  629. if self._downloader is None:
  630. return None
  631. downloader_params = self._downloader.params
  632. if downloader_params.get('twofactor') is not None:
  633. return downloader_params['twofactor']
  634. return compat_getpass('Type %s and press [Return]: ' % note)
  635. # Helper functions for extracting OpenGraph info
  636. @staticmethod
  637. def _og_regexes(prop):
  638. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  639. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  640. % {'prop': re.escape(prop)})
  641. template = r'<meta[^>]+?%s[^>]+?%s'
  642. return [
  643. template % (property_re, content_re),
  644. template % (content_re, property_re),
  645. ]
  646. @staticmethod
  647. def _meta_regex(prop):
  648. return r'''(?isx)<meta
  649. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  650. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  651. def _og_search_property(self, prop, html, name=None, **kargs):
  652. if not isinstance(prop, (list, tuple)):
  653. prop = [prop]
  654. if name is None:
  655. name = 'OpenGraph %s' % prop[0]
  656. og_regexes = []
  657. for p in prop:
  658. og_regexes.extend(self._og_regexes(p))
  659. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  660. if escaped is None:
  661. return None
  662. return unescapeHTML(escaped)
  663. def _og_search_thumbnail(self, html, **kargs):
  664. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  665. def _og_search_description(self, html, **kargs):
  666. return self._og_search_property('description', html, fatal=False, **kargs)
  667. def _og_search_title(self, html, **kargs):
  668. return self._og_search_property('title', html, **kargs)
  669. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  670. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  671. if secure:
  672. regexes = self._og_regexes('video:secure_url') + regexes
  673. return self._html_search_regex(regexes, html, name, **kargs)
  674. def _og_search_url(self, html, **kargs):
  675. return self._og_search_property('url', html, **kargs)
  676. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  677. if not isinstance(name, (list, tuple)):
  678. name = [name]
  679. if display_name is None:
  680. display_name = name[0]
  681. return self._html_search_regex(
  682. [self._meta_regex(n) for n in name],
  683. html, display_name, fatal=fatal, group='content', **kwargs)
  684. def _dc_search_uploader(self, html):
  685. return self._html_search_meta('dc.creator', html, 'uploader')
  686. def _rta_search(self, html):
  687. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  688. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  689. r' content="RTA-5042-1996-1400-1577-RTA"',
  690. html):
  691. return 18
  692. return 0
  693. def _media_rating_search(self, html):
  694. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  695. rating = self._html_search_meta('rating', html)
  696. if not rating:
  697. return None
  698. RATING_TABLE = {
  699. 'safe for kids': 0,
  700. 'general': 8,
  701. '14 years': 14,
  702. 'mature': 17,
  703. 'restricted': 19,
  704. }
  705. return RATING_TABLE.get(rating.lower())
  706. def _family_friendly_search(self, html):
  707. # See http://schema.org/VideoObject
  708. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  709. if not family_friendly:
  710. return None
  711. RATING_TABLE = {
  712. '1': 0,
  713. 'true': 0,
  714. '0': 18,
  715. 'false': 18,
  716. }
  717. return RATING_TABLE.get(family_friendly.lower())
  718. def _twitter_search_player(self, html):
  719. return self._html_search_meta('twitter:player', html,
  720. 'twitter card player')
  721. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  722. json_ld = self._search_regex(
  723. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  724. html, 'JSON-LD', group='json_ld', **kwargs)
  725. default = kwargs.get('default', NO_DEFAULT)
  726. if not json_ld:
  727. return default if default is not NO_DEFAULT else {}
  728. # JSON-LD may be malformed and thus `fatal` should be respected.
  729. # At the same time `default` may be passed that assumes `fatal=False`
  730. # for _search_regex. Let's simulate the same behavior here as well.
  731. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  732. return self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  733. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  734. if isinstance(json_ld, compat_str):
  735. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  736. if not json_ld:
  737. return {}
  738. info = {}
  739. if not isinstance(json_ld, (list, tuple, dict)):
  740. return info
  741. if isinstance(json_ld, dict):
  742. json_ld = [json_ld]
  743. for e in json_ld:
  744. if e.get('@context') == 'http://schema.org':
  745. item_type = e.get('@type')
  746. if expected_type is not None and expected_type != item_type:
  747. return info
  748. if item_type == 'TVEpisode':
  749. info.update({
  750. 'episode': unescapeHTML(e.get('name')),
  751. 'episode_number': int_or_none(e.get('episodeNumber')),
  752. 'description': unescapeHTML(e.get('description')),
  753. })
  754. part_of_season = e.get('partOfSeason')
  755. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  756. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  757. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  758. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  759. info['series'] = unescapeHTML(part_of_series.get('name'))
  760. elif item_type == 'Article':
  761. info.update({
  762. 'timestamp': parse_iso8601(e.get('datePublished')),
  763. 'title': unescapeHTML(e.get('headline')),
  764. 'description': unescapeHTML(e.get('articleBody')),
  765. })
  766. elif item_type == 'VideoObject':
  767. info.update({
  768. 'url': e.get('contentUrl'),
  769. 'title': unescapeHTML(e.get('name')),
  770. 'description': unescapeHTML(e.get('description')),
  771. 'thumbnail': e.get('thumbnailUrl'),
  772. 'duration': parse_duration(e.get('duration')),
  773. 'timestamp': unified_timestamp(e.get('uploadDate')),
  774. 'filesize': float_or_none(e.get('contentSize')),
  775. 'tbr': int_or_none(e.get('bitrate')),
  776. 'width': int_or_none(e.get('width')),
  777. 'height': int_or_none(e.get('height')),
  778. })
  779. break
  780. return dict((k, v) for k, v in info.items() if v is not None)
  781. @staticmethod
  782. def _hidden_inputs(html):
  783. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  784. hidden_inputs = {}
  785. for input in re.findall(r'(?i)<input([^>]+)>', html):
  786. if not re.search(r'type=(["\'])(?:hidden|submit)\1', input):
  787. continue
  788. name = re.search(r'(?:name|id)=(["\'])(?P<value>.+?)\1', input)
  789. if not name:
  790. continue
  791. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  792. if not value:
  793. continue
  794. hidden_inputs[name.group('value')] = value.group('value')
  795. return hidden_inputs
  796. def _form_hidden_inputs(self, form_id, html):
  797. form = self._search_regex(
  798. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  799. html, '%s form' % form_id, group='form')
  800. return self._hidden_inputs(form)
  801. def _sort_formats(self, formats, field_preference=None):
  802. if not formats:
  803. raise ExtractorError('No video formats found')
  804. for f in formats:
  805. # Automatically determine tbr when missing based on abr and vbr (improves
  806. # formats sorting in some cases)
  807. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  808. f['tbr'] = f['abr'] + f['vbr']
  809. def _formats_key(f):
  810. # TODO remove the following workaround
  811. from ..utils import determine_ext
  812. if not f.get('ext') and 'url' in f:
  813. f['ext'] = determine_ext(f['url'])
  814. if isinstance(field_preference, (list, tuple)):
  815. return tuple(
  816. f.get(field)
  817. if f.get(field) is not None
  818. else ('' if field == 'format_id' else -1)
  819. for field in field_preference)
  820. preference = f.get('preference')
  821. if preference is None:
  822. preference = 0
  823. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  824. preference -= 0.5
  825. protocol = f.get('protocol') or determine_protocol(f)
  826. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  827. if f.get('vcodec') == 'none': # audio only
  828. preference -= 50
  829. if self._downloader.params.get('prefer_free_formats'):
  830. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  831. else:
  832. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  833. ext_preference = 0
  834. try:
  835. audio_ext_preference = ORDER.index(f['ext'])
  836. except ValueError:
  837. audio_ext_preference = -1
  838. else:
  839. if f.get('acodec') == 'none': # video only
  840. preference -= 40
  841. if self._downloader.params.get('prefer_free_formats'):
  842. ORDER = ['flv', 'mp4', 'webm']
  843. else:
  844. ORDER = ['webm', 'flv', 'mp4']
  845. try:
  846. ext_preference = ORDER.index(f['ext'])
  847. except ValueError:
  848. ext_preference = -1
  849. audio_ext_preference = 0
  850. return (
  851. preference,
  852. f.get('language_preference') if f.get('language_preference') is not None else -1,
  853. f.get('quality') if f.get('quality') is not None else -1,
  854. f.get('tbr') if f.get('tbr') is not None else -1,
  855. f.get('filesize') if f.get('filesize') is not None else -1,
  856. f.get('vbr') if f.get('vbr') is not None else -1,
  857. f.get('height') if f.get('height') is not None else -1,
  858. f.get('width') if f.get('width') is not None else -1,
  859. proto_preference,
  860. ext_preference,
  861. f.get('abr') if f.get('abr') is not None else -1,
  862. audio_ext_preference,
  863. f.get('fps') if f.get('fps') is not None else -1,
  864. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  865. f.get('source_preference') if f.get('source_preference') is not None else -1,
  866. f.get('format_id') if f.get('format_id') is not None else '',
  867. )
  868. formats.sort(key=_formats_key)
  869. def _check_formats(self, formats, video_id):
  870. if formats:
  871. formats[:] = filter(
  872. lambda f: self._is_valid_url(
  873. f['url'], video_id,
  874. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  875. formats)
  876. @staticmethod
  877. def _remove_duplicate_formats(formats):
  878. format_urls = set()
  879. unique_formats = []
  880. for f in formats:
  881. if f['url'] not in format_urls:
  882. format_urls.add(f['url'])
  883. unique_formats.append(f)
  884. formats[:] = unique_formats
  885. def _is_valid_url(self, url, video_id, item='video'):
  886. url = self._proto_relative_url(url, scheme='http:')
  887. # For now assume non HTTP(S) URLs always valid
  888. if not (url.startswith('http://') or url.startswith('https://')):
  889. return True
  890. try:
  891. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  892. return True
  893. except ExtractorError as e:
  894. if isinstance(e.cause, compat_urllib_error.URLError):
  895. self.to_screen(
  896. '%s: %s URL is invalid, skipping' % (video_id, item))
  897. return False
  898. raise
  899. def http_scheme(self):
  900. """ Either "http:" or "https:", depending on the user's preferences """
  901. return (
  902. 'http:'
  903. if self._downloader.params.get('prefer_insecure', False)
  904. else 'https:')
  905. def _proto_relative_url(self, url, scheme=None):
  906. if url is None:
  907. return url
  908. if url.startswith('//'):
  909. if scheme is None:
  910. scheme = self.http_scheme()
  911. return scheme + url
  912. else:
  913. return url
  914. def _sleep(self, timeout, video_id, msg_template=None):
  915. if msg_template is None:
  916. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  917. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  918. self.to_screen(msg)
  919. time.sleep(timeout)
  920. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  921. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  922. fatal=True, m3u8_id=None):
  923. manifest = self._download_xml(
  924. manifest_url, video_id, 'Downloading f4m manifest',
  925. 'Unable to download f4m manifest',
  926. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  927. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  928. transform_source=transform_source,
  929. fatal=fatal)
  930. if manifest is False:
  931. return []
  932. return self._parse_f4m_formats(
  933. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  934. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  935. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  936. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  937. fatal=True, m3u8_id=None):
  938. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  939. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  940. if akamai_pv is not None and ';' in akamai_pv.text:
  941. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  942. if playerVerificationChallenge.strip() != '':
  943. return []
  944. formats = []
  945. manifest_version = '1.0'
  946. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  947. if not media_nodes:
  948. manifest_version = '2.0'
  949. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  950. # Remove unsupported DRM protected media from final formats
  951. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  952. media_nodes = remove_encrypted_media(media_nodes)
  953. if not media_nodes:
  954. return formats
  955. base_url = xpath_text(
  956. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  957. 'base URL', default=None)
  958. if base_url:
  959. base_url = base_url.strip()
  960. bootstrap_info = xpath_element(
  961. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  962. 'bootstrap info', default=None)
  963. for i, media_el in enumerate(media_nodes):
  964. tbr = int_or_none(media_el.attrib.get('bitrate'))
  965. width = int_or_none(media_el.attrib.get('width'))
  966. height = int_or_none(media_el.attrib.get('height'))
  967. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  968. # If <bootstrapInfo> is present, the specified f4m is a
  969. # stream-level manifest, and only set-level manifests may refer to
  970. # external resources. See section 11.4 and section 4 of F4M spec
  971. if bootstrap_info is None:
  972. media_url = None
  973. # @href is introduced in 2.0, see section 11.6 of F4M spec
  974. if manifest_version == '2.0':
  975. media_url = media_el.attrib.get('href')
  976. if media_url is None:
  977. media_url = media_el.attrib.get('url')
  978. if not media_url:
  979. continue
  980. manifest_url = (
  981. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  982. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  983. # If media_url is itself a f4m manifest do the recursive extraction
  984. # since bitrates in parent manifest (this one) and media_url manifest
  985. # may differ leading to inability to resolve the format by requested
  986. # bitrate in f4m downloader
  987. ext = determine_ext(manifest_url)
  988. if ext == 'f4m':
  989. f4m_formats = self._extract_f4m_formats(
  990. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  991. transform_source=transform_source, fatal=fatal)
  992. # Sometimes stream-level manifest contains single media entry that
  993. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  994. # At the same time parent's media entry in set-level manifest may
  995. # contain it. We will copy it from parent in such cases.
  996. if len(f4m_formats) == 1:
  997. f = f4m_formats[0]
  998. f.update({
  999. 'tbr': f.get('tbr') or tbr,
  1000. 'width': f.get('width') or width,
  1001. 'height': f.get('height') or height,
  1002. 'format_id': f.get('format_id') if not tbr else format_id,
  1003. })
  1004. formats.extend(f4m_formats)
  1005. continue
  1006. elif ext == 'm3u8':
  1007. formats.extend(self._extract_m3u8_formats(
  1008. manifest_url, video_id, 'mp4', preference=preference,
  1009. m3u8_id=m3u8_id, fatal=fatal))
  1010. continue
  1011. formats.append({
  1012. 'format_id': format_id,
  1013. 'url': manifest_url,
  1014. 'ext': 'flv' if bootstrap_info is not None else None,
  1015. 'tbr': tbr,
  1016. 'width': width,
  1017. 'height': height,
  1018. 'preference': preference,
  1019. })
  1020. return formats
  1021. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1022. return {
  1023. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1024. 'url': m3u8_url,
  1025. 'ext': ext,
  1026. 'protocol': 'm3u8',
  1027. 'preference': preference - 100 if preference else -100,
  1028. 'resolution': 'multiple',
  1029. 'format_note': 'Quality selection URL',
  1030. }
  1031. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1032. entry_protocol='m3u8', preference=None,
  1033. m3u8_id=None, note=None, errnote=None,
  1034. fatal=True, live=False):
  1035. formats = [self._m3u8_meta_format(m3u8_url, ext, preference, m3u8_id)]
  1036. format_url = lambda u: (
  1037. u
  1038. if re.match(r'^https?://', u)
  1039. else compat_urlparse.urljoin(m3u8_url, u))
  1040. res = self._download_webpage_handle(
  1041. m3u8_url, video_id,
  1042. note=note or 'Downloading m3u8 information',
  1043. errnote=errnote or 'Failed to download m3u8 information',
  1044. fatal=fatal)
  1045. if res is False:
  1046. return []
  1047. m3u8_doc, urlh = res
  1048. m3u8_url = urlh.geturl()
  1049. # We should try extracting formats only from master playlists [1], i.e.
  1050. # playlists that describe available qualities. On the other hand media
  1051. # playlists [2] should be returned as is since they contain just the media
  1052. # without qualities renditions.
  1053. # Fortunately, master playlist can be easily distinguished from media
  1054. # playlist based on particular tags availability. As of [1, 2] master
  1055. # playlist tags MUST NOT appear in a media playist and vice versa.
  1056. # As of [3] #EXT-X-TARGETDURATION tag is REQUIRED for every media playlist
  1057. # and MUST NOT appear in master playlist thus we can clearly detect media
  1058. # playlist with this criterion.
  1059. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.4
  1060. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  1061. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  1062. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1063. return [{
  1064. 'url': m3u8_url,
  1065. 'format_id': m3u8_id,
  1066. 'ext': ext,
  1067. 'protocol': entry_protocol,
  1068. 'preference': preference,
  1069. }]
  1070. last_info = None
  1071. last_media = None
  1072. for line in m3u8_doc.splitlines():
  1073. if line.startswith('#EXT-X-STREAM-INF:'):
  1074. last_info = parse_m3u8_attributes(line)
  1075. elif line.startswith('#EXT-X-MEDIA:'):
  1076. last_media = parse_m3u8_attributes(line)
  1077. elif line.startswith('#') or not line.strip():
  1078. continue
  1079. else:
  1080. if last_info is None:
  1081. formats.append({'url': format_url(line)})
  1082. continue
  1083. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  1084. format_id = []
  1085. if m3u8_id:
  1086. format_id.append(m3u8_id)
  1087. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') not in ('SUBTITLES', 'CLOSED-CAPTIONS') else None
  1088. # Despite specification does not mention NAME attribute for
  1089. # EXT-X-STREAM-INF it still sometimes may be present
  1090. stream_name = last_info.get('NAME') or last_media_name
  1091. # Bandwidth of live streams may differ over time thus making
  1092. # format_id unpredictable. So it's better to keep provided
  1093. # format_id intact.
  1094. if not live:
  1095. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1096. f = {
  1097. 'format_id': '-'.join(format_id),
  1098. 'url': format_url(line.strip()),
  1099. 'tbr': tbr,
  1100. 'ext': ext,
  1101. 'fps': float_or_none(last_info.get('FRAME-RATE')),
  1102. 'protocol': entry_protocol,
  1103. 'preference': preference,
  1104. }
  1105. resolution = last_info.get('RESOLUTION')
  1106. if resolution:
  1107. width_str, height_str = resolution.split('x')
  1108. f['width'] = int(width_str)
  1109. f['height'] = int(height_str)
  1110. # Unified Streaming Platform
  1111. mobj = re.search(
  1112. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1113. if mobj:
  1114. abr, vbr = mobj.groups()
  1115. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1116. f.update({
  1117. 'vbr': vbr,
  1118. 'abr': abr,
  1119. })
  1120. f.update(parse_codecs(last_info.get('CODECS')))
  1121. if last_media is not None:
  1122. f['m3u8_media'] = last_media
  1123. last_media = None
  1124. formats.append(f)
  1125. last_info = {}
  1126. return formats
  1127. @staticmethod
  1128. def _xpath_ns(path, namespace=None):
  1129. if not namespace:
  1130. return path
  1131. out = []
  1132. for c in path.split('/'):
  1133. if not c or c == '.':
  1134. out.append(c)
  1135. else:
  1136. out.append('{%s}%s' % (namespace, c))
  1137. return '/'.join(out)
  1138. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1139. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1140. if smil is False:
  1141. assert not fatal
  1142. return []
  1143. namespace = self._parse_smil_namespace(smil)
  1144. return self._parse_smil_formats(
  1145. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1146. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1147. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1148. if smil is False:
  1149. return {}
  1150. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1151. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1152. return self._download_xml(
  1153. smil_url, video_id, 'Downloading SMIL file',
  1154. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1155. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1156. namespace = self._parse_smil_namespace(smil)
  1157. formats = self._parse_smil_formats(
  1158. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1159. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1160. video_id = os.path.splitext(url_basename(smil_url))[0]
  1161. title = None
  1162. description = None
  1163. upload_date = None
  1164. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1165. name = meta.attrib.get('name')
  1166. content = meta.attrib.get('content')
  1167. if not name or not content:
  1168. continue
  1169. if not title and name == 'title':
  1170. title = content
  1171. elif not description and name in ('description', 'abstract'):
  1172. description = content
  1173. elif not upload_date and name == 'date':
  1174. upload_date = unified_strdate(content)
  1175. thumbnails = [{
  1176. 'id': image.get('type'),
  1177. 'url': image.get('src'),
  1178. 'width': int_or_none(image.get('width')),
  1179. 'height': int_or_none(image.get('height')),
  1180. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1181. return {
  1182. 'id': video_id,
  1183. 'title': title or video_id,
  1184. 'description': description,
  1185. 'upload_date': upload_date,
  1186. 'thumbnails': thumbnails,
  1187. 'formats': formats,
  1188. 'subtitles': subtitles,
  1189. }
  1190. def _parse_smil_namespace(self, smil):
  1191. return self._search_regex(
  1192. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1193. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1194. base = smil_url
  1195. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1196. b = meta.get('base') or meta.get('httpBase')
  1197. if b:
  1198. base = b
  1199. break
  1200. formats = []
  1201. rtmp_count = 0
  1202. http_count = 0
  1203. m3u8_count = 0
  1204. srcs = []
  1205. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1206. for medium in media:
  1207. src = medium.get('src')
  1208. if not src or src in srcs:
  1209. continue
  1210. srcs.append(src)
  1211. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1212. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1213. width = int_or_none(medium.get('width'))
  1214. height = int_or_none(medium.get('height'))
  1215. proto = medium.get('proto')
  1216. ext = medium.get('ext')
  1217. src_ext = determine_ext(src)
  1218. streamer = medium.get('streamer') or base
  1219. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1220. rtmp_count += 1
  1221. formats.append({
  1222. 'url': streamer,
  1223. 'play_path': src,
  1224. 'ext': 'flv',
  1225. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1226. 'tbr': bitrate,
  1227. 'filesize': filesize,
  1228. 'width': width,
  1229. 'height': height,
  1230. })
  1231. if transform_rtmp_url:
  1232. streamer, src = transform_rtmp_url(streamer, src)
  1233. formats[-1].update({
  1234. 'url': streamer,
  1235. 'play_path': src,
  1236. })
  1237. continue
  1238. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1239. src_url = src_url.strip()
  1240. if proto == 'm3u8' or src_ext == 'm3u8':
  1241. m3u8_formats = self._extract_m3u8_formats(
  1242. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1243. if len(m3u8_formats) == 1:
  1244. m3u8_count += 1
  1245. m3u8_formats[0].update({
  1246. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1247. 'tbr': bitrate,
  1248. 'width': width,
  1249. 'height': height,
  1250. })
  1251. formats.extend(m3u8_formats)
  1252. continue
  1253. if src_ext == 'f4m':
  1254. f4m_url = src_url
  1255. if not f4m_params:
  1256. f4m_params = {
  1257. 'hdcore': '3.2.0',
  1258. 'plugin': 'flowplayer-3.2.0.1',
  1259. }
  1260. f4m_url += '&' if '?' in f4m_url else '?'
  1261. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1262. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1263. continue
  1264. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1265. http_count += 1
  1266. formats.append({
  1267. 'url': src_url,
  1268. 'ext': ext or src_ext or 'flv',
  1269. 'format_id': 'http-%d' % (bitrate or http_count),
  1270. 'tbr': bitrate,
  1271. 'filesize': filesize,
  1272. 'width': width,
  1273. 'height': height,
  1274. })
  1275. continue
  1276. return formats
  1277. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1278. urls = []
  1279. subtitles = {}
  1280. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1281. src = textstream.get('src')
  1282. if not src or src in urls:
  1283. continue
  1284. urls.append(src)
  1285. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1286. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1287. subtitles.setdefault(lang, []).append({
  1288. 'url': src,
  1289. 'ext': ext,
  1290. })
  1291. return subtitles
  1292. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1293. xspf = self._download_xml(
  1294. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1295. 'Unable to download xspf manifest', fatal=fatal)
  1296. if xspf is False:
  1297. return []
  1298. return self._parse_xspf(xspf, playlist_id)
  1299. def _parse_xspf(self, playlist, playlist_id):
  1300. NS_MAP = {
  1301. 'xspf': 'http://xspf.org/ns/0/',
  1302. 's1': 'http://static.streamone.nl/player/ns/0',
  1303. }
  1304. entries = []
  1305. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1306. title = xpath_text(
  1307. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1308. description = xpath_text(
  1309. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1310. thumbnail = xpath_text(
  1311. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1312. duration = float_or_none(
  1313. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1314. formats = [{
  1315. 'url': location.text,
  1316. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1317. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1318. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1319. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1320. self._sort_formats(formats)
  1321. entries.append({
  1322. 'id': playlist_id,
  1323. 'title': title,
  1324. 'description': description,
  1325. 'thumbnail': thumbnail,
  1326. 'duration': duration,
  1327. 'formats': formats,
  1328. })
  1329. return entries
  1330. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1331. res = self._download_webpage_handle(
  1332. mpd_url, video_id,
  1333. note=note or 'Downloading MPD manifest',
  1334. errnote=errnote or 'Failed to download MPD manifest',
  1335. fatal=fatal)
  1336. if res is False:
  1337. return []
  1338. mpd, urlh = res
  1339. mpd_base_url = re.match(r'https?://.+/', urlh.geturl()).group()
  1340. return self._parse_mpd_formats(
  1341. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url, formats_dict=formats_dict)
  1342. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}):
  1343. """
  1344. Parse formats from MPD manifest.
  1345. References:
  1346. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  1347. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  1348. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  1349. """
  1350. if mpd_doc.get('type') == 'dynamic':
  1351. return []
  1352. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1353. def _add_ns(path):
  1354. return self._xpath_ns(path, namespace)
  1355. def is_drm_protected(element):
  1356. return element.find(_add_ns('ContentProtection')) is not None
  1357. def extract_multisegment_info(element, ms_parent_info):
  1358. ms_info = ms_parent_info.copy()
  1359. segment_list = element.find(_add_ns('SegmentList'))
  1360. if segment_list is not None:
  1361. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1362. if segment_urls_e:
  1363. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1364. initialization = segment_list.find(_add_ns('Initialization'))
  1365. if initialization is not None:
  1366. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1367. else:
  1368. segment_template = element.find(_add_ns('SegmentTemplate'))
  1369. if segment_template is not None:
  1370. start_number = segment_template.get('startNumber')
  1371. if start_number:
  1372. ms_info['start_number'] = int(start_number)
  1373. segment_timeline = segment_template.find(_add_ns('SegmentTimeline'))
  1374. if segment_timeline is not None:
  1375. s_e = segment_timeline.findall(_add_ns('S'))
  1376. if s_e:
  1377. ms_info['total_number'] = 0
  1378. ms_info['s'] = []
  1379. for s in s_e:
  1380. r = int(s.get('r', 0))
  1381. ms_info['total_number'] += 1 + r
  1382. ms_info['s'].append({
  1383. 't': int(s.get('t', 0)),
  1384. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  1385. 'd': int(s.attrib['d']),
  1386. 'r': r,
  1387. })
  1388. else:
  1389. timescale = segment_template.get('timescale')
  1390. if timescale:
  1391. ms_info['timescale'] = int(timescale)
  1392. segment_duration = segment_template.get('duration')
  1393. if segment_duration:
  1394. ms_info['segment_duration'] = int(segment_duration)
  1395. media_template = segment_template.get('media')
  1396. if media_template:
  1397. ms_info['media_template'] = media_template
  1398. initialization = segment_template.get('initialization')
  1399. if initialization:
  1400. ms_info['initialization_url'] = initialization
  1401. else:
  1402. initialization = segment_template.find(_add_ns('Initialization'))
  1403. if initialization is not None:
  1404. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1405. return ms_info
  1406. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1407. formats = []
  1408. for period in mpd_doc.findall(_add_ns('Period')):
  1409. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1410. period_ms_info = extract_multisegment_info(period, {
  1411. 'start_number': 1,
  1412. 'timescale': 1,
  1413. })
  1414. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1415. if is_drm_protected(adaptation_set):
  1416. continue
  1417. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1418. for representation in adaptation_set.findall(_add_ns('Representation')):
  1419. if is_drm_protected(representation):
  1420. continue
  1421. representation_attrib = adaptation_set.attrib.copy()
  1422. representation_attrib.update(representation.attrib)
  1423. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  1424. mime_type = representation_attrib['mimeType']
  1425. content_type = mime_type.split('/')[0]
  1426. if content_type == 'text':
  1427. # TODO implement WebVTT downloading
  1428. pass
  1429. elif content_type == 'video' or content_type == 'audio':
  1430. base_url = ''
  1431. for element in (representation, adaptation_set, period, mpd_doc):
  1432. base_url_e = element.find(_add_ns('BaseURL'))
  1433. if base_url_e is not None:
  1434. base_url = base_url_e.text + base_url
  1435. if re.match(r'^https?://', base_url):
  1436. break
  1437. if mpd_base_url and not re.match(r'^https?://', base_url):
  1438. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1439. mpd_base_url += '/'
  1440. base_url = mpd_base_url + base_url
  1441. representation_id = representation_attrib.get('id')
  1442. lang = representation_attrib.get('lang')
  1443. url_el = representation.find(_add_ns('BaseURL'))
  1444. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1445. f = {
  1446. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1447. 'url': base_url,
  1448. 'ext': mimetype2ext(mime_type),
  1449. 'width': int_or_none(representation_attrib.get('width')),
  1450. 'height': int_or_none(representation_attrib.get('height')),
  1451. 'tbr': int_or_none(representation_attrib.get('bandwidth'), 1000),
  1452. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1453. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1454. 'vcodec': 'none' if content_type == 'audio' else representation_attrib.get('codecs'),
  1455. 'acodec': 'none' if content_type == 'video' else representation_attrib.get('codecs'),
  1456. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1457. 'format_note': 'DASH %s' % content_type,
  1458. 'filesize': filesize,
  1459. }
  1460. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1461. if 'segment_urls' not in representation_ms_info and 'media_template' in representation_ms_info:
  1462. if 'total_number' not in representation_ms_info and 'segment_duration':
  1463. segment_duration = float(representation_ms_info['segment_duration']) / float(representation_ms_info['timescale'])
  1464. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1465. media_template = representation_ms_info['media_template']
  1466. media_template = media_template.replace('$RepresentationID$', representation_id)
  1467. media_template = re.sub(r'\$(Number|Bandwidth|Time)\$', r'%(\1)d', media_template)
  1468. media_template = re.sub(r'\$(Number|Bandwidth|Time)%([^$]+)\$', r'%(\1)\2', media_template)
  1469. media_template.replace('$$', '$')
  1470. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  1471. # can't be used at the same time
  1472. if '%(Number' in media_template:
  1473. representation_ms_info['segment_urls'] = [
  1474. media_template % {
  1475. 'Number': segment_number,
  1476. 'Bandwidth': representation_attrib.get('bandwidth'),
  1477. }
  1478. for segment_number in range(
  1479. representation_ms_info['start_number'],
  1480. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1481. else:
  1482. representation_ms_info['segment_urls'] = []
  1483. segment_time = 0
  1484. def add_segment_url():
  1485. representation_ms_info['segment_urls'].append(
  1486. media_template % {
  1487. 'Time': segment_time,
  1488. 'Bandwidth': representation_attrib.get('bandwidth'),
  1489. }
  1490. )
  1491. for num, s in enumerate(representation_ms_info['s']):
  1492. segment_time = s.get('t') or segment_time
  1493. add_segment_url()
  1494. for r in range(s.get('r', 0)):
  1495. segment_time += s['d']
  1496. add_segment_url()
  1497. segment_time += s['d']
  1498. if 'segment_urls' in representation_ms_info:
  1499. f.update({
  1500. 'segment_urls': representation_ms_info['segment_urls'],
  1501. 'protocol': 'http_dash_segments',
  1502. })
  1503. if 'initialization_url' in representation_ms_info:
  1504. initialization_url = representation_ms_info['initialization_url'].replace('$RepresentationID$', representation_id)
  1505. f.update({
  1506. 'initialization_url': initialization_url,
  1507. })
  1508. if not f.get('url'):
  1509. f['url'] = initialization_url
  1510. try:
  1511. existing_format = next(
  1512. fo for fo in formats
  1513. if fo['format_id'] == representation_id)
  1514. except StopIteration:
  1515. full_info = formats_dict.get(representation_id, {}).copy()
  1516. full_info.update(f)
  1517. formats.append(full_info)
  1518. else:
  1519. existing_format.update(f)
  1520. else:
  1521. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1522. return formats
  1523. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None):
  1524. def absolute_url(video_url):
  1525. return compat_urlparse.urljoin(base_url, video_url)
  1526. def parse_content_type(content_type):
  1527. if not content_type:
  1528. return {}
  1529. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  1530. if ctr:
  1531. mimetype, codecs = ctr.groups()
  1532. f = parse_codecs(codecs)
  1533. f['ext'] = mimetype2ext(mimetype)
  1534. return f
  1535. return {}
  1536. def _media_formats(src, cur_media_type):
  1537. full_url = absolute_url(src)
  1538. if determine_ext(full_url) == 'm3u8':
  1539. is_plain_url = False
  1540. formats = self._extract_m3u8_formats(
  1541. full_url, video_id, ext='mp4', entry_protocol='m3u8_native',
  1542. m3u8_id=m3u8_id)
  1543. else:
  1544. is_plain_url = True
  1545. formats = [{
  1546. 'url': full_url,
  1547. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  1548. }]
  1549. return is_plain_url, formats
  1550. entries = []
  1551. for media_tag, media_type, media_content in re.findall(r'(?s)(<(?P<tag>video|audio)[^>]*>)(.*?)</(?P=tag)>', webpage):
  1552. media_info = {
  1553. 'formats': [],
  1554. 'subtitles': {},
  1555. }
  1556. media_attributes = extract_attributes(media_tag)
  1557. src = media_attributes.get('src')
  1558. if src:
  1559. _, formats = _media_formats(src)
  1560. media_info['formats'].extend(formats)
  1561. media_info['thumbnail'] = media_attributes.get('poster')
  1562. if media_content:
  1563. for source_tag in re.findall(r'<source[^>]+>', media_content):
  1564. source_attributes = extract_attributes(source_tag)
  1565. src = source_attributes.get('src')
  1566. if not src:
  1567. continue
  1568. is_plain_url, formats = _media_formats(src, media_type)
  1569. if is_plain_url:
  1570. f = parse_content_type(source_attributes.get('type'))
  1571. f.update(formats[0])
  1572. media_info['formats'].append(f)
  1573. else:
  1574. media_info['formats'].extend(formats)
  1575. for track_tag in re.findall(r'<track[^>]+>', media_content):
  1576. track_attributes = extract_attributes(track_tag)
  1577. kind = track_attributes.get('kind')
  1578. if not kind or kind == 'subtitles':
  1579. src = track_attributes.get('src')
  1580. if not src:
  1581. continue
  1582. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  1583. media_info['subtitles'].setdefault(lang, []).append({
  1584. 'url': absolute_url(src),
  1585. })
  1586. if media_info['formats']:
  1587. entries.append(media_info)
  1588. return entries
  1589. def _live_title(self, name):
  1590. """ Generate the title for a live video """
  1591. now = datetime.datetime.now()
  1592. now_str = now.strftime('%Y-%m-%d %H:%M')
  1593. return name + ' ' + now_str
  1594. def _int(self, v, name, fatal=False, **kwargs):
  1595. res = int_or_none(v, **kwargs)
  1596. if 'get_attr' in kwargs:
  1597. print(getattr(v, kwargs['get_attr']))
  1598. if res is None:
  1599. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1600. if fatal:
  1601. raise ExtractorError(msg)
  1602. else:
  1603. self._downloader.report_warning(msg)
  1604. return res
  1605. def _float(self, v, name, fatal=False, **kwargs):
  1606. res = float_or_none(v, **kwargs)
  1607. if res is None:
  1608. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1609. if fatal:
  1610. raise ExtractorError(msg)
  1611. else:
  1612. self._downloader.report_warning(msg)
  1613. return res
  1614. def _set_cookie(self, domain, name, value, expire_time=None):
  1615. cookie = compat_cookiejar.Cookie(
  1616. 0, name, value, None, None, domain, None,
  1617. None, '/', True, False, expire_time, '', None, None, None)
  1618. self._downloader.cookiejar.set_cookie(cookie)
  1619. def _get_cookies(self, url):
  1620. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1621. req = sanitized_Request(url)
  1622. self._downloader.cookiejar.add_cookie_header(req)
  1623. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1624. def get_testcases(self, include_onlymatching=False):
  1625. t = getattr(self, '_TEST', None)
  1626. if t:
  1627. assert not hasattr(self, '_TESTS'), \
  1628. '%s has _TEST and _TESTS' % type(self).__name__
  1629. tests = [t]
  1630. else:
  1631. tests = getattr(self, '_TESTS', [])
  1632. for t in tests:
  1633. if not include_onlymatching and t.get('only_matching', False):
  1634. continue
  1635. t['name'] = type(self).__name__[:-len('IE')]
  1636. yield t
  1637. def is_suitable(self, age_limit):
  1638. """ Test whether the extractor is generally suitable for the given
  1639. age limit (i.e. pornographic sites are not, all others usually are) """
  1640. any_restricted = False
  1641. for tc in self.get_testcases(include_onlymatching=False):
  1642. if tc.get('playlist', []):
  1643. tc = tc['playlist'][0]
  1644. is_restricted = age_restricted(
  1645. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1646. if not is_restricted:
  1647. return True
  1648. any_restricted = any_restricted or is_restricted
  1649. return not any_restricted
  1650. def extract_subtitles(self, *args, **kwargs):
  1651. if (self._downloader.params.get('writesubtitles', False) or
  1652. self._downloader.params.get('listsubtitles')):
  1653. return self._get_subtitles(*args, **kwargs)
  1654. return {}
  1655. def _get_subtitles(self, *args, **kwargs):
  1656. raise NotImplementedError('This method must be implemented by subclasses')
  1657. @staticmethod
  1658. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1659. """ Merge subtitle items for one language. Items with duplicated URLs
  1660. will be dropped. """
  1661. list1_urls = set([item['url'] for item in subtitle_list1])
  1662. ret = list(subtitle_list1)
  1663. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1664. return ret
  1665. @classmethod
  1666. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1667. """ Merge two subtitle dictionaries, language by language. """
  1668. ret = dict(subtitle_dict1)
  1669. for lang in subtitle_dict2:
  1670. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1671. return ret
  1672. def extract_automatic_captions(self, *args, **kwargs):
  1673. if (self._downloader.params.get('writeautomaticsub', False) or
  1674. self._downloader.params.get('listsubtitles')):
  1675. return self._get_automatic_captions(*args, **kwargs)
  1676. return {}
  1677. def _get_automatic_captions(self, *args, **kwargs):
  1678. raise NotImplementedError('This method must be implemented by subclasses')
  1679. def mark_watched(self, *args, **kwargs):
  1680. if (self._downloader.params.get('mark_watched', False) and
  1681. (self._get_login_info()[0] is not None or
  1682. self._downloader.params.get('cookiefile') is not None)):
  1683. self._mark_watched(*args, **kwargs)
  1684. def _mark_watched(self, *args, **kwargs):
  1685. raise NotImplementedError('This method must be implemented by subclasses')
  1686. def geo_verification_headers(self):
  1687. headers = {}
  1688. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  1689. if geo_verification_proxy:
  1690. headers['Ytdl-request-proxy'] = geo_verification_proxy
  1691. return headers
  1692. class SearchInfoExtractor(InfoExtractor):
  1693. """
  1694. Base class for paged search queries extractors.
  1695. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1696. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1697. """
  1698. @classmethod
  1699. def _make_valid_url(cls):
  1700. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1701. @classmethod
  1702. def suitable(cls, url):
  1703. return re.match(cls._make_valid_url(), url) is not None
  1704. def _real_extract(self, query):
  1705. mobj = re.match(self._make_valid_url(), query)
  1706. if mobj is None:
  1707. raise ExtractorError('Invalid search query "%s"' % query)
  1708. prefix = mobj.group('prefix')
  1709. query = mobj.group('query')
  1710. if prefix == '':
  1711. return self._get_n_results(query, 1)
  1712. elif prefix == 'all':
  1713. return self._get_n_results(query, self._MAX_RESULTS)
  1714. else:
  1715. n = int(prefix)
  1716. if n <= 0:
  1717. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1718. elif n > self._MAX_RESULTS:
  1719. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1720. n = self._MAX_RESULTS
  1721. return self._get_n_results(query, n)
  1722. def _get_n_results(self, query, n):
  1723. """Get a specified number of results for a query"""
  1724. raise NotImplementedError('This method must be implemented by subclasses')
  1725. @property
  1726. def SEARCH_KEY(self):
  1727. return self._SEARCH_KEY