common.py 48 KB

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