common.py 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426
  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 random
  9. import re
  10. import socket
  11. import sys
  12. import time
  13. import math
  14. from ..compat import (
  15. compat_cookiejar,
  16. compat_cookies,
  17. compat_etree_fromstring,
  18. compat_getpass,
  19. compat_http_client,
  20. compat_os_name,
  21. compat_str,
  22. compat_urllib_error,
  23. compat_urllib_parse_unquote,
  24. compat_urllib_parse_urlencode,
  25. compat_urllib_request,
  26. compat_urlparse,
  27. )
  28. from ..downloader.f4m import remove_encrypted_media
  29. from ..utils import (
  30. NO_DEFAULT,
  31. age_restricted,
  32. base_url,
  33. bug_reports_message,
  34. clean_html,
  35. compiled_regex_type,
  36. determine_ext,
  37. error_to_compat_str,
  38. ExtractorError,
  39. fix_xml_ampersands,
  40. float_or_none,
  41. GeoRestrictedError,
  42. GeoUtils,
  43. int_or_none,
  44. js_to_json,
  45. parse_iso8601,
  46. RegexNotFoundError,
  47. sanitize_filename,
  48. sanitized_Request,
  49. unescapeHTML,
  50. unified_strdate,
  51. unified_timestamp,
  52. url_basename,
  53. xpath_element,
  54. xpath_text,
  55. xpath_with_ns,
  56. determine_protocol,
  57. parse_duration,
  58. mimetype2ext,
  59. update_Request,
  60. update_url_query,
  61. parse_m3u8_attributes,
  62. extract_attributes,
  63. parse_codecs,
  64. urljoin,
  65. )
  66. class InfoExtractor(object):
  67. """Information Extractor class.
  68. Information extractors are the classes that, given a URL, extract
  69. information about the video (or videos) the URL refers to. This
  70. information includes the real video URL, the video title, author and
  71. others. The information is stored in a dictionary which is then
  72. passed to the YoutubeDL. The YoutubeDL processes this
  73. information possibly downloading the video to the file system, among
  74. other possible outcomes.
  75. The type field determines the type of the result.
  76. By far the most common value (and the default if _type is missing) is
  77. "video", which indicates a single video.
  78. For a video, the dictionaries must include the following fields:
  79. id: Video identifier.
  80. title: Video title, unescaped.
  81. Additionally, it must contain either a formats entry or a url one:
  82. formats: A list of dictionaries for each format available, ordered
  83. from worst to best quality.
  84. Potential fields:
  85. * url Mandatory. The URL of the video file
  86. * manifest_url
  87. The URL of the manifest file in case of
  88. fragmented media (DASH, hls, hds)
  89. * ext Will be calculated from URL if missing
  90. * format A human-readable description of the format
  91. ("mp4 container with h264/opus").
  92. Calculated from the format_id, width, height.
  93. and format_note fields if missing.
  94. * format_id A short description of the format
  95. ("mp4_h264_opus" or "19").
  96. Technically optional, but strongly recommended.
  97. * format_note Additional info about the format
  98. ("3D" or "DASH video")
  99. * width Width of the video, if known
  100. * height Height of the video, if known
  101. * resolution Textual description of width and height
  102. * tbr Average bitrate of audio and video in KBit/s
  103. * abr Average audio bitrate in KBit/s
  104. * acodec Name of the audio codec in use
  105. * asr Audio sampling rate in Hertz
  106. * vbr Average video bitrate in KBit/s
  107. * fps Frame rate
  108. * vcodec Name of the video codec in use
  109. * container Name of the container format
  110. * filesize The number of bytes, if known in advance
  111. * filesize_approx An estimate for the number of bytes
  112. * player_url SWF Player URL (used for rtmpdump).
  113. * protocol The protocol that will be used for the actual
  114. download, lower-case.
  115. "http", "https", "rtsp", "rtmp", "rtmpe",
  116. "m3u8", "m3u8_native" or "http_dash_segments".
  117. * fragment_base_url
  118. Base URL for fragments. Each fragment's path
  119. value (if present) will be relative to
  120. this URL.
  121. * fragments A list of fragments of a fragmented media.
  122. Each fragment entry must contain either an url
  123. or a path. If an url is present it should be
  124. considered by a client. Otherwise both path and
  125. fragment_base_url must be present. Here is
  126. the list of all potential fields:
  127. * "url" - fragment's URL
  128. * "path" - fragment's path relative to
  129. fragment_base_url
  130. * "duration" (optional, int or float)
  131. * "filesize" (optional, int)
  132. * preference Order number of this format. If this field is
  133. present and not None, the formats get sorted
  134. by this field, regardless of all other values.
  135. -1 for default (order by other properties),
  136. -2 or smaller for less than default.
  137. < -1000 to hide the format (if there is
  138. another one which is strictly better)
  139. * language Language code, e.g. "de" or "en-US".
  140. * language_preference Is this in the language mentioned in
  141. the URL?
  142. 10 if it's what the URL is about,
  143. -1 for default (don't know),
  144. -10 otherwise, other values reserved for now.
  145. * quality Order number of the video quality of this
  146. format, irrespective of the file format.
  147. -1 for default (order by other properties),
  148. -2 or smaller for less than default.
  149. * source_preference Order number for this video source
  150. (quality takes higher priority)
  151. -1 for default (order by other properties),
  152. -2 or smaller for less than default.
  153. * http_headers A dictionary of additional HTTP headers
  154. to add to the request.
  155. * stretched_ratio If given and not 1, indicates that the
  156. video's pixels are not square.
  157. width : height ratio as float.
  158. * no_resume The server does not support resuming the
  159. (HTTP or RTMP) download. Boolean.
  160. url: Final video URL.
  161. ext: Video filename extension.
  162. format: The video format, defaults to ext (used for --get-format)
  163. player_url: SWF Player URL (used for rtmpdump).
  164. The following fields are optional:
  165. alt_title: A secondary title of the video.
  166. display_id An alternative identifier for the video, not necessarily
  167. unique, but available before title. Typically, id is
  168. something like "4234987", title "Dancing naked mole rats",
  169. and display_id "dancing-naked-mole-rats"
  170. thumbnails: A list of dictionaries, with the following entries:
  171. * "id" (optional, string) - Thumbnail format ID
  172. * "url"
  173. * "preference" (optional, int) - quality of the image
  174. * "width" (optional, int)
  175. * "height" (optional, int)
  176. * "resolution" (optional, string "{width}x{height"},
  177. deprecated)
  178. * "filesize" (optional, int)
  179. thumbnail: Full URL to a video thumbnail image.
  180. description: Full video description.
  181. uploader: Full name of the video uploader.
  182. license: License name the video is licensed under.
  183. creator: The creator of the video.
  184. release_date: The date (YYYYMMDD) when the video was released.
  185. timestamp: UNIX timestamp of the moment the video became available.
  186. upload_date: Video upload date (YYYYMMDD).
  187. If not explicitly set, calculated from timestamp.
  188. uploader_id: Nickname or id of the video uploader.
  189. uploader_url: Full URL to a personal webpage of the video uploader.
  190. location: Physical location where the video was filmed.
  191. subtitles: The available subtitles as a dictionary in the format
  192. {tag: subformats}. "tag" is usually a language code, and
  193. "subformats" is a list sorted from lower to higher
  194. preference, each element is a dictionary with the "ext"
  195. entry and one of:
  196. * "data": The subtitles file contents
  197. * "url": A URL pointing to the subtitles file
  198. "ext" will be calculated from URL if missing
  199. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  200. automatically generated captions
  201. duration: Length of the video in seconds, as an integer or float.
  202. view_count: How many users have watched the video on the platform.
  203. like_count: Number of positive ratings of the video
  204. dislike_count: Number of negative ratings of the video
  205. repost_count: Number of reposts of the video
  206. average_rating: Average rating give by users, the scale used depends on the webpage
  207. comment_count: Number of comments on the video
  208. comments: A list of comments, each with one or more of the following
  209. properties (all but one of text or html optional):
  210. * "author" - human-readable name of the comment author
  211. * "author_id" - user ID of the comment author
  212. * "id" - Comment ID
  213. * "html" - Comment as HTML
  214. * "text" - Plain text of the comment
  215. * "timestamp" - UNIX timestamp of comment
  216. * "parent" - ID of the comment this one is replying to.
  217. Set to "root" to indicate that this is a
  218. comment to the original video.
  219. age_limit: Age restriction for the video, as an integer (years)
  220. webpage_url: The URL to the video webpage, if given to youtube-dl it
  221. should allow to get the same result again. (It will be set
  222. by YoutubeDL if it's missing)
  223. categories: A list of categories that the video falls in, for example
  224. ["Sports", "Berlin"]
  225. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  226. is_live: True, False, or None (=unknown). Whether this video is a
  227. live stream that goes on instead of a fixed-length video.
  228. start_time: Time in seconds where the reproduction should start, as
  229. specified in the URL.
  230. end_time: Time in seconds where the reproduction should end, as
  231. specified in the URL.
  232. The following fields should only be used when the video belongs to some logical
  233. chapter or section:
  234. chapter: Name or title of the chapter the video belongs to.
  235. chapter_number: Number of the chapter the video belongs to, as an integer.
  236. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  237. The following fields should only be used when the video is an episode of some
  238. series, programme or podcast:
  239. series: Title of the series or programme the video episode belongs to.
  240. season: Title of the season the video episode belongs to.
  241. season_number: Number of the season the video episode belongs to, as an integer.
  242. season_id: Id of the season the video episode belongs to, as a unicode string.
  243. episode: Title of the video episode. Unlike mandatory video title field,
  244. this field should denote the exact title of the video episode
  245. without any kind of decoration.
  246. episode_number: Number of the video episode within a season, as an integer.
  247. episode_id: Id of the video episode, as a unicode string.
  248. The following fields should only be used when the media is a track or a part of
  249. a music album:
  250. track: Title of the track.
  251. track_number: Number of the track within an album or a disc, as an integer.
  252. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  253. as a unicode string.
  254. artist: Artist(s) of the track.
  255. genre: Genre(s) of the track.
  256. album: Title of the album the track belongs to.
  257. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  258. album_artist: List of all artists appeared on the album (e.g.
  259. "Ash Borer / Fell Voices" or "Various Artists", useful for splits
  260. and compilations).
  261. disc_number: Number of the disc or other physical medium the track belongs to,
  262. as an integer.
  263. release_year: Year (YYYY) when the album was released.
  264. Unless mentioned otherwise, the fields should be Unicode strings.
  265. Unless mentioned otherwise, None is equivalent to absence of information.
  266. _type "playlist" indicates multiple videos.
  267. There must be a key "entries", which is a list, an iterable, or a PagedList
  268. object, each element of which is a valid dictionary by this specification.
  269. Additionally, playlists can have "title", "description" and "id" attributes
  270. with the same semantics as videos (see above).
  271. _type "multi_video" indicates that there are multiple videos that
  272. form a single show, for examples multiple acts of an opera or TV episode.
  273. It must have an entries key like a playlist and contain all the keys
  274. required for a video at the same time.
  275. _type "url" indicates that the video must be extracted from another
  276. location, possibly by a different extractor. Its only required key is:
  277. "url" - the next URL to extract.
  278. The key "ie_key" can be set to the class name (minus the trailing "IE",
  279. e.g. "Youtube") if the extractor class is known in advance.
  280. Additionally, the dictionary may have any properties of the resolved entity
  281. known in advance, for example "title" if the title of the referred video is
  282. known ahead of time.
  283. _type "url_transparent" entities have the same specification as "url", but
  284. indicate that the given additional information is more precise than the one
  285. associated with the resolved URL.
  286. This is useful when a site employs a video service that hosts the video and
  287. its technical metadata, but that video service does not embed a useful
  288. title, description etc.
  289. Subclasses of this one should re-define the _real_initialize() and
  290. _real_extract() methods and define a _VALID_URL regexp.
  291. Probably, they should also be added to the list of extractors.
  292. _GEO_BYPASS attribute may be set to False in order to disable
  293. geo restriction bypass mechanisms for a particular extractor.
  294. Though it won't disable explicit geo restriction bypass based on
  295. country code provided with geo_bypass_country. (experimental)
  296. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  297. countries for this extractor. One of these countries will be used by
  298. geo restriction bypass mechanism right away in order to bypass
  299. geo restriction, of course, if the mechanism is not disabled. (experimental)
  300. Finally, the _WORKING attribute should be set to False for broken IEs
  301. in order to warn the users and skip the tests.
  302. """
  303. _ready = False
  304. _downloader = None
  305. _x_forwarded_for_ip = None
  306. _GEO_BYPASS = True
  307. _GEO_COUNTRIES = None
  308. _WORKING = True
  309. def __init__(self, downloader=None):
  310. """Constructor. Receives an optional downloader."""
  311. self._ready = False
  312. self._x_forwarded_for_ip = None
  313. self.set_downloader(downloader)
  314. @classmethod
  315. def suitable(cls, url):
  316. """Receives a URL and returns True if suitable for this IE."""
  317. # This does not use has/getattr intentionally - we want to know whether
  318. # we have cached the regexp for *this* class, whereas getattr would also
  319. # match the superclass
  320. if '_VALID_URL_RE' not in cls.__dict__:
  321. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  322. return cls._VALID_URL_RE.match(url) is not None
  323. @classmethod
  324. def _match_id(cls, url):
  325. if '_VALID_URL_RE' not in cls.__dict__:
  326. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  327. m = cls._VALID_URL_RE.match(url)
  328. assert m
  329. return m.group('id')
  330. @classmethod
  331. def working(cls):
  332. """Getter method for _WORKING."""
  333. return cls._WORKING
  334. def initialize(self):
  335. """Initializes an instance (authentication, etc)."""
  336. self.__initialize_geo_bypass()
  337. if not self._ready:
  338. self._real_initialize()
  339. self._ready = True
  340. def __initialize_geo_bypass(self):
  341. if not self._x_forwarded_for_ip:
  342. country_code = self._downloader.params.get('geo_bypass_country', None)
  343. # If there is no explicit country for geo bypass specified and
  344. # the extractor is known to be geo restricted let's fake IP
  345. # as X-Forwarded-For right away.
  346. if (not country_code and
  347. self._GEO_BYPASS and
  348. self._downloader.params.get('geo_bypass', True) and
  349. self._GEO_COUNTRIES):
  350. country_code = random.choice(self._GEO_COUNTRIES)
  351. if country_code:
  352. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  353. if self._downloader.params.get('verbose', False):
  354. self._downloader.to_stdout(
  355. '[debug] Using fake %s IP as X-Forwarded-For.' % self._x_forwarded_for_ip)
  356. def extract(self, url):
  357. """Extracts URL information and returns it in list of dicts."""
  358. try:
  359. for _ in range(2):
  360. try:
  361. self.initialize()
  362. ie_result = self._real_extract(url)
  363. if self._x_forwarded_for_ip:
  364. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  365. return ie_result
  366. except GeoRestrictedError as e:
  367. if self.__maybe_fake_ip_and_retry(e.countries):
  368. continue
  369. raise
  370. except ExtractorError:
  371. raise
  372. except compat_http_client.IncompleteRead as e:
  373. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  374. except (KeyError, StopIteration) as e:
  375. raise ExtractorError('An extractor error has occurred.', cause=e)
  376. def __maybe_fake_ip_and_retry(self, countries):
  377. if (not self._downloader.params.get('geo_bypass_country', None) and
  378. self._GEO_BYPASS and
  379. self._downloader.params.get('geo_bypass', True) and
  380. not self._x_forwarded_for_ip and
  381. countries):
  382. self._x_forwarded_for_ip = GeoUtils.random_ipv4(random.choice(countries))
  383. if self._x_forwarded_for_ip:
  384. self.report_warning(
  385. 'Video is geo restricted. Retrying extraction with fake %s IP as X-Forwarded-For.' % self._x_forwarded_for_ip)
  386. return True
  387. return False
  388. def set_downloader(self, downloader):
  389. """Sets the downloader for this IE."""
  390. self._downloader = downloader
  391. def _real_initialize(self):
  392. """Real initialization process. Redefine in subclasses."""
  393. pass
  394. def _real_extract(self, url):
  395. """Real extraction process. Redefine in subclasses."""
  396. pass
  397. @classmethod
  398. def ie_key(cls):
  399. """A string for getting the InfoExtractor with get_info_extractor"""
  400. return compat_str(cls.__name__[:-2])
  401. @property
  402. def IE_NAME(self):
  403. return compat_str(type(self).__name__[:-2])
  404. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  405. """ Returns the response handle """
  406. if note is None:
  407. self.report_download_webpage(video_id)
  408. elif note is not False:
  409. if video_id is None:
  410. self.to_screen('%s' % (note,))
  411. else:
  412. self.to_screen('%s: %s' % (video_id, note))
  413. if isinstance(url_or_request, compat_urllib_request.Request):
  414. url_or_request = update_Request(
  415. url_or_request, data=data, headers=headers, query=query)
  416. else:
  417. if query:
  418. url_or_request = update_url_query(url_or_request, query)
  419. if data is not None or headers:
  420. url_or_request = sanitized_Request(url_or_request, data, headers)
  421. try:
  422. return self._downloader.urlopen(url_or_request)
  423. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  424. if errnote is False:
  425. return False
  426. if errnote is None:
  427. errnote = 'Unable to download webpage'
  428. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  429. if fatal:
  430. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  431. else:
  432. self._downloader.report_warning(errmsg)
  433. return False
  434. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  435. """ Returns a tuple (page content as string, URL handle) """
  436. # Strip hashes from the URL (#1038)
  437. if isinstance(url_or_request, (compat_str, str)):
  438. url_or_request = url_or_request.partition('#')[0]
  439. # Some sites check X-Forwarded-For HTTP header in order to figure out
  440. # the origin of the client behind proxy. This allows bypassing geo
  441. # restriction by faking this header's value to IP that belongs to some
  442. # geo unrestricted country. We will do so once we encounter any
  443. # geo restriction error.
  444. if self._x_forwarded_for_ip:
  445. if 'X-Forwarded-For' not in headers:
  446. headers['X-Forwarded-For'] = self._x_forwarded_for_ip
  447. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query)
  448. if urlh is False:
  449. assert not fatal
  450. return False
  451. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  452. return (content, urlh)
  453. @staticmethod
  454. def _guess_encoding_from_content(content_type, webpage_bytes):
  455. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  456. if m:
  457. encoding = m.group(1)
  458. else:
  459. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  460. webpage_bytes[:1024])
  461. if m:
  462. encoding = m.group(1).decode('ascii')
  463. elif webpage_bytes.startswith(b'\xff\xfe'):
  464. encoding = 'utf-16'
  465. else:
  466. encoding = 'utf-8'
  467. return encoding
  468. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  469. content_type = urlh.headers.get('Content-Type', '')
  470. webpage_bytes = urlh.read()
  471. if prefix is not None:
  472. webpage_bytes = prefix + webpage_bytes
  473. if not encoding:
  474. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  475. if self._downloader.params.get('dump_intermediate_pages', False):
  476. try:
  477. url = url_or_request.get_full_url()
  478. except AttributeError:
  479. url = url_or_request
  480. self.to_screen('Dumping request to ' + url)
  481. dump = base64.b64encode(webpage_bytes).decode('ascii')
  482. self._downloader.to_screen(dump)
  483. if self._downloader.params.get('write_pages', False):
  484. try:
  485. url = url_or_request.get_full_url()
  486. except AttributeError:
  487. url = url_or_request
  488. basen = '%s_%s' % (video_id, url)
  489. if len(basen) > 240:
  490. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  491. basen = basen[:240 - len(h)] + h
  492. raw_filename = basen + '.dump'
  493. filename = sanitize_filename(raw_filename, restricted=True)
  494. self.to_screen('Saving request to ' + filename)
  495. # Working around MAX_PATH limitation on Windows (see
  496. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  497. if compat_os_name == 'nt':
  498. absfilepath = os.path.abspath(filename)
  499. if len(absfilepath) > 259:
  500. filename = '\\\\?\\' + absfilepath
  501. with open(filename, 'wb') as outf:
  502. outf.write(webpage_bytes)
  503. try:
  504. content = webpage_bytes.decode(encoding, 'replace')
  505. except LookupError:
  506. content = webpage_bytes.decode('utf-8', 'replace')
  507. if ('<title>Access to this site is blocked</title>' in content and
  508. 'Websense' in content[:512]):
  509. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  510. blocked_iframe = self._html_search_regex(
  511. r'<iframe src="([^"]+)"', content,
  512. 'Websense information URL', default=None)
  513. if blocked_iframe:
  514. msg += ' Visit %s for more details' % blocked_iframe
  515. raise ExtractorError(msg, expected=True)
  516. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  517. msg = (
  518. 'Access to this webpage has been blocked by Indian censorship. '
  519. 'Use a VPN or proxy server (with --proxy) to route around it.')
  520. block_msg = self._html_search_regex(
  521. r'</h1><p>(.*?)</p>',
  522. content, 'block message', default=None)
  523. if block_msg:
  524. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  525. raise ExtractorError(msg, expected=True)
  526. return content
  527. 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={}):
  528. """ Returns the data of the page as a string """
  529. success = False
  530. try_count = 0
  531. while success is False:
  532. try:
  533. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding, data=data, headers=headers, query=query)
  534. success = True
  535. except compat_http_client.IncompleteRead as e:
  536. try_count += 1
  537. if try_count >= tries:
  538. raise e
  539. self._sleep(timeout, video_id)
  540. if res is False:
  541. return res
  542. else:
  543. content, _ = res
  544. return content
  545. def _download_xml(self, url_or_request, video_id,
  546. note='Downloading XML', errnote='Unable to download XML',
  547. transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  548. """Return the xml as an xml.etree.ElementTree.Element"""
  549. xml_string = self._download_webpage(
  550. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding, data=data, headers=headers, query=query)
  551. if xml_string is False:
  552. return xml_string
  553. if transform_source:
  554. xml_string = transform_source(xml_string)
  555. return compat_etree_fromstring(xml_string.encode('utf-8'))
  556. def _download_json(self, url_or_request, video_id,
  557. note='Downloading JSON metadata',
  558. errnote='Unable to download JSON metadata',
  559. transform_source=None,
  560. fatal=True, encoding=None, data=None, headers={}, query={}):
  561. json_string = self._download_webpage(
  562. url_or_request, video_id, note, errnote, fatal=fatal,
  563. encoding=encoding, data=data, headers=headers, query=query)
  564. if (not fatal) and json_string is False:
  565. return None
  566. return self._parse_json(
  567. json_string, video_id, transform_source=transform_source, fatal=fatal)
  568. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  569. if transform_source:
  570. json_string = transform_source(json_string)
  571. try:
  572. return json.loads(json_string)
  573. except ValueError as ve:
  574. errmsg = '%s: Failed to parse JSON ' % video_id
  575. if fatal:
  576. raise ExtractorError(errmsg, cause=ve)
  577. else:
  578. self.report_warning(errmsg + str(ve))
  579. def report_warning(self, msg, video_id=None):
  580. idstr = '' if video_id is None else '%s: ' % video_id
  581. self._downloader.report_warning(
  582. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  583. def to_screen(self, msg):
  584. """Print msg to screen, prefixing it with '[ie_name]'"""
  585. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  586. def report_extraction(self, id_or_name):
  587. """Report information extraction."""
  588. self.to_screen('%s: Extracting information' % id_or_name)
  589. def report_download_webpage(self, video_id):
  590. """Report webpage download."""
  591. self.to_screen('%s: Downloading webpage' % video_id)
  592. def report_age_confirmation(self):
  593. """Report attempt to confirm age."""
  594. self.to_screen('Confirming age')
  595. def report_login(self):
  596. """Report attempt to log in."""
  597. self.to_screen('Logging in')
  598. @staticmethod
  599. def raise_login_required(msg='This video is only available for registered users'):
  600. raise ExtractorError(
  601. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  602. expected=True)
  603. @staticmethod
  604. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction', countries=None):
  605. raise GeoRestrictedError(msg, countries=countries)
  606. # Methods for following #608
  607. @staticmethod
  608. def url_result(url, ie=None, video_id=None, video_title=None):
  609. """Returns a URL that points to a page that should be processed"""
  610. # TODO: ie should be the class used for getting the info
  611. video_info = {'_type': 'url',
  612. 'url': url,
  613. 'ie_key': ie}
  614. if video_id is not None:
  615. video_info['id'] = video_id
  616. if video_title is not None:
  617. video_info['title'] = video_title
  618. return video_info
  619. @staticmethod
  620. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  621. """Returns a playlist"""
  622. video_info = {'_type': 'playlist',
  623. 'entries': entries}
  624. if playlist_id:
  625. video_info['id'] = playlist_id
  626. if playlist_title:
  627. video_info['title'] = playlist_title
  628. if playlist_description:
  629. video_info['description'] = playlist_description
  630. return video_info
  631. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  632. """
  633. Perform a regex search on the given string, using a single or a list of
  634. patterns returning the first matching group.
  635. In case of failure return a default value or raise a WARNING or a
  636. RegexNotFoundError, depending on fatal, specifying the field name.
  637. """
  638. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  639. mobj = re.search(pattern, string, flags)
  640. else:
  641. for p in pattern:
  642. mobj = re.search(p, string, flags)
  643. if mobj:
  644. break
  645. if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  646. _name = '\033[0;34m%s\033[0m' % name
  647. else:
  648. _name = name
  649. if mobj:
  650. if group is None:
  651. # return the first matching group
  652. return next(g for g in mobj.groups() if g is not None)
  653. else:
  654. return mobj.group(group)
  655. elif default is not NO_DEFAULT:
  656. return default
  657. elif fatal:
  658. raise RegexNotFoundError('Unable to extract %s' % _name)
  659. else:
  660. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  661. return None
  662. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  663. """
  664. Like _search_regex, but strips HTML tags and unescapes entities.
  665. """
  666. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  667. if res:
  668. return clean_html(res).strip()
  669. else:
  670. return res
  671. def _get_netrc_login_info(self, netrc_machine=None):
  672. username = None
  673. password = None
  674. netrc_machine = netrc_machine or self._NETRC_MACHINE
  675. if self._downloader.params.get('usenetrc', False):
  676. try:
  677. info = netrc.netrc().authenticators(netrc_machine)
  678. if info is not None:
  679. username = info[0]
  680. password = info[2]
  681. else:
  682. raise netrc.NetrcParseError(
  683. 'No authenticators for %s' % netrc_machine)
  684. except (IOError, netrc.NetrcParseError) as err:
  685. self._downloader.report_warning(
  686. 'parsing .netrc: %s' % error_to_compat_str(err))
  687. return username, password
  688. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  689. """
  690. Get the login info as (username, password)
  691. First look for the manually specified credentials using username_option
  692. and password_option as keys in params dictionary. If no such credentials
  693. available look in the netrc file using the netrc_machine or _NETRC_MACHINE
  694. value.
  695. If there's no info available, return (None, None)
  696. """
  697. if self._downloader is None:
  698. return (None, None)
  699. downloader_params = self._downloader.params
  700. # Attempt to use provided username and password or .netrc data
  701. if downloader_params.get(username_option) is not None:
  702. username = downloader_params[username_option]
  703. password = downloader_params[password_option]
  704. else:
  705. username, password = self._get_netrc_login_info(netrc_machine)
  706. return username, password
  707. def _get_tfa_info(self, note='two-factor verification code'):
  708. """
  709. Get the two-factor authentication info
  710. TODO - asking the user will be required for sms/phone verify
  711. currently just uses the command line option
  712. If there's no info available, return None
  713. """
  714. if self._downloader is None:
  715. return None
  716. downloader_params = self._downloader.params
  717. if downloader_params.get('twofactor') is not None:
  718. return downloader_params['twofactor']
  719. return compat_getpass('Type %s and press [Return]: ' % note)
  720. # Helper functions for extracting OpenGraph info
  721. @staticmethod
  722. def _og_regexes(prop):
  723. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  724. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  725. % {'prop': re.escape(prop)})
  726. template = r'<meta[^>]+?%s[^>]+?%s'
  727. return [
  728. template % (property_re, content_re),
  729. template % (content_re, property_re),
  730. ]
  731. @staticmethod
  732. def _meta_regex(prop):
  733. return r'''(?isx)<meta
  734. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  735. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  736. def _og_search_property(self, prop, html, name=None, **kargs):
  737. if not isinstance(prop, (list, tuple)):
  738. prop = [prop]
  739. if name is None:
  740. name = 'OpenGraph %s' % prop[0]
  741. og_regexes = []
  742. for p in prop:
  743. og_regexes.extend(self._og_regexes(p))
  744. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  745. if escaped is None:
  746. return None
  747. return unescapeHTML(escaped)
  748. def _og_search_thumbnail(self, html, **kargs):
  749. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  750. def _og_search_description(self, html, **kargs):
  751. return self._og_search_property('description', html, fatal=False, **kargs)
  752. def _og_search_title(self, html, **kargs):
  753. return self._og_search_property('title', html, **kargs)
  754. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  755. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  756. if secure:
  757. regexes = self._og_regexes('video:secure_url') + regexes
  758. return self._html_search_regex(regexes, html, name, **kargs)
  759. def _og_search_url(self, html, **kargs):
  760. return self._og_search_property('url', html, **kargs)
  761. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  762. if not isinstance(name, (list, tuple)):
  763. name = [name]
  764. if display_name is None:
  765. display_name = name[0]
  766. return self._html_search_regex(
  767. [self._meta_regex(n) for n in name],
  768. html, display_name, fatal=fatal, group='content', **kwargs)
  769. def _dc_search_uploader(self, html):
  770. return self._html_search_meta('dc.creator', html, 'uploader')
  771. def _rta_search(self, html):
  772. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  773. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  774. r' content="RTA-5042-1996-1400-1577-RTA"',
  775. html):
  776. return 18
  777. return 0
  778. def _media_rating_search(self, html):
  779. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  780. rating = self._html_search_meta('rating', html)
  781. if not rating:
  782. return None
  783. RATING_TABLE = {
  784. 'safe for kids': 0,
  785. 'general': 8,
  786. '14 years': 14,
  787. 'mature': 17,
  788. 'restricted': 19,
  789. }
  790. return RATING_TABLE.get(rating.lower())
  791. def _family_friendly_search(self, html):
  792. # See http://schema.org/VideoObject
  793. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  794. if not family_friendly:
  795. return None
  796. RATING_TABLE = {
  797. '1': 0,
  798. 'true': 0,
  799. '0': 18,
  800. 'false': 18,
  801. }
  802. return RATING_TABLE.get(family_friendly.lower())
  803. def _twitter_search_player(self, html):
  804. return self._html_search_meta('twitter:player', html,
  805. 'twitter card player')
  806. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  807. json_ld = self._search_regex(
  808. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  809. html, 'JSON-LD', group='json_ld', **kwargs)
  810. default = kwargs.get('default', NO_DEFAULT)
  811. if not json_ld:
  812. return default if default is not NO_DEFAULT else {}
  813. # JSON-LD may be malformed and thus `fatal` should be respected.
  814. # At the same time `default` may be passed that assumes `fatal=False`
  815. # for _search_regex. Let's simulate the same behavior here as well.
  816. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  817. return self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  818. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  819. if isinstance(json_ld, compat_str):
  820. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  821. if not json_ld:
  822. return {}
  823. info = {}
  824. if not isinstance(json_ld, (list, tuple, dict)):
  825. return info
  826. if isinstance(json_ld, dict):
  827. json_ld = [json_ld]
  828. for e in json_ld:
  829. if e.get('@context') == 'http://schema.org':
  830. item_type = e.get('@type')
  831. if expected_type is not None and expected_type != item_type:
  832. return info
  833. if item_type == 'TVEpisode':
  834. info.update({
  835. 'episode': unescapeHTML(e.get('name')),
  836. 'episode_number': int_or_none(e.get('episodeNumber')),
  837. 'description': unescapeHTML(e.get('description')),
  838. })
  839. part_of_season = e.get('partOfSeason')
  840. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  841. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  842. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  843. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  844. info['series'] = unescapeHTML(part_of_series.get('name'))
  845. elif item_type == 'Article':
  846. info.update({
  847. 'timestamp': parse_iso8601(e.get('datePublished')),
  848. 'title': unescapeHTML(e.get('headline')),
  849. 'description': unescapeHTML(e.get('articleBody')),
  850. })
  851. elif item_type == 'VideoObject':
  852. info.update({
  853. 'url': e.get('contentUrl'),
  854. 'title': unescapeHTML(e.get('name')),
  855. 'description': unescapeHTML(e.get('description')),
  856. 'thumbnail': e.get('thumbnailUrl') or e.get('thumbnailURL'),
  857. 'duration': parse_duration(e.get('duration')),
  858. 'timestamp': unified_timestamp(e.get('uploadDate')),
  859. 'filesize': float_or_none(e.get('contentSize')),
  860. 'tbr': int_or_none(e.get('bitrate')),
  861. 'width': int_or_none(e.get('width')),
  862. 'height': int_or_none(e.get('height')),
  863. })
  864. break
  865. return dict((k, v) for k, v in info.items() if v is not None)
  866. @staticmethod
  867. def _hidden_inputs(html):
  868. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  869. hidden_inputs = {}
  870. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  871. attrs = extract_attributes(input)
  872. if not input:
  873. continue
  874. if attrs.get('type') not in ('hidden', 'submit'):
  875. continue
  876. name = attrs.get('name') or attrs.get('id')
  877. value = attrs.get('value')
  878. if name and value is not None:
  879. hidden_inputs[name] = value
  880. return hidden_inputs
  881. def _form_hidden_inputs(self, form_id, html):
  882. form = self._search_regex(
  883. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  884. html, '%s form' % form_id, group='form')
  885. return self._hidden_inputs(form)
  886. def _sort_formats(self, formats, field_preference=None):
  887. if not formats:
  888. raise ExtractorError('No video formats found')
  889. for f in formats:
  890. # Automatically determine tbr when missing based on abr and vbr (improves
  891. # formats sorting in some cases)
  892. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  893. f['tbr'] = f['abr'] + f['vbr']
  894. def _formats_key(f):
  895. # TODO remove the following workaround
  896. from ..utils import determine_ext
  897. if not f.get('ext') and 'url' in f:
  898. f['ext'] = determine_ext(f['url'])
  899. if isinstance(field_preference, (list, tuple)):
  900. return tuple(
  901. f.get(field)
  902. if f.get(field) is not None
  903. else ('' if field == 'format_id' else -1)
  904. for field in field_preference)
  905. preference = f.get('preference')
  906. if preference is None:
  907. preference = 0
  908. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  909. preference -= 0.5
  910. protocol = f.get('protocol') or determine_protocol(f)
  911. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  912. if f.get('vcodec') == 'none': # audio only
  913. preference -= 50
  914. if self._downloader.params.get('prefer_free_formats'):
  915. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  916. else:
  917. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  918. ext_preference = 0
  919. try:
  920. audio_ext_preference = ORDER.index(f['ext'])
  921. except ValueError:
  922. audio_ext_preference = -1
  923. else:
  924. if f.get('acodec') == 'none': # video only
  925. preference -= 40
  926. if self._downloader.params.get('prefer_free_formats'):
  927. ORDER = ['flv', 'mp4', 'webm']
  928. else:
  929. ORDER = ['webm', 'flv', 'mp4']
  930. try:
  931. ext_preference = ORDER.index(f['ext'])
  932. except ValueError:
  933. ext_preference = -1
  934. audio_ext_preference = 0
  935. return (
  936. preference,
  937. f.get('language_preference') if f.get('language_preference') is not None else -1,
  938. f.get('quality') if f.get('quality') is not None else -1,
  939. f.get('tbr') if f.get('tbr') is not None else -1,
  940. f.get('filesize') if f.get('filesize') is not None else -1,
  941. f.get('vbr') if f.get('vbr') is not None else -1,
  942. f.get('height') if f.get('height') is not None else -1,
  943. f.get('width') if f.get('width') is not None else -1,
  944. proto_preference,
  945. ext_preference,
  946. f.get('abr') if f.get('abr') is not None else -1,
  947. audio_ext_preference,
  948. f.get('fps') if f.get('fps') is not None else -1,
  949. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  950. f.get('source_preference') if f.get('source_preference') is not None else -1,
  951. f.get('format_id') if f.get('format_id') is not None else '',
  952. )
  953. formats.sort(key=_formats_key)
  954. def _check_formats(self, formats, video_id):
  955. if formats:
  956. formats[:] = filter(
  957. lambda f: self._is_valid_url(
  958. f['url'], video_id,
  959. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  960. formats)
  961. @staticmethod
  962. def _remove_duplicate_formats(formats):
  963. format_urls = set()
  964. unique_formats = []
  965. for f in formats:
  966. if f['url'] not in format_urls:
  967. format_urls.add(f['url'])
  968. unique_formats.append(f)
  969. formats[:] = unique_formats
  970. def _is_valid_url(self, url, video_id, item='video', headers={}):
  971. url = self._proto_relative_url(url, scheme='http:')
  972. # For now assume non HTTP(S) URLs always valid
  973. if not (url.startswith('http://') or url.startswith('https://')):
  974. return True
  975. try:
  976. self._request_webpage(url, video_id, 'Checking %s URL' % item, headers=headers)
  977. return True
  978. except ExtractorError as e:
  979. if isinstance(e.cause, compat_urllib_error.URLError):
  980. self.to_screen(
  981. '%s: %s URL is invalid, skipping' % (video_id, item))
  982. return False
  983. raise
  984. def http_scheme(self):
  985. """ Either "http:" or "https:", depending on the user's preferences """
  986. return (
  987. 'http:'
  988. if self._downloader.params.get('prefer_insecure', False)
  989. else 'https:')
  990. def _proto_relative_url(self, url, scheme=None):
  991. if url is None:
  992. return url
  993. if url.startswith('//'):
  994. if scheme is None:
  995. scheme = self.http_scheme()
  996. return scheme + url
  997. else:
  998. return url
  999. def _sleep(self, timeout, video_id, msg_template=None):
  1000. if msg_template is None:
  1001. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1002. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1003. self.to_screen(msg)
  1004. time.sleep(timeout)
  1005. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  1006. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1007. fatal=True, m3u8_id=None):
  1008. manifest = self._download_xml(
  1009. manifest_url, video_id, 'Downloading f4m manifest',
  1010. 'Unable to download f4m manifest',
  1011. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1012. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  1013. transform_source=transform_source,
  1014. fatal=fatal)
  1015. if manifest is False:
  1016. return []
  1017. return self._parse_f4m_formats(
  1018. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1019. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1020. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  1021. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1022. fatal=True, m3u8_id=None):
  1023. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1024. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1025. if akamai_pv is not None and ';' in akamai_pv.text:
  1026. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  1027. if playerVerificationChallenge.strip() != '':
  1028. return []
  1029. formats = []
  1030. manifest_version = '1.0'
  1031. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1032. if not media_nodes:
  1033. manifest_version = '2.0'
  1034. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1035. # Remove unsupported DRM protected media from final formats
  1036. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  1037. media_nodes = remove_encrypted_media(media_nodes)
  1038. if not media_nodes:
  1039. return formats
  1040. base_url = xpath_text(
  1041. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  1042. 'base URL', default=None)
  1043. if base_url:
  1044. base_url = base_url.strip()
  1045. bootstrap_info = xpath_element(
  1046. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1047. 'bootstrap info', default=None)
  1048. vcodec = None
  1049. mime_type = xpath_text(
  1050. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1051. 'base URL', default=None)
  1052. if mime_type and mime_type.startswith('audio/'):
  1053. vcodec = 'none'
  1054. for i, media_el in enumerate(media_nodes):
  1055. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1056. width = int_or_none(media_el.attrib.get('width'))
  1057. height = int_or_none(media_el.attrib.get('height'))
  1058. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  1059. # If <bootstrapInfo> is present, the specified f4m is a
  1060. # stream-level manifest, and only set-level manifests may refer to
  1061. # external resources. See section 11.4 and section 4 of F4M spec
  1062. if bootstrap_info is None:
  1063. media_url = None
  1064. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1065. if manifest_version == '2.0':
  1066. media_url = media_el.attrib.get('href')
  1067. if media_url is None:
  1068. media_url = media_el.attrib.get('url')
  1069. if not media_url:
  1070. continue
  1071. manifest_url = (
  1072. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1073. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1074. # If media_url is itself a f4m manifest do the recursive extraction
  1075. # since bitrates in parent manifest (this one) and media_url manifest
  1076. # may differ leading to inability to resolve the format by requested
  1077. # bitrate in f4m downloader
  1078. ext = determine_ext(manifest_url)
  1079. if ext == 'f4m':
  1080. f4m_formats = self._extract_f4m_formats(
  1081. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1082. transform_source=transform_source, fatal=fatal)
  1083. # Sometimes stream-level manifest contains single media entry that
  1084. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1085. # At the same time parent's media entry in set-level manifest may
  1086. # contain it. We will copy it from parent in such cases.
  1087. if len(f4m_formats) == 1:
  1088. f = f4m_formats[0]
  1089. f.update({
  1090. 'tbr': f.get('tbr') or tbr,
  1091. 'width': f.get('width') or width,
  1092. 'height': f.get('height') or height,
  1093. 'format_id': f.get('format_id') if not tbr else format_id,
  1094. 'vcodec': vcodec,
  1095. })
  1096. formats.extend(f4m_formats)
  1097. continue
  1098. elif ext == 'm3u8':
  1099. formats.extend(self._extract_m3u8_formats(
  1100. manifest_url, video_id, 'mp4', preference=preference,
  1101. m3u8_id=m3u8_id, fatal=fatal))
  1102. continue
  1103. formats.append({
  1104. 'format_id': format_id,
  1105. 'url': manifest_url,
  1106. 'manifest_url': manifest_url,
  1107. 'ext': 'flv' if bootstrap_info is not None else None,
  1108. 'tbr': tbr,
  1109. 'width': width,
  1110. 'height': height,
  1111. 'vcodec': vcodec,
  1112. 'preference': preference,
  1113. })
  1114. return formats
  1115. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1116. return {
  1117. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1118. 'url': m3u8_url,
  1119. 'ext': ext,
  1120. 'protocol': 'm3u8',
  1121. 'preference': preference - 100 if preference else -100,
  1122. 'resolution': 'multiple',
  1123. 'format_note': 'Quality selection URL',
  1124. }
  1125. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1126. entry_protocol='m3u8', preference=None,
  1127. m3u8_id=None, note=None, errnote=None,
  1128. fatal=True, live=False):
  1129. res = self._download_webpage_handle(
  1130. m3u8_url, video_id,
  1131. note=note or 'Downloading m3u8 information',
  1132. errnote=errnote or 'Failed to download m3u8 information',
  1133. fatal=fatal)
  1134. if res is False:
  1135. return []
  1136. m3u8_doc, urlh = res
  1137. m3u8_url = urlh.geturl()
  1138. if '#EXT-X-FAXS-CM:' in m3u8_doc: # Adobe Flash Access
  1139. return []
  1140. formats = [self._m3u8_meta_format(m3u8_url, ext, preference, m3u8_id)]
  1141. format_url = lambda u: (
  1142. u
  1143. if re.match(r'^https?://', u)
  1144. else compat_urlparse.urljoin(m3u8_url, u))
  1145. # We should try extracting formats only from master playlists [1], i.e.
  1146. # playlists that describe available qualities. On the other hand media
  1147. # playlists [2] should be returned as is since they contain just the media
  1148. # without qualities renditions.
  1149. # Fortunately, master playlist can be easily distinguished from media
  1150. # playlist based on particular tags availability. As of [1, 2] master
  1151. # playlist tags MUST NOT appear in a media playist and vice versa.
  1152. # As of [3] #EXT-X-TARGETDURATION tag is REQUIRED for every media playlist
  1153. # and MUST NOT appear in master playlist thus we can clearly detect media
  1154. # playlist with this criterion.
  1155. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.4
  1156. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  1157. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  1158. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1159. return [{
  1160. 'url': m3u8_url,
  1161. 'format_id': m3u8_id,
  1162. 'ext': ext,
  1163. 'protocol': entry_protocol,
  1164. 'preference': preference,
  1165. }]
  1166. audio_in_video_stream = {}
  1167. last_info = {}
  1168. last_media = {}
  1169. for line in m3u8_doc.splitlines():
  1170. if line.startswith('#EXT-X-STREAM-INF:'):
  1171. last_info = parse_m3u8_attributes(line)
  1172. elif line.startswith('#EXT-X-MEDIA:'):
  1173. media = parse_m3u8_attributes(line)
  1174. media_type = media.get('TYPE')
  1175. if media_type in ('VIDEO', 'AUDIO'):
  1176. group_id = media.get('GROUP-ID')
  1177. media_url = media.get('URI')
  1178. if media_url:
  1179. format_id = []
  1180. for v in (group_id, media.get('NAME')):
  1181. if v:
  1182. format_id.append(v)
  1183. f = {
  1184. 'format_id': '-'.join(format_id),
  1185. 'url': format_url(media_url),
  1186. 'language': media.get('LANGUAGE'),
  1187. 'ext': ext,
  1188. 'protocol': entry_protocol,
  1189. 'preference': preference,
  1190. }
  1191. if media_type == 'AUDIO':
  1192. f['vcodec'] = 'none'
  1193. if group_id and not audio_in_video_stream.get(group_id):
  1194. audio_in_video_stream[group_id] = False
  1195. formats.append(f)
  1196. else:
  1197. # When there is no URI in EXT-X-MEDIA let this tag's
  1198. # data be used by regular URI lines below
  1199. last_media = media
  1200. if media_type == 'AUDIO' and group_id:
  1201. audio_in_video_stream[group_id] = True
  1202. elif line.startswith('#') or not line.strip():
  1203. continue
  1204. else:
  1205. tbr = int_or_none(last_info.get('AVERAGE-BANDWIDTH') or last_info.get('BANDWIDTH'), scale=1000)
  1206. format_id = []
  1207. if m3u8_id:
  1208. format_id.append(m3u8_id)
  1209. # Despite specification does not mention NAME attribute for
  1210. # EXT-X-STREAM-INF it still sometimes may be present
  1211. stream_name = last_info.get('NAME') or last_media.get('NAME')
  1212. # Bandwidth of live streams may differ over time thus making
  1213. # format_id unpredictable. So it's better to keep provided
  1214. # format_id intact.
  1215. if not live:
  1216. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1217. manifest_url = format_url(line.strip())
  1218. f = {
  1219. 'format_id': '-'.join(format_id),
  1220. 'url': manifest_url,
  1221. 'manifest_url': manifest_url,
  1222. 'tbr': tbr,
  1223. 'ext': ext,
  1224. 'fps': float_or_none(last_info.get('FRAME-RATE')),
  1225. 'protocol': entry_protocol,
  1226. 'preference': preference,
  1227. }
  1228. resolution = last_info.get('RESOLUTION')
  1229. if resolution:
  1230. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1231. if mobj:
  1232. f['width'] = int(mobj.group('width'))
  1233. f['height'] = int(mobj.group('height'))
  1234. # Unified Streaming Platform
  1235. mobj = re.search(
  1236. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1237. if mobj:
  1238. abr, vbr = mobj.groups()
  1239. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1240. f.update({
  1241. 'vbr': vbr,
  1242. 'abr': abr,
  1243. })
  1244. f.update(parse_codecs(last_info.get('CODECS')))
  1245. if audio_in_video_stream.get(last_info.get('AUDIO')) is False and f['vcodec'] != 'none':
  1246. # TODO: update acodec for audio only formats with the same GROUP-ID
  1247. f['acodec'] = 'none'
  1248. formats.append(f)
  1249. last_info = {}
  1250. last_media = {}
  1251. return formats
  1252. @staticmethod
  1253. def _xpath_ns(path, namespace=None):
  1254. if not namespace:
  1255. return path
  1256. out = []
  1257. for c in path.split('/'):
  1258. if not c or c == '.':
  1259. out.append(c)
  1260. else:
  1261. out.append('{%s}%s' % (namespace, c))
  1262. return '/'.join(out)
  1263. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1264. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1265. if smil is False:
  1266. assert not fatal
  1267. return []
  1268. namespace = self._parse_smil_namespace(smil)
  1269. return self._parse_smil_formats(
  1270. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1271. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1272. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1273. if smil is False:
  1274. return {}
  1275. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1276. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1277. return self._download_xml(
  1278. smil_url, video_id, 'Downloading SMIL file',
  1279. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1280. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1281. namespace = self._parse_smil_namespace(smil)
  1282. formats = self._parse_smil_formats(
  1283. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1284. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1285. video_id = os.path.splitext(url_basename(smil_url))[0]
  1286. title = None
  1287. description = None
  1288. upload_date = None
  1289. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1290. name = meta.attrib.get('name')
  1291. content = meta.attrib.get('content')
  1292. if not name or not content:
  1293. continue
  1294. if not title and name == 'title':
  1295. title = content
  1296. elif not description and name in ('description', 'abstract'):
  1297. description = content
  1298. elif not upload_date and name == 'date':
  1299. upload_date = unified_strdate(content)
  1300. thumbnails = [{
  1301. 'id': image.get('type'),
  1302. 'url': image.get('src'),
  1303. 'width': int_or_none(image.get('width')),
  1304. 'height': int_or_none(image.get('height')),
  1305. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1306. return {
  1307. 'id': video_id,
  1308. 'title': title or video_id,
  1309. 'description': description,
  1310. 'upload_date': upload_date,
  1311. 'thumbnails': thumbnails,
  1312. 'formats': formats,
  1313. 'subtitles': subtitles,
  1314. }
  1315. def _parse_smil_namespace(self, smil):
  1316. return self._search_regex(
  1317. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1318. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1319. base = smil_url
  1320. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1321. b = meta.get('base') or meta.get('httpBase')
  1322. if b:
  1323. base = b
  1324. break
  1325. formats = []
  1326. rtmp_count = 0
  1327. http_count = 0
  1328. m3u8_count = 0
  1329. srcs = []
  1330. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1331. for medium in media:
  1332. src = medium.get('src')
  1333. if not src or src in srcs:
  1334. continue
  1335. srcs.append(src)
  1336. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1337. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1338. width = int_or_none(medium.get('width'))
  1339. height = int_or_none(medium.get('height'))
  1340. proto = medium.get('proto')
  1341. ext = medium.get('ext')
  1342. src_ext = determine_ext(src)
  1343. streamer = medium.get('streamer') or base
  1344. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1345. rtmp_count += 1
  1346. formats.append({
  1347. 'url': streamer,
  1348. 'play_path': src,
  1349. 'ext': 'flv',
  1350. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1351. 'tbr': bitrate,
  1352. 'filesize': filesize,
  1353. 'width': width,
  1354. 'height': height,
  1355. })
  1356. if transform_rtmp_url:
  1357. streamer, src = transform_rtmp_url(streamer, src)
  1358. formats[-1].update({
  1359. 'url': streamer,
  1360. 'play_path': src,
  1361. })
  1362. continue
  1363. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1364. src_url = src_url.strip()
  1365. if proto == 'm3u8' or src_ext == 'm3u8':
  1366. m3u8_formats = self._extract_m3u8_formats(
  1367. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1368. if len(m3u8_formats) == 1:
  1369. m3u8_count += 1
  1370. m3u8_formats[0].update({
  1371. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1372. 'tbr': bitrate,
  1373. 'width': width,
  1374. 'height': height,
  1375. })
  1376. formats.extend(m3u8_formats)
  1377. continue
  1378. if src_ext == 'f4m':
  1379. f4m_url = src_url
  1380. if not f4m_params:
  1381. f4m_params = {
  1382. 'hdcore': '3.2.0',
  1383. 'plugin': 'flowplayer-3.2.0.1',
  1384. }
  1385. f4m_url += '&' if '?' in f4m_url else '?'
  1386. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1387. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1388. continue
  1389. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1390. http_count += 1
  1391. formats.append({
  1392. 'url': src_url,
  1393. 'ext': ext or src_ext or 'flv',
  1394. 'format_id': 'http-%d' % (bitrate or http_count),
  1395. 'tbr': bitrate,
  1396. 'filesize': filesize,
  1397. 'width': width,
  1398. 'height': height,
  1399. })
  1400. continue
  1401. return formats
  1402. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1403. urls = []
  1404. subtitles = {}
  1405. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1406. src = textstream.get('src')
  1407. if not src or src in urls:
  1408. continue
  1409. urls.append(src)
  1410. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1411. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1412. subtitles.setdefault(lang, []).append({
  1413. 'url': src,
  1414. 'ext': ext,
  1415. })
  1416. return subtitles
  1417. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1418. xspf = self._download_xml(
  1419. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1420. 'Unable to download xspf manifest', fatal=fatal)
  1421. if xspf is False:
  1422. return []
  1423. return self._parse_xspf(xspf, playlist_id)
  1424. def _parse_xspf(self, playlist, playlist_id):
  1425. NS_MAP = {
  1426. 'xspf': 'http://xspf.org/ns/0/',
  1427. 's1': 'http://static.streamone.nl/player/ns/0',
  1428. }
  1429. entries = []
  1430. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1431. title = xpath_text(
  1432. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1433. description = xpath_text(
  1434. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1435. thumbnail = xpath_text(
  1436. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1437. duration = float_or_none(
  1438. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1439. formats = [{
  1440. 'url': location.text,
  1441. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1442. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1443. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1444. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1445. self._sort_formats(formats)
  1446. entries.append({
  1447. 'id': playlist_id,
  1448. 'title': title,
  1449. 'description': description,
  1450. 'thumbnail': thumbnail,
  1451. 'duration': duration,
  1452. 'formats': formats,
  1453. })
  1454. return entries
  1455. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1456. res = self._download_webpage_handle(
  1457. mpd_url, video_id,
  1458. note=note or 'Downloading MPD manifest',
  1459. errnote=errnote or 'Failed to download MPD manifest',
  1460. fatal=fatal)
  1461. if res is False:
  1462. return []
  1463. mpd, urlh = res
  1464. mpd_base_url = base_url(urlh.geturl())
  1465. return self._parse_mpd_formats(
  1466. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url,
  1467. formats_dict=formats_dict, mpd_url=mpd_url)
  1468. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}, mpd_url=None):
  1469. """
  1470. Parse formats from MPD manifest.
  1471. References:
  1472. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  1473. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  1474. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  1475. """
  1476. if mpd_doc.get('type') == 'dynamic':
  1477. return []
  1478. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1479. def _add_ns(path):
  1480. return self._xpath_ns(path, namespace)
  1481. def is_drm_protected(element):
  1482. return element.find(_add_ns('ContentProtection')) is not None
  1483. def extract_multisegment_info(element, ms_parent_info):
  1484. ms_info = ms_parent_info.copy()
  1485. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  1486. # common attributes and elements. We will only extract relevant
  1487. # for us.
  1488. def extract_common(source):
  1489. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  1490. if segment_timeline is not None:
  1491. s_e = segment_timeline.findall(_add_ns('S'))
  1492. if s_e:
  1493. ms_info['total_number'] = 0
  1494. ms_info['s'] = []
  1495. for s in s_e:
  1496. r = int(s.get('r', 0))
  1497. ms_info['total_number'] += 1 + r
  1498. ms_info['s'].append({
  1499. 't': int(s.get('t', 0)),
  1500. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  1501. 'd': int(s.attrib['d']),
  1502. 'r': r,
  1503. })
  1504. start_number = source.get('startNumber')
  1505. if start_number:
  1506. ms_info['start_number'] = int(start_number)
  1507. timescale = source.get('timescale')
  1508. if timescale:
  1509. ms_info['timescale'] = int(timescale)
  1510. segment_duration = source.get('duration')
  1511. if segment_duration:
  1512. ms_info['segment_duration'] = int(segment_duration)
  1513. def extract_Initialization(source):
  1514. initialization = source.find(_add_ns('Initialization'))
  1515. if initialization is not None:
  1516. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1517. segment_list = element.find(_add_ns('SegmentList'))
  1518. if segment_list is not None:
  1519. extract_common(segment_list)
  1520. extract_Initialization(segment_list)
  1521. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1522. if segment_urls_e:
  1523. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1524. else:
  1525. segment_template = element.find(_add_ns('SegmentTemplate'))
  1526. if segment_template is not None:
  1527. extract_common(segment_template)
  1528. media = segment_template.get('media')
  1529. if media:
  1530. ms_info['media'] = media
  1531. initialization = segment_template.get('initialization')
  1532. if initialization:
  1533. ms_info['initialization'] = initialization
  1534. else:
  1535. extract_Initialization(segment_template)
  1536. return ms_info
  1537. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1538. formats = []
  1539. for period in mpd_doc.findall(_add_ns('Period')):
  1540. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1541. period_ms_info = extract_multisegment_info(period, {
  1542. 'start_number': 1,
  1543. 'timescale': 1,
  1544. })
  1545. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1546. if is_drm_protected(adaptation_set):
  1547. continue
  1548. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1549. for representation in adaptation_set.findall(_add_ns('Representation')):
  1550. if is_drm_protected(representation):
  1551. continue
  1552. representation_attrib = adaptation_set.attrib.copy()
  1553. representation_attrib.update(representation.attrib)
  1554. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  1555. mime_type = representation_attrib['mimeType']
  1556. content_type = mime_type.split('/')[0]
  1557. if content_type == 'text':
  1558. # TODO implement WebVTT downloading
  1559. pass
  1560. elif content_type == 'video' or content_type == 'audio':
  1561. base_url = ''
  1562. for element in (representation, adaptation_set, period, mpd_doc):
  1563. base_url_e = element.find(_add_ns('BaseURL'))
  1564. if base_url_e is not None:
  1565. base_url = base_url_e.text + base_url
  1566. if re.match(r'^https?://', base_url):
  1567. break
  1568. if mpd_base_url and not re.match(r'^https?://', base_url):
  1569. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1570. mpd_base_url += '/'
  1571. base_url = mpd_base_url + base_url
  1572. representation_id = representation_attrib.get('id')
  1573. lang = representation_attrib.get('lang')
  1574. url_el = representation.find(_add_ns('BaseURL'))
  1575. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1576. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  1577. f = {
  1578. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1579. 'url': base_url,
  1580. 'manifest_url': mpd_url,
  1581. 'ext': mimetype2ext(mime_type),
  1582. 'width': int_or_none(representation_attrib.get('width')),
  1583. 'height': int_or_none(representation_attrib.get('height')),
  1584. 'tbr': int_or_none(bandwidth, 1000),
  1585. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1586. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1587. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1588. 'format_note': 'DASH %s' % content_type,
  1589. 'filesize': filesize,
  1590. }
  1591. f.update(parse_codecs(representation_attrib.get('codecs')))
  1592. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1593. def prepare_template(template_name, identifiers):
  1594. t = representation_ms_info[template_name]
  1595. t = t.replace('$RepresentationID$', representation_id)
  1596. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  1597. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  1598. t.replace('$$', '$')
  1599. return t
  1600. # @initialization is a regular template like @media one
  1601. # so it should be handled just the same way (see
  1602. # https://github.com/rg3/youtube-dl/issues/11605)
  1603. if 'initialization' in representation_ms_info:
  1604. initialization_template = prepare_template(
  1605. 'initialization',
  1606. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  1607. # $Time$ shall not be included for @initialization thus
  1608. # only $Bandwidth$ remains
  1609. ('Bandwidth', ))
  1610. representation_ms_info['initialization_url'] = initialization_template % {
  1611. 'Bandwidth': bandwidth,
  1612. }
  1613. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  1614. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  1615. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  1616. # can't be used at the same time
  1617. if '%(Number' in media_template and 's' not in representation_ms_info:
  1618. segment_duration = None
  1619. if 'total_number' not in representation_ms_info and 'segment_duration':
  1620. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  1621. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1622. representation_ms_info['fragments'] = [{
  1623. 'url': media_template % {
  1624. 'Number': segment_number,
  1625. 'Bandwidth': bandwidth,
  1626. },
  1627. 'duration': segment_duration,
  1628. } for segment_number in range(
  1629. representation_ms_info['start_number'],
  1630. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1631. else:
  1632. # $Number*$ or $Time$ in media template with S list available
  1633. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  1634. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  1635. representation_ms_info['fragments'] = []
  1636. segment_time = 0
  1637. segment_d = None
  1638. segment_number = representation_ms_info['start_number']
  1639. def add_segment_url():
  1640. segment_url = media_template % {
  1641. 'Time': segment_time,
  1642. 'Bandwidth': bandwidth,
  1643. 'Number': segment_number,
  1644. }
  1645. representation_ms_info['fragments'].append({
  1646. 'url': segment_url,
  1647. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  1648. })
  1649. for num, s in enumerate(representation_ms_info['s']):
  1650. segment_time = s.get('t') or segment_time
  1651. segment_d = s['d']
  1652. add_segment_url()
  1653. segment_number += 1
  1654. for r in range(s.get('r', 0)):
  1655. segment_time += segment_d
  1656. add_segment_url()
  1657. segment_number += 1
  1658. segment_time += segment_d
  1659. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  1660. # No media template
  1661. # Example: https://www.youtube.com/watch?v=iXZV5uAYMJI
  1662. # or any YouTube dashsegments video
  1663. fragments = []
  1664. segment_index = 0
  1665. timescale = representation_ms_info['timescale']
  1666. for s in representation_ms_info['s']:
  1667. duration = float_or_none(s['d'], timescale)
  1668. for r in range(s.get('r', 0) + 1):
  1669. fragments.append({
  1670. 'url': representation_ms_info['segment_urls'][segment_index],
  1671. 'duration': duration,
  1672. })
  1673. segment_index += 1
  1674. representation_ms_info['fragments'] = fragments
  1675. # NB: MPD manifest may contain direct URLs to unfragmented media.
  1676. # No fragments key is present in this case.
  1677. if 'fragments' in representation_ms_info:
  1678. f.update({
  1679. 'fragments': [],
  1680. 'protocol': 'http_dash_segments',
  1681. })
  1682. if 'initialization_url' in representation_ms_info:
  1683. initialization_url = representation_ms_info['initialization_url']
  1684. if not f.get('url'):
  1685. f['url'] = initialization_url
  1686. f['fragments'].append({'url': initialization_url})
  1687. f['fragments'].extend(representation_ms_info['fragments'])
  1688. for fragment in f['fragments']:
  1689. fragment['url'] = urljoin(base_url, fragment['url'])
  1690. try:
  1691. existing_format = next(
  1692. fo for fo in formats
  1693. if fo['format_id'] == representation_id)
  1694. except StopIteration:
  1695. full_info = formats_dict.get(representation_id, {}).copy()
  1696. full_info.update(f)
  1697. formats.append(full_info)
  1698. else:
  1699. existing_format.update(f)
  1700. else:
  1701. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1702. return formats
  1703. def _extract_ism_formats(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True):
  1704. res = self._download_webpage_handle(
  1705. ism_url, video_id,
  1706. note=note or 'Downloading ISM manifest',
  1707. errnote=errnote or 'Failed to download ISM manifest',
  1708. fatal=fatal)
  1709. if res is False:
  1710. return []
  1711. ism, urlh = res
  1712. return self._parse_ism_formats(
  1713. compat_etree_fromstring(ism.encode('utf-8')), urlh.geturl(), ism_id)
  1714. def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
  1715. if ism_doc.get('IsLive') == 'TRUE' or ism_doc.find('Protection') is not None:
  1716. return []
  1717. duration = int(ism_doc.attrib['Duration'])
  1718. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  1719. formats = []
  1720. for stream in ism_doc.findall('StreamIndex'):
  1721. stream_type = stream.get('Type')
  1722. if stream_type not in ('video', 'audio'):
  1723. continue
  1724. url_pattern = stream.attrib['Url']
  1725. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  1726. stream_name = stream.get('Name')
  1727. for track in stream.findall('QualityLevel'):
  1728. fourcc = track.get('FourCC')
  1729. # TODO: add support for WVC1 and WMAP
  1730. if fourcc not in ('H264', 'AVC1', 'AACL'):
  1731. self.report_warning('%s is not a supported codec' % fourcc)
  1732. continue
  1733. tbr = int(track.attrib['Bitrate']) // 1000
  1734. width = int_or_none(track.get('MaxWidth'))
  1735. height = int_or_none(track.get('MaxHeight'))
  1736. sampling_rate = int_or_none(track.get('SamplingRate'))
  1737. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  1738. track_url_pattern = compat_urlparse.urljoin(ism_url, track_url_pattern)
  1739. fragments = []
  1740. fragment_ctx = {
  1741. 'time': 0,
  1742. }
  1743. stream_fragments = stream.findall('c')
  1744. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  1745. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  1746. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  1747. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  1748. if not fragment_ctx['duration']:
  1749. try:
  1750. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  1751. except IndexError:
  1752. next_fragment_time = duration
  1753. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  1754. for _ in range(fragment_repeat):
  1755. fragments.append({
  1756. 'url': re.sub(r'{start[ _]time}', compat_str(fragment_ctx['time']), track_url_pattern),
  1757. 'duration': fragment_ctx['duration'] / stream_timescale,
  1758. })
  1759. fragment_ctx['time'] += fragment_ctx['duration']
  1760. format_id = []
  1761. if ism_id:
  1762. format_id.append(ism_id)
  1763. if stream_name:
  1764. format_id.append(stream_name)
  1765. format_id.append(compat_str(tbr))
  1766. formats.append({
  1767. 'format_id': '-'.join(format_id),
  1768. 'url': ism_url,
  1769. 'manifest_url': ism_url,
  1770. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  1771. 'width': width,
  1772. 'height': height,
  1773. 'tbr': tbr,
  1774. 'asr': sampling_rate,
  1775. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  1776. 'acodec': 'none' if stream_type == 'video' else fourcc,
  1777. 'protocol': 'ism',
  1778. 'fragments': fragments,
  1779. '_download_params': {
  1780. 'duration': duration,
  1781. 'timescale': stream_timescale,
  1782. 'width': width or 0,
  1783. 'height': height or 0,
  1784. 'fourcc': fourcc,
  1785. 'codec_private_data': track.get('CodecPrivateData'),
  1786. 'sampling_rate': sampling_rate,
  1787. 'channels': int_or_none(track.get('Channels', 2)),
  1788. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  1789. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  1790. },
  1791. })
  1792. return formats
  1793. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8', mpd_id=None):
  1794. def absolute_url(video_url):
  1795. return compat_urlparse.urljoin(base_url, video_url)
  1796. def parse_content_type(content_type):
  1797. if not content_type:
  1798. return {}
  1799. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  1800. if ctr:
  1801. mimetype, codecs = ctr.groups()
  1802. f = parse_codecs(codecs)
  1803. f['ext'] = mimetype2ext(mimetype)
  1804. return f
  1805. return {}
  1806. def _media_formats(src, cur_media_type):
  1807. full_url = absolute_url(src)
  1808. ext = determine_ext(full_url)
  1809. if ext == 'm3u8':
  1810. is_plain_url = False
  1811. formats = self._extract_m3u8_formats(
  1812. full_url, video_id, ext='mp4',
  1813. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id)
  1814. elif ext == 'mpd':
  1815. is_plain_url = False
  1816. formats = self._extract_mpd_formats(
  1817. full_url, video_id, mpd_id=mpd_id)
  1818. else:
  1819. is_plain_url = True
  1820. formats = [{
  1821. 'url': full_url,
  1822. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  1823. }]
  1824. return is_plain_url, formats
  1825. entries = []
  1826. media_tags = [(media_tag, media_type, '')
  1827. for media_tag, media_type
  1828. in re.findall(r'(?s)(<(video|audio)[^>]*/>)', webpage)]
  1829. media_tags.extend(re.findall(
  1830. # We only allow video|audio followed by a whitespace or '>'.
  1831. # Allowing more characters may end up in significant slow down (see
  1832. # https://github.com/rg3/youtube-dl/issues/11979, example URL:
  1833. # http://www.porntrex.com/maps/videositemap.xml).
  1834. r'(?s)(<(?P<tag>video|audio)(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  1835. for media_tag, media_type, media_content in media_tags:
  1836. media_info = {
  1837. 'formats': [],
  1838. 'subtitles': {},
  1839. }
  1840. media_attributes = extract_attributes(media_tag)
  1841. src = media_attributes.get('src')
  1842. if src:
  1843. _, formats = _media_formats(src, media_type)
  1844. media_info['formats'].extend(formats)
  1845. media_info['thumbnail'] = media_attributes.get('poster')
  1846. if media_content:
  1847. for source_tag in re.findall(r'<source[^>]+>', media_content):
  1848. source_attributes = extract_attributes(source_tag)
  1849. src = source_attributes.get('src')
  1850. if not src:
  1851. continue
  1852. is_plain_url, formats = _media_formats(src, media_type)
  1853. if is_plain_url:
  1854. f = parse_content_type(source_attributes.get('type'))
  1855. f.update(formats[0])
  1856. media_info['formats'].append(f)
  1857. else:
  1858. media_info['formats'].extend(formats)
  1859. for track_tag in re.findall(r'<track[^>]+>', media_content):
  1860. track_attributes = extract_attributes(track_tag)
  1861. kind = track_attributes.get('kind')
  1862. if not kind or kind in ('subtitles', 'captions'):
  1863. src = track_attributes.get('src')
  1864. if not src:
  1865. continue
  1866. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  1867. media_info['subtitles'].setdefault(lang, []).append({
  1868. 'url': absolute_url(src),
  1869. })
  1870. if media_info['formats'] or media_info['subtitles']:
  1871. entries.append(media_info)
  1872. return entries
  1873. def _extract_akamai_formats(self, manifest_url, video_id, hosts={}):
  1874. formats = []
  1875. hdcore_sign = 'hdcore=3.7.0'
  1876. f4m_url = re.sub(r'(https?://[^/+])/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  1877. hds_host = hosts.get('hds')
  1878. if hds_host:
  1879. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  1880. if 'hdcore=' not in f4m_url:
  1881. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  1882. f4m_formats = self._extract_f4m_formats(
  1883. f4m_url, video_id, f4m_id='hds', fatal=False)
  1884. for entry in f4m_formats:
  1885. entry.update({'extra_param_to_segment_url': hdcore_sign})
  1886. formats.extend(f4m_formats)
  1887. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  1888. hls_host = hosts.get('hls')
  1889. if hls_host:
  1890. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  1891. formats.extend(self._extract_m3u8_formats(
  1892. m3u8_url, video_id, 'mp4', 'm3u8_native',
  1893. m3u8_id='hls', fatal=False))
  1894. return formats
  1895. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  1896. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  1897. url_base = self._search_regex(r'(?:https?|rtmp|rtsp)(://[^?]+)', url, 'format url')
  1898. http_base_url = 'http' + url_base
  1899. formats = []
  1900. if 'm3u8' not in skip_protocols:
  1901. formats.extend(self._extract_m3u8_formats(
  1902. http_base_url + '/playlist.m3u8', video_id, 'mp4',
  1903. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  1904. if 'f4m' not in skip_protocols:
  1905. formats.extend(self._extract_f4m_formats(
  1906. http_base_url + '/manifest.f4m',
  1907. video_id, f4m_id='hds', fatal=False))
  1908. if 'dash' not in skip_protocols:
  1909. formats.extend(self._extract_mpd_formats(
  1910. http_base_url + '/manifest.mpd',
  1911. video_id, mpd_id='dash', fatal=False))
  1912. if re.search(r'(?:/smil:|\.smil)', url_base):
  1913. if 'smil' not in skip_protocols:
  1914. rtmp_formats = self._extract_smil_formats(
  1915. http_base_url + '/jwplayer.smil',
  1916. video_id, fatal=False)
  1917. for rtmp_format in rtmp_formats:
  1918. rtsp_format = rtmp_format.copy()
  1919. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  1920. del rtsp_format['play_path']
  1921. del rtsp_format['ext']
  1922. rtsp_format.update({
  1923. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  1924. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  1925. 'protocol': 'rtsp',
  1926. })
  1927. formats.extend([rtmp_format, rtsp_format])
  1928. else:
  1929. for protocol in ('rtmp', 'rtsp'):
  1930. if protocol not in skip_protocols:
  1931. formats.append({
  1932. 'url': protocol + url_base,
  1933. 'format_id': protocol,
  1934. 'protocol': protocol,
  1935. })
  1936. return formats
  1937. @staticmethod
  1938. def _find_jwplayer_data(webpage):
  1939. mobj = re.search(
  1940. r'jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)\.setup\s*\((?P<options>[^)]+)\)',
  1941. webpage)
  1942. if mobj:
  1943. return mobj.group('options')
  1944. def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
  1945. jwplayer_data = self._parse_json(
  1946. self._find_jwplayer_data(webpage), video_id,
  1947. transform_source=js_to_json)
  1948. return self._parse_jwplayer_data(
  1949. jwplayer_data, video_id, *args, **kwargs)
  1950. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  1951. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  1952. # JWPlayer backward compatibility: flattened playlists
  1953. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  1954. if 'playlist' not in jwplayer_data:
  1955. jwplayer_data = {'playlist': [jwplayer_data]}
  1956. entries = []
  1957. # JWPlayer backward compatibility: single playlist item
  1958. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  1959. if not isinstance(jwplayer_data['playlist'], list):
  1960. jwplayer_data['playlist'] = [jwplayer_data['playlist']]
  1961. for video_data in jwplayer_data['playlist']:
  1962. # JWPlayer backward compatibility: flattened sources
  1963. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  1964. if 'sources' not in video_data:
  1965. video_data['sources'] = [video_data]
  1966. this_video_id = video_id or video_data['mediaid']
  1967. formats = []
  1968. for source in video_data['sources']:
  1969. source_url = self._proto_relative_url(source['file'])
  1970. if base_url:
  1971. source_url = compat_urlparse.urljoin(base_url, source_url)
  1972. source_type = source.get('type') or ''
  1973. ext = mimetype2ext(source_type) or determine_ext(source_url)
  1974. if source_type == 'hls' or ext == 'm3u8':
  1975. formats.extend(self._extract_m3u8_formats(
  1976. source_url, this_video_id, 'mp4', 'm3u8_native', m3u8_id=m3u8_id, fatal=False))
  1977. elif ext == 'mpd':
  1978. formats.extend(self._extract_mpd_formats(
  1979. source_url, this_video_id, mpd_id=mpd_id, fatal=False))
  1980. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  1981. elif source_type.startswith('audio') or ext in ('oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  1982. formats.append({
  1983. 'url': source_url,
  1984. 'vcodec': 'none',
  1985. 'ext': ext,
  1986. })
  1987. else:
  1988. height = int_or_none(source.get('height'))
  1989. if height is None:
  1990. # Often no height is provided but there is a label in
  1991. # format like 1080p.
  1992. height = int_or_none(self._search_regex(
  1993. r'^(\d{3,})[pP]$', source.get('label') or '',
  1994. 'height', default=None))
  1995. a_format = {
  1996. 'url': source_url,
  1997. 'width': int_or_none(source.get('width')),
  1998. 'height': height,
  1999. 'ext': ext,
  2000. }
  2001. if source_url.startswith('rtmp'):
  2002. a_format['ext'] = 'flv'
  2003. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  2004. # of jwplayer.flash.swf
  2005. rtmp_url_parts = re.split(
  2006. r'((?:mp4|mp3|flv):)', source_url, 1)
  2007. if len(rtmp_url_parts) == 3:
  2008. rtmp_url, prefix, play_path = rtmp_url_parts
  2009. a_format.update({
  2010. 'url': rtmp_url,
  2011. 'play_path': prefix + play_path,
  2012. })
  2013. if rtmp_params:
  2014. a_format.update(rtmp_params)
  2015. formats.append(a_format)
  2016. self._sort_formats(formats)
  2017. subtitles = {}
  2018. tracks = video_data.get('tracks')
  2019. if tracks and isinstance(tracks, list):
  2020. for track in tracks:
  2021. if track.get('kind') != 'captions':
  2022. continue
  2023. track_url = urljoin(base_url, track.get('file'))
  2024. if not track_url:
  2025. continue
  2026. subtitles.setdefault(track.get('label') or 'en', []).append({
  2027. 'url': self._proto_relative_url(track_url)
  2028. })
  2029. entries.append({
  2030. 'id': this_video_id,
  2031. 'title': video_data['title'] if require_title else video_data.get('title'),
  2032. 'description': video_data.get('description'),
  2033. 'thumbnail': self._proto_relative_url(video_data.get('image')),
  2034. 'timestamp': int_or_none(video_data.get('pubdate')),
  2035. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  2036. 'subtitles': subtitles,
  2037. 'formats': formats,
  2038. })
  2039. if len(entries) == 1:
  2040. return entries[0]
  2041. else:
  2042. return self.playlist_result(entries)
  2043. def _live_title(self, name):
  2044. """ Generate the title for a live video """
  2045. now = datetime.datetime.now()
  2046. now_str = now.strftime('%Y-%m-%d %H:%M')
  2047. return name + ' ' + now_str
  2048. def _int(self, v, name, fatal=False, **kwargs):
  2049. res = int_or_none(v, **kwargs)
  2050. if 'get_attr' in kwargs:
  2051. print(getattr(v, kwargs['get_attr']))
  2052. if res is None:
  2053. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2054. if fatal:
  2055. raise ExtractorError(msg)
  2056. else:
  2057. self._downloader.report_warning(msg)
  2058. return res
  2059. def _float(self, v, name, fatal=False, **kwargs):
  2060. res = float_or_none(v, **kwargs)
  2061. if res is None:
  2062. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2063. if fatal:
  2064. raise ExtractorError(msg)
  2065. else:
  2066. self._downloader.report_warning(msg)
  2067. return res
  2068. def _set_cookie(self, domain, name, value, expire_time=None):
  2069. cookie = compat_cookiejar.Cookie(
  2070. 0, name, value, None, None, domain, None,
  2071. None, '/', True, False, expire_time, '', None, None, None)
  2072. self._downloader.cookiejar.set_cookie(cookie)
  2073. def _get_cookies(self, url):
  2074. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  2075. req = sanitized_Request(url)
  2076. self._downloader.cookiejar.add_cookie_header(req)
  2077. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  2078. def get_testcases(self, include_onlymatching=False):
  2079. t = getattr(self, '_TEST', None)
  2080. if t:
  2081. assert not hasattr(self, '_TESTS'), \
  2082. '%s has _TEST and _TESTS' % type(self).__name__
  2083. tests = [t]
  2084. else:
  2085. tests = getattr(self, '_TESTS', [])
  2086. for t in tests:
  2087. if not include_onlymatching and t.get('only_matching', False):
  2088. continue
  2089. t['name'] = type(self).__name__[:-len('IE')]
  2090. yield t
  2091. def is_suitable(self, age_limit):
  2092. """ Test whether the extractor is generally suitable for the given
  2093. age limit (i.e. pornographic sites are not, all others usually are) """
  2094. any_restricted = False
  2095. for tc in self.get_testcases(include_onlymatching=False):
  2096. if tc.get('playlist', []):
  2097. tc = tc['playlist'][0]
  2098. is_restricted = age_restricted(
  2099. tc.get('info_dict', {}).get('age_limit'), age_limit)
  2100. if not is_restricted:
  2101. return True
  2102. any_restricted = any_restricted or is_restricted
  2103. return not any_restricted
  2104. def extract_subtitles(self, *args, **kwargs):
  2105. if (self._downloader.params.get('writesubtitles', False) or
  2106. self._downloader.params.get('listsubtitles')):
  2107. return self._get_subtitles(*args, **kwargs)
  2108. return {}
  2109. def _get_subtitles(self, *args, **kwargs):
  2110. raise NotImplementedError('This method must be implemented by subclasses')
  2111. @staticmethod
  2112. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  2113. """ Merge subtitle items for one language. Items with duplicated URLs
  2114. will be dropped. """
  2115. list1_urls = set([item['url'] for item in subtitle_list1])
  2116. ret = list(subtitle_list1)
  2117. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  2118. return ret
  2119. @classmethod
  2120. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  2121. """ Merge two subtitle dictionaries, language by language. """
  2122. ret = dict(subtitle_dict1)
  2123. for lang in subtitle_dict2:
  2124. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  2125. return ret
  2126. def extract_automatic_captions(self, *args, **kwargs):
  2127. if (self._downloader.params.get('writeautomaticsub', False) or
  2128. self._downloader.params.get('listsubtitles')):
  2129. return self._get_automatic_captions(*args, **kwargs)
  2130. return {}
  2131. def _get_automatic_captions(self, *args, **kwargs):
  2132. raise NotImplementedError('This method must be implemented by subclasses')
  2133. def mark_watched(self, *args, **kwargs):
  2134. if (self._downloader.params.get('mark_watched', False) and
  2135. (self._get_login_info()[0] is not None or
  2136. self._downloader.params.get('cookiefile') is not None)):
  2137. self._mark_watched(*args, **kwargs)
  2138. def _mark_watched(self, *args, **kwargs):
  2139. raise NotImplementedError('This method must be implemented by subclasses')
  2140. def geo_verification_headers(self):
  2141. headers = {}
  2142. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  2143. if geo_verification_proxy:
  2144. headers['Ytdl-request-proxy'] = geo_verification_proxy
  2145. return headers
  2146. def _generic_id(self, url):
  2147. return compat_urllib_parse_unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  2148. def _generic_title(self, url):
  2149. return compat_urllib_parse_unquote(os.path.splitext(url_basename(url))[0])
  2150. class SearchInfoExtractor(InfoExtractor):
  2151. """
  2152. Base class for paged search queries extractors.
  2153. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  2154. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  2155. """
  2156. @classmethod
  2157. def _make_valid_url(cls):
  2158. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  2159. @classmethod
  2160. def suitable(cls, url):
  2161. return re.match(cls._make_valid_url(), url) is not None
  2162. def _real_extract(self, query):
  2163. mobj = re.match(self._make_valid_url(), query)
  2164. if mobj is None:
  2165. raise ExtractorError('Invalid search query "%s"' % query)
  2166. prefix = mobj.group('prefix')
  2167. query = mobj.group('query')
  2168. if prefix == '':
  2169. return self._get_n_results(query, 1)
  2170. elif prefix == 'all':
  2171. return self._get_n_results(query, self._MAX_RESULTS)
  2172. else:
  2173. n = int(prefix)
  2174. if n <= 0:
  2175. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  2176. elif n > self._MAX_RESULTS:
  2177. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  2178. n = self._MAX_RESULTS
  2179. return self._get_n_results(query, n)
  2180. def _get_n_results(self, query, n):
  2181. """Get a specified number of results for a query"""
  2182. raise NotImplementedError('This method must be implemented by subclasses')
  2183. @property
  2184. def SEARCH_KEY(self):
  2185. return self._SEARCH_KEY