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.

1398 lines
58 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
11 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. from ..compat import (
  13. compat_cookiejar,
  14. compat_cookies,
  15. compat_getpass,
  16. compat_http_client,
  17. compat_urllib_error,
  18. compat_urllib_parse,
  19. compat_urllib_parse_urlparse,
  20. compat_urlparse,
  21. compat_str,
  22. compat_etree_fromstring,
  23. )
  24. from ..utils import (
  25. NO_DEFAULT,
  26. age_restricted,
  27. bug_reports_message,
  28. clean_html,
  29. compiled_regex_type,
  30. determine_ext,
  31. ExtractorError,
  32. fix_xml_ampersands,
  33. float_or_none,
  34. int_or_none,
  35. RegexNotFoundError,
  36. sanitize_filename,
  37. sanitized_Request,
  38. unescapeHTML,
  39. unified_strdate,
  40. url_basename,
  41. xpath_text,
  42. xpath_with_ns,
  43. )
  44. class InfoExtractor(object):
  45. """Information Extractor class.
  46. Information extractors are the classes that, given a URL, extract
  47. information about the video (or videos) the URL refers to. This
  48. information includes the real video URL, the video title, author and
  49. others. The information is stored in a dictionary which is then
  50. passed to the YoutubeDL. The YoutubeDL processes this
  51. information possibly downloading the video to the file system, among
  52. other possible outcomes.
  53. The type field determines the type of the result.
  54. By far the most common value (and the default if _type is missing) is
  55. "video", which indicates a single video.
  56. For a video, the dictionaries must include the following fields:
  57. id: Video identifier.
  58. title: Video title, unescaped.
  59. Additionally, it must contain either a formats entry or a url one:
  60. formats: A list of dictionaries for each format available, ordered
  61. from worst to best quality.
  62. Potential fields:
  63. * url Mandatory. The URL of the video file
  64. * ext Will be calculated from URL if missing
  65. * format A human-readable description of the format
  66. ("mp4 container with h264/opus").
  67. Calculated from the format_id, width, height.
  68. and format_note fields if missing.
  69. * format_id A short description of the format
  70. ("mp4_h264_opus" or "19").
  71. Technically optional, but strongly recommended.
  72. * format_note Additional info about the format
  73. ("3D" or "DASH video")
  74. * width Width of the video, if known
  75. * height Height of the video, if known
  76. * resolution Textual description of width and height
  77. * tbr Average bitrate of audio and video in KBit/s
  78. * abr Average audio bitrate in KBit/s
  79. * acodec Name of the audio codec in use
  80. * asr Audio sampling rate in Hertz
  81. * vbr Average video bitrate in KBit/s
  82. * fps Frame rate
  83. * vcodec Name of the video codec in use
  84. * container Name of the container format
  85. * filesize The number of bytes, if known in advance
  86. * filesize_approx An estimate for the number of bytes
  87. * player_url SWF Player URL (used for rtmpdump).
  88. * protocol The protocol that will be used for the actual
  89. download, lower-case.
  90. "http", "https", "rtsp", "rtmp", "rtmpe",
  91. "m3u8", or "m3u8_native".
  92. * preference Order number of this format. If this field is
  93. present and not None, the formats get sorted
  94. by this field, regardless of all other values.
  95. -1 for default (order by other properties),
  96. -2 or smaller for less than default.
  97. < -1000 to hide the format (if there is
  98. another one which is strictly better)
  99. * language_preference Is this in the correct requested
  100. language?
  101. 10 if it's what the URL is about,
  102. -1 for default (don't know),
  103. -10 otherwise, other values reserved for now.
  104. * quality Order number of the video quality of this
  105. format, irrespective of the file format.
  106. -1 for default (order by other properties),
  107. -2 or smaller for less than default.
  108. * source_preference Order number for this video source
  109. (quality takes higher priority)
  110. -1 for default (order by other properties),
  111. -2 or smaller for less than default.
  112. * http_headers A dictionary of additional HTTP headers
  113. to add to the request.
  114. * stretched_ratio If given and not 1, indicates that the
  115. video's pixels are not square.
  116. width : height ratio as float.
  117. * no_resume The server does not support resuming the
  118. (HTTP or RTMP) download. Boolean.
  119. url: Final video URL.
  120. ext: Video filename extension.
  121. format: The video format, defaults to ext (used for --get-format)
  122. player_url: SWF Player URL (used for rtmpdump).
  123. The following fields are optional:
  124. alt_title: A secondary title of the video.
  125. display_id An alternative identifier for the video, not necessarily
  126. unique, but available before title. Typically, id is
  127. something like "4234987", title "Dancing naked mole rats",
  128. and display_id "dancing-naked-mole-rats"
  129. thumbnails: A list of dictionaries, with the following entries:
  130. * "id" (optional, string) - Thumbnail format ID
  131. * "url"
  132. * "preference" (optional, int) - quality of the image
  133. * "width" (optional, int)
  134. * "height" (optional, int)
  135. * "resolution" (optional, string "{width}x{height"},
  136. deprecated)
  137. thumbnail: Full URL to a video thumbnail image.
  138. description: Full video description.
  139. uploader: Full name of the video uploader.
  140. creator: The main artist who created the video.
  141. release_date: The date (YYYYMMDD) when the video was released.
  142. timestamp: UNIX timestamp of the moment the video became available.
  143. upload_date: Video upload date (YYYYMMDD).
  144. If not explicitly set, calculated from timestamp.
  145. uploader_id: Nickname or id of the video uploader.
  146. location: Physical location where the video was filmed.
  147. subtitles: The available subtitles as a dictionary in the format
  148. {language: subformats}. "subformats" is a list sorted from
  149. lower to higher preference, each element is a dictionary
  150. with the "ext" entry and one of:
  151. * "data": The subtitles file contents
  152. * "url": A URL pointing to the subtitles file
  153. "ext" will be calculated from URL if missing
  154. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  155. automatically generated captions
  156. duration: Length of the video in seconds, as an integer or float.
  157. view_count: How many users have watched the video on the platform.
  158. like_count: Number of positive ratings of the video
  159. dislike_count: Number of negative ratings of the video
  160. repost_count: Number of reposts of the video
  161. average_rating: Average rating give by users, the scale used depends on the webpage
  162. comment_count: Number of comments on the video
  163. comments: A list of comments, each with one or more of the following
  164. properties (all but one of text or html optional):
  165. * "author" - human-readable name of the comment author
  166. * "author_id" - user ID of the comment author
  167. * "id" - Comment ID
  168. * "html" - Comment as HTML
  169. * "text" - Plain text of the comment
  170. * "timestamp" - UNIX timestamp of comment
  171. * "parent" - ID of the comment this one is replying to.
  172. Set to "root" to indicate that this is a
  173. comment to the original video.
  174. age_limit: Age restriction for the video, as an integer (years)
  175. webpage_url: The URL to the video webpage, if given to youtube-dl it
  176. should allow to get the same result again. (It will be set
  177. by YoutubeDL if it's missing)
  178. categories: A list of categories that the video falls in, for example
  179. ["Sports", "Berlin"]
  180. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  181. is_live: True, False, or None (=unknown). Whether this video is a
  182. live stream that goes on instead of a fixed-length video.
  183. start_time: Time in seconds where the reproduction should start, as
  184. specified in the URL.
  185. end_time: Time in seconds where the reproduction should end, as
  186. specified in the URL.
  187. Unless mentioned otherwise, the fields should be Unicode strings.
  188. Unless mentioned otherwise, None is equivalent to absence of information.
  189. _type "playlist" indicates multiple videos.
  190. There must be a key "entries", which is a list, an iterable, or a PagedList
  191. object, each element of which is a valid dictionary by this specification.
  192. Additionally, playlists can have "title", "description" and "id" attributes
  193. with the same semantics as videos (see above).
  194. _type "multi_video" indicates that there are multiple videos that
  195. form a single show, for examples multiple acts of an opera or TV episode.
  196. It must have an entries key like a playlist and contain all the keys
  197. required for a video at the same time.
  198. _type "url" indicates that the video must be extracted from another
  199. location, possibly by a different extractor. Its only required key is:
  200. "url" - the next URL to extract.
  201. The key "ie_key" can be set to the class name (minus the trailing "IE",
  202. e.g. "Youtube") if the extractor class is known in advance.
  203. Additionally, the dictionary may have any properties of the resolved entity
  204. known in advance, for example "title" if the title of the referred video is
  205. known ahead of time.
  206. _type "url_transparent" entities have the same specification as "url", but
  207. indicate that the given additional information is more precise than the one
  208. associated with the resolved URL.
  209. This is useful when a site employs a video service that hosts the video and
  210. its technical metadata, but that video service does not embed a useful
  211. title, description etc.
  212. Subclasses of this one should re-define the _real_initialize() and
  213. _real_extract() methods and define a _VALID_URL regexp.
  214. Probably, they should also be added to the list of extractors.
  215. Finally, the _WORKING attribute should be set to False for broken IEs
  216. in order to warn the users and skip the tests.
  217. """
  218. _ready = False
  219. _downloader = None
  220. _WORKING = True
  221. def __init__(self, downloader=None):
  222. """Constructor. Receives an optional downloader."""
  223. self._ready = False
  224. self.set_downloader(downloader)
  225. @classmethod
  226. def suitable(cls, url):
  227. """Receives a URL and returns True if suitable for this IE."""
  228. # This does not use has/getattr intentionally - we want to know whether
  229. # we have cached the regexp for *this* class, whereas getattr would also
  230. # match the superclass
  231. if '_VALID_URL_RE' not in cls.__dict__:
  232. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  233. return cls._VALID_URL_RE.match(url) is not None
  234. @classmethod
  235. def _match_id(cls, url):
  236. if '_VALID_URL_RE' not in cls.__dict__:
  237. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  238. m = cls._VALID_URL_RE.match(url)
  239. assert m
  240. return m.group('id')
  241. @classmethod
  242. def working(cls):
  243. """Getter method for _WORKING."""
  244. return cls._WORKING
  245. def initialize(self):
  246. """Initializes an instance (authentication, etc)."""
  247. if not self._ready:
  248. self._real_initialize()
  249. self._ready = True
  250. def extract(self, url):
  251. """Extracts URL information and returns it in list of dicts."""
  252. try:
  253. self.initialize()
  254. return self._real_extract(url)
  255. except ExtractorError:
  256. raise
  257. except compat_http_client.IncompleteRead as e:
  258. raise ExtractorError('A network error has occured.', cause=e, expected=True)
  259. except (KeyError, StopIteration) as e:
  260. raise ExtractorError('An extractor error has occured.', cause=e)
  261. def set_downloader(self, downloader):
  262. """Sets the downloader for this IE."""
  263. self._downloader = downloader
  264. def _real_initialize(self):
  265. """Real initialization process. Redefine in subclasses."""
  266. pass
  267. def _real_extract(self, url):
  268. """Real extraction process. Redefine in subclasses."""
  269. pass
  270. @classmethod
  271. def ie_key(cls):
  272. """A string for getting the InfoExtractor with get_info_extractor"""
  273. return compat_str(cls.__name__[:-2])
  274. @property
  275. def IE_NAME(self):
  276. return compat_str(type(self).__name__[:-2])
  277. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  278. """ Returns the response handle """
  279. if note is None:
  280. self.report_download_webpage(video_id)
  281. elif note is not False:
  282. if video_id is None:
  283. self.to_screen('%s' % (note,))
  284. else:
  285. self.to_screen('%s: %s' % (video_id, note))
  286. try:
  287. return self._downloader.urlopen(url_or_request)
  288. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  289. if errnote is False:
  290. return False
  291. if errnote is None:
  292. errnote = 'Unable to download webpage'
  293. errmsg = '%s: %s' % (errnote, compat_str(err))
  294. if fatal:
  295. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  296. else:
  297. self._downloader.report_warning(errmsg)
  298. return False
  299. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None):
  300. """ Returns a tuple (page content as string, URL handle) """
  301. # Strip hashes from the URL (#1038)
  302. if isinstance(url_or_request, (compat_str, str)):
  303. url_or_request = url_or_request.partition('#')[0]
  304. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
  305. if urlh is False:
  306. assert not fatal
  307. return False
  308. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  309. return (content, urlh)
  310. @staticmethod
  311. def _guess_encoding_from_content(content_type, webpage_bytes):
  312. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  313. if m:
  314. encoding = m.group(1)
  315. else:
  316. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  317. webpage_bytes[:1024])
  318. if m:
  319. encoding = m.group(1).decode('ascii')
  320. elif webpage_bytes.startswith(b'\xff\xfe'):
  321. encoding = 'utf-16'
  322. else:
  323. encoding = 'utf-8'
  324. return encoding
  325. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  326. content_type = urlh.headers.get('Content-Type', '')
  327. webpage_bytes = urlh.read()
  328. if prefix is not None:
  329. webpage_bytes = prefix + webpage_bytes
  330. if not encoding:
  331. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  332. if self._downloader.params.get('dump_intermediate_pages', False):
  333. try:
  334. url = url_or_request.get_full_url()
  335. except AttributeError:
  336. url = url_or_request
  337. self.to_screen('Dumping request to ' + url)
  338. dump = base64.b64encode(webpage_bytes).decode('ascii')
  339. self._downloader.to_screen(dump)
  340. if self._downloader.params.get('write_pages', False):
  341. try:
  342. url = url_or_request.get_full_url()
  343. except AttributeError:
  344. url = url_or_request
  345. basen = '%s_%s' % (video_id, url)
  346. if len(basen) > 240:
  347. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  348. basen = basen[:240 - len(h)] + h
  349. raw_filename = basen + '.dump'
  350. filename = sanitize_filename(raw_filename, restricted=True)
  351. self.to_screen('Saving request to ' + filename)
  352. # Working around MAX_PATH limitation on Windows (see
  353. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  354. if os.name == 'nt':
  355. absfilepath = os.path.abspath(filename)
  356. if len(absfilepath) > 259:
  357. filename = '\\\\?\\' + absfilepath
  358. with open(filename, 'wb') as outf:
  359. outf.write(webpage_bytes)
  360. try:
  361. content = webpage_bytes.decode(encoding, 'replace')
  362. except LookupError:
  363. content = webpage_bytes.decode('utf-8', 'replace')
  364. if ('<title>Access to this site is blocked</title>' in content and
  365. 'Websense' in content[:512]):
  366. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  367. blocked_iframe = self._html_search_regex(
  368. r'<iframe src="([^"]+)"', content,
  369. 'Websense information URL', default=None)
  370. if blocked_iframe:
  371. msg += ' Visit %s for more details' % blocked_iframe
  372. raise ExtractorError(msg, expected=True)
  373. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  374. msg = (
  375. 'Access to this webpage has been blocked by Indian censorship. '
  376. 'Use a VPN or proxy server (with --proxy) to route around it.')
  377. block_msg = self._html_search_regex(
  378. r'</h1><p>(.*?)</p>',
  379. content, 'block message', default=None)
  380. if block_msg:
  381. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  382. raise ExtractorError(msg, expected=True)
  383. return content
  384. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
  385. """ Returns the data of the page as a string """
  386. success = False
  387. try_count = 0
  388. while success is False:
  389. try:
  390. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  391. success = True
  392. except compat_http_client.IncompleteRead as e:
  393. try_count += 1
  394. if try_count >= tries:
  395. raise e
  396. self._sleep(timeout, video_id)
  397. if res is False:
  398. return res
  399. else:
  400. content, _ = res
  401. return content
  402. def _download_xml(self, url_or_request, video_id,
  403. note='Downloading XML', errnote='Unable to download XML',
  404. transform_source=None, fatal=True, encoding=None):
  405. """Return the xml as an xml.etree.ElementTree.Element"""
  406. xml_string = self._download_webpage(
  407. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding)
  408. if xml_string is False:
  409. return xml_string
  410. if transform_source:
  411. xml_string = transform_source(xml_string)
  412. return compat_etree_fromstring(xml_string.encode('utf-8'))
  413. def _download_json(self, url_or_request, video_id,
  414. note='Downloading JSON metadata',
  415. errnote='Unable to download JSON metadata',
  416. transform_source=None,
  417. fatal=True, encoding=None):
  418. json_string = self._download_webpage(
  419. url_or_request, video_id, note, errnote, fatal=fatal,
  420. encoding=encoding)
  421. if (not fatal) and json_string is False:
  422. return None
  423. return self._parse_json(
  424. json_string, video_id, transform_source=transform_source, fatal=fatal)
  425. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  426. if transform_source:
  427. json_string = transform_source(json_string)
  428. try:
  429. return json.loads(json_string)
  430. except ValueError as ve:
  431. errmsg = '%s: Failed to parse JSON ' % video_id
  432. if fatal:
  433. raise ExtractorError(errmsg, cause=ve)
  434. else:
  435. self.report_warning(errmsg + str(ve))
  436. def report_warning(self, msg, video_id=None):
  437. idstr = '' if video_id is None else '%s: ' % video_id
  438. self._downloader.report_warning(
  439. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  440. def to_screen(self, msg):
  441. """Print msg to screen, prefixing it with '[ie_name]'"""
  442. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  443. def report_extraction(self, id_or_name):
  444. """Report information extraction."""
  445. self.to_screen('%s: Extracting information' % id_or_name)
  446. def report_download_webpage(self, video_id):
  447. """Report webpage download."""
  448. self.to_screen('%s: Downloading webpage' % video_id)
  449. def report_age_confirmation(self):
  450. """Report attempt to confirm age."""
  451. self.to_screen('Confirming age')
  452. def report_login(self):
  453. """Report attempt to log in."""
  454. self.to_screen('Logging in')
  455. @staticmethod
  456. def raise_login_required(msg='This video is only available for registered users'):
  457. raise ExtractorError(
  458. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  459. expected=True)
  460. @staticmethod
  461. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction'):
  462. raise ExtractorError(
  463. '%s. You might want to use --proxy to workaround.' % msg,
  464. expected=True)
  465. # Methods for following #608
  466. @staticmethod
  467. def url_result(url, ie=None, video_id=None, video_title=None):
  468. """Returns a URL that points to a page that should be processed"""
  469. # TODO: ie should be the class used for getting the info
  470. video_info = {'_type': 'url',
  471. 'url': url,
  472. 'ie_key': ie}
  473. if video_id is not None:
  474. video_info['id'] = video_id
  475. if video_title is not None:
  476. video_info['title'] = video_title
  477. return video_info
  478. @staticmethod
  479. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  480. """Returns a playlist"""
  481. video_info = {'_type': 'playlist',
  482. 'entries': entries}
  483. if playlist_id:
  484. video_info['id'] = playlist_id
  485. if playlist_title:
  486. video_info['title'] = playlist_title
  487. if playlist_description:
  488. video_info['description'] = playlist_description
  489. return video_info
  490. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  491. """
  492. Perform a regex search on the given string, using a single or a list of
  493. patterns returning the first matching group.
  494. In case of failure return a default value or raise a WARNING or a
  495. RegexNotFoundError, depending on fatal, specifying the field name.
  496. """
  497. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  498. mobj = re.search(pattern, string, flags)
  499. else:
  500. for p in pattern:
  501. mobj = re.search(p, string, flags)
  502. if mobj:
  503. break
  504. if not self._downloader.params.get('no_color') and os.name != 'nt' and sys.stderr.isatty():
  505. _name = '\033[0;34m%s\033[0m' % name
  506. else:
  507. _name = name
  508. if mobj:
  509. if group is None:
  510. # return the first matching group
  511. return next(g for g in mobj.groups() if g is not None)
  512. else:
  513. return mobj.group(group)
  514. elif default is not NO_DEFAULT:
  515. return default
  516. elif fatal:
  517. raise RegexNotFoundError('Unable to extract %s' % _name)
  518. else:
  519. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  520. return None
  521. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  522. """
  523. Like _search_regex, but strips HTML tags and unescapes entities.
  524. """
  525. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  526. if res:
  527. return clean_html(res).strip()
  528. else:
  529. return res
  530. def _get_login_info(self):
  531. """
  532. Get the login info as (username, password)
  533. It will look in the netrc file using the _NETRC_MACHINE value
  534. If there's no info available, return (None, None)
  535. """
  536. if self._downloader is None:
  537. return (None, None)
  538. username = None
  539. password = None
  540. downloader_params = self._downloader.params
  541. # Attempt to use provided username and password or .netrc data
  542. if downloader_params.get('username', None) is not None:
  543. username = downloader_params['username']
  544. password = downloader_params['password']
  545. elif downloader_params.get('usenetrc', False):
  546. try:
  547. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  548. if info is not None:
  549. username = info[0]
  550. password = info[2]
  551. else:
  552. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  553. except (IOError, netrc.NetrcParseError) as err:
  554. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  555. return (username, password)
  556. def _get_tfa_info(self, note='two-factor verification code'):
  557. """
  558. Get the two-factor authentication info
  559. TODO - asking the user will be required for sms/phone verify
  560. currently just uses the command line option
  561. If there's no info available, return None
  562. """
  563. if self._downloader is None:
  564. return None
  565. downloader_params = self._downloader.params
  566. if downloader_params.get('twofactor', None) is not None:
  567. return downloader_params['twofactor']
  568. return compat_getpass('Type %s and press [Return]: ' % note)
  569. # Helper functions for extracting OpenGraph info
  570. @staticmethod
  571. def _og_regexes(prop):
  572. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  573. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  574. % {'prop': re.escape(prop)})
  575. template = r'<meta[^>]+?%s[^>]+?%s'
  576. return [
  577. template % (property_re, content_re),
  578. template % (content_re, property_re),
  579. ]
  580. @staticmethod
  581. def _meta_regex(prop):
  582. return r'''(?isx)<meta
  583. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  584. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  585. def _og_search_property(self, prop, html, name=None, **kargs):
  586. if name is None:
  587. name = 'OpenGraph %s' % prop
  588. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  589. if escaped is None:
  590. return None
  591. return unescapeHTML(escaped)
  592. def _og_search_thumbnail(self, html, **kargs):
  593. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  594. def _og_search_description(self, html, **kargs):
  595. return self._og_search_property('description', html, fatal=False, **kargs)
  596. def _og_search_title(self, html, **kargs):
  597. return self._og_search_property('title', html, **kargs)
  598. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  599. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  600. if secure:
  601. regexes = self._og_regexes('video:secure_url') + regexes
  602. return self._html_search_regex(regexes, html, name, **kargs)
  603. def _og_search_url(self, html, **kargs):
  604. return self._og_search_property('url', html, **kargs)
  605. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  606. if display_name is None:
  607. display_name = name
  608. return self._html_search_regex(
  609. self._meta_regex(name),
  610. html, display_name, fatal=fatal, group='content', **kwargs)
  611. def _dc_search_uploader(self, html):
  612. return self._html_search_meta('dc.creator', html, 'uploader')
  613. def _rta_search(self, html):
  614. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  615. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  616. r' content="RTA-5042-1996-1400-1577-RTA"',
  617. html):
  618. return 18
  619. return 0
  620. def _media_rating_search(self, html):
  621. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  622. rating = self._html_search_meta('rating', html)
  623. if not rating:
  624. return None
  625. RATING_TABLE = {
  626. 'safe for kids': 0,
  627. 'general': 8,
  628. '14 years': 14,
  629. 'mature': 17,
  630. 'restricted': 19,
  631. }
  632. return RATING_TABLE.get(rating.lower(), None)
  633. def _family_friendly_search(self, html):
  634. # See http://schema.org/VideoObject
  635. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  636. if not family_friendly:
  637. return None
  638. RATING_TABLE = {
  639. '1': 0,
  640. 'true': 0,
  641. '0': 18,
  642. 'false': 18,
  643. }
  644. return RATING_TABLE.get(family_friendly.lower(), None)
  645. def _twitter_search_player(self, html):
  646. return self._html_search_meta('twitter:player', html,
  647. 'twitter card player')
  648. @staticmethod
  649. def _hidden_inputs(html):
  650. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  651. hidden_inputs = {}
  652. for input in re.findall(r'(?i)<input([^>]+)>', html):
  653. if not re.search(r'type=(["\'])(?:hidden|submit)\1', input):
  654. continue
  655. name = re.search(r'name=(["\'])(?P<value>.+?)\1', input)
  656. if not name:
  657. continue
  658. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  659. if not value:
  660. continue
  661. hidden_inputs[name.group('value')] = value.group('value')
  662. return hidden_inputs
  663. def _form_hidden_inputs(self, form_id, html):
  664. form = self._search_regex(
  665. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  666. html, '%s form' % form_id, group='form')
  667. return self._hidden_inputs(form)
  668. def _sort_formats(self, formats, field_preference=None):
  669. if not formats:
  670. raise ExtractorError('No video formats found')
  671. def _formats_key(f):
  672. # TODO remove the following workaround
  673. from ..utils import determine_ext
  674. if not f.get('ext') and 'url' in f:
  675. f['ext'] = determine_ext(f['url'])
  676. if isinstance(field_preference, (list, tuple)):
  677. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  678. preference = f.get('preference')
  679. if preference is None:
  680. proto = f.get('protocol')
  681. if proto is None:
  682. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  683. preference = 0 if proto in ['http', 'https'] else -0.1
  684. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  685. preference -= 0.5
  686. if f.get('vcodec') == 'none': # audio only
  687. if self._downloader.params.get('prefer_free_formats'):
  688. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  689. else:
  690. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  691. ext_preference = 0
  692. try:
  693. audio_ext_preference = ORDER.index(f['ext'])
  694. except ValueError:
  695. audio_ext_preference = -1
  696. else:
  697. if self._downloader.params.get('prefer_free_formats'):
  698. ORDER = ['flv', 'mp4', 'webm']
  699. else:
  700. ORDER = ['webm', 'flv', 'mp4']
  701. try:
  702. ext_preference = ORDER.index(f['ext'])
  703. except ValueError:
  704. ext_preference = -1
  705. audio_ext_preference = 0
  706. return (
  707. preference,
  708. f.get('language_preference') if f.get('language_preference') is not None else -1,
  709. f.get('quality') if f.get('quality') is not None else -1,
  710. f.get('tbr') if f.get('tbr') is not None else -1,
  711. f.get('filesize') if f.get('filesize') is not None else -1,
  712. f.get('vbr') if f.get('vbr') is not None else -1,
  713. f.get('height') if f.get('height') is not None else -1,
  714. f.get('width') if f.get('width') is not None else -1,
  715. ext_preference,
  716. f.get('abr') if f.get('abr') is not None else -1,
  717. audio_ext_preference,
  718. f.get('fps') if f.get('fps') is not None else -1,
  719. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  720. f.get('source_preference') if f.get('source_preference') is not None else -1,
  721. f.get('format_id') if f.get('format_id') is not None else '',
  722. )
  723. formats.sort(key=_formats_key)
  724. def _check_formats(self, formats, video_id):
  725. if formats:
  726. formats[:] = filter(
  727. lambda f: self._is_valid_url(
  728. f['url'], video_id,
  729. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  730. formats)
  731. def _is_valid_url(self, url, video_id, item='video'):
  732. url = self._proto_relative_url(url, scheme='http:')
  733. # For now assume non HTTP(S) URLs always valid
  734. if not (url.startswith('http://') or url.startswith('https://')):
  735. return True
  736. try:
  737. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  738. return True
  739. except ExtractorError as e:
  740. if isinstance(e.cause, compat_urllib_error.URLError):
  741. self.to_screen(
  742. '%s: %s URL is invalid, skipping' % (video_id, item))
  743. return False
  744. raise
  745. def http_scheme(self):
  746. """ Either "http:" or "https:", depending on the user's preferences """
  747. return (
  748. 'http:'
  749. if self._downloader.params.get('prefer_insecure', False)
  750. else 'https:')
  751. def _proto_relative_url(self, url, scheme=None):
  752. if url is None:
  753. return url
  754. if url.startswith('//'):
  755. if scheme is None:
  756. scheme = self.http_scheme()
  757. return scheme + url
  758. else:
  759. return url
  760. def _sleep(self, timeout, video_id, msg_template=None):
  761. if msg_template is None:
  762. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  763. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  764. self.to_screen(msg)
  765. time.sleep(timeout)
  766. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  767. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  768. fatal=True):
  769. manifest = self._download_xml(
  770. manifest_url, video_id, 'Downloading f4m manifest',
  771. 'Unable to download f4m manifest',
  772. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  773. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  774. transform_source=transform_source,
  775. fatal=fatal)
  776. if manifest is False:
  777. return manifest
  778. formats = []
  779. manifest_version = '1.0'
  780. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  781. if not media_nodes:
  782. manifest_version = '2.0'
  783. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  784. base_url = xpath_text(
  785. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  786. 'base URL', default=None)
  787. if base_url:
  788. base_url = base_url.strip()
  789. for i, media_el in enumerate(media_nodes):
  790. if manifest_version == '2.0':
  791. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  792. if not media_url:
  793. continue
  794. manifest_url = (
  795. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  796. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  797. # If media_url is itself a f4m manifest do the recursive extraction
  798. # since bitrates in parent manifest (this one) and media_url manifest
  799. # may differ leading to inability to resolve the format by requested
  800. # bitrate in f4m downloader
  801. if determine_ext(manifest_url) == 'f4m':
  802. f4m_formats = self._extract_f4m_formats(
  803. manifest_url, video_id, preference, f4m_id, fatal=fatal)
  804. if f4m_formats:
  805. formats.extend(f4m_formats)
  806. continue
  807. tbr = int_or_none(media_el.attrib.get('bitrate'))
  808. formats.append({
  809. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  810. 'url': manifest_url,
  811. 'ext': 'flv',
  812. 'tbr': tbr,
  813. 'width': int_or_none(media_el.attrib.get('width')),
  814. 'height': int_or_none(media_el.attrib.get('height')),
  815. 'preference': preference,
  816. })
  817. self._sort_formats(formats)
  818. return formats
  819. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  820. entry_protocol='m3u8', preference=None,
  821. m3u8_id=None, note=None, errnote=None,
  822. fatal=True):
  823. formats = [{
  824. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  825. 'url': m3u8_url,
  826. 'ext': ext,
  827. 'protocol': 'm3u8',
  828. 'preference': preference - 1 if preference else -1,
  829. 'resolution': 'multiple',
  830. 'format_note': 'Quality selection URL',
  831. }]
  832. format_url = lambda u: (
  833. u
  834. if re.match(r'^https?://', u)
  835. else compat_urlparse.urljoin(m3u8_url, u))
  836. res = self._download_webpage_handle(
  837. m3u8_url, video_id,
  838. note=note or 'Downloading m3u8 information',
  839. errnote=errnote or 'Failed to download m3u8 information',
  840. fatal=fatal)
  841. if res is False:
  842. return res
  843. m3u8_doc, urlh = res
  844. m3u8_url = urlh.geturl()
  845. last_info = None
  846. last_media = None
  847. kv_rex = re.compile(
  848. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  849. for line in m3u8_doc.splitlines():
  850. if line.startswith('#EXT-X-STREAM-INF:'):
  851. last_info = {}
  852. for m in kv_rex.finditer(line):
  853. v = m.group('val')
  854. if v.startswith('"'):
  855. v = v[1:-1]
  856. last_info[m.group('key')] = v
  857. elif line.startswith('#EXT-X-MEDIA:'):
  858. last_media = {}
  859. for m in kv_rex.finditer(line):
  860. v = m.group('val')
  861. if v.startswith('"'):
  862. v = v[1:-1]
  863. last_media[m.group('key')] = v
  864. elif line.startswith('#') or not line.strip():
  865. continue
  866. else:
  867. if last_info is None:
  868. formats.append({'url': format_url(line)})
  869. continue
  870. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  871. format_id = []
  872. if m3u8_id:
  873. format_id.append(m3u8_id)
  874. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  875. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  876. f = {
  877. 'format_id': '-'.join(format_id),
  878. 'url': format_url(line.strip()),
  879. 'tbr': tbr,
  880. 'ext': ext,
  881. 'protocol': entry_protocol,
  882. 'preference': preference,
  883. }
  884. codecs = last_info.get('CODECS')
  885. if codecs:
  886. # TODO: looks like video codec is not always necessarily goes first
  887. va_codecs = codecs.split(',')
  888. if va_codecs[0]:
  889. f['vcodec'] = va_codecs[0].partition('.')[0]
  890. if len(va_codecs) > 1 and va_codecs[1]:
  891. f['acodec'] = va_codecs[1].partition('.')[0]
  892. resolution = last_info.get('RESOLUTION')
  893. if resolution:
  894. width_str, height_str = resolution.split('x')
  895. f['width'] = int(width_str)
  896. f['height'] = int(height_str)
  897. if last_media is not None:
  898. f['m3u8_media'] = last_media
  899. last_media = None
  900. formats.append(f)
  901. last_info = {}
  902. self._sort_formats(formats)
  903. return formats
  904. @staticmethod
  905. def _xpath_ns(path, namespace=None):
  906. if not namespace:
  907. return path
  908. out = []
  909. for c in path.split('/'):
  910. if not c or c == '.':
  911. out.append(c)
  912. else:
  913. out.append('{%s}%s' % (namespace, c))
  914. return '/'.join(out)
  915. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  916. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  917. if smil is False:
  918. assert not fatal
  919. return []
  920. namespace = self._parse_smil_namespace(smil)
  921. return self._parse_smil_formats(
  922. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  923. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  924. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  925. if smil is False:
  926. return {}
  927. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  928. def _download_smil(self, smil_url, video_id, fatal=True):
  929. return self._download_xml(
  930. smil_url, video_id, 'Downloading SMIL file',
  931. 'Unable to download SMIL file', fatal=fatal)
  932. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  933. namespace = self._parse_smil_namespace(smil)
  934. formats = self._parse_smil_formats(
  935. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  936. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  937. video_id = os.path.splitext(url_basename(smil_url))[0]
  938. title = None
  939. description = None
  940. upload_date = None
  941. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  942. name = meta.attrib.get('name')
  943. content = meta.attrib.get('content')
  944. if not name or not content:
  945. continue
  946. if not title and name == 'title':
  947. title = content
  948. elif not description and name in ('description', 'abstract'):
  949. description = content
  950. elif not upload_date and name == 'date':
  951. upload_date = unified_strdate(content)
  952. thumbnails = [{
  953. 'id': image.get('type'),
  954. 'url': image.get('src'),
  955. 'width': int_or_none(image.get('width')),
  956. 'height': int_or_none(image.get('height')),
  957. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  958. return {
  959. 'id': video_id,
  960. 'title': title or video_id,
  961. 'description': description,
  962. 'upload_date': upload_date,
  963. 'thumbnails': thumbnails,
  964. 'formats': formats,
  965. 'subtitles': subtitles,
  966. }
  967. def _parse_smil_namespace(self, smil):
  968. return self._search_regex(
  969. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  970. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  971. base = smil_url
  972. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  973. b = meta.get('base') or meta.get('httpBase')
  974. if b:
  975. base = b
  976. break
  977. formats = []
  978. rtmp_count = 0
  979. http_count = 0
  980. videos = smil.findall(self._xpath_ns('.//video', namespace))
  981. for video in videos:
  982. src = video.get('src')
  983. if not src:
  984. continue
  985. bitrate = float_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  986. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  987. width = int_or_none(video.get('width'))
  988. height = int_or_none(video.get('height'))
  989. proto = video.get('proto')
  990. ext = video.get('ext')
  991. src_ext = determine_ext(src)
  992. streamer = video.get('streamer') or base
  993. if proto == 'rtmp' or streamer.startswith('rtmp'):
  994. rtmp_count += 1
  995. formats.append({
  996. 'url': streamer,
  997. 'play_path': src,
  998. 'ext': 'flv',
  999. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1000. 'tbr': bitrate,
  1001. 'filesize': filesize,
  1002. 'width': width,
  1003. 'height': height,
  1004. })
  1005. if transform_rtmp_url:
  1006. streamer, src = transform_rtmp_url(streamer, src)
  1007. formats[-1].update({
  1008. 'url': streamer,
  1009. 'play_path': src,
  1010. })
  1011. continue
  1012. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1013. if proto == 'm3u8' or src_ext == 'm3u8':
  1014. m3u8_formats = self._extract_m3u8_formats(
  1015. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1016. if m3u8_formats:
  1017. formats.extend(m3u8_formats)
  1018. continue
  1019. if src_ext == 'f4m':
  1020. f4m_url = src_url
  1021. if not f4m_params:
  1022. f4m_params = {
  1023. 'hdcore': '3.2.0',
  1024. 'plugin': 'flowplayer-3.2.0.1',
  1025. }
  1026. f4m_url += '&' if '?' in f4m_url else '?'
  1027. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  1028. f4m_formats = self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False)
  1029. if f4m_formats:
  1030. formats.extend(f4m_formats)
  1031. continue
  1032. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1033. http_count += 1
  1034. formats.append({
  1035. 'url': src_url,
  1036. 'ext': ext or src_ext or 'flv',
  1037. 'format_id': 'http-%d' % (bitrate or http_count),
  1038. 'tbr': bitrate,
  1039. 'filesize': filesize,
  1040. 'width': width,
  1041. 'height': height,
  1042. })
  1043. continue
  1044. self._sort_formats(formats)
  1045. return formats
  1046. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1047. subtitles = {}
  1048. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1049. src = textstream.get('src')
  1050. if not src:
  1051. continue
  1052. ext = textstream.get('ext') or determine_ext(src)
  1053. if not ext:
  1054. type_ = textstream.get('type')
  1055. SUBTITLES_TYPES = {
  1056. 'text/vtt': 'vtt',
  1057. 'text/srt': 'srt',
  1058. 'application/smptett+xml': 'tt',
  1059. }
  1060. if type_ in SUBTITLES_TYPES:
  1061. ext = SUBTITLES_TYPES[type_]
  1062. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1063. subtitles.setdefault(lang, []).append({
  1064. 'url': src,
  1065. 'ext': ext,
  1066. })
  1067. return subtitles
  1068. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1069. xspf = self._download_xml(
  1070. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1071. 'Unable to download xspf manifest', fatal=fatal)
  1072. if xspf is False:
  1073. return []
  1074. return self._parse_xspf(xspf, playlist_id)
  1075. def _parse_xspf(self, playlist, playlist_id):
  1076. NS_MAP = {
  1077. 'xspf': 'http://xspf.org/ns/0/',
  1078. 's1': 'http://static.streamone.nl/player/ns/0',
  1079. }
  1080. entries = []
  1081. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1082. title = xpath_text(
  1083. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1084. description = xpath_text(
  1085. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1086. thumbnail = xpath_text(
  1087. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1088. duration = float_or_none(
  1089. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1090. formats = [{
  1091. 'url': location.text,
  1092. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1093. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1094. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1095. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1096. self._sort_formats(formats)
  1097. entries.append({
  1098. 'id': playlist_id,
  1099. 'title': title,
  1100. 'description': description,
  1101. 'thumbnail': thumbnail,
  1102. 'duration': duration,
  1103. 'formats': formats,
  1104. })
  1105. return entries
  1106. def _live_title(self, name):
  1107. """ Generate the title for a live video """
  1108. now = datetime.datetime.now()
  1109. now_str = now.strftime("%Y-%m-%d %H:%M")
  1110. return name + ' ' + now_str
  1111. def _int(self, v, name, fatal=False, **kwargs):
  1112. res = int_or_none(v, **kwargs)
  1113. if 'get_attr' in kwargs:
  1114. print(getattr(v, kwargs['get_attr']))
  1115. if res is None:
  1116. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1117. if fatal:
  1118. raise ExtractorError(msg)
  1119. else:
  1120. self._downloader.report_warning(msg)
  1121. return res
  1122. def _float(self, v, name, fatal=False, **kwargs):
  1123. res = float_or_none(v, **kwargs)
  1124. if res is None:
  1125. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1126. if fatal:
  1127. raise ExtractorError(msg)
  1128. else:
  1129. self._downloader.report_warning(msg)
  1130. return res
  1131. def _set_cookie(self, domain, name, value, expire_time=None):
  1132. cookie = compat_cookiejar.Cookie(
  1133. 0, name, value, None, None, domain, None,
  1134. None, '/', True, False, expire_time, '', None, None, None)
  1135. self._downloader.cookiejar.set_cookie(cookie)
  1136. def _get_cookies(self, url):
  1137. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1138. req = sanitized_Request(url)
  1139. self._downloader.cookiejar.add_cookie_header(req)
  1140. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1141. def get_testcases(self, include_onlymatching=False):
  1142. t = getattr(self, '_TEST', None)
  1143. if t:
  1144. assert not hasattr(self, '_TESTS'), \
  1145. '%s has _TEST and _TESTS' % type(self).__name__
  1146. tests = [t]
  1147. else:
  1148. tests = getattr(self, '_TESTS', [])
  1149. for t in tests:
  1150. if not include_onlymatching and t.get('only_matching', False):
  1151. continue
  1152. t['name'] = type(self).__name__[:-len('IE')]
  1153. yield t
  1154. def is_suitable(self, age_limit):
  1155. """ Test whether the extractor is generally suitable for the given
  1156. age limit (i.e. pornographic sites are not, all others usually are) """
  1157. any_restricted = False
  1158. for tc in self.get_testcases(include_onlymatching=False):
  1159. if 'playlist' in tc:
  1160. tc = tc['playlist'][0]
  1161. is_restricted = age_restricted(
  1162. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1163. if not is_restricted:
  1164. return True
  1165. any_restricted = any_restricted or is_restricted
  1166. return not any_restricted
  1167. def extract_subtitles(self, *args, **kwargs):
  1168. if (self._downloader.params.get('writesubtitles', False) or
  1169. self._downloader.params.get('listsubtitles')):
  1170. return self._get_subtitles(*args, **kwargs)
  1171. return {}
  1172. def _get_subtitles(self, *args, **kwargs):
  1173. raise NotImplementedError("This method must be implemented by subclasses")
  1174. @staticmethod
  1175. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1176. """ Merge subtitle items for one language. Items with duplicated URLs
  1177. will be dropped. """
  1178. list1_urls = set([item['url'] for item in subtitle_list1])
  1179. ret = list(subtitle_list1)
  1180. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1181. return ret
  1182. @classmethod
  1183. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1184. """ Merge two subtitle dictionaries, language by language. """
  1185. ret = dict(subtitle_dict1)
  1186. for lang in subtitle_dict2:
  1187. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1188. return ret
  1189. def extract_automatic_captions(self, *args, **kwargs):
  1190. if (self._downloader.params.get('writeautomaticsub', False) or
  1191. self._downloader.params.get('listsubtitles')):
  1192. return self._get_automatic_captions(*args, **kwargs)
  1193. return {}
  1194. def _get_automatic_captions(self, *args, **kwargs):
  1195. raise NotImplementedError("This method must be implemented by subclasses")
  1196. class SearchInfoExtractor(InfoExtractor):
  1197. """
  1198. Base class for paged search queries extractors.
  1199. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1200. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1201. """
  1202. @classmethod
  1203. def _make_valid_url(cls):
  1204. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1205. @classmethod
  1206. def suitable(cls, url):
  1207. return re.match(cls._make_valid_url(), url) is not None
  1208. def _real_extract(self, query):
  1209. mobj = re.match(self._make_valid_url(), query)
  1210. if mobj is None:
  1211. raise ExtractorError('Invalid search query "%s"' % query)
  1212. prefix = mobj.group('prefix')
  1213. query = mobj.group('query')
  1214. if prefix == '':
  1215. return self._get_n_results(query, 1)
  1216. elif prefix == 'all':
  1217. return self._get_n_results(query, self._MAX_RESULTS)
  1218. else:
  1219. n = int(prefix)
  1220. if n <= 0:
  1221. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1222. elif n > self._MAX_RESULTS:
  1223. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1224. n = self._MAX_RESULTS
  1225. return self._get_n_results(query, n)
  1226. def _get_n_results(self, query, n):
  1227. """Get a specified number of results for a query"""
  1228. raise NotImplementedError("This method must be implemented by subclasses")
  1229. @property
  1230. def SEARCH_KEY(self):
  1231. return self._SEARCH_KEY