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.

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