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.

1117 lines
46 KiB

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