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.

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