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.

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