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.

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