common.py 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  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(self, url_or_request, video_id,
  613. note='Downloading JSON metadata',
  614. errnote='Unable to download JSON metadata',
  615. transform_source=None,
  616. fatal=True, encoding=None, data=None, headers={}, query={}):
  617. json_string = self._download_webpage(
  618. url_or_request, video_id, note, errnote, fatal=fatal,
  619. encoding=encoding, data=data, headers=headers, query=query)
  620. if (not fatal) and json_string is False:
  621. return None
  622. return self._parse_json(
  623. json_string, video_id, transform_source=transform_source, fatal=fatal)
  624. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  625. if transform_source:
  626. json_string = transform_source(json_string)
  627. try:
  628. return json.loads(json_string)
  629. except ValueError as ve:
  630. errmsg = '%s: Failed to parse JSON ' % video_id
  631. if fatal:
  632. raise ExtractorError(errmsg, cause=ve)
  633. else:
  634. self.report_warning(errmsg + str(ve))
  635. def report_warning(self, msg, video_id=None):
  636. idstr = '' if video_id is None else '%s: ' % video_id
  637. self._downloader.report_warning(
  638. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  639. def to_screen(self, msg):
  640. """Print msg to screen, prefixing it with '[ie_name]'"""
  641. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  642. def report_extraction(self, id_or_name):
  643. """Report information extraction."""
  644. self.to_screen('%s: Extracting information' % id_or_name)
  645. def report_download_webpage(self, video_id):
  646. """Report webpage download."""
  647. self.to_screen('%s: Downloading webpage' % video_id)
  648. def report_age_confirmation(self):
  649. """Report attempt to confirm age."""
  650. self.to_screen('Confirming age')
  651. def report_login(self):
  652. """Report attempt to log in."""
  653. self.to_screen('Logging in')
  654. @staticmethod
  655. def raise_login_required(msg='This video is only available for registered users'):
  656. raise ExtractorError(
  657. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  658. expected=True)
  659. @staticmethod
  660. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction', countries=None):
  661. raise GeoRestrictedError(msg, countries=countries)
  662. # Methods for following #608
  663. @staticmethod
  664. def url_result(url, ie=None, video_id=None, video_title=None):
  665. """Returns a URL that points to a page that should be processed"""
  666. # TODO: ie should be the class used for getting the info
  667. video_info = {'_type': 'url',
  668. 'url': url,
  669. 'ie_key': ie}
  670. if video_id is not None:
  671. video_info['id'] = video_id
  672. if video_title is not None:
  673. video_info['title'] = video_title
  674. return video_info
  675. def playlist_from_matches(self, matches, playlist_id=None, playlist_title=None, getter=None, ie=None):
  676. urls = orderedSet(
  677. self.url_result(self._proto_relative_url(getter(m) if getter else m), ie)
  678. for m in matches)
  679. return self.playlist_result(
  680. urls, playlist_id=playlist_id, playlist_title=playlist_title)
  681. @staticmethod
  682. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  683. """Returns a playlist"""
  684. video_info = {'_type': 'playlist',
  685. 'entries': entries}
  686. if playlist_id:
  687. video_info['id'] = playlist_id
  688. if playlist_title:
  689. video_info['title'] = playlist_title
  690. if playlist_description:
  691. video_info['description'] = playlist_description
  692. return video_info
  693. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  694. """
  695. Perform a regex search on the given string, using a single or a list of
  696. patterns returning the first matching group.
  697. In case of failure return a default value or raise a WARNING or a
  698. RegexNotFoundError, depending on fatal, specifying the field name.
  699. """
  700. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  701. mobj = re.search(pattern, string, flags)
  702. else:
  703. for p in pattern:
  704. mobj = re.search(p, string, flags)
  705. if mobj:
  706. break
  707. if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  708. _name = '\033[0;34m%s\033[0m' % name
  709. else:
  710. _name = name
  711. if mobj:
  712. if group is None:
  713. # return the first matching group
  714. return next(g for g in mobj.groups() if g is not None)
  715. else:
  716. return mobj.group(group)
  717. elif default is not NO_DEFAULT:
  718. return default
  719. elif fatal:
  720. raise RegexNotFoundError('Unable to extract %s' % _name)
  721. else:
  722. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  723. return None
  724. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  725. """
  726. Like _search_regex, but strips HTML tags and unescapes entities.
  727. """
  728. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  729. if res:
  730. return clean_html(res).strip()
  731. else:
  732. return res
  733. def _get_netrc_login_info(self, netrc_machine=None):
  734. username = None
  735. password = None
  736. netrc_machine = netrc_machine or self._NETRC_MACHINE
  737. if self._downloader.params.get('usenetrc', False):
  738. try:
  739. info = netrc.netrc().authenticators(netrc_machine)
  740. if info is not None:
  741. username = info[0]
  742. password = info[2]
  743. else:
  744. raise netrc.NetrcParseError(
  745. 'No authenticators for %s' % netrc_machine)
  746. except (IOError, netrc.NetrcParseError) as err:
  747. self._downloader.report_warning(
  748. 'parsing .netrc: %s' % error_to_compat_str(err))
  749. return username, password
  750. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  751. """
  752. Get the login info as (username, password)
  753. First look for the manually specified credentials using username_option
  754. and password_option as keys in params dictionary. If no such credentials
  755. available look in the netrc file using the netrc_machine or _NETRC_MACHINE
  756. value.
  757. If there's no info available, return (None, None)
  758. """
  759. if self._downloader is None:
  760. return (None, None)
  761. downloader_params = self._downloader.params
  762. # Attempt to use provided username and password or .netrc data
  763. if downloader_params.get(username_option) is not None:
  764. username = downloader_params[username_option]
  765. password = downloader_params[password_option]
  766. else:
  767. username, password = self._get_netrc_login_info(netrc_machine)
  768. return username, password
  769. def _get_tfa_info(self, note='two-factor verification code'):
  770. """
  771. Get the two-factor authentication info
  772. TODO - asking the user will be required for sms/phone verify
  773. currently just uses the command line option
  774. If there's no info available, return None
  775. """
  776. if self._downloader is None:
  777. return None
  778. downloader_params = self._downloader.params
  779. if downloader_params.get('twofactor') is not None:
  780. return downloader_params['twofactor']
  781. return compat_getpass('Type %s and press [Return]: ' % note)
  782. # Helper functions for extracting OpenGraph info
  783. @staticmethod
  784. def _og_regexes(prop):
  785. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  786. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  787. % {'prop': re.escape(prop)})
  788. template = r'<meta[^>]+?%s[^>]+?%s'
  789. return [
  790. template % (property_re, content_re),
  791. template % (content_re, property_re),
  792. ]
  793. @staticmethod
  794. def _meta_regex(prop):
  795. return r'''(?isx)<meta
  796. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  797. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  798. def _og_search_property(self, prop, html, name=None, **kargs):
  799. if not isinstance(prop, (list, tuple)):
  800. prop = [prop]
  801. if name is None:
  802. name = 'OpenGraph %s' % prop[0]
  803. og_regexes = []
  804. for p in prop:
  805. og_regexes.extend(self._og_regexes(p))
  806. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  807. if escaped is None:
  808. return None
  809. return unescapeHTML(escaped)
  810. def _og_search_thumbnail(self, html, **kargs):
  811. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  812. def _og_search_description(self, html, **kargs):
  813. return self._og_search_property('description', html, fatal=False, **kargs)
  814. def _og_search_title(self, html, **kargs):
  815. return self._og_search_property('title', html, **kargs)
  816. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  817. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  818. if secure:
  819. regexes = self._og_regexes('video:secure_url') + regexes
  820. return self._html_search_regex(regexes, html, name, **kargs)
  821. def _og_search_url(self, html, **kargs):
  822. return self._og_search_property('url', html, **kargs)
  823. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  824. if not isinstance(name, (list, tuple)):
  825. name = [name]
  826. if display_name is None:
  827. display_name = name[0]
  828. return self._html_search_regex(
  829. [self._meta_regex(n) for n in name],
  830. html, display_name, fatal=fatal, group='content', **kwargs)
  831. def _dc_search_uploader(self, html):
  832. return self._html_search_meta('dc.creator', html, 'uploader')
  833. def _rta_search(self, html):
  834. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  835. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  836. r' content="RTA-5042-1996-1400-1577-RTA"',
  837. html):
  838. return 18
  839. return 0
  840. def _media_rating_search(self, html):
  841. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  842. rating = self._html_search_meta('rating', html)
  843. if not rating:
  844. return None
  845. RATING_TABLE = {
  846. 'safe for kids': 0,
  847. 'general': 8,
  848. '14 years': 14,
  849. 'mature': 17,
  850. 'restricted': 19,
  851. }
  852. return RATING_TABLE.get(rating.lower())
  853. def _family_friendly_search(self, html):
  854. # See http://schema.org/VideoObject
  855. family_friendly = self._html_search_meta(
  856. 'isFamilyFriendly', html, default=None)
  857. if not family_friendly:
  858. return None
  859. RATING_TABLE = {
  860. '1': 0,
  861. 'true': 0,
  862. '0': 18,
  863. 'false': 18,
  864. }
  865. return RATING_TABLE.get(family_friendly.lower())
  866. def _twitter_search_player(self, html):
  867. return self._html_search_meta('twitter:player', html,
  868. 'twitter card player')
  869. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  870. json_ld = self._search_regex(
  871. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  872. html, 'JSON-LD', group='json_ld', **kwargs)
  873. default = kwargs.get('default', NO_DEFAULT)
  874. if not json_ld:
  875. return default if default is not NO_DEFAULT else {}
  876. # JSON-LD may be malformed and thus `fatal` should be respected.
  877. # At the same time `default` may be passed that assumes `fatal=False`
  878. # for _search_regex. Let's simulate the same behavior here as well.
  879. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  880. return self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  881. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  882. if isinstance(json_ld, compat_str):
  883. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  884. if not json_ld:
  885. return {}
  886. info = {}
  887. if not isinstance(json_ld, (list, tuple, dict)):
  888. return info
  889. if isinstance(json_ld, dict):
  890. json_ld = [json_ld]
  891. def extract_video_object(e):
  892. assert e['@type'] == 'VideoObject'
  893. info.update({
  894. 'url': e.get('contentUrl'),
  895. 'title': unescapeHTML(e.get('name')),
  896. 'description': unescapeHTML(e.get('description')),
  897. 'thumbnail': e.get('thumbnailUrl') or e.get('thumbnailURL'),
  898. 'duration': parse_duration(e.get('duration')),
  899. 'timestamp': unified_timestamp(e.get('uploadDate')),
  900. 'filesize': float_or_none(e.get('contentSize')),
  901. 'tbr': int_or_none(e.get('bitrate')),
  902. 'width': int_or_none(e.get('width')),
  903. 'height': int_or_none(e.get('height')),
  904. 'view_count': int_or_none(e.get('interactionCount')),
  905. })
  906. for e in json_ld:
  907. if e.get('@context') == 'http://schema.org':
  908. item_type = e.get('@type')
  909. if expected_type is not None and expected_type != item_type:
  910. return info
  911. if item_type in ('TVEpisode', 'Episode'):
  912. info.update({
  913. 'episode': unescapeHTML(e.get('name')),
  914. 'episode_number': int_or_none(e.get('episodeNumber')),
  915. 'description': unescapeHTML(e.get('description')),
  916. })
  917. part_of_season = e.get('partOfSeason')
  918. if isinstance(part_of_season, dict) and part_of_season.get('@type') in ('TVSeason', 'Season', 'CreativeWorkSeason'):
  919. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  920. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  921. if isinstance(part_of_series, dict) and part_of_series.get('@type') in ('TVSeries', 'Series', 'CreativeWorkSeries'):
  922. info['series'] = unescapeHTML(part_of_series.get('name'))
  923. elif item_type in ('Article', 'NewsArticle'):
  924. info.update({
  925. 'timestamp': parse_iso8601(e.get('datePublished')),
  926. 'title': unescapeHTML(e.get('headline')),
  927. 'description': unescapeHTML(e.get('articleBody')),
  928. })
  929. elif item_type == 'VideoObject':
  930. extract_video_object(e)
  931. continue
  932. video = e.get('video')
  933. if isinstance(video, dict) and video.get('@type') == 'VideoObject':
  934. extract_video_object(video)
  935. break
  936. return dict((k, v) for k, v in info.items() if v is not None)
  937. @staticmethod
  938. def _hidden_inputs(html):
  939. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  940. hidden_inputs = {}
  941. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  942. attrs = extract_attributes(input)
  943. if not input:
  944. continue
  945. if attrs.get('type') not in ('hidden', 'submit'):
  946. continue
  947. name = attrs.get('name') or attrs.get('id')
  948. value = attrs.get('value')
  949. if name and value is not None:
  950. hidden_inputs[name] = value
  951. return hidden_inputs
  952. def _form_hidden_inputs(self, form_id, html):
  953. form = self._search_regex(
  954. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  955. html, '%s form' % form_id, group='form')
  956. return self._hidden_inputs(form)
  957. def _sort_formats(self, formats, field_preference=None):
  958. if not formats:
  959. raise ExtractorError('No video formats found')
  960. for f in formats:
  961. # Automatically determine tbr when missing based on abr and vbr (improves
  962. # formats sorting in some cases)
  963. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  964. f['tbr'] = f['abr'] + f['vbr']
  965. def _formats_key(f):
  966. # TODO remove the following workaround
  967. from ..utils import determine_ext
  968. if not f.get('ext') and 'url' in f:
  969. f['ext'] = determine_ext(f['url'])
  970. if isinstance(field_preference, (list, tuple)):
  971. return tuple(
  972. f.get(field)
  973. if f.get(field) is not None
  974. else ('' if field == 'format_id' else -1)
  975. for field in field_preference)
  976. preference = f.get('preference')
  977. if preference is None:
  978. preference = 0
  979. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  980. preference -= 0.5
  981. protocol = f.get('protocol') or determine_protocol(f)
  982. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  983. if f.get('vcodec') == 'none': # audio only
  984. preference -= 50
  985. if self._downloader.params.get('prefer_free_formats'):
  986. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  987. else:
  988. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  989. ext_preference = 0
  990. try:
  991. audio_ext_preference = ORDER.index(f['ext'])
  992. except ValueError:
  993. audio_ext_preference = -1
  994. else:
  995. if f.get('acodec') == 'none': # video only
  996. preference -= 40
  997. if self._downloader.params.get('prefer_free_formats'):
  998. ORDER = ['flv', 'mp4', 'webm']
  999. else:
  1000. ORDER = ['webm', 'flv', 'mp4']
  1001. try:
  1002. ext_preference = ORDER.index(f['ext'])
  1003. except ValueError:
  1004. ext_preference = -1
  1005. audio_ext_preference = 0
  1006. return (
  1007. preference,
  1008. f.get('language_preference') if f.get('language_preference') is not None else -1,
  1009. f.get('quality') if f.get('quality') is not None else -1,
  1010. f.get('tbr') if f.get('tbr') is not None else -1,
  1011. f.get('filesize') if f.get('filesize') is not None else -1,
  1012. f.get('vbr') if f.get('vbr') is not None else -1,
  1013. f.get('height') if f.get('height') is not None else -1,
  1014. f.get('width') if f.get('width') is not None else -1,
  1015. proto_preference,
  1016. ext_preference,
  1017. f.get('abr') if f.get('abr') is not None else -1,
  1018. audio_ext_preference,
  1019. f.get('fps') if f.get('fps') is not None else -1,
  1020. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  1021. f.get('source_preference') if f.get('source_preference') is not None else -1,
  1022. f.get('format_id') if f.get('format_id') is not None else '',
  1023. )
  1024. formats.sort(key=_formats_key)
  1025. def _check_formats(self, formats, video_id):
  1026. if formats:
  1027. formats[:] = filter(
  1028. lambda f: self._is_valid_url(
  1029. f['url'], video_id,
  1030. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  1031. formats)
  1032. @staticmethod
  1033. def _remove_duplicate_formats(formats):
  1034. format_urls = set()
  1035. unique_formats = []
  1036. for f in formats:
  1037. if f['url'] not in format_urls:
  1038. format_urls.add(f['url'])
  1039. unique_formats.append(f)
  1040. formats[:] = unique_formats
  1041. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1042. url = self._proto_relative_url(url, scheme='http:')
  1043. # For now assume non HTTP(S) URLs always valid
  1044. if not (url.startswith('http://') or url.startswith('https://')):
  1045. return True
  1046. try:
  1047. self._request_webpage(url, video_id, 'Checking %s URL' % item, headers=headers)
  1048. return True
  1049. except ExtractorError as e:
  1050. if isinstance(e.cause, compat_urllib_error.URLError):
  1051. self.to_screen(
  1052. '%s: %s URL is invalid, skipping' % (video_id, item))
  1053. return False
  1054. raise
  1055. def http_scheme(self):
  1056. """ Either "http:" or "https:", depending on the user's preferences """
  1057. return (
  1058. 'http:'
  1059. if self._downloader.params.get('prefer_insecure', False)
  1060. else 'https:')
  1061. def _proto_relative_url(self, url, scheme=None):
  1062. if url is None:
  1063. return url
  1064. if url.startswith('//'):
  1065. if scheme is None:
  1066. scheme = self.http_scheme()
  1067. return scheme + url
  1068. else:
  1069. return url
  1070. def _sleep(self, timeout, video_id, msg_template=None):
  1071. if msg_template is None:
  1072. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1073. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1074. self.to_screen(msg)
  1075. time.sleep(timeout)
  1076. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  1077. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1078. fatal=True, m3u8_id=None):
  1079. manifest = self._download_xml(
  1080. manifest_url, video_id, 'Downloading f4m manifest',
  1081. 'Unable to download f4m manifest',
  1082. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1083. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  1084. transform_source=transform_source,
  1085. fatal=fatal)
  1086. if manifest is False:
  1087. return []
  1088. return self._parse_f4m_formats(
  1089. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1090. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1091. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  1092. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1093. fatal=True, m3u8_id=None):
  1094. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1095. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1096. if akamai_pv is not None and ';' in akamai_pv.text:
  1097. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  1098. if playerVerificationChallenge.strip() != '':
  1099. return []
  1100. formats = []
  1101. manifest_version = '1.0'
  1102. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1103. if not media_nodes:
  1104. manifest_version = '2.0'
  1105. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1106. # Remove unsupported DRM protected media from final formats
  1107. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  1108. media_nodes = remove_encrypted_media(media_nodes)
  1109. if not media_nodes:
  1110. return formats
  1111. manifest_base_url = get_base_url(manifest)
  1112. bootstrap_info = xpath_element(
  1113. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1114. 'bootstrap info', default=None)
  1115. vcodec = None
  1116. mime_type = xpath_text(
  1117. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1118. 'base URL', default=None)
  1119. if mime_type and mime_type.startswith('audio/'):
  1120. vcodec = 'none'
  1121. for i, media_el in enumerate(media_nodes):
  1122. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1123. width = int_or_none(media_el.attrib.get('width'))
  1124. height = int_or_none(media_el.attrib.get('height'))
  1125. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  1126. # If <bootstrapInfo> is present, the specified f4m is a
  1127. # stream-level manifest, and only set-level manifests may refer to
  1128. # external resources. See section 11.4 and section 4 of F4M spec
  1129. if bootstrap_info is None:
  1130. media_url = None
  1131. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1132. if manifest_version == '2.0':
  1133. media_url = media_el.attrib.get('href')
  1134. if media_url is None:
  1135. media_url = media_el.attrib.get('url')
  1136. if not media_url:
  1137. continue
  1138. manifest_url = (
  1139. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1140. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1141. # If media_url is itself a f4m manifest do the recursive extraction
  1142. # since bitrates in parent manifest (this one) and media_url manifest
  1143. # may differ leading to inability to resolve the format by requested
  1144. # bitrate in f4m downloader
  1145. ext = determine_ext(manifest_url)
  1146. if ext == 'f4m':
  1147. f4m_formats = self._extract_f4m_formats(
  1148. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1149. transform_source=transform_source, fatal=fatal)
  1150. # Sometimes stream-level manifest contains single media entry that
  1151. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1152. # At the same time parent's media entry in set-level manifest may
  1153. # contain it. We will copy it from parent in such cases.
  1154. if len(f4m_formats) == 1:
  1155. f = f4m_formats[0]
  1156. f.update({
  1157. 'tbr': f.get('tbr') or tbr,
  1158. 'width': f.get('width') or width,
  1159. 'height': f.get('height') or height,
  1160. 'format_id': f.get('format_id') if not tbr else format_id,
  1161. 'vcodec': vcodec,
  1162. })
  1163. formats.extend(f4m_formats)
  1164. continue
  1165. elif ext == 'm3u8':
  1166. formats.extend(self._extract_m3u8_formats(
  1167. manifest_url, video_id, 'mp4', preference=preference,
  1168. m3u8_id=m3u8_id, fatal=fatal))
  1169. continue
  1170. formats.append({
  1171. 'format_id': format_id,
  1172. 'url': manifest_url,
  1173. 'manifest_url': manifest_url,
  1174. 'ext': 'flv' if bootstrap_info is not None else None,
  1175. 'protocol': 'f4m',
  1176. 'tbr': tbr,
  1177. 'width': width,
  1178. 'height': height,
  1179. 'vcodec': vcodec,
  1180. 'preference': preference,
  1181. })
  1182. return formats
  1183. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1184. return {
  1185. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1186. 'url': m3u8_url,
  1187. 'ext': ext,
  1188. 'protocol': 'm3u8',
  1189. 'preference': preference - 100 if preference else -100,
  1190. 'resolution': 'multiple',
  1191. 'format_note': 'Quality selection URL',
  1192. }
  1193. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1194. entry_protocol='m3u8', preference=None,
  1195. m3u8_id=None, note=None, errnote=None,
  1196. fatal=True, live=False):
  1197. res = self._download_webpage_handle(
  1198. m3u8_url, video_id,
  1199. note=note or 'Downloading m3u8 information',
  1200. errnote=errnote or 'Failed to download m3u8 information',
  1201. fatal=fatal)
  1202. if res is False:
  1203. return []
  1204. m3u8_doc, urlh = res
  1205. m3u8_url = urlh.geturl()
  1206. return self._parse_m3u8_formats(
  1207. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1208. preference=preference, m3u8_id=m3u8_id, live=live)
  1209. def _parse_m3u8_formats(self, m3u8_doc, m3u8_url, ext=None,
  1210. entry_protocol='m3u8', preference=None,
  1211. m3u8_id=None, live=False):
  1212. if '#EXT-X-FAXS-CM:' in m3u8_doc: # Adobe Flash Access
  1213. return []
  1214. if re.search(r'#EXT-X-SESSION-KEY:.*?URI="skd://', m3u8_doc): # Apple FairPlay
  1215. return []
  1216. formats = []
  1217. format_url = lambda u: (
  1218. u
  1219. if re.match(r'^https?://', u)
  1220. else compat_urlparse.urljoin(m3u8_url, u))
  1221. # References:
  1222. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1223. # 2. https://github.com/rg3/youtube-dl/issues/12211
  1224. # We should try extracting formats only from master playlists [1, 4.3.4],
  1225. # i.e. playlists that describe available qualities. On the other hand
  1226. # media playlists [1, 4.3.3] should be returned as is since they contain
  1227. # just the media without qualities renditions.
  1228. # Fortunately, master playlist can be easily distinguished from media
  1229. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1230. # master playlist tags MUST NOT appear in a media playist and vice versa.
  1231. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1232. # media playlist and MUST NOT appear in master playlist thus we can
  1233. # clearly detect media playlist with this criterion.
  1234. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1235. return [{
  1236. 'url': m3u8_url,
  1237. 'format_id': m3u8_id,
  1238. 'ext': ext,
  1239. 'protocol': entry_protocol,
  1240. 'preference': preference,
  1241. }]
  1242. groups = {}
  1243. last_stream_inf = {}
  1244. def extract_media(x_media_line):
  1245. media = parse_m3u8_attributes(x_media_line)
  1246. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1247. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1248. if not (media_type and group_id and name):
  1249. return
  1250. groups.setdefault(group_id, []).append(media)
  1251. if media_type not in ('VIDEO', 'AUDIO'):
  1252. return
  1253. media_url = media.get('URI')
  1254. if media_url:
  1255. format_id = []
  1256. for v in (m3u8_id, group_id, name):
  1257. if v:
  1258. format_id.append(v)
  1259. f = {
  1260. 'format_id': '-'.join(format_id),
  1261. 'url': format_url(media_url),
  1262. 'manifest_url': m3u8_url,
  1263. 'language': media.get('LANGUAGE'),
  1264. 'ext': ext,
  1265. 'protocol': entry_protocol,
  1266. 'preference': preference,
  1267. }
  1268. if media_type == 'AUDIO':
  1269. f['vcodec'] = 'none'
  1270. formats.append(f)
  1271. def build_stream_name():
  1272. # Despite specification does not mention NAME attribute for
  1273. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1274. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1275. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1276. stream_name = last_stream_inf.get('NAME')
  1277. if stream_name:
  1278. return stream_name
  1279. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1280. # from corresponding rendition group
  1281. stream_group_id = last_stream_inf.get('VIDEO')
  1282. if not stream_group_id:
  1283. return
  1284. stream_group = groups.get(stream_group_id)
  1285. if not stream_group:
  1286. return stream_group_id
  1287. rendition = stream_group[0]
  1288. return rendition.get('NAME') or stream_group_id
  1289. for line in m3u8_doc.splitlines():
  1290. if line.startswith('#EXT-X-STREAM-INF:'):
  1291. last_stream_inf = parse_m3u8_attributes(line)
  1292. elif line.startswith('#EXT-X-MEDIA:'):
  1293. extract_media(line)
  1294. elif line.startswith('#') or not line.strip():
  1295. continue
  1296. else:
  1297. tbr = float_or_none(
  1298. last_stream_inf.get('AVERAGE-BANDWIDTH') or
  1299. last_stream_inf.get('BANDWIDTH'), scale=1000)
  1300. format_id = []
  1301. if m3u8_id:
  1302. format_id.append(m3u8_id)
  1303. stream_name = build_stream_name()
  1304. # Bandwidth of live streams may differ over time thus making
  1305. # format_id unpredictable. So it's better to keep provided
  1306. # format_id intact.
  1307. if not live:
  1308. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1309. manifest_url = format_url(line.strip())
  1310. f = {
  1311. 'format_id': '-'.join(format_id),
  1312. 'url': manifest_url,
  1313. 'manifest_url': m3u8_url,
  1314. 'tbr': tbr,
  1315. 'ext': ext,
  1316. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  1317. 'protocol': entry_protocol,
  1318. 'preference': preference,
  1319. }
  1320. resolution = last_stream_inf.get('RESOLUTION')
  1321. if resolution:
  1322. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1323. if mobj:
  1324. f['width'] = int(mobj.group('width'))
  1325. f['height'] = int(mobj.group('height'))
  1326. # Unified Streaming Platform
  1327. mobj = re.search(
  1328. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1329. if mobj:
  1330. abr, vbr = mobj.groups()
  1331. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1332. f.update({
  1333. 'vbr': vbr,
  1334. 'abr': abr,
  1335. })
  1336. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  1337. f.update(codecs)
  1338. audio_group_id = last_stream_inf.get('AUDIO')
  1339. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  1340. # references a rendition group MUST have a CODECS attribute.
  1341. # However, this is not always respected, for example, [2]
  1342. # contains EXT-X-STREAM-INF tag which references AUDIO
  1343. # rendition group but does not have CODECS and despite
  1344. # referencing audio group an audio group, it represents
  1345. # a complete (with audio and video) format. So, for such cases
  1346. # we will ignore references to rendition groups and treat them
  1347. # as complete formats.
  1348. if audio_group_id and codecs and f.get('vcodec') != 'none':
  1349. audio_group = groups.get(audio_group_id)
  1350. if audio_group and audio_group[0].get('URI'):
  1351. # TODO: update acodec for audio only formats with
  1352. # the same GROUP-ID
  1353. f['acodec'] = 'none'
  1354. formats.append(f)
  1355. last_stream_inf = {}
  1356. return formats
  1357. @staticmethod
  1358. def _xpath_ns(path, namespace=None):
  1359. if not namespace:
  1360. return path
  1361. out = []
  1362. for c in path.split('/'):
  1363. if not c or c == '.':
  1364. out.append(c)
  1365. else:
  1366. out.append('{%s}%s' % (namespace, c))
  1367. return '/'.join(out)
  1368. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1369. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1370. if smil is False:
  1371. assert not fatal
  1372. return []
  1373. namespace = self._parse_smil_namespace(smil)
  1374. return self._parse_smil_formats(
  1375. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1376. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1377. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1378. if smil is False:
  1379. return {}
  1380. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1381. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1382. return self._download_xml(
  1383. smil_url, video_id, 'Downloading SMIL file',
  1384. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1385. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1386. namespace = self._parse_smil_namespace(smil)
  1387. formats = self._parse_smil_formats(
  1388. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1389. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1390. video_id = os.path.splitext(url_basename(smil_url))[0]
  1391. title = None
  1392. description = None
  1393. upload_date = None
  1394. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1395. name = meta.attrib.get('name')
  1396. content = meta.attrib.get('content')
  1397. if not name or not content:
  1398. continue
  1399. if not title and name == 'title':
  1400. title = content
  1401. elif not description and name in ('description', 'abstract'):
  1402. description = content
  1403. elif not upload_date and name == 'date':
  1404. upload_date = unified_strdate(content)
  1405. thumbnails = [{
  1406. 'id': image.get('type'),
  1407. 'url': image.get('src'),
  1408. 'width': int_or_none(image.get('width')),
  1409. 'height': int_or_none(image.get('height')),
  1410. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1411. return {
  1412. 'id': video_id,
  1413. 'title': title or video_id,
  1414. 'description': description,
  1415. 'upload_date': upload_date,
  1416. 'thumbnails': thumbnails,
  1417. 'formats': formats,
  1418. 'subtitles': subtitles,
  1419. }
  1420. def _parse_smil_namespace(self, smil):
  1421. return self._search_regex(
  1422. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1423. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1424. base = smil_url
  1425. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1426. b = meta.get('base') or meta.get('httpBase')
  1427. if b:
  1428. base = b
  1429. break
  1430. formats = []
  1431. rtmp_count = 0
  1432. http_count = 0
  1433. m3u8_count = 0
  1434. srcs = []
  1435. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1436. for medium in media:
  1437. src = medium.get('src')
  1438. if not src or src in srcs:
  1439. continue
  1440. srcs.append(src)
  1441. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1442. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1443. width = int_or_none(medium.get('width'))
  1444. height = int_or_none(medium.get('height'))
  1445. proto = medium.get('proto')
  1446. ext = medium.get('ext')
  1447. src_ext = determine_ext(src)
  1448. streamer = medium.get('streamer') or base
  1449. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1450. rtmp_count += 1
  1451. formats.append({
  1452. 'url': streamer,
  1453. 'play_path': src,
  1454. 'ext': 'flv',
  1455. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1456. 'tbr': bitrate,
  1457. 'filesize': filesize,
  1458. 'width': width,
  1459. 'height': height,
  1460. })
  1461. if transform_rtmp_url:
  1462. streamer, src = transform_rtmp_url(streamer, src)
  1463. formats[-1].update({
  1464. 'url': streamer,
  1465. 'play_path': src,
  1466. })
  1467. continue
  1468. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1469. src_url = src_url.strip()
  1470. if proto == 'm3u8' or src_ext == 'm3u8':
  1471. m3u8_formats = self._extract_m3u8_formats(
  1472. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1473. if len(m3u8_formats) == 1:
  1474. m3u8_count += 1
  1475. m3u8_formats[0].update({
  1476. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1477. 'tbr': bitrate,
  1478. 'width': width,
  1479. 'height': height,
  1480. })
  1481. formats.extend(m3u8_formats)
  1482. continue
  1483. if src_ext == 'f4m':
  1484. f4m_url = src_url
  1485. if not f4m_params:
  1486. f4m_params = {
  1487. 'hdcore': '3.2.0',
  1488. 'plugin': 'flowplayer-3.2.0.1',
  1489. }
  1490. f4m_url += '&' if '?' in f4m_url else '?'
  1491. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1492. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1493. continue
  1494. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1495. http_count += 1
  1496. formats.append({
  1497. 'url': src_url,
  1498. 'ext': ext or src_ext or 'flv',
  1499. 'format_id': 'http-%d' % (bitrate or http_count),
  1500. 'tbr': bitrate,
  1501. 'filesize': filesize,
  1502. 'width': width,
  1503. 'height': height,
  1504. })
  1505. continue
  1506. return formats
  1507. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1508. urls = []
  1509. subtitles = {}
  1510. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1511. src = textstream.get('src')
  1512. if not src or src in urls:
  1513. continue
  1514. urls.append(src)
  1515. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1516. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1517. subtitles.setdefault(lang, []).append({
  1518. 'url': src,
  1519. 'ext': ext,
  1520. })
  1521. return subtitles
  1522. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  1523. xspf = self._download_xml(
  1524. xspf_url, playlist_id, 'Downloading xpsf playlist',
  1525. 'Unable to download xspf manifest', fatal=fatal)
  1526. if xspf is False:
  1527. return []
  1528. return self._parse_xspf(
  1529. xspf, playlist_id, xspf_url=xspf_url,
  1530. xspf_base_url=base_url(xspf_url))
  1531. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  1532. NS_MAP = {
  1533. 'xspf': 'http://xspf.org/ns/0/',
  1534. 's1': 'http://static.streamone.nl/player/ns/0',
  1535. }
  1536. entries = []
  1537. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1538. title = xpath_text(
  1539. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1540. description = xpath_text(
  1541. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1542. thumbnail = xpath_text(
  1543. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1544. duration = float_or_none(
  1545. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1546. formats = []
  1547. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  1548. format_url = urljoin(xspf_base_url, location.text)
  1549. if not format_url:
  1550. continue
  1551. formats.append({
  1552. 'url': format_url,
  1553. 'manifest_url': xspf_url,
  1554. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1555. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1556. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1557. })
  1558. self._sort_formats(formats)
  1559. entries.append({
  1560. 'id': playlist_id,
  1561. 'title': title,
  1562. 'description': description,
  1563. 'thumbnail': thumbnail,
  1564. 'duration': duration,
  1565. 'formats': formats,
  1566. })
  1567. return entries
  1568. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1569. res = self._download_xml_handle(
  1570. mpd_url, video_id,
  1571. note=note or 'Downloading MPD manifest',
  1572. errnote=errnote or 'Failed to download MPD manifest',
  1573. fatal=fatal)
  1574. if res is False:
  1575. return []
  1576. mpd_doc, urlh = res
  1577. mpd_base_url = base_url(urlh.geturl())
  1578. return self._parse_mpd_formats(
  1579. mpd_doc, mpd_id=mpd_id, mpd_base_url=mpd_base_url,
  1580. formats_dict=formats_dict, mpd_url=mpd_url)
  1581. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}, mpd_url=None):
  1582. """
  1583. Parse formats from MPD manifest.
  1584. References:
  1585. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  1586. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  1587. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  1588. """
  1589. if mpd_doc.get('type') == 'dynamic':
  1590. return []
  1591. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1592. def _add_ns(path):
  1593. return self._xpath_ns(path, namespace)
  1594. def is_drm_protected(element):
  1595. return element.find(_add_ns('ContentProtection')) is not None
  1596. def extract_multisegment_info(element, ms_parent_info):
  1597. ms_info = ms_parent_info.copy()
  1598. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  1599. # common attributes and elements. We will only extract relevant
  1600. # for us.
  1601. def extract_common(source):
  1602. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  1603. if segment_timeline is not None:
  1604. s_e = segment_timeline.findall(_add_ns('S'))
  1605. if s_e:
  1606. ms_info['total_number'] = 0
  1607. ms_info['s'] = []
  1608. for s in s_e:
  1609. r = int(s.get('r', 0))
  1610. ms_info['total_number'] += 1 + r
  1611. ms_info['s'].append({
  1612. 't': int(s.get('t', 0)),
  1613. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  1614. 'd': int(s.attrib['d']),
  1615. 'r': r,
  1616. })
  1617. start_number = source.get('startNumber')
  1618. if start_number:
  1619. ms_info['start_number'] = int(start_number)
  1620. timescale = source.get('timescale')
  1621. if timescale:
  1622. ms_info['timescale'] = int(timescale)
  1623. segment_duration = source.get('duration')
  1624. if segment_duration:
  1625. ms_info['segment_duration'] = float(segment_duration)
  1626. def extract_Initialization(source):
  1627. initialization = source.find(_add_ns('Initialization'))
  1628. if initialization is not None:
  1629. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1630. segment_list = element.find(_add_ns('SegmentList'))
  1631. if segment_list is not None:
  1632. extract_common(segment_list)
  1633. extract_Initialization(segment_list)
  1634. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1635. if segment_urls_e:
  1636. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1637. else:
  1638. segment_template = element.find(_add_ns('SegmentTemplate'))
  1639. if segment_template is not None:
  1640. extract_common(segment_template)
  1641. media = segment_template.get('media')
  1642. if media:
  1643. ms_info['media'] = media
  1644. initialization = segment_template.get('initialization')
  1645. if initialization:
  1646. ms_info['initialization'] = initialization
  1647. else:
  1648. extract_Initialization(segment_template)
  1649. return ms_info
  1650. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1651. formats = []
  1652. for period in mpd_doc.findall(_add_ns('Period')):
  1653. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1654. period_ms_info = extract_multisegment_info(period, {
  1655. 'start_number': 1,
  1656. 'timescale': 1,
  1657. })
  1658. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1659. if is_drm_protected(adaptation_set):
  1660. continue
  1661. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1662. for representation in adaptation_set.findall(_add_ns('Representation')):
  1663. if is_drm_protected(representation):
  1664. continue
  1665. representation_attrib = adaptation_set.attrib.copy()
  1666. representation_attrib.update(representation.attrib)
  1667. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  1668. mime_type = representation_attrib['mimeType']
  1669. content_type = mime_type.split('/')[0]
  1670. if content_type == 'text':
  1671. # TODO implement WebVTT downloading
  1672. pass
  1673. elif content_type in ('video', 'audio'):
  1674. base_url = ''
  1675. for element in (representation, adaptation_set, period, mpd_doc):
  1676. base_url_e = element.find(_add_ns('BaseURL'))
  1677. if base_url_e is not None:
  1678. base_url = base_url_e.text + base_url
  1679. if re.match(r'^https?://', base_url):
  1680. break
  1681. if mpd_base_url and not re.match(r'^https?://', base_url):
  1682. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1683. mpd_base_url += '/'
  1684. base_url = mpd_base_url + base_url
  1685. representation_id = representation_attrib.get('id')
  1686. lang = representation_attrib.get('lang')
  1687. url_el = representation.find(_add_ns('BaseURL'))
  1688. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1689. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  1690. f = {
  1691. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1692. 'url': base_url,
  1693. 'manifest_url': mpd_url,
  1694. 'ext': mimetype2ext(mime_type),
  1695. 'width': int_or_none(representation_attrib.get('width')),
  1696. 'height': int_or_none(representation_attrib.get('height')),
  1697. 'tbr': float_or_none(bandwidth, 1000),
  1698. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1699. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1700. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1701. 'format_note': 'DASH %s' % content_type,
  1702. 'filesize': filesize,
  1703. 'container': mimetype2ext(mime_type) + '_dash',
  1704. }
  1705. f.update(parse_codecs(representation_attrib.get('codecs')))
  1706. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1707. def prepare_template(template_name, identifiers):
  1708. t = representation_ms_info[template_name]
  1709. t = t.replace('$RepresentationID$', representation_id)
  1710. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  1711. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  1712. t.replace('$$', '$')
  1713. return t
  1714. # @initialization is a regular template like @media one
  1715. # so it should be handled just the same way (see
  1716. # https://github.com/rg3/youtube-dl/issues/11605)
  1717. if 'initialization' in representation_ms_info:
  1718. initialization_template = prepare_template(
  1719. 'initialization',
  1720. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  1721. # $Time$ shall not be included for @initialization thus
  1722. # only $Bandwidth$ remains
  1723. ('Bandwidth', ))
  1724. representation_ms_info['initialization_url'] = initialization_template % {
  1725. 'Bandwidth': bandwidth,
  1726. }
  1727. def location_key(location):
  1728. return 'url' if re.match(r'^https?://', location) else 'path'
  1729. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  1730. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  1731. media_location_key = location_key(media_template)
  1732. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  1733. # can't be used at the same time
  1734. if '%(Number' in media_template and 's' not in representation_ms_info:
  1735. segment_duration = None
  1736. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  1737. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  1738. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1739. representation_ms_info['fragments'] = [{
  1740. media_location_key: media_template % {
  1741. 'Number': segment_number,
  1742. 'Bandwidth': bandwidth,
  1743. },
  1744. 'duration': segment_duration,
  1745. } for segment_number in range(
  1746. representation_ms_info['start_number'],
  1747. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1748. else:
  1749. # $Number*$ or $Time$ in media template with S list available
  1750. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  1751. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  1752. representation_ms_info['fragments'] = []
  1753. segment_time = 0
  1754. segment_d = None
  1755. segment_number = representation_ms_info['start_number']
  1756. def add_segment_url():
  1757. segment_url = media_template % {
  1758. 'Time': segment_time,
  1759. 'Bandwidth': bandwidth,
  1760. 'Number': segment_number,
  1761. }
  1762. representation_ms_info['fragments'].append({
  1763. media_location_key: segment_url,
  1764. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  1765. })
  1766. for num, s in enumerate(representation_ms_info['s']):
  1767. segment_time = s.get('t') or segment_time
  1768. segment_d = s['d']
  1769. add_segment_url()
  1770. segment_number += 1
  1771. for r in range(s.get('r', 0)):
  1772. segment_time += segment_d
  1773. add_segment_url()
  1774. segment_number += 1
  1775. segment_time += segment_d
  1776. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  1777. # No media template
  1778. # Example: https://www.youtube.com/watch?v=iXZV5uAYMJI
  1779. # or any YouTube dashsegments video
  1780. fragments = []
  1781. segment_index = 0
  1782. timescale = representation_ms_info['timescale']
  1783. for s in representation_ms_info['s']:
  1784. duration = float_or_none(s['d'], timescale)
  1785. for r in range(s.get('r', 0) + 1):
  1786. segment_uri = representation_ms_info['segment_urls'][segment_index]
  1787. fragments.append({
  1788. location_key(segment_uri): segment_uri,
  1789. 'duration': duration,
  1790. })
  1791. segment_index += 1
  1792. representation_ms_info['fragments'] = fragments
  1793. elif 'segment_urls' in representation_ms_info:
  1794. # Segment URLs with no SegmentTimeline
  1795. # Example: https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  1796. # https://github.com/rg3/youtube-dl/pull/14844
  1797. fragments = []
  1798. segment_duration = float_or_none(
  1799. representation_ms_info['segment_duration'],
  1800. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  1801. for segment_url in representation_ms_info['segment_urls']:
  1802. fragment = {
  1803. location_key(segment_url): segment_url,
  1804. }
  1805. if segment_duration:
  1806. fragment['duration'] = segment_duration
  1807. fragments.append(fragment)
  1808. representation_ms_info['fragments'] = fragments
  1809. # NB: MPD manifest may contain direct URLs to unfragmented media.
  1810. # No fragments key is present in this case.
  1811. if 'fragments' in representation_ms_info:
  1812. f.update({
  1813. 'fragment_base_url': base_url,
  1814. 'fragments': [],
  1815. 'protocol': 'http_dash_segments',
  1816. })
  1817. if 'initialization_url' in representation_ms_info:
  1818. initialization_url = representation_ms_info['initialization_url']
  1819. if not f.get('url'):
  1820. f['url'] = initialization_url
  1821. f['fragments'].append({location_key(initialization_url): initialization_url})
  1822. f['fragments'].extend(representation_ms_info['fragments'])
  1823. # According to [1, 5.3.5.2, Table 7, page 35] @id of Representation
  1824. # is not necessarily unique within a Period thus formats with
  1825. # the same `format_id` are quite possible. There are numerous examples
  1826. # of such manifests (see https://github.com/rg3/youtube-dl/issues/15111,
  1827. # https://github.com/rg3/youtube-dl/issues/13919)
  1828. full_info = formats_dict.get(representation_id, {}).copy()
  1829. full_info.update(f)
  1830. formats.append(full_info)
  1831. else:
  1832. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1833. return formats
  1834. def _extract_ism_formats(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True):
  1835. res = self._download_xml_handle(
  1836. ism_url, video_id,
  1837. note=note or 'Downloading ISM manifest',
  1838. errnote=errnote or 'Failed to download ISM manifest',
  1839. fatal=fatal)
  1840. if res is False:
  1841. return []
  1842. ism_doc, urlh = res
  1843. return self._parse_ism_formats(ism_doc, urlh.geturl(), ism_id)
  1844. def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
  1845. """
  1846. Parse formats from ISM manifest.
  1847. References:
  1848. 1. [MS-SSTR]: Smooth Streaming Protocol,
  1849. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  1850. """
  1851. if ism_doc.get('IsLive') == 'TRUE' or ism_doc.find('Protection') is not None:
  1852. return []
  1853. duration = int(ism_doc.attrib['Duration'])
  1854. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  1855. formats = []
  1856. for stream in ism_doc.findall('StreamIndex'):
  1857. stream_type = stream.get('Type')
  1858. if stream_type not in ('video', 'audio'):
  1859. continue
  1860. url_pattern = stream.attrib['Url']
  1861. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  1862. stream_name = stream.get('Name')
  1863. for track in stream.findall('QualityLevel'):
  1864. fourcc = track.get('FourCC', 'AACL' if track.get('AudioTag') == '255' else None)
  1865. # TODO: add support for WVC1 and WMAP
  1866. if fourcc not in ('H264', 'AVC1', 'AACL'):
  1867. self.report_warning('%s is not a supported codec' % fourcc)
  1868. continue
  1869. tbr = int(track.attrib['Bitrate']) // 1000
  1870. # [1] does not mention Width and Height attributes. However,
  1871. # they're often present while MaxWidth and MaxHeight are
  1872. # missing, so should be used as fallbacks
  1873. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  1874. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  1875. sampling_rate = int_or_none(track.get('SamplingRate'))
  1876. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  1877. track_url_pattern = compat_urlparse.urljoin(ism_url, track_url_pattern)
  1878. fragments = []
  1879. fragment_ctx = {
  1880. 'time': 0,
  1881. }
  1882. stream_fragments = stream.findall('c')
  1883. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  1884. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  1885. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  1886. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  1887. if not fragment_ctx['duration']:
  1888. try:
  1889. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  1890. except IndexError:
  1891. next_fragment_time = duration
  1892. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  1893. for _ in range(fragment_repeat):
  1894. fragments.append({
  1895. 'url': re.sub(r'{start[ _]time}', compat_str(fragment_ctx['time']), track_url_pattern),
  1896. 'duration': fragment_ctx['duration'] / stream_timescale,
  1897. })
  1898. fragment_ctx['time'] += fragment_ctx['duration']
  1899. format_id = []
  1900. if ism_id:
  1901. format_id.append(ism_id)
  1902. if stream_name:
  1903. format_id.append(stream_name)
  1904. format_id.append(compat_str(tbr))
  1905. formats.append({
  1906. 'format_id': '-'.join(format_id),
  1907. 'url': ism_url,
  1908. 'manifest_url': ism_url,
  1909. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  1910. 'width': width,
  1911. 'height': height,
  1912. 'tbr': tbr,
  1913. 'asr': sampling_rate,
  1914. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  1915. 'acodec': 'none' if stream_type == 'video' else fourcc,
  1916. 'protocol': 'ism',
  1917. 'fragments': fragments,
  1918. '_download_params': {
  1919. 'duration': duration,
  1920. 'timescale': stream_timescale,
  1921. 'width': width or 0,
  1922. 'height': height or 0,
  1923. 'fourcc': fourcc,
  1924. 'codec_private_data': track.get('CodecPrivateData'),
  1925. 'sampling_rate': sampling_rate,
  1926. 'channels': int_or_none(track.get('Channels', 2)),
  1927. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  1928. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  1929. },
  1930. })
  1931. return formats
  1932. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8', mpd_id=None, preference=None):
  1933. def absolute_url(video_url):
  1934. return compat_urlparse.urljoin(base_url, video_url)
  1935. def parse_content_type(content_type):
  1936. if not content_type:
  1937. return {}
  1938. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  1939. if ctr:
  1940. mimetype, codecs = ctr.groups()
  1941. f = parse_codecs(codecs)
  1942. f['ext'] = mimetype2ext(mimetype)
  1943. return f
  1944. return {}
  1945. def _media_formats(src, cur_media_type, type_info={}):
  1946. full_url = absolute_url(src)
  1947. ext = type_info.get('ext') or determine_ext(full_url)
  1948. if ext == 'm3u8':
  1949. is_plain_url = False
  1950. formats = self._extract_m3u8_formats(
  1951. full_url, video_id, ext='mp4',
  1952. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  1953. preference=preference, fatal=False)
  1954. elif ext == 'mpd':
  1955. is_plain_url = False
  1956. formats = self._extract_mpd_formats(
  1957. full_url, video_id, mpd_id=mpd_id, fatal=False)
  1958. else:
  1959. is_plain_url = True
  1960. formats = [{
  1961. 'url': full_url,
  1962. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  1963. }]
  1964. return is_plain_url, formats
  1965. entries = []
  1966. # amp-video and amp-audio are very similar to their HTML5 counterparts
  1967. # so we wll include them right here (see
  1968. # https://www.ampproject.org/docs/reference/components/amp-video)
  1969. media_tags = [(media_tag, media_type, '')
  1970. for media_tag, media_type
  1971. in re.findall(r'(?s)(<(?:amp-)?(video|audio)[^>]*/>)', webpage)]
  1972. media_tags.extend(re.findall(
  1973. # We only allow video|audio followed by a whitespace or '>'.
  1974. # Allowing more characters may end up in significant slow down (see
  1975. # https://github.com/rg3/youtube-dl/issues/11979, example URL:
  1976. # http://www.porntrex.com/maps/videositemap.xml).
  1977. r'(?s)(<(?P<tag>(?:amp-)?(?:video|audio))(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  1978. for media_tag, media_type, media_content in media_tags:
  1979. media_info = {
  1980. 'formats': [],
  1981. 'subtitles': {},
  1982. }
  1983. media_attributes = extract_attributes(media_tag)
  1984. src = media_attributes.get('src')
  1985. if src:
  1986. _, formats = _media_formats(src, media_type)
  1987. media_info['formats'].extend(formats)
  1988. media_info['thumbnail'] = media_attributes.get('poster')
  1989. if media_content:
  1990. for source_tag in re.findall(r'<source[^>]+>', media_content):
  1991. source_attributes = extract_attributes(source_tag)
  1992. src = source_attributes.get('src')
  1993. if not src:
  1994. continue
  1995. f = parse_content_type(source_attributes.get('type'))
  1996. is_plain_url, formats = _media_formats(src, media_type, f)
  1997. if is_plain_url:
  1998. # res attribute is not standard but seen several times
  1999. # in the wild
  2000. f.update({
  2001. 'height': int_or_none(source_attributes.get('res')),
  2002. 'format_id': source_attributes.get('label'),
  2003. })
  2004. f.update(formats[0])
  2005. media_info['formats'].append(f)
  2006. else:
  2007. media_info['formats'].extend(formats)
  2008. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2009. track_attributes = extract_attributes(track_tag)
  2010. kind = track_attributes.get('kind')
  2011. if not kind or kind in ('subtitles', 'captions'):
  2012. src = track_attributes.get('src')
  2013. if not src:
  2014. continue
  2015. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2016. media_info['subtitles'].setdefault(lang, []).append({
  2017. 'url': absolute_url(src),
  2018. })
  2019. if media_info['formats'] or media_info['subtitles']:
  2020. entries.append(media_info)
  2021. return entries
  2022. def _extract_akamai_formats(self, manifest_url, video_id, hosts={}):
  2023. formats = []
  2024. hdcore_sign = 'hdcore=3.7.0'
  2025. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  2026. hds_host = hosts.get('hds')
  2027. if hds_host:
  2028. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  2029. if 'hdcore=' not in f4m_url:
  2030. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  2031. f4m_formats = self._extract_f4m_formats(
  2032. f4m_url, video_id, f4m_id='hds', fatal=False)
  2033. for entry in f4m_formats:
  2034. entry.update({'extra_param_to_segment_url': hdcore_sign})
  2035. formats.extend(f4m_formats)
  2036. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  2037. hls_host = hosts.get('hls')
  2038. if hls_host:
  2039. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  2040. formats.extend(self._extract_m3u8_formats(
  2041. m3u8_url, video_id, 'mp4', 'm3u8_native',
  2042. m3u8_id='hls', fatal=False))
  2043. return formats
  2044. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  2045. query = compat_urlparse.urlparse(url).query
  2046. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  2047. mobj = re.search(
  2048. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  2049. url_base = mobj.group('url')
  2050. http_base_url = '%s%s:%s' % ('http', mobj.group('s') or '', url_base)
  2051. formats = []
  2052. def manifest_url(manifest):
  2053. m_url = '%s/%s' % (http_base_url, manifest)
  2054. if query:
  2055. m_url += '?%s' % query
  2056. return m_url
  2057. if 'm3u8' not in skip_protocols:
  2058. formats.extend(self._extract_m3u8_formats(
  2059. manifest_url('playlist.m3u8'), video_id, 'mp4',
  2060. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  2061. if 'f4m' not in skip_protocols:
  2062. formats.extend(self._extract_f4m_formats(
  2063. manifest_url('manifest.f4m'),
  2064. video_id, f4m_id='hds', fatal=False))
  2065. if 'dash' not in skip_protocols:
  2066. formats.extend(self._extract_mpd_formats(
  2067. manifest_url('manifest.mpd'),
  2068. video_id, mpd_id='dash', fatal=False))
  2069. if re.search(r'(?:/smil:|\.smil)', url_base):
  2070. if 'smil' not in skip_protocols:
  2071. rtmp_formats = self._extract_smil_formats(
  2072. manifest_url('jwplayer.smil'),
  2073. video_id, fatal=False)
  2074. for rtmp_format in rtmp_formats:
  2075. rtsp_format = rtmp_format.copy()
  2076. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  2077. del rtsp_format['play_path']
  2078. del rtsp_format['ext']
  2079. rtsp_format.update({
  2080. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  2081. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  2082. 'protocol': 'rtsp',
  2083. })
  2084. formats.extend([rtmp_format, rtsp_format])
  2085. else:
  2086. for protocol in ('rtmp', 'rtsp'):
  2087. if protocol not in skip_protocols:
  2088. formats.append({
  2089. 'url': '%s:%s' % (protocol, url_base),
  2090. 'format_id': protocol,
  2091. 'protocol': protocol,
  2092. })
  2093. return formats
  2094. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  2095. mobj = re.search(
  2096. r'(?s)jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)(?!</script>).*?\.setup\s*\((?P<options>[^)]+)\)',
  2097. webpage)
  2098. if mobj:
  2099. try:
  2100. jwplayer_data = self._parse_json(mobj.group('options'),
  2101. video_id=video_id,
  2102. transform_source=transform_source)
  2103. except ExtractorError:
  2104. pass
  2105. else:
  2106. if isinstance(jwplayer_data, dict):
  2107. return jwplayer_data
  2108. def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
  2109. jwplayer_data = self._find_jwplayer_data(
  2110. webpage, video_id, transform_source=js_to_json)
  2111. return self._parse_jwplayer_data(
  2112. jwplayer_data, video_id, *args, **kwargs)
  2113. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  2114. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  2115. # JWPlayer backward compatibility: flattened playlists
  2116. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  2117. if 'playlist' not in jwplayer_data:
  2118. jwplayer_data = {'playlist': [jwplayer_data]}
  2119. entries = []
  2120. # JWPlayer backward compatibility: single playlist item
  2121. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  2122. if not isinstance(jwplayer_data['playlist'], list):
  2123. jwplayer_data['playlist'] = [jwplayer_data['playlist']]
  2124. for video_data in jwplayer_data['playlist']:
  2125. # JWPlayer backward compatibility: flattened sources
  2126. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  2127. if 'sources' not in video_data:
  2128. video_data['sources'] = [video_data]
  2129. this_video_id = video_id or video_data['mediaid']
  2130. formats = self._parse_jwplayer_formats(
  2131. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  2132. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  2133. subtitles = {}
  2134. tracks = video_data.get('tracks')
  2135. if tracks and isinstance(tracks, list):
  2136. for track in tracks:
  2137. if not isinstance(track, dict):
  2138. continue
  2139. track_kind = track.get('kind')
  2140. if not track_kind or not isinstance(track_kind, compat_str):
  2141. continue
  2142. if track_kind.lower() not in ('captions', 'subtitles'):
  2143. continue
  2144. track_url = urljoin(base_url, track.get('file'))
  2145. if not track_url:
  2146. continue
  2147. subtitles.setdefault(track.get('label') or 'en', []).append({
  2148. 'url': self._proto_relative_url(track_url)
  2149. })
  2150. entry = {
  2151. 'id': this_video_id,
  2152. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  2153. 'description': video_data.get('description'),
  2154. 'thumbnail': self._proto_relative_url(video_data.get('image')),
  2155. 'timestamp': int_or_none(video_data.get('pubdate')),
  2156. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  2157. 'subtitles': subtitles,
  2158. }
  2159. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  2160. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  2161. entry.update({
  2162. '_type': 'url_transparent',
  2163. 'url': formats[0]['url'],
  2164. })
  2165. else:
  2166. self._sort_formats(formats)
  2167. entry['formats'] = formats
  2168. entries.append(entry)
  2169. if len(entries) == 1:
  2170. return entries[0]
  2171. else:
  2172. return self.playlist_result(entries)
  2173. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  2174. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  2175. urls = []
  2176. formats = []
  2177. for source in jwplayer_sources_data:
  2178. if not isinstance(source, dict):
  2179. continue
  2180. source_url = self._proto_relative_url(source.get('file'))
  2181. if not source_url:
  2182. continue
  2183. if base_url:
  2184. source_url = compat_urlparse.urljoin(base_url, source_url)
  2185. if source_url in urls:
  2186. continue
  2187. urls.append(source_url)
  2188. source_type = source.get('type') or ''
  2189. ext = mimetype2ext(source_type) or determine_ext(source_url)
  2190. if source_type == 'hls' or ext == 'm3u8':
  2191. formats.extend(self._extract_m3u8_formats(
  2192. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  2193. m3u8_id=m3u8_id, fatal=False))
  2194. elif source_type == 'dash' or ext == 'mpd':
  2195. formats.extend(self._extract_mpd_formats(
  2196. source_url, video_id, mpd_id=mpd_id, fatal=False))
  2197. elif ext == 'smil':
  2198. formats.extend(self._extract_smil_formats(
  2199. source_url, video_id, fatal=False))
  2200. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  2201. elif source_type.startswith('audio') or ext in (
  2202. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  2203. formats.append({
  2204. 'url': source_url,
  2205. 'vcodec': 'none',
  2206. 'ext': ext,
  2207. })
  2208. else:
  2209. height = int_or_none(source.get('height'))
  2210. if height is None:
  2211. # Often no height is provided but there is a label in
  2212. # format like "1080p", "720p SD", or 1080.
  2213. height = int_or_none(self._search_regex(
  2214. r'^(\d{3,4})[pP]?(?:\b|$)', compat_str(source.get('label') or ''),
  2215. 'height', default=None))
  2216. a_format = {
  2217. 'url': source_url,
  2218. 'width': int_or_none(source.get('width')),
  2219. 'height': height,
  2220. 'tbr': int_or_none(source.get('bitrate')),
  2221. 'ext': ext,
  2222. }
  2223. if source_url.startswith('rtmp'):
  2224. a_format['ext'] = 'flv'
  2225. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  2226. # of jwplayer.flash.swf
  2227. rtmp_url_parts = re.split(
  2228. r'((?:mp4|mp3|flv):)', source_url, 1)
  2229. if len(rtmp_url_parts) == 3:
  2230. rtmp_url, prefix, play_path = rtmp_url_parts
  2231. a_format.update({
  2232. 'url': rtmp_url,
  2233. 'play_path': prefix + play_path,
  2234. })
  2235. if rtmp_params:
  2236. a_format.update(rtmp_params)
  2237. formats.append(a_format)
  2238. return formats
  2239. def _live_title(self, name):
  2240. """ Generate the title for a live video """
  2241. now = datetime.datetime.now()
  2242. now_str = now.strftime('%Y-%m-%d %H:%M')
  2243. return name + ' ' + now_str
  2244. def _int(self, v, name, fatal=False, **kwargs):
  2245. res = int_or_none(v, **kwargs)
  2246. if 'get_attr' in kwargs:
  2247. print(getattr(v, kwargs['get_attr']))
  2248. if res is None:
  2249. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2250. if fatal:
  2251. raise ExtractorError(msg)
  2252. else:
  2253. self._downloader.report_warning(msg)
  2254. return res
  2255. def _float(self, v, name, fatal=False, **kwargs):
  2256. res = float_or_none(v, **kwargs)
  2257. if res is None:
  2258. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2259. if fatal:
  2260. raise ExtractorError(msg)
  2261. else:
  2262. self._downloader.report_warning(msg)
  2263. return res
  2264. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  2265. path='/', secure=False, discard=False, rest={}, **kwargs):
  2266. cookie = compat_cookiejar.Cookie(
  2267. 0, name, value, port, port is not None, domain, True,
  2268. domain.startswith('.'), path, True, secure, expire_time,
  2269. discard, None, None, rest)
  2270. self._downloader.cookiejar.set_cookie(cookie)
  2271. def _get_cookies(self, url):
  2272. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  2273. req = sanitized_Request(url)
  2274. self._downloader.cookiejar.add_cookie_header(req)
  2275. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  2276. def get_testcases(self, include_onlymatching=False):
  2277. t = getattr(self, '_TEST', None)
  2278. if t:
  2279. assert not hasattr(self, '_TESTS'), \
  2280. '%s has _TEST and _TESTS' % type(self).__name__
  2281. tests = [t]
  2282. else:
  2283. tests = getattr(self, '_TESTS', [])
  2284. for t in tests:
  2285. if not include_onlymatching and t.get('only_matching', False):
  2286. continue
  2287. t['name'] = type(self).__name__[:-len('IE')]
  2288. yield t
  2289. def is_suitable(self, age_limit):
  2290. """ Test whether the extractor is generally suitable for the given
  2291. age limit (i.e. pornographic sites are not, all others usually are) """
  2292. any_restricted = False
  2293. for tc in self.get_testcases(include_onlymatching=False):
  2294. if tc.get('playlist', []):
  2295. tc = tc['playlist'][0]
  2296. is_restricted = age_restricted(
  2297. tc.get('info_dict', {}).get('age_limit'), age_limit)
  2298. if not is_restricted:
  2299. return True
  2300. any_restricted = any_restricted or is_restricted
  2301. return not any_restricted
  2302. def extract_subtitles(self, *args, **kwargs):
  2303. if (self._downloader.params.get('writesubtitles', False) or
  2304. self._downloader.params.get('listsubtitles')):
  2305. return self._get_subtitles(*args, **kwargs)
  2306. return {}
  2307. def _get_subtitles(self, *args, **kwargs):
  2308. raise NotImplementedError('This method must be implemented by subclasses')
  2309. @staticmethod
  2310. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  2311. """ Merge subtitle items for one language. Items with duplicated URLs
  2312. will be dropped. """
  2313. list1_urls = set([item['url'] for item in subtitle_list1])
  2314. ret = list(subtitle_list1)
  2315. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  2316. return ret
  2317. @classmethod
  2318. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  2319. """ Merge two subtitle dictionaries, language by language. """
  2320. ret = dict(subtitle_dict1)
  2321. for lang in subtitle_dict2:
  2322. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  2323. return ret
  2324. def extract_automatic_captions(self, *args, **kwargs):
  2325. if (self._downloader.params.get('writeautomaticsub', False) or
  2326. self._downloader.params.get('listsubtitles')):
  2327. return self._get_automatic_captions(*args, **kwargs)
  2328. return {}
  2329. def _get_automatic_captions(self, *args, **kwargs):
  2330. raise NotImplementedError('This method must be implemented by subclasses')
  2331. def mark_watched(self, *args, **kwargs):
  2332. if (self._downloader.params.get('mark_watched', False) and
  2333. (self._get_login_info()[0] is not None or
  2334. self._downloader.params.get('cookiefile') is not None)):
  2335. self._mark_watched(*args, **kwargs)
  2336. def _mark_watched(self, *args, **kwargs):
  2337. raise NotImplementedError('This method must be implemented by subclasses')
  2338. def geo_verification_headers(self):
  2339. headers = {}
  2340. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  2341. if geo_verification_proxy:
  2342. headers['Ytdl-request-proxy'] = geo_verification_proxy
  2343. return headers
  2344. def _generic_id(self, url):
  2345. return compat_urllib_parse_unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  2346. def _generic_title(self, url):
  2347. return compat_urllib_parse_unquote(os.path.splitext(url_basename(url))[0])
  2348. class SearchInfoExtractor(InfoExtractor):
  2349. """
  2350. Base class for paged search queries extractors.
  2351. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  2352. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  2353. """
  2354. @classmethod
  2355. def _make_valid_url(cls):
  2356. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  2357. @classmethod
  2358. def suitable(cls, url):
  2359. return re.match(cls._make_valid_url(), url) is not None
  2360. def _real_extract(self, query):
  2361. mobj = re.match(self._make_valid_url(), query)
  2362. if mobj is None:
  2363. raise ExtractorError('Invalid search query "%s"' % query)
  2364. prefix = mobj.group('prefix')
  2365. query = mobj.group('query')
  2366. if prefix == '':
  2367. return self._get_n_results(query, 1)
  2368. elif prefix == 'all':
  2369. return self._get_n_results(query, self._MAX_RESULTS)
  2370. else:
  2371. n = int(prefix)
  2372. if n <= 0:
  2373. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  2374. elif n > self._MAX_RESULTS:
  2375. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  2376. n = self._MAX_RESULTS
  2377. return self._get_n_results(query, n)
  2378. def _get_n_results(self, query, n):
  2379. """Get a specified number of results for a query"""
  2380. raise NotImplementedError('This method must be implemented by subclasses')
  2381. @property
  2382. def SEARCH_KEY(self):
  2383. return self._SEARCH_KEY