common.py 122 KB

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