common.py 58 KB

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