common.py 39 KB

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