common.py 40 KB

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