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.

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