common.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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 math
  13. from ..compat import (
  14. compat_cookiejar,
  15. compat_cookies,
  16. compat_etree_fromstring,
  17. compat_getpass,
  18. compat_http_client,
  19. compat_os_name,
  20. compat_str,
  21. compat_urllib_error,
  22. compat_urllib_parse_urlencode,
  23. compat_urllib_request,
  24. compat_urlparse,
  25. )
  26. from ..downloader.f4m import remove_encrypted_media
  27. from ..utils import (
  28. NO_DEFAULT,
  29. age_restricted,
  30. bug_reports_message,
  31. clean_html,
  32. compiled_regex_type,
  33. determine_ext,
  34. error_to_compat_str,
  35. ExtractorError,
  36. fix_xml_ampersands,
  37. float_or_none,
  38. int_or_none,
  39. parse_iso8601,
  40. RegexNotFoundError,
  41. sanitize_filename,
  42. sanitized_Request,
  43. unescapeHTML,
  44. unified_strdate,
  45. url_basename,
  46. xpath_element,
  47. xpath_text,
  48. xpath_with_ns,
  49. determine_protocol,
  50. parse_duration,
  51. mimetype2ext,
  52. update_Request,
  53. update_url_query,
  54. parse_m3u8_attributes,
  55. )
  56. class InfoExtractor(object):
  57. """Information Extractor class.
  58. Information extractors are the classes that, given a URL, extract
  59. information about the video (or videos) the URL refers to. This
  60. information includes the real video URL, the video title, author and
  61. others. The information is stored in a dictionary which is then
  62. passed to the YoutubeDL. The YoutubeDL processes this
  63. information possibly downloading the video to the file system, among
  64. other possible outcomes.
  65. The type field determines the type of the result.
  66. By far the most common value (and the default if _type is missing) is
  67. "video", which indicates a single video.
  68. For a video, the dictionaries must include the following fields:
  69. id: Video identifier.
  70. title: Video title, unescaped.
  71. Additionally, it must contain either a formats entry or a url one:
  72. formats: A list of dictionaries for each format available, ordered
  73. from worst to best quality.
  74. Potential fields:
  75. * url Mandatory. The URL of the video file
  76. * ext Will be calculated from URL if missing
  77. * format A human-readable description of the format
  78. ("mp4 container with h264/opus").
  79. Calculated from the format_id, width, height.
  80. and format_note fields if missing.
  81. * format_id A short description of the format
  82. ("mp4_h264_opus" or "19").
  83. Technically optional, but strongly recommended.
  84. * format_note Additional info about the format
  85. ("3D" or "DASH video")
  86. * width Width of the video, if known
  87. * height Height of the video, if known
  88. * resolution Textual description of width and height
  89. * tbr Average bitrate of audio and video in KBit/s
  90. * abr Average audio bitrate in KBit/s
  91. * acodec Name of the audio codec in use
  92. * asr Audio sampling rate in Hertz
  93. * vbr Average video bitrate in KBit/s
  94. * fps Frame rate
  95. * vcodec Name of the video codec in use
  96. * container Name of the container format
  97. * filesize The number of bytes, if known in advance
  98. * filesize_approx An estimate for the number of bytes
  99. * player_url SWF Player URL (used for rtmpdump).
  100. * protocol The protocol that will be used for the actual
  101. download, lower-case.
  102. "http", "https", "rtsp", "rtmp", "rtmpe",
  103. "m3u8", "m3u8_native" or "http_dash_segments".
  104. * preference Order number of this format. If this field is
  105. present and not None, the formats get sorted
  106. by this field, regardless of all other values.
  107. -1 for default (order by other properties),
  108. -2 or smaller for less than default.
  109. < -1000 to hide the format (if there is
  110. another one which is strictly better)
  111. * language Language code, e.g. "de" or "en-US".
  112. * language_preference Is this in the language mentioned in
  113. the URL?
  114. 10 if it's what the URL is about,
  115. -1 for default (don't know),
  116. -10 otherwise, other values reserved for now.
  117. * quality Order number of the video quality of this
  118. format, irrespective of the file format.
  119. -1 for default (order by other properties),
  120. -2 or smaller for less than default.
  121. * source_preference Order number for this video source
  122. (quality takes higher priority)
  123. -1 for default (order by other properties),
  124. -2 or smaller for less than default.
  125. * http_headers A dictionary of additional HTTP headers
  126. to add to the request.
  127. * stretched_ratio If given and not 1, indicates that the
  128. video's pixels are not square.
  129. width : height ratio as float.
  130. * no_resume The server does not support resuming the
  131. (HTTP or RTMP) download. Boolean.
  132. url: Final video URL.
  133. ext: Video filename extension.
  134. format: The video format, defaults to ext (used for --get-format)
  135. player_url: SWF Player URL (used for rtmpdump).
  136. The following fields are optional:
  137. alt_title: A secondary title of the video.
  138. display_id An alternative identifier for the video, not necessarily
  139. unique, but available before title. Typically, id is
  140. something like "4234987", title "Dancing naked mole rats",
  141. and display_id "dancing-naked-mole-rats"
  142. thumbnails: A list of dictionaries, with the following entries:
  143. * "id" (optional, string) - Thumbnail format ID
  144. * "url"
  145. * "preference" (optional, int) - quality of the image
  146. * "width" (optional, int)
  147. * "height" (optional, int)
  148. * "resolution" (optional, string "{width}x{height"},
  149. deprecated)
  150. * "filesize" (optional, int)
  151. thumbnail: Full URL to a video thumbnail image.
  152. description: Full video description.
  153. uploader: Full name of the video uploader.
  154. license: License name the video is licensed under.
  155. creator: The creator of the video.
  156. release_date: The date (YYYYMMDD) when the video was released.
  157. timestamp: UNIX timestamp of the moment the video became available.
  158. upload_date: Video upload date (YYYYMMDD).
  159. If not explicitly set, calculated from timestamp.
  160. uploader_id: Nickname or id of the video uploader.
  161. uploader_url: Full URL to a personal webpage of the video uploader.
  162. location: Physical location where the video was filmed.
  163. subtitles: The available subtitles as a dictionary in the format
  164. {language: subformats}. "subformats" is a list sorted from
  165. lower to higher preference, each element is a dictionary
  166. with the "ext" entry and one of:
  167. * "data": The subtitles file contents
  168. * "url": A URL pointing to the subtitles file
  169. "ext" will be calculated from URL if missing
  170. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  171. automatically generated captions
  172. duration: Length of the video in seconds, as an integer or float.
  173. view_count: How many users have watched the video on the platform.
  174. like_count: Number of positive ratings of the video
  175. dislike_count: Number of negative ratings of the video
  176. repost_count: Number of reposts of the video
  177. average_rating: Average rating give by users, the scale used depends on the webpage
  178. comment_count: Number of comments on the video
  179. comments: A list of comments, each with one or more of the following
  180. properties (all but one of text or html optional):
  181. * "author" - human-readable name of the comment author
  182. * "author_id" - user ID of the comment author
  183. * "id" - Comment ID
  184. * "html" - Comment as HTML
  185. * "text" - Plain text of the comment
  186. * "timestamp" - UNIX timestamp of comment
  187. * "parent" - ID of the comment this one is replying to.
  188. Set to "root" to indicate that this is a
  189. comment to the original video.
  190. age_limit: Age restriction for the video, as an integer (years)
  191. webpage_url: The URL to the video webpage, if given to youtube-dl it
  192. should allow to get the same result again. (It will be set
  193. by YoutubeDL if it's missing)
  194. categories: A list of categories that the video falls in, for example
  195. ["Sports", "Berlin"]
  196. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  197. is_live: True, False, or None (=unknown). Whether this video is a
  198. live stream that goes on instead of a fixed-length video.
  199. start_time: Time in seconds where the reproduction should start, as
  200. specified in the URL.
  201. end_time: Time in seconds where the reproduction should end, as
  202. specified in the URL.
  203. The following fields should only be used when the video belongs to some logical
  204. chapter or section:
  205. chapter: Name or title of the chapter the video belongs to.
  206. chapter_number: Number of the chapter the video belongs to, as an integer.
  207. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  208. The following fields should only be used when the video is an episode of some
  209. series or programme:
  210. series: Title of the series or programme the video episode belongs to.
  211. season: Title of the season the video episode belongs to.
  212. season_number: Number of the season the video episode belongs to, as an integer.
  213. season_id: Id of the season the video episode belongs to, as a unicode string.
  214. episode: Title of the video episode. Unlike mandatory video title field,
  215. this field should denote the exact title of the video episode
  216. without any kind of decoration.
  217. episode_number: Number of the video episode within a season, as an integer.
  218. episode_id: Id of the video episode, as a unicode string.
  219. The following fields should only be used when the media is a track or a part of
  220. a music album:
  221. track: Title of the track.
  222. track_number: Number of the track within an album or a disc, as an integer.
  223. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  224. as a unicode string.
  225. artist: Artist(s) of the track.
  226. genre: Genre(s) of the track.
  227. album: Title of the album the track belongs to.
  228. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  229. album_artist: List of all artists appeared on the album (e.g.
  230. "Ash Borer / Fell Voices" or "Various Artists", useful for splits
  231. and compilations).
  232. disc_number: Number of the disc or other physical medium the track belongs to,
  233. as an integer.
  234. release_year: Year (YYYY) when the album was released.
  235. Unless mentioned otherwise, the fields should be Unicode strings.
  236. Unless mentioned otherwise, None is equivalent to absence of information.
  237. _type "playlist" indicates multiple videos.
  238. There must be a key "entries", which is a list, an iterable, or a PagedList
  239. object, each element of which is a valid dictionary by this specification.
  240. Additionally, playlists can have "title", "description" and "id" attributes
  241. with the same semantics as videos (see above).
  242. _type "multi_video" indicates that there are multiple videos that
  243. form a single show, for examples multiple acts of an opera or TV episode.
  244. It must have an entries key like a playlist and contain all the keys
  245. required for a video at the same time.
  246. _type "url" indicates that the video must be extracted from another
  247. location, possibly by a different extractor. Its only required key is:
  248. "url" - the next URL to extract.
  249. The key "ie_key" can be set to the class name (minus the trailing "IE",
  250. e.g. "Youtube") if the extractor class is known in advance.
  251. Additionally, the dictionary may have any properties of the resolved entity
  252. known in advance, for example "title" if the title of the referred video is
  253. known ahead of time.
  254. _type "url_transparent" entities have the same specification as "url", but
  255. indicate that the given additional information is more precise than the one
  256. associated with the resolved URL.
  257. This is useful when a site employs a video service that hosts the video and
  258. its technical metadata, but that video service does not embed a useful
  259. title, description etc.
  260. Subclasses of this one should re-define the _real_initialize() and
  261. _real_extract() methods and define a _VALID_URL regexp.
  262. Probably, they should also be added to the list of extractors.
  263. Finally, the _WORKING attribute should be set to False for broken IEs
  264. in order to warn the users and skip the tests.
  265. """
  266. _ready = False
  267. _downloader = None
  268. _WORKING = True
  269. def __init__(self, downloader=None):
  270. """Constructor. Receives an optional downloader."""
  271. self._ready = False
  272. self.set_downloader(downloader)
  273. @classmethod
  274. def suitable(cls, url):
  275. """Receives a URL and returns True if suitable for this IE."""
  276. # This does not use has/getattr intentionally - we want to know whether
  277. # we have cached the regexp for *this* class, whereas getattr would also
  278. # match the superclass
  279. if '_VALID_URL_RE' not in cls.__dict__:
  280. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  281. return cls._VALID_URL_RE.match(url) is not None
  282. @classmethod
  283. def _match_id(cls, url):
  284. if '_VALID_URL_RE' not in cls.__dict__:
  285. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  286. m = cls._VALID_URL_RE.match(url)
  287. assert m
  288. return m.group('id')
  289. @classmethod
  290. def working(cls):
  291. """Getter method for _WORKING."""
  292. return cls._WORKING
  293. def initialize(self):
  294. """Initializes an instance (authentication, etc)."""
  295. if not self._ready:
  296. self._real_initialize()
  297. self._ready = True
  298. def extract(self, url):
  299. """Extracts URL information and returns it in list of dicts."""
  300. try:
  301. self.initialize()
  302. return self._real_extract(url)
  303. except ExtractorError:
  304. raise
  305. except compat_http_client.IncompleteRead as e:
  306. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  307. except (KeyError, StopIteration) as e:
  308. raise ExtractorError('An extractor error has occurred.', cause=e)
  309. def set_downloader(self, downloader):
  310. """Sets the downloader for this IE."""
  311. self._downloader = downloader
  312. def _real_initialize(self):
  313. """Real initialization process. Redefine in subclasses."""
  314. pass
  315. def _real_extract(self, url):
  316. """Real extraction process. Redefine in subclasses."""
  317. pass
  318. @classmethod
  319. def ie_key(cls):
  320. """A string for getting the InfoExtractor with get_info_extractor"""
  321. return compat_str(cls.__name__[:-2])
  322. @property
  323. def IE_NAME(self):
  324. return compat_str(type(self).__name__[:-2])
  325. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  326. """ Returns the response handle """
  327. if note is None:
  328. self.report_download_webpage(video_id)
  329. elif note is not False:
  330. if video_id is None:
  331. self.to_screen('%s' % (note,))
  332. else:
  333. self.to_screen('%s: %s' % (video_id, note))
  334. if isinstance(url_or_request, compat_urllib_request.Request):
  335. url_or_request = update_Request(
  336. url_or_request, data=data, headers=headers, query=query)
  337. else:
  338. if query:
  339. url_or_request = update_url_query(url_or_request, query)
  340. if data is not None or headers:
  341. url_or_request = sanitized_Request(url_or_request, data, headers)
  342. try:
  343. return self._downloader.urlopen(url_or_request)
  344. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  345. if errnote is False:
  346. return False
  347. if errnote is None:
  348. errnote = 'Unable to download webpage'
  349. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  350. if fatal:
  351. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  352. else:
  353. self._downloader.report_warning(errmsg)
  354. return False
  355. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  356. """ Returns a tuple (page content as string, URL handle) """
  357. # Strip hashes from the URL (#1038)
  358. if isinstance(url_or_request, (compat_str, str)):
  359. url_or_request = url_or_request.partition('#')[0]
  360. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query)
  361. if urlh is False:
  362. assert not fatal
  363. return False
  364. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  365. return (content, urlh)
  366. @staticmethod
  367. def _guess_encoding_from_content(content_type, webpage_bytes):
  368. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  369. if m:
  370. encoding = m.group(1)
  371. else:
  372. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  373. webpage_bytes[:1024])
  374. if m:
  375. encoding = m.group(1).decode('ascii')
  376. elif webpage_bytes.startswith(b'\xff\xfe'):
  377. encoding = 'utf-16'
  378. else:
  379. encoding = 'utf-8'
  380. return encoding
  381. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  382. content_type = urlh.headers.get('Content-Type', '')
  383. webpage_bytes = urlh.read()
  384. if prefix is not None:
  385. webpage_bytes = prefix + webpage_bytes
  386. if not encoding:
  387. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  388. if self._downloader.params.get('dump_intermediate_pages', False):
  389. try:
  390. url = url_or_request.get_full_url()
  391. except AttributeError:
  392. url = url_or_request
  393. self.to_screen('Dumping request to ' + url)
  394. dump = base64.b64encode(webpage_bytes).decode('ascii')
  395. self._downloader.to_screen(dump)
  396. if self._downloader.params.get('write_pages', False):
  397. try:
  398. url = url_or_request.get_full_url()
  399. except AttributeError:
  400. url = url_or_request
  401. basen = '%s_%s' % (video_id, url)
  402. if len(basen) > 240:
  403. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  404. basen = basen[:240 - len(h)] + h
  405. raw_filename = basen + '.dump'
  406. filename = sanitize_filename(raw_filename, restricted=True)
  407. self.to_screen('Saving request to ' + filename)
  408. # Working around MAX_PATH limitation on Windows (see
  409. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  410. if compat_os_name == 'nt':
  411. absfilepath = os.path.abspath(filename)
  412. if len(absfilepath) > 259:
  413. filename = '\\\\?\\' + absfilepath
  414. with open(filename, 'wb') as outf:
  415. outf.write(webpage_bytes)
  416. try:
  417. content = webpage_bytes.decode(encoding, 'replace')
  418. except LookupError:
  419. content = webpage_bytes.decode('utf-8', 'replace')
  420. if ('<title>Access to this site is blocked</title>' in content and
  421. 'Websense' in content[:512]):
  422. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  423. blocked_iframe = self._html_search_regex(
  424. r'<iframe src="([^"]+)"', content,
  425. 'Websense information URL', default=None)
  426. if blocked_iframe:
  427. msg += ' Visit %s for more details' % blocked_iframe
  428. raise ExtractorError(msg, expected=True)
  429. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  430. msg = (
  431. 'Access to this webpage has been blocked by Indian censorship. '
  432. 'Use a VPN or proxy server (with --proxy) to route around it.')
  433. block_msg = self._html_search_regex(
  434. r'</h1><p>(.*?)</p>',
  435. content, 'block message', default=None)
  436. if block_msg:
  437. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  438. raise ExtractorError(msg, expected=True)
  439. return content
  440. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None, data=None, headers={}, query={}):
  441. """ Returns the data of the page as a string """
  442. success = False
  443. try_count = 0
  444. while success is False:
  445. try:
  446. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding, data=data, headers=headers, query=query)
  447. success = True
  448. except compat_http_client.IncompleteRead as e:
  449. try_count += 1
  450. if try_count >= tries:
  451. raise e
  452. self._sleep(timeout, video_id)
  453. if res is False:
  454. return res
  455. else:
  456. content, _ = res
  457. return content
  458. def _download_xml(self, url_or_request, video_id,
  459. note='Downloading XML', errnote='Unable to download XML',
  460. transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  461. """Return the xml as an xml.etree.ElementTree.Element"""
  462. xml_string = self._download_webpage(
  463. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding, data=data, headers=headers, query=query)
  464. if xml_string is False:
  465. return xml_string
  466. if transform_source:
  467. xml_string = transform_source(xml_string)
  468. return compat_etree_fromstring(xml_string.encode('utf-8'))
  469. def _download_json(self, url_or_request, video_id,
  470. note='Downloading JSON metadata',
  471. errnote='Unable to download JSON metadata',
  472. transform_source=None,
  473. fatal=True, encoding=None, data=None, headers={}, query={}):
  474. json_string = self._download_webpage(
  475. url_or_request, video_id, note, errnote, fatal=fatal,
  476. encoding=encoding, data=data, headers=headers, query=query)
  477. if (not fatal) and json_string is False:
  478. return None
  479. return self._parse_json(
  480. json_string, video_id, transform_source=transform_source, fatal=fatal)
  481. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  482. if transform_source:
  483. json_string = transform_source(json_string)
  484. try:
  485. return json.loads(json_string)
  486. except ValueError as ve:
  487. errmsg = '%s: Failed to parse JSON ' % video_id
  488. if fatal:
  489. raise ExtractorError(errmsg, cause=ve)
  490. else:
  491. self.report_warning(errmsg + str(ve))
  492. def report_warning(self, msg, video_id=None):
  493. idstr = '' if video_id is None else '%s: ' % video_id
  494. self._downloader.report_warning(
  495. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  496. def to_screen(self, msg):
  497. """Print msg to screen, prefixing it with '[ie_name]'"""
  498. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  499. def report_extraction(self, id_or_name):
  500. """Report information extraction."""
  501. self.to_screen('%s: Extracting information' % id_or_name)
  502. def report_download_webpage(self, video_id):
  503. """Report webpage download."""
  504. self.to_screen('%s: Downloading webpage' % video_id)
  505. def report_age_confirmation(self):
  506. """Report attempt to confirm age."""
  507. self.to_screen('Confirming age')
  508. def report_login(self):
  509. """Report attempt to log in."""
  510. self.to_screen('Logging in')
  511. @staticmethod
  512. def raise_login_required(msg='This video is only available for registered users'):
  513. raise ExtractorError(
  514. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  515. expected=True)
  516. @staticmethod
  517. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction'):
  518. raise ExtractorError(
  519. '%s. You might want to use --proxy to workaround.' % msg,
  520. expected=True)
  521. # Methods for following #608
  522. @staticmethod
  523. def url_result(url, ie=None, video_id=None, video_title=None):
  524. """Returns a URL that points to a page that should be processed"""
  525. # TODO: ie should be the class used for getting the info
  526. video_info = {'_type': 'url',
  527. 'url': url,
  528. 'ie_key': ie}
  529. if video_id is not None:
  530. video_info['id'] = video_id
  531. if video_title is not None:
  532. video_info['title'] = video_title
  533. return video_info
  534. @staticmethod
  535. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  536. """Returns a playlist"""
  537. video_info = {'_type': 'playlist',
  538. 'entries': entries}
  539. if playlist_id:
  540. video_info['id'] = playlist_id
  541. if playlist_title:
  542. video_info['title'] = playlist_title
  543. if playlist_description:
  544. video_info['description'] = playlist_description
  545. return video_info
  546. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  547. """
  548. Perform a regex search on the given string, using a single or a list of
  549. patterns returning the first matching group.
  550. In case of failure return a default value or raise a WARNING or a
  551. RegexNotFoundError, depending on fatal, specifying the field name.
  552. """
  553. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  554. mobj = re.search(pattern, string, flags)
  555. else:
  556. for p in pattern:
  557. mobj = re.search(p, string, flags)
  558. if mobj:
  559. break
  560. if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  561. _name = '\033[0;34m%s\033[0m' % name
  562. else:
  563. _name = name
  564. if mobj:
  565. if group is None:
  566. # return the first matching group
  567. return next(g for g in mobj.groups() if g is not None)
  568. else:
  569. return mobj.group(group)
  570. elif default is not NO_DEFAULT:
  571. return default
  572. elif fatal:
  573. raise RegexNotFoundError('Unable to extract %s' % _name)
  574. else:
  575. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  576. return None
  577. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  578. """
  579. Like _search_regex, but strips HTML tags and unescapes entities.
  580. """
  581. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  582. if res:
  583. return clean_html(res).strip()
  584. else:
  585. return res
  586. def _get_login_info(self):
  587. """
  588. Get the login info as (username, password)
  589. It will look in the netrc file using the _NETRC_MACHINE value
  590. If there's no info available, return (None, None)
  591. """
  592. if self._downloader is None:
  593. return (None, None)
  594. username = None
  595. password = None
  596. downloader_params = self._downloader.params
  597. # Attempt to use provided username and password or .netrc data
  598. if downloader_params.get('username') is not None:
  599. username = downloader_params['username']
  600. password = downloader_params['password']
  601. elif downloader_params.get('usenetrc', False):
  602. try:
  603. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  604. if info is not None:
  605. username = info[0]
  606. password = info[2]
  607. else:
  608. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  609. except (IOError, netrc.NetrcParseError) as err:
  610. self._downloader.report_warning('parsing .netrc: %s' % error_to_compat_str(err))
  611. return (username, password)
  612. def _get_tfa_info(self, note='two-factor verification code'):
  613. """
  614. Get the two-factor authentication info
  615. TODO - asking the user will be required for sms/phone verify
  616. currently just uses the command line option
  617. If there's no info available, return None
  618. """
  619. if self._downloader is None:
  620. return None
  621. downloader_params = self._downloader.params
  622. if downloader_params.get('twofactor') is not None:
  623. return downloader_params['twofactor']
  624. return compat_getpass('Type %s and press [Return]: ' % note)
  625. # Helper functions for extracting OpenGraph info
  626. @staticmethod
  627. def _og_regexes(prop):
  628. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  629. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  630. % {'prop': re.escape(prop)})
  631. template = r'<meta[^>]+?%s[^>]+?%s'
  632. return [
  633. template % (property_re, content_re),
  634. template % (content_re, property_re),
  635. ]
  636. @staticmethod
  637. def _meta_regex(prop):
  638. return r'''(?isx)<meta
  639. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  640. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  641. def _og_search_property(self, prop, html, name=None, **kargs):
  642. if name is None:
  643. name = 'OpenGraph %s' % prop
  644. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  645. if escaped is None:
  646. return None
  647. return unescapeHTML(escaped)
  648. def _og_search_thumbnail(self, html, **kargs):
  649. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  650. def _og_search_description(self, html, **kargs):
  651. return self._og_search_property('description', html, fatal=False, **kargs)
  652. def _og_search_title(self, html, **kargs):
  653. return self._og_search_property('title', html, **kargs)
  654. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  655. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  656. if secure:
  657. regexes = self._og_regexes('video:secure_url') + regexes
  658. return self._html_search_regex(regexes, html, name, **kargs)
  659. def _og_search_url(self, html, **kargs):
  660. return self._og_search_property('url', html, **kargs)
  661. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  662. if not isinstance(name, (list, tuple)):
  663. name = [name]
  664. if display_name is None:
  665. display_name = name[0]
  666. return self._html_search_regex(
  667. [self._meta_regex(n) for n in name],
  668. html, display_name, fatal=fatal, group='content', **kwargs)
  669. def _dc_search_uploader(self, html):
  670. return self._html_search_meta('dc.creator', html, 'uploader')
  671. def _rta_search(self, html):
  672. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  673. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  674. r' content="RTA-5042-1996-1400-1577-RTA"',
  675. html):
  676. return 18
  677. return 0
  678. def _media_rating_search(self, html):
  679. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  680. rating = self._html_search_meta('rating', html)
  681. if not rating:
  682. return None
  683. RATING_TABLE = {
  684. 'safe for kids': 0,
  685. 'general': 8,
  686. '14 years': 14,
  687. 'mature': 17,
  688. 'restricted': 19,
  689. }
  690. return RATING_TABLE.get(rating.lower())
  691. def _family_friendly_search(self, html):
  692. # See http://schema.org/VideoObject
  693. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  694. if not family_friendly:
  695. return None
  696. RATING_TABLE = {
  697. '1': 0,
  698. 'true': 0,
  699. '0': 18,
  700. 'false': 18,
  701. }
  702. return RATING_TABLE.get(family_friendly.lower())
  703. def _twitter_search_player(self, html):
  704. return self._html_search_meta('twitter:player', html,
  705. 'twitter card player')
  706. def _search_json_ld(self, html, video_id, **kwargs):
  707. json_ld = self._search_regex(
  708. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  709. html, 'JSON-LD', group='json_ld', **kwargs)
  710. if not json_ld:
  711. return {}
  712. return self._json_ld(json_ld, video_id, fatal=kwargs.get('fatal', True))
  713. def _json_ld(self, json_ld, video_id, fatal=True):
  714. if isinstance(json_ld, compat_str):
  715. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  716. if not json_ld:
  717. return {}
  718. info = {}
  719. if json_ld.get('@context') == 'http://schema.org':
  720. item_type = json_ld.get('@type')
  721. if item_type == 'TVEpisode':
  722. info.update({
  723. 'episode': unescapeHTML(json_ld.get('name')),
  724. 'episode_number': int_or_none(json_ld.get('episodeNumber')),
  725. 'description': unescapeHTML(json_ld.get('description')),
  726. })
  727. part_of_season = json_ld.get('partOfSeason')
  728. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  729. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  730. part_of_series = json_ld.get('partOfSeries')
  731. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  732. info['series'] = unescapeHTML(part_of_series.get('name'))
  733. elif item_type == 'Article':
  734. info.update({
  735. 'timestamp': parse_iso8601(json_ld.get('datePublished')),
  736. 'title': unescapeHTML(json_ld.get('headline')),
  737. 'description': unescapeHTML(json_ld.get('articleBody')),
  738. })
  739. elif item_type == 'VideoObject':
  740. info.update({
  741. 'title': unescapeHTML(json_ld.get('name')),
  742. 'description': unescapeHTML(json_ld.get('description')),
  743. 'upload_date': unified_strdate(json_ld.get('upload_date')),
  744. 'url': unescapeHTML(json_ld.get('contentUrl')),
  745. })
  746. return dict((k, v) for k, v in info.items() if v is not None)
  747. @staticmethod
  748. def _hidden_inputs(html):
  749. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  750. hidden_inputs = {}
  751. for input in re.findall(r'(?i)<input([^>]+)>', html):
  752. if not re.search(r'type=(["\'])(?:hidden|submit)\1', input):
  753. continue
  754. name = re.search(r'(?:name|id)=(["\'])(?P<value>.+?)\1', input)
  755. if not name:
  756. continue
  757. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  758. if not value:
  759. continue
  760. hidden_inputs[name.group('value')] = value.group('value')
  761. return hidden_inputs
  762. def _form_hidden_inputs(self, form_id, html):
  763. form = self._search_regex(
  764. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  765. html, '%s form' % form_id, group='form')
  766. return self._hidden_inputs(form)
  767. def _sort_formats(self, formats, field_preference=None):
  768. if not formats:
  769. raise ExtractorError('No video formats found')
  770. for f in formats:
  771. # Automatically determine tbr when missing based on abr and vbr (improves
  772. # formats sorting in some cases)
  773. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  774. f['tbr'] = f['abr'] + f['vbr']
  775. def _formats_key(f):
  776. # TODO remove the following workaround
  777. from ..utils import determine_ext
  778. if not f.get('ext') and 'url' in f:
  779. f['ext'] = determine_ext(f['url'])
  780. if isinstance(field_preference, (list, tuple)):
  781. return tuple(
  782. f.get(field)
  783. if f.get(field) is not None
  784. else ('' if field == 'format_id' else -1)
  785. for field in field_preference)
  786. preference = f.get('preference')
  787. if preference is None:
  788. preference = 0
  789. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  790. preference -= 0.5
  791. proto_preference = 0 if determine_protocol(f) in ['http', 'https'] else -0.1
  792. if f.get('vcodec') == 'none': # audio only
  793. preference -= 50
  794. if self._downloader.params.get('prefer_free_formats'):
  795. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  796. else:
  797. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  798. ext_preference = 0
  799. try:
  800. audio_ext_preference = ORDER.index(f['ext'])
  801. except ValueError:
  802. audio_ext_preference = -1
  803. else:
  804. if f.get('acodec') == 'none': # video only
  805. preference -= 40
  806. if self._downloader.params.get('prefer_free_formats'):
  807. ORDER = ['flv', 'mp4', 'webm']
  808. else:
  809. ORDER = ['webm', 'flv', 'mp4']
  810. try:
  811. ext_preference = ORDER.index(f['ext'])
  812. except ValueError:
  813. ext_preference = -1
  814. audio_ext_preference = 0
  815. return (
  816. preference,
  817. f.get('language_preference') if f.get('language_preference') is not None else -1,
  818. f.get('quality') if f.get('quality') is not None else -1,
  819. f.get('tbr') if f.get('tbr') is not None else -1,
  820. f.get('filesize') if f.get('filesize') is not None else -1,
  821. f.get('vbr') if f.get('vbr') is not None else -1,
  822. f.get('height') if f.get('height') is not None else -1,
  823. f.get('width') if f.get('width') is not None else -1,
  824. proto_preference,
  825. ext_preference,
  826. f.get('abr') if f.get('abr') is not None else -1,
  827. audio_ext_preference,
  828. f.get('fps') if f.get('fps') is not None else -1,
  829. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  830. f.get('source_preference') if f.get('source_preference') is not None else -1,
  831. f.get('format_id') if f.get('format_id') is not None else '',
  832. )
  833. formats.sort(key=_formats_key)
  834. def _check_formats(self, formats, video_id):
  835. if formats:
  836. formats[:] = filter(
  837. lambda f: self._is_valid_url(
  838. f['url'], video_id,
  839. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  840. formats)
  841. @staticmethod
  842. def _remove_duplicate_formats(formats):
  843. format_urls = set()
  844. unique_formats = []
  845. for f in formats:
  846. if f['url'] not in format_urls:
  847. format_urls.add(f['url'])
  848. unique_formats.append(f)
  849. formats[:] = unique_formats
  850. def _is_valid_url(self, url, video_id, item='video'):
  851. url = self._proto_relative_url(url, scheme='http:')
  852. # For now assume non HTTP(S) URLs always valid
  853. if not (url.startswith('http://') or url.startswith('https://')):
  854. return True
  855. try:
  856. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  857. return True
  858. except ExtractorError as e:
  859. if isinstance(e.cause, compat_urllib_error.URLError):
  860. self.to_screen(
  861. '%s: %s URL is invalid, skipping' % (video_id, item))
  862. return False
  863. raise
  864. def http_scheme(self):
  865. """ Either "http:" or "https:", depending on the user's preferences """
  866. return (
  867. 'http:'
  868. if self._downloader.params.get('prefer_insecure', False)
  869. else 'https:')
  870. def _proto_relative_url(self, url, scheme=None):
  871. if url is None:
  872. return url
  873. if url.startswith('//'):
  874. if scheme is None:
  875. scheme = self.http_scheme()
  876. return scheme + url
  877. else:
  878. return url
  879. def _sleep(self, timeout, video_id, msg_template=None):
  880. if msg_template is None:
  881. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  882. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  883. self.to_screen(msg)
  884. time.sleep(timeout)
  885. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  886. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  887. fatal=True, m3u8_id=None):
  888. manifest = self._download_xml(
  889. manifest_url, video_id, 'Downloading f4m manifest',
  890. 'Unable to download f4m manifest',
  891. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  892. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  893. transform_source=transform_source,
  894. fatal=fatal)
  895. if manifest is False:
  896. return []
  897. return self._parse_f4m_formats(
  898. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  899. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  900. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  901. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  902. fatal=True, m3u8_id=None):
  903. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  904. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  905. if akamai_pv is not None and ';' in akamai_pv.text:
  906. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  907. if playerVerificationChallenge.strip() != '':
  908. return []
  909. formats = []
  910. manifest_version = '1.0'
  911. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  912. if not media_nodes:
  913. manifest_version = '2.0'
  914. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  915. # Remove unsupported DRM protected media from final formats
  916. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  917. media_nodes = remove_encrypted_media(media_nodes)
  918. if not media_nodes:
  919. return formats
  920. base_url = xpath_text(
  921. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  922. 'base URL', default=None)
  923. if base_url:
  924. base_url = base_url.strip()
  925. bootstrap_info = xpath_element(
  926. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  927. 'bootstrap info', default=None)
  928. for i, media_el in enumerate(media_nodes):
  929. tbr = int_or_none(media_el.attrib.get('bitrate'))
  930. width = int_or_none(media_el.attrib.get('width'))
  931. height = int_or_none(media_el.attrib.get('height'))
  932. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  933. # If <bootstrapInfo> is present, the specified f4m is a
  934. # stream-level manifest, and only set-level manifests may refer to
  935. # external resources. See section 11.4 and section 4 of F4M spec
  936. if bootstrap_info is None:
  937. media_url = None
  938. # @href is introduced in 2.0, see section 11.6 of F4M spec
  939. if manifest_version == '2.0':
  940. media_url = media_el.attrib.get('href')
  941. if media_url is None:
  942. media_url = media_el.attrib.get('url')
  943. if not media_url:
  944. continue
  945. manifest_url = (
  946. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  947. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  948. # If media_url is itself a f4m manifest do the recursive extraction
  949. # since bitrates in parent manifest (this one) and media_url manifest
  950. # may differ leading to inability to resolve the format by requested
  951. # bitrate in f4m downloader
  952. ext = determine_ext(manifest_url)
  953. if ext == 'f4m':
  954. f4m_formats = self._extract_f4m_formats(
  955. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  956. transform_source=transform_source, fatal=fatal)
  957. # Sometimes stream-level manifest contains single media entry that
  958. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  959. # At the same time parent's media entry in set-level manifest may
  960. # contain it. We will copy it from parent in such cases.
  961. if len(f4m_formats) == 1:
  962. f = f4m_formats[0]
  963. f.update({
  964. 'tbr': f.get('tbr') or tbr,
  965. 'width': f.get('width') or width,
  966. 'height': f.get('height') or height,
  967. 'format_id': f.get('format_id') if not tbr else format_id,
  968. })
  969. formats.extend(f4m_formats)
  970. continue
  971. elif ext == 'm3u8':
  972. formats.extend(self._extract_m3u8_formats(
  973. manifest_url, video_id, 'mp4', preference=preference,
  974. m3u8_id=m3u8_id, fatal=fatal))
  975. continue
  976. formats.append({
  977. 'format_id': format_id,
  978. 'url': manifest_url,
  979. 'ext': 'flv' if bootstrap_info is not None else None,
  980. 'tbr': tbr,
  981. 'width': width,
  982. 'height': height,
  983. 'preference': preference,
  984. })
  985. return formats
  986. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  987. return {
  988. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  989. 'url': m3u8_url,
  990. 'ext': ext,
  991. 'protocol': 'm3u8',
  992. 'preference': preference - 1 if preference else -1,
  993. 'resolution': 'multiple',
  994. 'format_note': 'Quality selection URL',
  995. }
  996. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  997. entry_protocol='m3u8', preference=None,
  998. m3u8_id=None, note=None, errnote=None,
  999. fatal=True, live=False):
  1000. formats = [self._m3u8_meta_format(m3u8_url, ext, preference, m3u8_id)]
  1001. format_url = lambda u: (
  1002. u
  1003. if re.match(r'^https?://', u)
  1004. else compat_urlparse.urljoin(m3u8_url, u))
  1005. res = self._download_webpage_handle(
  1006. m3u8_url, video_id,
  1007. note=note or 'Downloading m3u8 information',
  1008. errnote=errnote or 'Failed to download m3u8 information',
  1009. fatal=fatal)
  1010. if res is False:
  1011. return []
  1012. m3u8_doc, urlh = res
  1013. m3u8_url = urlh.geturl()
  1014. # We should try extracting formats only from master playlists [1], i.e.
  1015. # playlists that describe available qualities. On the other hand media
  1016. # playlists [2] should be returned as is since they contain just the media
  1017. # without qualities renditions.
  1018. # Fortunately, master playlist can be easily distinguished from media
  1019. # playlist based on particular tags availability. As of [1, 2] master
  1020. # playlist tags MUST NOT appear in a media playist and vice versa.
  1021. # As of [3] #EXT-X-TARGETDURATION tag is REQUIRED for every media playlist
  1022. # and MUST NOT appear in master playlist thus we can clearly detect media
  1023. # playlist with this criterion.
  1024. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.4
  1025. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  1026. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  1027. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1028. return [{
  1029. 'url': m3u8_url,
  1030. 'format_id': m3u8_id,
  1031. 'ext': ext,
  1032. 'protocol': entry_protocol,
  1033. 'preference': preference,
  1034. }]
  1035. last_info = None
  1036. last_media = None
  1037. for line in m3u8_doc.splitlines():
  1038. if line.startswith('#EXT-X-STREAM-INF:'):
  1039. last_info = parse_m3u8_attributes(line)
  1040. elif line.startswith('#EXT-X-MEDIA:'):
  1041. last_media = parse_m3u8_attributes(line)
  1042. elif line.startswith('#') or not line.strip():
  1043. continue
  1044. else:
  1045. if last_info is None:
  1046. formats.append({'url': format_url(line)})
  1047. continue
  1048. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  1049. format_id = []
  1050. if m3u8_id:
  1051. format_id.append(m3u8_id)
  1052. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') not in ('SUBTITLES', 'CLOSED-CAPTIONS') else None
  1053. # Despite specification does not mention NAME attribute for
  1054. # EXT-X-STREAM-INF it still sometimes may be present
  1055. stream_name = last_info.get('NAME') or last_media_name
  1056. # Bandwidth of live streams may differ over time thus making
  1057. # format_id unpredictable. So it's better to keep provided
  1058. # format_id intact.
  1059. if not live:
  1060. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1061. f = {
  1062. 'format_id': '-'.join(format_id),
  1063. 'url': format_url(line.strip()),
  1064. 'tbr': tbr,
  1065. 'ext': ext,
  1066. 'protocol': entry_protocol,
  1067. 'preference': preference,
  1068. }
  1069. resolution = last_info.get('RESOLUTION')
  1070. if resolution:
  1071. width_str, height_str = resolution.split('x')
  1072. f['width'] = int(width_str)
  1073. f['height'] = int(height_str)
  1074. codecs = last_info.get('CODECS')
  1075. if codecs:
  1076. vcodec, acodec = [None] * 2
  1077. va_codecs = codecs.split(',')
  1078. if len(va_codecs) == 1:
  1079. # Audio only entries usually come with single codec and
  1080. # no resolution. For more robustness we also check it to
  1081. # be mp4 audio.
  1082. if not resolution and va_codecs[0].startswith('mp4a'):
  1083. vcodec, acodec = 'none', va_codecs[0]
  1084. else:
  1085. vcodec = va_codecs[0]
  1086. else:
  1087. vcodec, acodec = va_codecs[:2]
  1088. f.update({
  1089. 'acodec': acodec,
  1090. 'vcodec': vcodec,
  1091. })
  1092. if last_media is not None:
  1093. f['m3u8_media'] = last_media
  1094. last_media = None
  1095. formats.append(f)
  1096. last_info = {}
  1097. return formats
  1098. @staticmethod
  1099. def _xpath_ns(path, namespace=None):
  1100. if not namespace:
  1101. return path
  1102. out = []
  1103. for c in path.split('/'):
  1104. if not c or c == '.':
  1105. out.append(c)
  1106. else:
  1107. out.append('{%s}%s' % (namespace, c))
  1108. return '/'.join(out)
  1109. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1110. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1111. if smil is False:
  1112. assert not fatal
  1113. return []
  1114. namespace = self._parse_smil_namespace(smil)
  1115. return self._parse_smil_formats(
  1116. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1117. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1118. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1119. if smil is False:
  1120. return {}
  1121. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1122. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1123. return self._download_xml(
  1124. smil_url, video_id, 'Downloading SMIL file',
  1125. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1126. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1127. namespace = self._parse_smil_namespace(smil)
  1128. formats = self._parse_smil_formats(
  1129. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1130. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1131. video_id = os.path.splitext(url_basename(smil_url))[0]
  1132. title = None
  1133. description = None
  1134. upload_date = None
  1135. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1136. name = meta.attrib.get('name')
  1137. content = meta.attrib.get('content')
  1138. if not name or not content:
  1139. continue
  1140. if not title and name == 'title':
  1141. title = content
  1142. elif not description and name in ('description', 'abstract'):
  1143. description = content
  1144. elif not upload_date and name == 'date':
  1145. upload_date = unified_strdate(content)
  1146. thumbnails = [{
  1147. 'id': image.get('type'),
  1148. 'url': image.get('src'),
  1149. 'width': int_or_none(image.get('width')),
  1150. 'height': int_or_none(image.get('height')),
  1151. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1152. return {
  1153. 'id': video_id,
  1154. 'title': title or video_id,
  1155. 'description': description,
  1156. 'upload_date': upload_date,
  1157. 'thumbnails': thumbnails,
  1158. 'formats': formats,
  1159. 'subtitles': subtitles,
  1160. }
  1161. def _parse_smil_namespace(self, smil):
  1162. return self._search_regex(
  1163. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1164. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1165. base = smil_url
  1166. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1167. b = meta.get('base') or meta.get('httpBase')
  1168. if b:
  1169. base = b
  1170. break
  1171. formats = []
  1172. rtmp_count = 0
  1173. http_count = 0
  1174. m3u8_count = 0
  1175. srcs = []
  1176. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1177. for medium in media:
  1178. src = medium.get('src')
  1179. if not src or src in srcs:
  1180. continue
  1181. srcs.append(src)
  1182. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1183. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1184. width = int_or_none(medium.get('width'))
  1185. height = int_or_none(medium.get('height'))
  1186. proto = medium.get('proto')
  1187. ext = medium.get('ext')
  1188. src_ext = determine_ext(src)
  1189. streamer = medium.get('streamer') or base
  1190. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1191. rtmp_count += 1
  1192. formats.append({
  1193. 'url': streamer,
  1194. 'play_path': src,
  1195. 'ext': 'flv',
  1196. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1197. 'tbr': bitrate,
  1198. 'filesize': filesize,
  1199. 'width': width,
  1200. 'height': height,
  1201. })
  1202. if transform_rtmp_url:
  1203. streamer, src = transform_rtmp_url(streamer, src)
  1204. formats[-1].update({
  1205. 'url': streamer,
  1206. 'play_path': src,
  1207. })
  1208. continue
  1209. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1210. src_url = src_url.strip()
  1211. if proto == 'm3u8' or src_ext == 'm3u8':
  1212. m3u8_formats = self._extract_m3u8_formats(
  1213. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1214. if len(m3u8_formats) == 1:
  1215. m3u8_count += 1
  1216. m3u8_formats[0].update({
  1217. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1218. 'tbr': bitrate,
  1219. 'width': width,
  1220. 'height': height,
  1221. })
  1222. formats.extend(m3u8_formats)
  1223. continue
  1224. if src_ext == 'f4m':
  1225. f4m_url = src_url
  1226. if not f4m_params:
  1227. f4m_params = {
  1228. 'hdcore': '3.2.0',
  1229. 'plugin': 'flowplayer-3.2.0.1',
  1230. }
  1231. f4m_url += '&' if '?' in f4m_url else '?'
  1232. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1233. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1234. continue
  1235. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1236. http_count += 1
  1237. formats.append({
  1238. 'url': src_url,
  1239. 'ext': ext or src_ext or 'flv',
  1240. 'format_id': 'http-%d' % (bitrate or http_count),
  1241. 'tbr': bitrate,
  1242. 'filesize': filesize,
  1243. 'width': width,
  1244. 'height': height,
  1245. })
  1246. continue
  1247. return formats
  1248. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1249. urls = []
  1250. subtitles = {}
  1251. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1252. src = textstream.get('src')
  1253. if not src or src in urls:
  1254. continue
  1255. urls.append(src)
  1256. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1257. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1258. subtitles.setdefault(lang, []).append({
  1259. 'url': src,
  1260. 'ext': ext,
  1261. })
  1262. return subtitles
  1263. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1264. xspf = self._download_xml(
  1265. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1266. 'Unable to download xspf manifest', fatal=fatal)
  1267. if xspf is False:
  1268. return []
  1269. return self._parse_xspf(xspf, playlist_id)
  1270. def _parse_xspf(self, playlist, playlist_id):
  1271. NS_MAP = {
  1272. 'xspf': 'http://xspf.org/ns/0/',
  1273. 's1': 'http://static.streamone.nl/player/ns/0',
  1274. }
  1275. entries = []
  1276. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1277. title = xpath_text(
  1278. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1279. description = xpath_text(
  1280. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1281. thumbnail = xpath_text(
  1282. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1283. duration = float_or_none(
  1284. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1285. formats = [{
  1286. 'url': location.text,
  1287. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1288. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1289. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1290. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1291. self._sort_formats(formats)
  1292. entries.append({
  1293. 'id': playlist_id,
  1294. 'title': title,
  1295. 'description': description,
  1296. 'thumbnail': thumbnail,
  1297. 'duration': duration,
  1298. 'formats': formats,
  1299. })
  1300. return entries
  1301. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1302. res = self._download_webpage_handle(
  1303. mpd_url, video_id,
  1304. note=note or 'Downloading MPD manifest',
  1305. errnote=errnote or 'Failed to download MPD manifest',
  1306. fatal=fatal)
  1307. if res is False:
  1308. return []
  1309. mpd, urlh = res
  1310. mpd_base_url = re.match(r'https?://.+/', urlh.geturl()).group()
  1311. return self._parse_mpd_formats(
  1312. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url, formats_dict=formats_dict)
  1313. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}):
  1314. if mpd_doc.get('type') == 'dynamic':
  1315. return []
  1316. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1317. def _add_ns(path):
  1318. return self._xpath_ns(path, namespace)
  1319. def is_drm_protected(element):
  1320. return element.find(_add_ns('ContentProtection')) is not None
  1321. def extract_multisegment_info(element, ms_parent_info):
  1322. ms_info = ms_parent_info.copy()
  1323. segment_list = element.find(_add_ns('SegmentList'))
  1324. if segment_list is not None:
  1325. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1326. if segment_urls_e:
  1327. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1328. initialization = segment_list.find(_add_ns('Initialization'))
  1329. if initialization is not None:
  1330. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1331. else:
  1332. segment_template = element.find(_add_ns('SegmentTemplate'))
  1333. if segment_template is not None:
  1334. start_number = segment_template.get('startNumber')
  1335. if start_number:
  1336. ms_info['start_number'] = int(start_number)
  1337. segment_timeline = segment_template.find(_add_ns('SegmentTimeline'))
  1338. if segment_timeline is not None:
  1339. s_e = segment_timeline.findall(_add_ns('S'))
  1340. if s_e:
  1341. ms_info['total_number'] = 0
  1342. for s in s_e:
  1343. ms_info['total_number'] += 1 + int(s.get('r', '0'))
  1344. else:
  1345. timescale = segment_template.get('timescale')
  1346. if timescale:
  1347. ms_info['timescale'] = int(timescale)
  1348. segment_duration = segment_template.get('duration')
  1349. if segment_duration:
  1350. ms_info['segment_duration'] = int(segment_duration)
  1351. media_template = segment_template.get('media')
  1352. if media_template:
  1353. ms_info['media_template'] = media_template
  1354. initialization = segment_template.get('initialization')
  1355. if initialization:
  1356. ms_info['initialization_url'] = initialization
  1357. else:
  1358. initialization = segment_template.find(_add_ns('Initialization'))
  1359. if initialization is not None:
  1360. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1361. return ms_info
  1362. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1363. formats = []
  1364. for period in mpd_doc.findall(_add_ns('Period')):
  1365. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1366. period_ms_info = extract_multisegment_info(period, {
  1367. 'start_number': 1,
  1368. 'timescale': 1,
  1369. })
  1370. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1371. if is_drm_protected(adaptation_set):
  1372. continue
  1373. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1374. for representation in adaptation_set.findall(_add_ns('Representation')):
  1375. if is_drm_protected(representation):
  1376. continue
  1377. representation_attrib = adaptation_set.attrib.copy()
  1378. representation_attrib.update(representation.attrib)
  1379. # According to page 41 of ISO/IEC 29001-1:2014, @mimeType is mandatory
  1380. mime_type = representation_attrib['mimeType']
  1381. content_type = mime_type.split('/')[0]
  1382. if content_type == 'text':
  1383. # TODO implement WebVTT downloading
  1384. pass
  1385. elif content_type == 'video' or content_type == 'audio':
  1386. base_url = ''
  1387. for element in (representation, adaptation_set, period, mpd_doc):
  1388. base_url_e = element.find(_add_ns('BaseURL'))
  1389. if base_url_e is not None:
  1390. base_url = base_url_e.text + base_url
  1391. if re.match(r'^https?://', base_url):
  1392. break
  1393. if mpd_base_url and not re.match(r'^https?://', base_url):
  1394. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1395. mpd_base_url += '/'
  1396. base_url = mpd_base_url + base_url
  1397. representation_id = representation_attrib.get('id')
  1398. lang = representation_attrib.get('lang')
  1399. url_el = representation.find(_add_ns('BaseURL'))
  1400. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1401. f = {
  1402. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1403. 'url': base_url,
  1404. 'ext': mimetype2ext(mime_type),
  1405. 'width': int_or_none(representation_attrib.get('width')),
  1406. 'height': int_or_none(representation_attrib.get('height')),
  1407. 'tbr': int_or_none(representation_attrib.get('bandwidth'), 1000),
  1408. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1409. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1410. 'vcodec': 'none' if content_type == 'audio' else representation_attrib.get('codecs'),
  1411. 'acodec': 'none' if content_type == 'video' else representation_attrib.get('codecs'),
  1412. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1413. 'format_note': 'DASH %s' % content_type,
  1414. 'filesize': filesize,
  1415. }
  1416. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1417. if 'segment_urls' not in representation_ms_info and 'media_template' in representation_ms_info:
  1418. if 'total_number' not in representation_ms_info and 'segment_duration':
  1419. segment_duration = float(representation_ms_info['segment_duration']) / float(representation_ms_info['timescale'])
  1420. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1421. media_template = representation_ms_info['media_template']
  1422. media_template = media_template.replace('$RepresentationID$', representation_id)
  1423. media_template = re.sub(r'\$(Number|Bandwidth)\$', r'%(\1)d', media_template)
  1424. media_template = re.sub(r'\$(Number|Bandwidth)%([^$]+)\$', r'%(\1)\2', media_template)
  1425. media_template.replace('$$', '$')
  1426. representation_ms_info['segment_urls'] = [
  1427. media_template % {
  1428. 'Number': segment_number,
  1429. 'Bandwidth': representation_attrib.get('bandwidth')}
  1430. for segment_number in range(
  1431. representation_ms_info['start_number'],
  1432. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1433. if 'segment_urls' in representation_ms_info:
  1434. f.update({
  1435. 'segment_urls': representation_ms_info['segment_urls'],
  1436. 'protocol': 'http_dash_segments',
  1437. })
  1438. if 'initialization_url' in representation_ms_info:
  1439. initialization_url = representation_ms_info['initialization_url'].replace('$RepresentationID$', representation_id)
  1440. f.update({
  1441. 'initialization_url': initialization_url,
  1442. })
  1443. if not f.get('url'):
  1444. f['url'] = initialization_url
  1445. try:
  1446. existing_format = next(
  1447. fo for fo in formats
  1448. if fo['format_id'] == representation_id)
  1449. except StopIteration:
  1450. full_info = formats_dict.get(representation_id, {}).copy()
  1451. full_info.update(f)
  1452. formats.append(full_info)
  1453. else:
  1454. existing_format.update(f)
  1455. else:
  1456. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1457. return formats
  1458. def _live_title(self, name):
  1459. """ Generate the title for a live video """
  1460. now = datetime.datetime.now()
  1461. now_str = now.strftime('%Y-%m-%d %H:%M')
  1462. return name + ' ' + now_str
  1463. def _int(self, v, name, fatal=False, **kwargs):
  1464. res = int_or_none(v, **kwargs)
  1465. if 'get_attr' in kwargs:
  1466. print(getattr(v, kwargs['get_attr']))
  1467. if res is None:
  1468. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1469. if fatal:
  1470. raise ExtractorError(msg)
  1471. else:
  1472. self._downloader.report_warning(msg)
  1473. return res
  1474. def _float(self, v, name, fatal=False, **kwargs):
  1475. res = float_or_none(v, **kwargs)
  1476. if res is None:
  1477. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1478. if fatal:
  1479. raise ExtractorError(msg)
  1480. else:
  1481. self._downloader.report_warning(msg)
  1482. return res
  1483. def _set_cookie(self, domain, name, value, expire_time=None):
  1484. cookie = compat_cookiejar.Cookie(
  1485. 0, name, value, None, None, domain, None,
  1486. None, '/', True, False, expire_time, '', None, None, None)
  1487. self._downloader.cookiejar.set_cookie(cookie)
  1488. def _get_cookies(self, url):
  1489. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1490. req = sanitized_Request(url)
  1491. self._downloader.cookiejar.add_cookie_header(req)
  1492. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1493. def get_testcases(self, include_onlymatching=False):
  1494. t = getattr(self, '_TEST', None)
  1495. if t:
  1496. assert not hasattr(self, '_TESTS'), \
  1497. '%s has _TEST and _TESTS' % type(self).__name__
  1498. tests = [t]
  1499. else:
  1500. tests = getattr(self, '_TESTS', [])
  1501. for t in tests:
  1502. if not include_onlymatching and t.get('only_matching', False):
  1503. continue
  1504. t['name'] = type(self).__name__[:-len('IE')]
  1505. yield t
  1506. def is_suitable(self, age_limit):
  1507. """ Test whether the extractor is generally suitable for the given
  1508. age limit (i.e. pornographic sites are not, all others usually are) """
  1509. any_restricted = False
  1510. for tc in self.get_testcases(include_onlymatching=False):
  1511. if 'playlist' in tc:
  1512. tc = tc['playlist'][0]
  1513. is_restricted = age_restricted(
  1514. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1515. if not is_restricted:
  1516. return True
  1517. any_restricted = any_restricted or is_restricted
  1518. return not any_restricted
  1519. def extract_subtitles(self, *args, **kwargs):
  1520. if (self._downloader.params.get('writesubtitles', False) or
  1521. self._downloader.params.get('listsubtitles')):
  1522. return self._get_subtitles(*args, **kwargs)
  1523. return {}
  1524. def _get_subtitles(self, *args, **kwargs):
  1525. raise NotImplementedError('This method must be implemented by subclasses')
  1526. @staticmethod
  1527. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1528. """ Merge subtitle items for one language. Items with duplicated URLs
  1529. will be dropped. """
  1530. list1_urls = set([item['url'] for item in subtitle_list1])
  1531. ret = list(subtitle_list1)
  1532. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1533. return ret
  1534. @classmethod
  1535. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1536. """ Merge two subtitle dictionaries, language by language. """
  1537. ret = dict(subtitle_dict1)
  1538. for lang in subtitle_dict2:
  1539. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1540. return ret
  1541. def extract_automatic_captions(self, *args, **kwargs):
  1542. if (self._downloader.params.get('writeautomaticsub', False) or
  1543. self._downloader.params.get('listsubtitles')):
  1544. return self._get_automatic_captions(*args, **kwargs)
  1545. return {}
  1546. def _get_automatic_captions(self, *args, **kwargs):
  1547. raise NotImplementedError('This method must be implemented by subclasses')
  1548. def mark_watched(self, *args, **kwargs):
  1549. if (self._downloader.params.get('mark_watched', False) and
  1550. (self._get_login_info()[0] is not None or
  1551. self._downloader.params.get('cookiefile') is not None)):
  1552. self._mark_watched(*args, **kwargs)
  1553. def _mark_watched(self, *args, **kwargs):
  1554. raise NotImplementedError('This method must be implemented by subclasses')
  1555. def geo_verification_headers(self):
  1556. headers = {}
  1557. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  1558. if geo_verification_proxy:
  1559. headers['Ytdl-request-proxy'] = geo_verification_proxy
  1560. return headers
  1561. class SearchInfoExtractor(InfoExtractor):
  1562. """
  1563. Base class for paged search queries extractors.
  1564. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1565. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1566. """
  1567. @classmethod
  1568. def _make_valid_url(cls):
  1569. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1570. @classmethod
  1571. def suitable(cls, url):
  1572. return re.match(cls._make_valid_url(), url) is not None
  1573. def _real_extract(self, query):
  1574. mobj = re.match(self._make_valid_url(), query)
  1575. if mobj is None:
  1576. raise ExtractorError('Invalid search query "%s"' % query)
  1577. prefix = mobj.group('prefix')
  1578. query = mobj.group('query')
  1579. if prefix == '':
  1580. return self._get_n_results(query, 1)
  1581. elif prefix == 'all':
  1582. return self._get_n_results(query, self._MAX_RESULTS)
  1583. else:
  1584. n = int(prefix)
  1585. if n <= 0:
  1586. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1587. elif n > self._MAX_RESULTS:
  1588. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1589. n = self._MAX_RESULTS
  1590. return self._get_n_results(query, n)
  1591. def _get_n_results(self, query, n):
  1592. """Get a specified number of results for a query"""
  1593. raise NotImplementedError('This method must be implemented by subclasses')
  1594. @property
  1595. def SEARCH_KEY(self):
  1596. return self._SEARCH_KEY