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.

1010 lines
41 KiB

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