common.py 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989
  1. import base64
  2. import collections
  3. import functools
  4. import getpass
  5. import hashlib
  6. import http.client
  7. import http.cookiejar
  8. import http.cookies
  9. import inspect
  10. import itertools
  11. import json
  12. import math
  13. import netrc
  14. import os
  15. import random
  16. import re
  17. import subprocess
  18. import sys
  19. import time
  20. import types
  21. import urllib.parse
  22. import urllib.request
  23. import xml.etree.ElementTree
  24. from ..compat import (
  25. compat_etree_fromstring,
  26. compat_expanduser,
  27. compat_os_name,
  28. urllib_req_to_req,
  29. )
  30. from ..cookies import LenientSimpleCookie
  31. from ..downloader.f4m import get_base_url, remove_encrypted_media
  32. from ..downloader.hls import HlsFD
  33. from ..networking import HEADRequest, Request
  34. from ..networking.exceptions import (
  35. HTTPError,
  36. IncompleteRead,
  37. network_exceptions,
  38. )
  39. from ..networking.impersonate import ImpersonateTarget
  40. from ..utils import (
  41. IDENTITY,
  42. JSON_LD_RE,
  43. NO_DEFAULT,
  44. ExtractorError,
  45. FormatSorter,
  46. GeoRestrictedError,
  47. GeoUtils,
  48. LenientJSONDecoder,
  49. Popen,
  50. RegexNotFoundError,
  51. RetryManager,
  52. UnsupportedError,
  53. age_restricted,
  54. base_url,
  55. bug_reports_message,
  56. classproperty,
  57. clean_html,
  58. deprecation_warning,
  59. determine_ext,
  60. dict_get,
  61. encode_data_uri,
  62. extract_attributes,
  63. filter_dict,
  64. fix_xml_ampersands,
  65. float_or_none,
  66. format_field,
  67. int_or_none,
  68. join_nonempty,
  69. js_to_json,
  70. mimetype2ext,
  71. netrc_from_content,
  72. orderedSet,
  73. parse_bitrate,
  74. parse_codecs,
  75. parse_duration,
  76. parse_iso8601,
  77. parse_m3u8_attributes,
  78. parse_resolution,
  79. sanitize_filename,
  80. sanitize_url,
  81. smuggle_url,
  82. str_or_none,
  83. str_to_int,
  84. strip_or_none,
  85. traverse_obj,
  86. truncate_string,
  87. try_call,
  88. try_get,
  89. unescapeHTML,
  90. unified_strdate,
  91. unified_timestamp,
  92. url_basename,
  93. url_or_none,
  94. urlhandle_detect_ext,
  95. urljoin,
  96. variadic,
  97. xpath_element,
  98. xpath_text,
  99. xpath_with_ns,
  100. )
  101. class InfoExtractor:
  102. """Information Extractor class.
  103. Information extractors are the classes that, given a URL, extract
  104. information about the video (or videos) the URL refers to. This
  105. information includes the real video URL, the video title, author and
  106. others. The information is stored in a dictionary which is then
  107. passed to the YoutubeDL. The YoutubeDL processes this
  108. information possibly downloading the video to the file system, among
  109. other possible outcomes.
  110. The type field determines the type of the result.
  111. By far the most common value (and the default if _type is missing) is
  112. "video", which indicates a single video.
  113. For a video, the dictionaries must include the following fields:
  114. id: Video identifier.
  115. title: Video title, unescaped. Set to an empty string if video has
  116. no title as opposed to "None" which signifies that the
  117. extractor failed to obtain a title
  118. Additionally, it must contain either a formats entry or a url one:
  119. formats: A list of dictionaries for each format available, ordered
  120. from worst to best quality.
  121. Potential fields:
  122. * url The mandatory URL representing the media:
  123. for plain file media - HTTP URL of this file,
  124. for RTMP - RTMP URL,
  125. for HLS - URL of the M3U8 media playlist,
  126. for HDS - URL of the F4M manifest,
  127. for DASH
  128. - HTTP URL to plain file media (in case of
  129. unfragmented media)
  130. - URL of the MPD manifest or base URL
  131. representing the media if MPD manifest
  132. is parsed from a string (in case of
  133. fragmented media)
  134. for MSS - URL of the ISM manifest.
  135. * request_data Data to send in POST request to the URL
  136. * manifest_url
  137. The URL of the manifest file in case of
  138. fragmented media:
  139. for HLS - URL of the M3U8 master playlist,
  140. for HDS - URL of the F4M manifest,
  141. for DASH - URL of the MPD manifest,
  142. for MSS - URL of the ISM manifest.
  143. * manifest_stream_number (For internal use only)
  144. The index of the stream in the manifest file
  145. * ext Will be calculated from URL if missing
  146. * format A human-readable description of the format
  147. ("mp4 container with h264/opus").
  148. Calculated from the format_id, width, height.
  149. and format_note fields if missing.
  150. * format_id A short description of the format
  151. ("mp4_h264_opus" or "19").
  152. Technically optional, but strongly recommended.
  153. * format_note Additional info about the format
  154. ("3D" or "DASH video")
  155. * width Width of the video, if known
  156. * height Height of the video, if known
  157. * aspect_ratio Aspect ratio of the video, if known
  158. Automatically calculated from width and height
  159. * resolution Textual description of width and height
  160. Automatically calculated from width and height
  161. * dynamic_range The dynamic range of the video. One of:
  162. "SDR" (None), "HDR10", "HDR10+, "HDR12", "HLG, "DV"
  163. * tbr Average bitrate of audio and video in kbps (1000 bits/sec)
  164. * abr Average audio bitrate in kbps (1000 bits/sec)
  165. * acodec Name of the audio codec in use
  166. * asr Audio sampling rate in Hertz
  167. * audio_channels Number of audio channels
  168. * vbr Average video bitrate in kbps (1000 bits/sec)
  169. * fps Frame rate
  170. * vcodec Name of the video codec in use
  171. * container Name of the container format
  172. * filesize The number of bytes, if known in advance
  173. * filesize_approx An estimate for the number of bytes
  174. * player_url SWF Player URL (used for rtmpdump).
  175. * protocol The protocol that will be used for the actual
  176. download, lower-case. One of "http", "https" or
  177. one of the protocols defined in downloader.PROTOCOL_MAP
  178. * fragment_base_url
  179. Base URL for fragments. Each fragment's path
  180. value (if present) will be relative to
  181. this URL.
  182. * fragments A list of fragments of a fragmented media.
  183. Each fragment entry must contain either an url
  184. or a path. If an url is present it should be
  185. considered by a client. Otherwise both path and
  186. fragment_base_url must be present. Here is
  187. the list of all potential fields:
  188. * "url" - fragment's URL
  189. * "path" - fragment's path relative to
  190. fragment_base_url
  191. * "duration" (optional, int or float)
  192. * "filesize" (optional, int)
  193. * is_from_start Is a live format that can be downloaded
  194. from the start. Boolean
  195. * preference Order number of this format. If this field is
  196. present and not None, the formats get sorted
  197. by this field, regardless of all other values.
  198. -1 for default (order by other properties),
  199. -2 or smaller for less than default.
  200. < -1000 to hide the format (if there is
  201. another one which is strictly better)
  202. * language Language code, e.g. "de" or "en-US".
  203. * language_preference Is this in the language mentioned in
  204. the URL?
  205. 10 if it's what the URL is about,
  206. -1 for default (don't know),
  207. -10 otherwise, other values reserved for now.
  208. * quality Order number of the video quality of this
  209. format, irrespective of the file format.
  210. -1 for default (order by other properties),
  211. -2 or smaller for less than default.
  212. * source_preference Order number for this video source
  213. (quality takes higher priority)
  214. -1 for default (order by other properties),
  215. -2 or smaller for less than default.
  216. * http_headers A dictionary of additional HTTP headers
  217. to add to the request.
  218. * stretched_ratio If given and not 1, indicates that the
  219. video's pixels are not square.
  220. width : height ratio as float.
  221. * no_resume The server does not support resuming the
  222. (HTTP or RTMP) download. Boolean.
  223. * has_drm True if the format has DRM and cannot be downloaded.
  224. 'maybe' if the format may have DRM and has to be tested before download.
  225. * extra_param_to_segment_url A query string to append to each
  226. fragment's URL, or to update each existing query string
  227. with. If it is an HLS stream with an AES-128 decryption key,
  228. the query paramaters will be passed to the key URI as well,
  229. unless there is an `extra_param_to_key_url` given,
  230. or unless an external key URI is provided via `hls_aes`.
  231. Only applied by the native HLS/DASH downloaders.
  232. * extra_param_to_key_url A query string to append to the URL
  233. of the format's HLS AES-128 decryption key.
  234. Only applied by the native HLS downloader.
  235. * hls_aes A dictionary of HLS AES-128 decryption information
  236. used by the native HLS downloader to override the
  237. values in the media playlist when an '#EXT-X-KEY' tag
  238. is present in the playlist:
  239. * uri The URI from which the key will be downloaded
  240. * key The key (as hex) used to decrypt fragments.
  241. If `key` is given, any key URI will be ignored
  242. * iv The IV (as hex) used to decrypt fragments
  243. * downloader_options A dictionary of downloader options
  244. (For internal use only)
  245. * http_chunk_size Chunk size for HTTP downloads
  246. * ffmpeg_args Extra arguments for ffmpeg downloader (input)
  247. * ffmpeg_args_out Extra arguments for ffmpeg downloader (output)
  248. * is_dash_periods Whether the format is a result of merging
  249. multiple DASH periods.
  250. RTMP formats can also have the additional fields: page_url,
  251. app, play_path, tc_url, flash_version, rtmp_live, rtmp_conn,
  252. rtmp_protocol, rtmp_real_time
  253. url: Final video URL.
  254. ext: Video filename extension.
  255. format: The video format, defaults to ext (used for --get-format)
  256. player_url: SWF Player URL (used for rtmpdump).
  257. The following fields are optional:
  258. direct: True if a direct video file was given (must only be set by GenericIE)
  259. alt_title: A secondary title of the video.
  260. display_id: An alternative identifier for the video, not necessarily
  261. unique, but available before title. Typically, id is
  262. something like "4234987", title "Dancing naked mole rats",
  263. and display_id "dancing-naked-mole-rats"
  264. thumbnails: A list of dictionaries, with the following entries:
  265. * "id" (optional, string) - Thumbnail format ID
  266. * "url"
  267. * "preference" (optional, int) - quality of the image
  268. * "width" (optional, int)
  269. * "height" (optional, int)
  270. * "resolution" (optional, string "{width}x{height}",
  271. deprecated)
  272. * "filesize" (optional, int)
  273. * "http_headers" (dict) - HTTP headers for the request
  274. thumbnail: Full URL to a video thumbnail image.
  275. description: Full video description.
  276. uploader: Full name of the video uploader.
  277. license: License name the video is licensed under.
  278. creators: List of creators of the video.
  279. timestamp: UNIX timestamp of the moment the video was uploaded
  280. upload_date: Video upload date in UTC (YYYYMMDD).
  281. If not explicitly set, calculated from timestamp
  282. release_timestamp: UNIX timestamp of the moment the video was released.
  283. If it is not clear whether to use timestamp or this, use the former
  284. release_date: The date (YYYYMMDD) when the video was released in UTC.
  285. If not explicitly set, calculated from release_timestamp
  286. release_year: Year (YYYY) as integer when the video or album was released.
  287. To be used if no exact release date is known.
  288. If not explicitly set, calculated from release_date.
  289. modified_timestamp: UNIX timestamp of the moment the video was last modified.
  290. modified_date: The date (YYYYMMDD) when the video was last modified in UTC.
  291. If not explicitly set, calculated from modified_timestamp
  292. uploader_id: Nickname or id of the video uploader.
  293. uploader_url: Full URL to a personal webpage of the video uploader.
  294. channel: Full name of the channel the video is uploaded on.
  295. Note that channel fields may or may not repeat uploader
  296. fields. This depends on a particular extractor.
  297. channel_id: Id of the channel.
  298. channel_url: Full URL to a channel webpage.
  299. channel_follower_count: Number of followers of the channel.
  300. channel_is_verified: Whether the channel is verified on the platform.
  301. location: Physical location where the video was filmed.
  302. subtitles: The available subtitles as a dictionary in the format
  303. {tag: subformats}. "tag" is usually a language code, and
  304. "subformats" is a list sorted from lower to higher
  305. preference, each element is a dictionary with the "ext"
  306. entry and one of:
  307. * "data": The subtitles file contents
  308. * "url": A URL pointing to the subtitles file
  309. It can optionally also have:
  310. * "name": Name or description of the subtitles
  311. * "http_headers": A dictionary of additional HTTP headers
  312. to add to the request.
  313. "ext" will be calculated from URL if missing
  314. automatic_captions: Like 'subtitles'; contains automatically generated
  315. captions instead of normal subtitles
  316. duration: Length of the video in seconds, as an integer or float.
  317. view_count: How many users have watched the video on the platform.
  318. concurrent_view_count: How many users are currently watching the video on the platform.
  319. like_count: Number of positive ratings of the video
  320. dislike_count: Number of negative ratings of the video
  321. repost_count: Number of reposts of the video
  322. average_rating: Average rating give by users, the scale used depends on the webpage
  323. comment_count: Number of comments on the video
  324. comments: A list of comments, each with one or more of the following
  325. properties (all but one of text or html optional):
  326. * "author" - human-readable name of the comment author
  327. * "author_id" - user ID of the comment author
  328. * "author_thumbnail" - The thumbnail of the comment author
  329. * "author_url" - The url to the comment author's page
  330. * "author_is_verified" - Whether the author is verified
  331. on the platform
  332. * "author_is_uploader" - Whether the comment is made by
  333. the video uploader
  334. * "id" - Comment ID
  335. * "html" - Comment as HTML
  336. * "text" - Plain text of the comment
  337. * "timestamp" - UNIX timestamp of comment
  338. * "parent" - ID of the comment this one is replying to.
  339. Set to "root" to indicate that this is a
  340. comment to the original video.
  341. * "like_count" - Number of positive ratings of the comment
  342. * "dislike_count" - Number of negative ratings of the comment
  343. * "is_favorited" - Whether the comment is marked as
  344. favorite by the video uploader
  345. * "is_pinned" - Whether the comment is pinned to
  346. the top of the comments
  347. age_limit: Age restriction for the video, as an integer (years)
  348. webpage_url: The URL to the video webpage, if given to yt-dlp it
  349. should allow to get the same result again. (It will be set
  350. by YoutubeDL if it's missing)
  351. categories: A list of categories that the video falls in, for example
  352. ["Sports", "Berlin"]
  353. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  354. cast: A list of the video cast
  355. is_live: True, False, or None (=unknown). Whether this video is a
  356. live stream that goes on instead of a fixed-length video.
  357. was_live: True, False, or None (=unknown). Whether this video was
  358. originally a live stream.
  359. live_status: None (=unknown), 'is_live', 'is_upcoming', 'was_live', 'not_live',
  360. or 'post_live' (was live, but VOD is not yet processed)
  361. If absent, automatically set from is_live, was_live
  362. start_time: Time in seconds where the reproduction should start, as
  363. specified in the URL.
  364. end_time: Time in seconds where the reproduction should end, as
  365. specified in the URL.
  366. chapters: A list of dictionaries, with the following entries:
  367. * "start_time" - The start time of the chapter in seconds
  368. * "end_time" - The end time of the chapter in seconds
  369. * "title" (optional, string)
  370. heatmap: A list of dictionaries, with the following entries:
  371. * "start_time" - The start time of the data point in seconds
  372. * "end_time" - The end time of the data point in seconds
  373. * "value" - The normalized value of the data point (float between 0 and 1)
  374. playable_in_embed: Whether this video is allowed to play in embedded
  375. players on other sites. Can be True (=always allowed),
  376. False (=never allowed), None (=unknown), or a string
  377. specifying the criteria for embedability; e.g. 'whitelist'
  378. availability: Under what condition the video is available. One of
  379. 'private', 'premium_only', 'subscriber_only', 'needs_auth',
  380. 'unlisted' or 'public'. Use 'InfoExtractor._availability'
  381. to set it
  382. media_type: The type of media as classified by the site, e.g. "episode", "clip", "trailer"
  383. _old_archive_ids: A list of old archive ids needed for backward compatibility
  384. _format_sort_fields: A list of fields to use for sorting formats
  385. __post_extractor: A function to be called just before the metadata is
  386. written to either disk, logger or console. The function
  387. must return a dict which will be added to the info_dict.
  388. This is usefull for additional information that is
  389. time-consuming to extract. Note that the fields thus
  390. extracted will not be available to output template and
  391. match_filter. So, only "comments" and "comment_count" are
  392. currently allowed to be extracted via this method.
  393. The following fields should only be used when the video belongs to some logical
  394. chapter or section:
  395. chapter: Name or title of the chapter the video belongs to.
  396. chapter_number: Number of the chapter the video belongs to, as an integer.
  397. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  398. The following fields should only be used when the video is an episode of some
  399. series, programme or podcast:
  400. series: Title of the series or programme the video episode belongs to.
  401. series_id: Id of the series or programme the video episode belongs to, as a unicode string.
  402. season: Title of the season the video episode belongs to.
  403. season_number: Number of the season the video episode belongs to, as an integer.
  404. season_id: Id of the season the video episode belongs to, as a unicode string.
  405. episode: Title of the video episode. Unlike mandatory video title field,
  406. this field should denote the exact title of the video episode
  407. without any kind of decoration.
  408. episode_number: Number of the video episode within a season, as an integer.
  409. episode_id: Id of the video episode, as a unicode string.
  410. The following fields should only be used when the media is a track or a part of
  411. a music album:
  412. track: Title of the track.
  413. track_number: Number of the track within an album or a disc, as an integer.
  414. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  415. as a unicode string.
  416. artists: List of artists of the track.
  417. composers: List of composers of the piece.
  418. genres: List of genres of the track.
  419. album: Title of the album the track belongs to.
  420. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  421. album_artists: List of all artists appeared on the album.
  422. E.g. ["Ash Borer", "Fell Voices"] or ["Various Artists"].
  423. Useful for splits and compilations.
  424. disc_number: Number of the disc or other physical medium the track belongs to,
  425. as an integer.
  426. The following fields should only be set for clips that should be cut from the original video:
  427. section_start: Start time of the section in seconds
  428. section_end: End time of the section in seconds
  429. The following fields should only be set for storyboards:
  430. rows: Number of rows in each storyboard fragment, as an integer
  431. columns: Number of columns in each storyboard fragment, as an integer
  432. The following fields are deprecated and should not be set by new code:
  433. composer: Use "composers" instead.
  434. Composer(s) of the piece, comma-separated.
  435. artist: Use "artists" instead.
  436. Artist(s) of the track, comma-separated.
  437. genre: Use "genres" instead.
  438. Genre(s) of the track, comma-separated.
  439. album_artist: Use "album_artists" instead.
  440. All artists appeared on the album, comma-separated.
  441. creator: Use "creators" instead.
  442. The creator of the video.
  443. Unless mentioned otherwise, the fields should be Unicode strings.
  444. Unless mentioned otherwise, None is equivalent to absence of information.
  445. _type "playlist" indicates multiple videos.
  446. There must be a key "entries", which is a list, an iterable, or a PagedList
  447. object, each element of which is a valid dictionary by this specification.
  448. Additionally, playlists can have "id", "title", and any other relevant
  449. attributes with the same semantics as videos (see above).
  450. It can also have the following optional fields:
  451. playlist_count: The total number of videos in a playlist. If not given,
  452. YoutubeDL tries to calculate it from "entries"
  453. _type "multi_video" indicates that there are multiple videos that
  454. form a single show, for examples multiple acts of an opera or TV episode.
  455. It must have an entries key like a playlist and contain all the keys
  456. required for a video at the same time.
  457. _type "url" indicates that the video must be extracted from another
  458. location, possibly by a different extractor. Its only required key is:
  459. "url" - the next URL to extract.
  460. The key "ie_key" can be set to the class name (minus the trailing "IE",
  461. e.g. "Youtube") if the extractor class is known in advance.
  462. Additionally, the dictionary may have any properties of the resolved entity
  463. known in advance, for example "title" if the title of the referred video is
  464. known ahead of time.
  465. _type "url_transparent" entities have the same specification as "url", but
  466. indicate that the given additional information is more precise than the one
  467. associated with the resolved URL.
  468. This is useful when a site employs a video service that hosts the video and
  469. its technical metadata, but that video service does not embed a useful
  470. title, description etc.
  471. Subclasses of this should also be added to the list of extractors and
  472. should define _VALID_URL as a regexp or a Sequence of regexps, and
  473. re-define the _real_extract() and (optionally) _real_initialize() methods.
  474. Subclasses may also override suitable() if necessary, but ensure the function
  475. signature is preserved and that this function imports everything it needs
  476. (except other extractors), so that lazy_extractors works correctly.
  477. Subclasses can define a list of _EMBED_REGEX, which will be searched for in
  478. the HTML of Generic webpages. It may also override _extract_embed_urls
  479. or _extract_from_webpage as necessary. While these are normally classmethods,
  480. _extract_from_webpage is allowed to be an instance method.
  481. _extract_from_webpage may raise self.StopExtraction() to stop further
  482. processing of the webpage and obtain exclusive rights to it. This is useful
  483. when the extractor cannot reliably be matched using just the URL,
  484. e.g. invidious/peertube instances
  485. Embed-only extractors can be defined by setting _VALID_URL = False.
  486. To support username + password (or netrc) login, the extractor must define a
  487. _NETRC_MACHINE and re-define _perform_login(username, password) and
  488. (optionally) _initialize_pre_login() methods. The _perform_login method will
  489. be called between _initialize_pre_login and _real_initialize if credentials
  490. are passed by the user. In cases where it is necessary to have the login
  491. process as part of the extraction rather than initialization, _perform_login
  492. can be left undefined.
  493. _GEO_BYPASS attribute may be set to False in order to disable
  494. geo restriction bypass mechanisms for a particular extractor.
  495. Though it won't disable explicit geo restriction bypass based on
  496. country code provided with geo_bypass_country.
  497. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  498. countries for this extractor. One of these countries will be used by
  499. geo restriction bypass mechanism right away in order to bypass
  500. geo restriction, of course, if the mechanism is not disabled.
  501. _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
  502. IP blocks in CIDR notation for this extractor. One of these IP blocks
  503. will be used by geo restriction bypass mechanism similarly
  504. to _GEO_COUNTRIES.
  505. The _ENABLED attribute should be set to False for IEs that
  506. are disabled by default and must be explicitly enabled.
  507. The _WORKING attribute should be set to False for broken IEs
  508. in order to warn the users and skip the tests.
  509. """
  510. _ready = False
  511. _downloader = None
  512. _x_forwarded_for_ip = None
  513. _GEO_BYPASS = True
  514. _GEO_COUNTRIES = None
  515. _GEO_IP_BLOCKS = None
  516. _WORKING = True
  517. _ENABLED = True
  518. _NETRC_MACHINE = None
  519. IE_DESC = None
  520. SEARCH_KEY = None
  521. _VALID_URL = None
  522. _EMBED_REGEX = []
  523. def _login_hint(self, method=NO_DEFAULT, netrc=None):
  524. password_hint = f'--username and --password, --netrc-cmd, or --netrc ({netrc or self._NETRC_MACHINE}) to provide account credentials'
  525. return {
  526. None: '',
  527. 'any': f'Use --cookies, --cookies-from-browser, {password_hint}',
  528. 'password': f'Use {password_hint}',
  529. 'cookies': (
  530. 'Use --cookies-from-browser or --cookies for the authentication. '
  531. 'See https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp for how to manually pass cookies'),
  532. }[method if method is not NO_DEFAULT else 'any' if self.supports_login() else 'cookies']
  533. def __init__(self, downloader=None):
  534. """Constructor. Receives an optional downloader (a YoutubeDL instance).
  535. If a downloader is not passed during initialization,
  536. it must be set using "set_downloader()" before "extract()" is called"""
  537. self._ready = False
  538. self._x_forwarded_for_ip = None
  539. self._printed_messages = set()
  540. self.set_downloader(downloader)
  541. @classmethod
  542. def _match_valid_url(cls, url):
  543. if cls._VALID_URL is False:
  544. return None
  545. # This does not use has/getattr intentionally - we want to know whether
  546. # we have cached the regexp for *this* class, whereas getattr would also
  547. # match the superclass
  548. if '_VALID_URL_RE' not in cls.__dict__:
  549. cls._VALID_URL_RE = tuple(map(re.compile, variadic(cls._VALID_URL)))
  550. return next(filter(None, (regex.match(url) for regex in cls._VALID_URL_RE)), None)
  551. @classmethod
  552. def suitable(cls, url):
  553. """Receives a URL and returns True if suitable for this IE."""
  554. # This function must import everything it needs (except other extractors),
  555. # so that lazy_extractors works correctly
  556. return cls._match_valid_url(url) is not None
  557. @classmethod
  558. def _match_id(cls, url):
  559. return cls._match_valid_url(url).group('id')
  560. @classmethod
  561. def get_temp_id(cls, url):
  562. try:
  563. return cls._match_id(url)
  564. except (IndexError, AttributeError):
  565. return None
  566. @classmethod
  567. def working(cls):
  568. """Getter method for _WORKING."""
  569. return cls._WORKING
  570. @classmethod
  571. def supports_login(cls):
  572. return bool(cls._NETRC_MACHINE)
  573. def initialize(self):
  574. """Initializes an instance (authentication, etc)."""
  575. self._printed_messages = set()
  576. self._initialize_geo_bypass({
  577. 'countries': self._GEO_COUNTRIES,
  578. 'ip_blocks': self._GEO_IP_BLOCKS,
  579. })
  580. if not self._ready:
  581. self._initialize_pre_login()
  582. if self.supports_login():
  583. username, password = self._get_login_info()
  584. if username:
  585. self._perform_login(username, password)
  586. elif self.get_param('username') and False not in (self.IE_DESC, self._NETRC_MACHINE):
  587. self.report_warning(f'Login with password is not supported for this website. {self._login_hint("cookies")}')
  588. self._real_initialize()
  589. self._ready = True
  590. def _initialize_geo_bypass(self, geo_bypass_context):
  591. """
  592. Initialize geo restriction bypass mechanism.
  593. This method is used to initialize geo bypass mechanism based on faking
  594. X-Forwarded-For HTTP header. A random country from provided country list
  595. is selected and a random IP belonging to this country is generated. This
  596. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  597. HTTP requests.
  598. This method will be used for initial geo bypass mechanism initialization
  599. during the instance initialization with _GEO_COUNTRIES and
  600. _GEO_IP_BLOCKS.
  601. You may also manually call it from extractor's code if geo bypass
  602. information is not available beforehand (e.g. obtained during
  603. extraction) or due to some other reason. In this case you should pass
  604. this information in geo bypass context passed as first argument. It may
  605. contain following fields:
  606. countries: List of geo unrestricted countries (similar
  607. to _GEO_COUNTRIES)
  608. ip_blocks: List of geo unrestricted IP blocks in CIDR notation
  609. (similar to _GEO_IP_BLOCKS)
  610. """
  611. if not self._x_forwarded_for_ip:
  612. # Geo bypass mechanism is explicitly disabled by user
  613. if not self.get_param('geo_bypass', True):
  614. return
  615. if not geo_bypass_context:
  616. geo_bypass_context = {}
  617. # Backward compatibility: previously _initialize_geo_bypass
  618. # expected a list of countries, some 3rd party code may still use
  619. # it this way
  620. if isinstance(geo_bypass_context, (list, tuple)):
  621. geo_bypass_context = {
  622. 'countries': geo_bypass_context,
  623. }
  624. # The whole point of geo bypass mechanism is to fake IP
  625. # as X-Forwarded-For HTTP header based on some IP block or
  626. # country code.
  627. # Path 1: bypassing based on IP block in CIDR notation
  628. # Explicit IP block specified by user, use it right away
  629. # regardless of whether extractor is geo bypassable or not
  630. ip_block = self.get_param('geo_bypass_ip_block', None)
  631. # Otherwise use random IP block from geo bypass context but only
  632. # if extractor is known as geo bypassable
  633. if not ip_block:
  634. ip_blocks = geo_bypass_context.get('ip_blocks')
  635. if self._GEO_BYPASS and ip_blocks:
  636. ip_block = random.choice(ip_blocks)
  637. if ip_block:
  638. self._x_forwarded_for_ip = GeoUtils.random_ipv4(ip_block)
  639. self.write_debug(f'Using fake IP {self._x_forwarded_for_ip} as X-Forwarded-For')
  640. return
  641. # Path 2: bypassing based on country code
  642. # Explicit country code specified by user, use it right away
  643. # regardless of whether extractor is geo bypassable or not
  644. country = self.get_param('geo_bypass_country', None)
  645. # Otherwise use random country code from geo bypass context but
  646. # only if extractor is known as geo bypassable
  647. if not country:
  648. countries = geo_bypass_context.get('countries')
  649. if self._GEO_BYPASS and countries:
  650. country = random.choice(countries)
  651. if country:
  652. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country)
  653. self._downloader.write_debug(
  654. f'Using fake IP {self._x_forwarded_for_ip} ({country.upper()}) as X-Forwarded-For')
  655. def extract(self, url):
  656. """Extracts URL information and returns it in list of dicts."""
  657. try:
  658. for _ in range(2):
  659. try:
  660. self.initialize()
  661. self.to_screen('Extracting URL: %s' % (
  662. url if self.get_param('verbose') else truncate_string(url, 100, 20)))
  663. ie_result = self._real_extract(url)
  664. if ie_result is None:
  665. return None
  666. if self._x_forwarded_for_ip:
  667. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  668. subtitles = ie_result.get('subtitles') or {}
  669. if 'no-live-chat' in self.get_param('compat_opts'):
  670. for lang in ('live_chat', 'comments', 'danmaku'):
  671. subtitles.pop(lang, None)
  672. return ie_result
  673. except GeoRestrictedError as e:
  674. if self.__maybe_fake_ip_and_retry(e.countries):
  675. continue
  676. raise
  677. except UnsupportedError:
  678. raise
  679. except ExtractorError as e:
  680. e.video_id = e.video_id or self.get_temp_id(url)
  681. e.ie = e.ie or self.IE_NAME
  682. e.traceback = e.traceback or sys.exc_info()[2]
  683. raise
  684. except IncompleteRead as e:
  685. raise ExtractorError('A network error has occurred.', cause=e, expected=True, video_id=self.get_temp_id(url))
  686. except (KeyError, StopIteration) as e:
  687. raise ExtractorError('An extractor error has occurred.', cause=e, video_id=self.get_temp_id(url))
  688. def __maybe_fake_ip_and_retry(self, countries):
  689. if (not self.get_param('geo_bypass_country', None)
  690. and self._GEO_BYPASS
  691. and self.get_param('geo_bypass', True)
  692. and not self._x_forwarded_for_ip
  693. and countries):
  694. country_code = random.choice(countries)
  695. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  696. if self._x_forwarded_for_ip:
  697. self.report_warning(
  698. 'Video is geo restricted. Retrying extraction with fake IP '
  699. f'{self._x_forwarded_for_ip} ({country_code.upper()}) as X-Forwarded-For.')
  700. return True
  701. return False
  702. def set_downloader(self, downloader):
  703. """Sets a YoutubeDL instance as the downloader for this IE."""
  704. self._downloader = downloader
  705. @property
  706. def cache(self):
  707. return self._downloader.cache
  708. @property
  709. def cookiejar(self):
  710. return self._downloader.cookiejar
  711. def _initialize_pre_login(self):
  712. """ Initialization before login. Redefine in subclasses."""
  713. pass
  714. def _perform_login(self, username, password):
  715. """ Login with username and password. Redefine in subclasses."""
  716. pass
  717. def _real_initialize(self):
  718. """Real initialization process. Redefine in subclasses."""
  719. pass
  720. def _real_extract(self, url):
  721. """Real extraction process. Redefine in subclasses."""
  722. raise NotImplementedError('This method must be implemented by subclasses')
  723. @classmethod
  724. def ie_key(cls):
  725. """A string for getting the InfoExtractor with get_info_extractor"""
  726. return cls.__name__[:-2]
  727. @classproperty
  728. def IE_NAME(cls):
  729. return cls.__name__[:-2]
  730. @staticmethod
  731. def __can_accept_status_code(err, expected_status):
  732. assert isinstance(err, HTTPError)
  733. if expected_status is None:
  734. return False
  735. elif callable(expected_status):
  736. return expected_status(err.status) is True
  737. else:
  738. return err.status in variadic(expected_status)
  739. def _create_request(self, url_or_request, data=None, headers=None, query=None, extensions=None):
  740. if isinstance(url_or_request, urllib.request.Request):
  741. self._downloader.deprecation_warning(
  742. 'Passing a urllib.request.Request to _create_request() is deprecated. '
  743. 'Use yt_dlp.networking.common.Request instead.')
  744. url_or_request = urllib_req_to_req(url_or_request)
  745. elif not isinstance(url_or_request, Request):
  746. url_or_request = Request(url_or_request)
  747. url_or_request.update(data=data, headers=headers, query=query, extensions=extensions)
  748. return url_or_request
  749. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None,
  750. headers=None, query=None, expected_status=None, impersonate=None, require_impersonation=False):
  751. """
  752. Return the response handle.
  753. See _download_webpage docstring for arguments specification.
  754. """
  755. if not self._downloader._first_webpage_request:
  756. sleep_interval = self.get_param('sleep_interval_requests') or 0
  757. if sleep_interval > 0:
  758. self.to_screen(f'Sleeping {sleep_interval} seconds ...')
  759. time.sleep(sleep_interval)
  760. else:
  761. self._downloader._first_webpage_request = False
  762. if note is None:
  763. self.report_download_webpage(video_id)
  764. elif note is not False:
  765. if video_id is None:
  766. self.to_screen(str(note))
  767. else:
  768. self.to_screen(f'{video_id}: {note}')
  769. # Some sites check X-Forwarded-For HTTP header in order to figure out
  770. # the origin of the client behind proxy. This allows bypassing geo
  771. # restriction by faking this header's value to IP that belongs to some
  772. # geo unrestricted country. We will do so once we encounter any
  773. # geo restriction error.
  774. if self._x_forwarded_for_ip:
  775. headers = (headers or {}).copy()
  776. headers.setdefault('X-Forwarded-For', self._x_forwarded_for_ip)
  777. extensions = {}
  778. if impersonate in (True, ''):
  779. impersonate = ImpersonateTarget()
  780. requested_targets = [
  781. t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t)
  782. for t in variadic(impersonate)
  783. ] if impersonate else []
  784. available_target = next(filter(self._downloader._impersonate_target_available, requested_targets), None)
  785. if available_target:
  786. extensions['impersonate'] = available_target
  787. elif requested_targets:
  788. message = 'The extractor is attempting impersonation, but '
  789. message += (
  790. 'no impersonate target is available' if not str(impersonate)
  791. else f'none of these impersonate targets are available: "{", ".join(map(str, requested_targets))}"')
  792. info_msg = ('see https://github.com/yt-dlp/yt-dlp#impersonation '
  793. 'for information on installing the required dependencies')
  794. if require_impersonation:
  795. raise ExtractorError(f'{message}; {info_msg}', expected=True)
  796. self.report_warning(f'{message}; if you encounter errors, then {info_msg}', only_once=True)
  797. try:
  798. return self._downloader.urlopen(self._create_request(url_or_request, data, headers, query, extensions))
  799. except network_exceptions as err:
  800. if isinstance(err, HTTPError):
  801. if self.__can_accept_status_code(err, expected_status):
  802. return err.response
  803. if errnote is False:
  804. return False
  805. if errnote is None:
  806. errnote = 'Unable to download webpage'
  807. errmsg = f'{errnote}: {err}'
  808. if fatal:
  809. raise ExtractorError(errmsg, cause=err)
  810. else:
  811. self.report_warning(errmsg)
  812. return False
  813. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True,
  814. encoding=None, data=None, headers={}, query={}, expected_status=None,
  815. impersonate=None, require_impersonation=False):
  816. """
  817. Return a tuple (page content as string, URL handle).
  818. Arguments:
  819. url_or_request -- plain text URL as a string or
  820. a yt_dlp.networking.Request object
  821. video_id -- Video/playlist/item identifier (string)
  822. Keyword arguments:
  823. note -- note printed before downloading (string)
  824. errnote -- note printed in case of an error (string)
  825. fatal -- flag denoting whether error should be considered fatal,
  826. i.e. whether it should cause ExtractionError to be raised,
  827. otherwise a warning will be reported and extraction continued
  828. encoding -- encoding for a page content decoding, guessed automatically
  829. when not explicitly specified
  830. data -- POST data (bytes)
  831. headers -- HTTP headers (dict)
  832. query -- URL query (dict)
  833. expected_status -- allows to accept failed HTTP requests (non 2xx
  834. status code) by explicitly specifying a set of accepted status
  835. codes. Can be any of the following entities:
  836. - an integer type specifying an exact failed status code to
  837. accept
  838. - a list or a tuple of integer types specifying a list of
  839. failed status codes to accept
  840. - a callable accepting an actual failed status code and
  841. returning True if it should be accepted
  842. Note that this argument does not affect success status codes (2xx)
  843. which are always accepted.
  844. impersonate -- the impersonate target. Can be any of the following entities:
  845. - an instance of yt_dlp.networking.impersonate.ImpersonateTarget
  846. - a string in the format of CLIENT[:OS]
  847. - a list or a tuple of CLIENT[:OS] strings or ImpersonateTarget instances
  848. - a boolean value; True means any impersonate target is sufficient
  849. require_impersonation -- flag to toggle whether the request should raise an error
  850. if impersonation is not possible (bool, default: False)
  851. """
  852. # Strip hashes from the URL (#1038)
  853. if isinstance(url_or_request, str):
  854. url_or_request = url_or_request.partition('#')[0]
  855. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data,
  856. headers=headers, query=query, expected_status=expected_status,
  857. impersonate=impersonate, require_impersonation=require_impersonation)
  858. if urlh is False:
  859. assert not fatal
  860. return False
  861. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal,
  862. encoding=encoding, data=data)
  863. return (content, urlh)
  864. @staticmethod
  865. def _guess_encoding_from_content(content_type, webpage_bytes):
  866. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  867. if m:
  868. encoding = m.group(1)
  869. else:
  870. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  871. webpage_bytes[:1024])
  872. if m:
  873. encoding = m.group(1).decode('ascii')
  874. elif webpage_bytes.startswith(b'\xff\xfe'):
  875. encoding = 'utf-16'
  876. else:
  877. encoding = 'utf-8'
  878. return encoding
  879. def __check_blocked(self, content):
  880. first_block = content[:512]
  881. if ('<title>Access to this site is blocked</title>' in content
  882. and 'Websense' in first_block):
  883. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  884. blocked_iframe = self._html_search_regex(
  885. r'<iframe src="([^"]+)"', content,
  886. 'Websense information URL', default=None)
  887. if blocked_iframe:
  888. msg += f' Visit {blocked_iframe} for more details'
  889. raise ExtractorError(msg, expected=True)
  890. if '<title>The URL you requested has been blocked</title>' in first_block:
  891. msg = (
  892. 'Access to this webpage has been blocked by Indian censorship. '
  893. 'Use a VPN or proxy server (with --proxy) to route around it.')
  894. block_msg = self._html_search_regex(
  895. r'</h1><p>(.*?)</p>',
  896. content, 'block message', default=None)
  897. if block_msg:
  898. msg += ' (Message: "{}")'.format(block_msg.replace('\n', ' '))
  899. raise ExtractorError(msg, expected=True)
  900. if ('<title>TTK :: Доступ к ресурсу ограничен</title>' in content
  901. and 'blocklist.rkn.gov.ru' in content):
  902. raise ExtractorError(
  903. 'Access to this webpage has been blocked by decision of the Russian government. '
  904. 'Visit http://blocklist.rkn.gov.ru/ for a block reason.',
  905. expected=True)
  906. def _request_dump_filename(self, url, video_id, data=None):
  907. if data is not None:
  908. data = hashlib.md5(data).hexdigest()
  909. basen = join_nonempty(video_id, data, url, delim='_')
  910. trim_length = self.get_param('trim_file_name') or 240
  911. if len(basen) > trim_length:
  912. h = '___' + hashlib.md5(basen.encode()).hexdigest()
  913. basen = basen[:trim_length - len(h)] + h
  914. filename = sanitize_filename(f'{basen}.dump', restricted=True)
  915. # Working around MAX_PATH limitation on Windows (see
  916. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  917. if compat_os_name == 'nt':
  918. absfilepath = os.path.abspath(filename)
  919. if len(absfilepath) > 259:
  920. filename = fR'\\?\{absfilepath}'
  921. return filename
  922. def __decode_webpage(self, webpage_bytes, encoding, headers):
  923. if not encoding:
  924. encoding = self._guess_encoding_from_content(headers.get('Content-Type', ''), webpage_bytes)
  925. try:
  926. return webpage_bytes.decode(encoding, 'replace')
  927. except LookupError:
  928. return webpage_bytes.decode('utf-8', 'replace')
  929. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True,
  930. prefix=None, encoding=None, data=None):
  931. webpage_bytes = urlh.read()
  932. if prefix is not None:
  933. webpage_bytes = prefix + webpage_bytes
  934. if self.get_param('dump_intermediate_pages', False):
  935. self.to_screen('Dumping request to ' + urlh.url)
  936. dump = base64.b64encode(webpage_bytes).decode('ascii')
  937. self._downloader.to_screen(dump)
  938. if self.get_param('write_pages'):
  939. if isinstance(url_or_request, Request):
  940. data = self._create_request(url_or_request, data).data
  941. filename = self._request_dump_filename(urlh.url, video_id, data)
  942. self.to_screen(f'Saving request to {filename}')
  943. with open(filename, 'wb') as outf:
  944. outf.write(webpage_bytes)
  945. content = self.__decode_webpage(webpage_bytes, encoding, urlh.headers)
  946. self.__check_blocked(content)
  947. return content
  948. def __print_error(self, errnote, fatal, video_id, err):
  949. if fatal:
  950. raise ExtractorError(f'{video_id}: {errnote}', cause=err)
  951. elif errnote:
  952. self.report_warning(f'{video_id}: {errnote}: {err}')
  953. def _parse_xml(self, xml_string, video_id, transform_source=None, fatal=True, errnote=None):
  954. if transform_source:
  955. xml_string = transform_source(xml_string)
  956. try:
  957. return compat_etree_fromstring(xml_string.encode())
  958. except xml.etree.ElementTree.ParseError as ve:
  959. self.__print_error('Failed to parse XML' if errnote is None else errnote, fatal, video_id, ve)
  960. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True, errnote=None, **parser_kwargs):
  961. try:
  962. return json.loads(
  963. json_string, cls=LenientJSONDecoder, strict=False, transform_source=transform_source, **parser_kwargs)
  964. except ValueError as ve:
  965. self.__print_error('Failed to parse JSON' if errnote is None else errnote, fatal, video_id, ve)
  966. def _parse_socket_response_as_json(self, data, *args, **kwargs):
  967. return self._parse_json(data[data.find('{'):data.rfind('}') + 1], *args, **kwargs)
  968. def __create_download_methods(name, parser, note, errnote, return_value):
  969. def parse(ie, content, *args, errnote=errnote, **kwargs):
  970. if parser is None:
  971. return content
  972. if errnote is False:
  973. kwargs['errnote'] = errnote
  974. # parser is fetched by name so subclasses can override it
  975. return getattr(ie, parser)(content, *args, **kwargs)
  976. def download_handle(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  977. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  978. impersonate=None, require_impersonation=False):
  979. res = self._download_webpage_handle(
  980. url_or_request, video_id, note=note, errnote=errnote, fatal=fatal, encoding=encoding,
  981. data=data, headers=headers, query=query, expected_status=expected_status,
  982. impersonate=impersonate, require_impersonation=require_impersonation)
  983. if res is False:
  984. return res
  985. content, urlh = res
  986. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote), urlh
  987. def download_content(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  988. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  989. impersonate=None, require_impersonation=False):
  990. if self.get_param('load_pages'):
  991. url_or_request = self._create_request(url_or_request, data, headers, query)
  992. filename = self._request_dump_filename(url_or_request.url, video_id, url_or_request.data)
  993. self.to_screen(f'Loading request from {filename}')
  994. try:
  995. with open(filename, 'rb') as dumpf:
  996. webpage_bytes = dumpf.read()
  997. except OSError as e:
  998. self.report_warning(f'Unable to load request from disk: {e}')
  999. else:
  1000. content = self.__decode_webpage(webpage_bytes, encoding, url_or_request.headers)
  1001. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote)
  1002. kwargs = {
  1003. 'note': note,
  1004. 'errnote': errnote,
  1005. 'transform_source': transform_source,
  1006. 'fatal': fatal,
  1007. 'encoding': encoding,
  1008. 'data': data,
  1009. 'headers': headers,
  1010. 'query': query,
  1011. 'expected_status': expected_status,
  1012. 'impersonate': impersonate,
  1013. 'require_impersonation': require_impersonation,
  1014. }
  1015. if parser is None:
  1016. kwargs.pop('transform_source')
  1017. # The method is fetched by name so subclasses can override _download_..._handle
  1018. res = getattr(self, download_handle.__name__)(url_or_request, video_id, **kwargs)
  1019. return res if res is False else res[0]
  1020. def impersonate(func, name, return_value):
  1021. func.__name__, func.__qualname__ = name, f'InfoExtractor.{name}'
  1022. func.__doc__ = f'''
  1023. @param transform_source Apply this transformation before parsing
  1024. @returns {return_value}
  1025. See _download_webpage_handle docstring for other arguments specification
  1026. '''
  1027. impersonate(download_handle, f'_download_{name}_handle', f'({return_value}, URL handle)')
  1028. impersonate(download_content, f'_download_{name}', f'{return_value}')
  1029. return download_handle, download_content
  1030. _download_xml_handle, _download_xml = __create_download_methods(
  1031. 'xml', '_parse_xml', 'Downloading XML', 'Unable to download XML', 'xml as an xml.etree.ElementTree.Element')
  1032. _download_json_handle, _download_json = __create_download_methods(
  1033. 'json', '_parse_json', 'Downloading JSON metadata', 'Unable to download JSON metadata', 'JSON object as a dict')
  1034. _download_socket_json_handle, _download_socket_json = __create_download_methods(
  1035. 'socket_json', '_parse_socket_response_as_json', 'Polling socket', 'Unable to poll socket', 'JSON object as a dict')
  1036. __download_webpage = __create_download_methods('webpage', None, None, None, 'data of the page as a string')[1]
  1037. def _download_webpage(
  1038. self, url_or_request, video_id, note=None, errnote=None,
  1039. fatal=True, tries=1, timeout=NO_DEFAULT, *args, **kwargs):
  1040. """
  1041. Return the data of the page as a string.
  1042. Keyword arguments:
  1043. tries -- number of tries
  1044. timeout -- sleep interval between tries
  1045. See _download_webpage_handle docstring for other arguments specification.
  1046. """
  1047. R''' # NB: These are unused; should they be deprecated?
  1048. if tries != 1:
  1049. self._downloader.deprecation_warning('tries argument is deprecated in InfoExtractor._download_webpage')
  1050. if timeout is NO_DEFAULT:
  1051. timeout = 5
  1052. else:
  1053. self._downloader.deprecation_warning('timeout argument is deprecated in InfoExtractor._download_webpage')
  1054. '''
  1055. try_count = 0
  1056. while True:
  1057. try:
  1058. return self.__download_webpage(url_or_request, video_id, note, errnote, None, fatal, *args, **kwargs)
  1059. except IncompleteRead as e:
  1060. try_count += 1
  1061. if try_count >= tries:
  1062. raise e
  1063. self._sleep(timeout, video_id)
  1064. def report_warning(self, msg, video_id=None, *args, only_once=False, **kwargs):
  1065. idstr = format_field(video_id, None, '%s: ')
  1066. msg = f'[{self.IE_NAME}] {idstr}{msg}'
  1067. if only_once:
  1068. if f'WARNING: {msg}' in self._printed_messages:
  1069. return
  1070. self._printed_messages.add(f'WARNING: {msg}')
  1071. self._downloader.report_warning(msg, *args, **kwargs)
  1072. def to_screen(self, msg, *args, **kwargs):
  1073. """Print msg to screen, prefixing it with '[ie_name]'"""
  1074. self._downloader.to_screen(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1075. def write_debug(self, msg, *args, **kwargs):
  1076. self._downloader.write_debug(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1077. def get_param(self, name, default=None, *args, **kwargs):
  1078. if self._downloader:
  1079. return self._downloader.params.get(name, default, *args, **kwargs)
  1080. return default
  1081. def report_drm(self, video_id, partial=NO_DEFAULT):
  1082. if partial is not NO_DEFAULT:
  1083. self._downloader.deprecation_warning('InfoExtractor.report_drm no longer accepts the argument partial')
  1084. self.raise_no_formats('This video is DRM protected', expected=True, video_id=video_id)
  1085. def report_extraction(self, id_or_name):
  1086. """Report information extraction."""
  1087. self.to_screen(f'{id_or_name}: Extracting information')
  1088. def report_download_webpage(self, video_id):
  1089. """Report webpage download."""
  1090. self.to_screen(f'{video_id}: Downloading webpage')
  1091. def report_age_confirmation(self):
  1092. """Report attempt to confirm age."""
  1093. self.to_screen('Confirming age')
  1094. def report_login(self):
  1095. """Report attempt to log in."""
  1096. self.to_screen('Logging in')
  1097. def raise_login_required(
  1098. self, msg='This video is only available for registered users',
  1099. metadata_available=False, method=NO_DEFAULT):
  1100. if metadata_available and (
  1101. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1102. self.report_warning(msg)
  1103. return
  1104. msg += format_field(self._login_hint(method), None, '. %s')
  1105. raise ExtractorError(msg, expected=True)
  1106. def raise_geo_restricted(
  1107. self, msg='This video is not available from your location due to geo restriction',
  1108. countries=None, metadata_available=False):
  1109. if metadata_available and (
  1110. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1111. self.report_warning(msg)
  1112. else:
  1113. raise GeoRestrictedError(msg, countries=countries)
  1114. def raise_no_formats(self, msg, expected=False, video_id=None):
  1115. if expected and (
  1116. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1117. self.report_warning(msg, video_id)
  1118. elif isinstance(msg, ExtractorError):
  1119. raise msg
  1120. else:
  1121. raise ExtractorError(msg, expected=expected, video_id=video_id)
  1122. # Methods for following #608
  1123. @staticmethod
  1124. def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs):
  1125. """Returns a URL that points to a page that should be processed"""
  1126. if ie is not None:
  1127. kwargs['ie_key'] = ie if isinstance(ie, str) else ie.ie_key()
  1128. if video_id is not None:
  1129. kwargs['id'] = video_id
  1130. if video_title is not None:
  1131. kwargs['title'] = video_title
  1132. return {
  1133. **kwargs,
  1134. '_type': 'url_transparent' if url_transparent else 'url',
  1135. 'url': url,
  1136. }
  1137. @classmethod
  1138. def playlist_from_matches(cls, matches, playlist_id=None, playlist_title=None,
  1139. getter=IDENTITY, ie=None, video_kwargs=None, **kwargs):
  1140. return cls.playlist_result(
  1141. (cls.url_result(m, ie, **(video_kwargs or {})) for m in orderedSet(map(getter, matches), lazy=True)),
  1142. playlist_id, playlist_title, **kwargs)
  1143. @staticmethod
  1144. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None, *, multi_video=False, **kwargs):
  1145. """Returns a playlist"""
  1146. if playlist_id:
  1147. kwargs['id'] = playlist_id
  1148. if playlist_title:
  1149. kwargs['title'] = playlist_title
  1150. if playlist_description is not None:
  1151. kwargs['description'] = playlist_description
  1152. return {
  1153. **kwargs,
  1154. '_type': 'multi_video' if multi_video else 'playlist',
  1155. 'entries': entries,
  1156. }
  1157. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1158. """
  1159. Perform a regex search on the given string, using a single or a list of
  1160. patterns returning the first matching group.
  1161. In case of failure return a default value or raise a WARNING or a
  1162. RegexNotFoundError, depending on fatal, specifying the field name.
  1163. """
  1164. if string is None:
  1165. mobj = None
  1166. elif isinstance(pattern, (str, re.Pattern)):
  1167. mobj = re.search(pattern, string, flags)
  1168. else:
  1169. for p in pattern:
  1170. mobj = re.search(p, string, flags)
  1171. if mobj:
  1172. break
  1173. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1174. if mobj:
  1175. if group is None:
  1176. # return the first matching group
  1177. return next(g for g in mobj.groups() if g is not None)
  1178. elif isinstance(group, (list, tuple)):
  1179. return tuple(mobj.group(g) for g in group)
  1180. else:
  1181. return mobj.group(group)
  1182. elif default is not NO_DEFAULT:
  1183. return default
  1184. elif fatal:
  1185. raise RegexNotFoundError(f'Unable to extract {_name}')
  1186. else:
  1187. self.report_warning(f'unable to extract {_name}' + bug_reports_message())
  1188. return None
  1189. def _search_json(self, start_pattern, string, name, video_id, *, end_pattern='',
  1190. contains_pattern=r'{(?s:.+)}', fatal=True, default=NO_DEFAULT, **kwargs):
  1191. """Searches string for the JSON object specified by start_pattern"""
  1192. # NB: end_pattern is only used to reduce the size of the initial match
  1193. if default is NO_DEFAULT:
  1194. default, has_default = {}, False
  1195. else:
  1196. fatal, has_default = False, True
  1197. json_string = self._search_regex(
  1198. rf'(?:{start_pattern})\s*(?P<json>{contains_pattern})\s*(?:{end_pattern})',
  1199. string, name, group='json', fatal=fatal, default=None if has_default else NO_DEFAULT)
  1200. if not json_string:
  1201. return default
  1202. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1203. try:
  1204. return self._parse_json(json_string, video_id, ignore_extra=True, **kwargs)
  1205. except ExtractorError as e:
  1206. if fatal:
  1207. raise ExtractorError(
  1208. f'Unable to extract {_name} - Failed to parse JSON', cause=e.cause, video_id=video_id)
  1209. elif not has_default:
  1210. self.report_warning(
  1211. f'Unable to extract {_name} - Failed to parse JSON: {e}', video_id=video_id)
  1212. return default
  1213. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1214. """
  1215. Like _search_regex, but strips HTML tags and unescapes entities.
  1216. """
  1217. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  1218. if isinstance(res, tuple):
  1219. return tuple(map(clean_html, res))
  1220. return clean_html(res)
  1221. def _get_netrc_login_info(self, netrc_machine=None):
  1222. netrc_machine = netrc_machine or self._NETRC_MACHINE
  1223. cmd = self.get_param('netrc_cmd')
  1224. if cmd:
  1225. cmd = cmd.replace('{}', netrc_machine)
  1226. self.to_screen(f'Executing command: {cmd}')
  1227. stdout, _, ret = Popen.run(cmd, text=True, shell=True, stdout=subprocess.PIPE)
  1228. if ret != 0:
  1229. raise OSError(f'Command returned error code {ret}')
  1230. info = netrc_from_content(stdout).authenticators(netrc_machine)
  1231. elif self.get_param('usenetrc', False):
  1232. netrc_file = compat_expanduser(self.get_param('netrc_location') or '~')
  1233. if os.path.isdir(netrc_file):
  1234. netrc_file = os.path.join(netrc_file, '.netrc')
  1235. info = netrc.netrc(netrc_file).authenticators(netrc_machine)
  1236. else:
  1237. return None, None
  1238. if not info:
  1239. self.to_screen(f'No authenticators for {netrc_machine}')
  1240. return None, None
  1241. self.write_debug(f'Using netrc for {netrc_machine} authentication')
  1242. return info[0], info[2]
  1243. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  1244. """
  1245. Get the login info as (username, password)
  1246. First look for the manually specified credentials using username_option
  1247. and password_option as keys in params dictionary. If no such credentials
  1248. are available try the netrc_cmd if it is defined or look in the
  1249. netrc file using the netrc_machine or _NETRC_MACHINE value.
  1250. If there's no info available, return (None, None)
  1251. """
  1252. username = self.get_param(username_option)
  1253. if username is not None:
  1254. password = self.get_param(password_option)
  1255. else:
  1256. try:
  1257. username, password = self._get_netrc_login_info(netrc_machine)
  1258. except (OSError, netrc.NetrcParseError) as err:
  1259. self.report_warning(f'Failed to parse .netrc: {err}')
  1260. return None, None
  1261. return username, password
  1262. def _get_tfa_info(self, note='two-factor verification code'):
  1263. """
  1264. Get the two-factor authentication info
  1265. TODO - asking the user will be required for sms/phone verify
  1266. currently just uses the command line option
  1267. If there's no info available, return None
  1268. """
  1269. tfa = self.get_param('twofactor')
  1270. if tfa is not None:
  1271. return tfa
  1272. return getpass.getpass(f'Type {note} and press [Return]: ')
  1273. # Helper functions for extracting OpenGraph info
  1274. @staticmethod
  1275. def _og_regexes(prop):
  1276. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))'
  1277. property_re = r'(?:name|property)=(?:\'og{sep}{prop}\'|"og{sep}{prop}"|\s*og{sep}{prop}\b)'.format(
  1278. prop=re.escape(prop), sep='(?:&#x3A;|[:-])')
  1279. template = r'<meta[^>]+?%s[^>]+?%s'
  1280. return [
  1281. template % (property_re, content_re),
  1282. template % (content_re, property_re),
  1283. ]
  1284. @staticmethod
  1285. def _meta_regex(prop):
  1286. return rf'''(?isx)<meta
  1287. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?){re.escape(prop)}\1)
  1288. [^>]+?content=(["\'])(?P<content>.*?)\2'''
  1289. def _og_search_property(self, prop, html, name=None, **kargs):
  1290. prop = variadic(prop)
  1291. if name is None:
  1292. name = f'OpenGraph {prop[0]}'
  1293. og_regexes = []
  1294. for p in prop:
  1295. og_regexes.extend(self._og_regexes(p))
  1296. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  1297. if escaped is None:
  1298. return None
  1299. return unescapeHTML(escaped)
  1300. def _og_search_thumbnail(self, html, **kargs):
  1301. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  1302. def _og_search_description(self, html, **kargs):
  1303. return self._og_search_property('description', html, fatal=False, **kargs)
  1304. def _og_search_title(self, html, *, fatal=False, **kargs):
  1305. return self._og_search_property('title', html, fatal=fatal, **kargs)
  1306. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  1307. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  1308. if secure:
  1309. regexes = self._og_regexes('video:secure_url') + regexes
  1310. return self._html_search_regex(regexes, html, name, **kargs)
  1311. def _og_search_url(self, html, **kargs):
  1312. return self._og_search_property('url', html, **kargs)
  1313. def _html_extract_title(self, html, name='title', *, fatal=False, **kwargs):
  1314. return self._html_search_regex(r'(?s)<title\b[^>]*>([^<]+)</title>', html, name, fatal=fatal, **kwargs)
  1315. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  1316. name = variadic(name)
  1317. if display_name is None:
  1318. display_name = name[0]
  1319. return self._html_search_regex(
  1320. [self._meta_regex(n) for n in name],
  1321. html, display_name, fatal=fatal, group='content', **kwargs)
  1322. def _dc_search_uploader(self, html):
  1323. return self._html_search_meta('dc.creator', html, 'uploader')
  1324. @staticmethod
  1325. def _rta_search(html):
  1326. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  1327. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  1328. r' content="RTA-5042-1996-1400-1577-RTA"',
  1329. html):
  1330. return 18
  1331. # And then there are the jokers who advertise that they use RTA, but actually don't.
  1332. AGE_LIMIT_MARKERS = [
  1333. r'Proudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>',
  1334. r'>[^<]*you acknowledge you are at least (\d+) years old',
  1335. r'>\s*(?:18\s+U(?:\.S\.C\.|SC)\s+)?(?:§+\s*)?2257\b',
  1336. ]
  1337. age_limit = 0
  1338. for marker in AGE_LIMIT_MARKERS:
  1339. mobj = re.search(marker, html)
  1340. if mobj:
  1341. age_limit = max(age_limit, int(traverse_obj(mobj, 1, default=18)))
  1342. return age_limit
  1343. def _media_rating_search(self, html):
  1344. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  1345. rating = self._html_search_meta('rating', html)
  1346. if not rating:
  1347. return None
  1348. RATING_TABLE = {
  1349. 'safe for kids': 0,
  1350. 'general': 8,
  1351. '14 years': 14,
  1352. 'mature': 17,
  1353. 'restricted': 19,
  1354. }
  1355. return RATING_TABLE.get(rating.lower())
  1356. def _family_friendly_search(self, html):
  1357. # See http://schema.org/VideoObject
  1358. family_friendly = self._html_search_meta(
  1359. 'isFamilyFriendly', html, default=None)
  1360. if not family_friendly:
  1361. return None
  1362. RATING_TABLE = {
  1363. '1': 0,
  1364. 'true': 0,
  1365. '0': 18,
  1366. 'false': 18,
  1367. }
  1368. return RATING_TABLE.get(family_friendly.lower())
  1369. def _twitter_search_player(self, html):
  1370. return self._html_search_meta('twitter:player', html,
  1371. 'twitter card player')
  1372. def _yield_json_ld(self, html, video_id, *, fatal=True, default=NO_DEFAULT):
  1373. """Yield all json ld objects in the html"""
  1374. if default is not NO_DEFAULT:
  1375. fatal = False
  1376. for mobj in re.finditer(JSON_LD_RE, html):
  1377. json_ld_item = self._parse_json(mobj.group('json_ld'), video_id, fatal=fatal)
  1378. for json_ld in variadic(json_ld_item):
  1379. if isinstance(json_ld, dict):
  1380. yield json_ld
  1381. def _search_json_ld(self, html, video_id, expected_type=None, *, fatal=True, default=NO_DEFAULT):
  1382. """Search for a video in any json ld in the html"""
  1383. if default is not NO_DEFAULT:
  1384. fatal = False
  1385. info = self._json_ld(
  1386. list(self._yield_json_ld(html, video_id, fatal=fatal, default=default)),
  1387. video_id, fatal=fatal, expected_type=expected_type)
  1388. if info:
  1389. return info
  1390. if default is not NO_DEFAULT:
  1391. return default
  1392. elif fatal:
  1393. raise RegexNotFoundError('Unable to extract JSON-LD')
  1394. else:
  1395. self.report_warning(f'unable to extract JSON-LD {bug_reports_message()}')
  1396. return {}
  1397. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  1398. if isinstance(json_ld, str):
  1399. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  1400. if not json_ld:
  1401. return {}
  1402. info = {}
  1403. INTERACTION_TYPE_MAP = {
  1404. 'CommentAction': 'comment',
  1405. 'AgreeAction': 'like',
  1406. 'DisagreeAction': 'dislike',
  1407. 'LikeAction': 'like',
  1408. 'DislikeAction': 'dislike',
  1409. 'ListenAction': 'view',
  1410. 'WatchAction': 'view',
  1411. 'ViewAction': 'view',
  1412. }
  1413. def is_type(e, *expected_types):
  1414. type_ = variadic(traverse_obj(e, '@type'))
  1415. return any(x in type_ for x in expected_types)
  1416. def extract_interaction_type(e):
  1417. interaction_type = e.get('interactionType')
  1418. if isinstance(interaction_type, dict):
  1419. interaction_type = interaction_type.get('@type')
  1420. return str_or_none(interaction_type)
  1421. def extract_interaction_statistic(e):
  1422. interaction_statistic = e.get('interactionStatistic')
  1423. if isinstance(interaction_statistic, dict):
  1424. interaction_statistic = [interaction_statistic]
  1425. if not isinstance(interaction_statistic, list):
  1426. return
  1427. for is_e in interaction_statistic:
  1428. if not is_type(is_e, 'InteractionCounter'):
  1429. continue
  1430. interaction_type = extract_interaction_type(is_e)
  1431. if not interaction_type:
  1432. continue
  1433. # For interaction count some sites provide string instead of
  1434. # an integer (as per spec) with non digit characters (e.g. ",")
  1435. # so extracting count with more relaxed str_to_int
  1436. interaction_count = str_to_int(is_e.get('userInteractionCount'))
  1437. if interaction_count is None:
  1438. continue
  1439. count_kind = INTERACTION_TYPE_MAP.get(interaction_type.split('/')[-1])
  1440. if not count_kind:
  1441. continue
  1442. count_key = f'{count_kind}_count'
  1443. if info.get(count_key) is not None:
  1444. continue
  1445. info[count_key] = interaction_count
  1446. def extract_chapter_information(e):
  1447. chapters = [{
  1448. 'title': part.get('name'),
  1449. 'start_time': part.get('startOffset'),
  1450. 'end_time': part.get('endOffset'),
  1451. } for part in variadic(e.get('hasPart') or []) if part.get('@type') == 'Clip']
  1452. for idx, (last_c, current_c, next_c) in enumerate(zip(
  1453. [{'end_time': 0}, *chapters], chapters, chapters[1:])):
  1454. current_c['end_time'] = current_c['end_time'] or next_c['start_time']
  1455. current_c['start_time'] = current_c['start_time'] or last_c['end_time']
  1456. if None in current_c.values():
  1457. self.report_warning(f'Chapter {idx} contains broken data. Not extracting chapters')
  1458. return
  1459. if chapters:
  1460. chapters[-1]['end_time'] = chapters[-1]['end_time'] or info['duration']
  1461. info['chapters'] = chapters
  1462. def extract_video_object(e):
  1463. author = e.get('author')
  1464. info.update({
  1465. 'url': url_or_none(e.get('contentUrl')),
  1466. 'ext': mimetype2ext(e.get('encodingFormat')),
  1467. 'title': unescapeHTML(e.get('name')),
  1468. 'description': unescapeHTML(e.get('description')),
  1469. 'thumbnails': [{'url': unescapeHTML(url)}
  1470. for url in variadic(traverse_obj(e, 'thumbnailUrl', 'thumbnailURL'))
  1471. if url_or_none(url)],
  1472. 'duration': parse_duration(e.get('duration')),
  1473. 'timestamp': unified_timestamp(e.get('uploadDate')),
  1474. # author can be an instance of 'Organization' or 'Person' types.
  1475. # both types can have 'name' property(inherited from 'Thing' type). [1]
  1476. # however some websites are using 'Text' type instead.
  1477. # 1. https://schema.org/VideoObject
  1478. 'uploader': author.get('name') if isinstance(author, dict) else author if isinstance(author, str) else None,
  1479. 'artist': traverse_obj(e, ('byArtist', 'name'), expected_type=str),
  1480. 'filesize': int_or_none(float_or_none(e.get('contentSize'))),
  1481. 'tbr': int_or_none(e.get('bitrate')),
  1482. 'width': int_or_none(e.get('width')),
  1483. 'height': int_or_none(e.get('height')),
  1484. 'view_count': int_or_none(e.get('interactionCount')),
  1485. 'tags': try_call(lambda: e.get('keywords').split(',')),
  1486. })
  1487. if is_type(e, 'AudioObject'):
  1488. info.update({
  1489. 'vcodec': 'none',
  1490. 'abr': int_or_none(e.get('bitrate')),
  1491. })
  1492. extract_interaction_statistic(e)
  1493. extract_chapter_information(e)
  1494. def traverse_json_ld(json_ld, at_top_level=True):
  1495. for e in variadic(json_ld):
  1496. if not isinstance(e, dict):
  1497. continue
  1498. if at_top_level and '@context' not in e:
  1499. continue
  1500. if at_top_level and set(e.keys()) == {'@context', '@graph'}:
  1501. traverse_json_ld(e['@graph'], at_top_level=False)
  1502. continue
  1503. if expected_type is not None and not is_type(e, expected_type):
  1504. continue
  1505. rating = traverse_obj(e, ('aggregateRating', 'ratingValue'), expected_type=float_or_none)
  1506. if rating is not None:
  1507. info['average_rating'] = rating
  1508. if is_type(e, 'TVEpisode', 'Episode'):
  1509. episode_name = unescapeHTML(e.get('name'))
  1510. info.update({
  1511. 'episode': episode_name,
  1512. 'episode_number': int_or_none(e.get('episodeNumber')),
  1513. 'description': unescapeHTML(e.get('description')),
  1514. })
  1515. if not info.get('title') and episode_name:
  1516. info['title'] = episode_name
  1517. part_of_season = e.get('partOfSeason')
  1518. if is_type(part_of_season, 'TVSeason', 'Season', 'CreativeWorkSeason'):
  1519. info.update({
  1520. 'season': unescapeHTML(part_of_season.get('name')),
  1521. 'season_number': int_or_none(part_of_season.get('seasonNumber')),
  1522. })
  1523. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  1524. if is_type(part_of_series, 'TVSeries', 'Series', 'CreativeWorkSeries'):
  1525. info['series'] = unescapeHTML(part_of_series.get('name'))
  1526. elif is_type(e, 'Movie'):
  1527. info.update({
  1528. 'title': unescapeHTML(e.get('name')),
  1529. 'description': unescapeHTML(e.get('description')),
  1530. 'duration': parse_duration(e.get('duration')),
  1531. 'timestamp': unified_timestamp(e.get('dateCreated')),
  1532. })
  1533. elif is_type(e, 'Article', 'NewsArticle'):
  1534. info.update({
  1535. 'timestamp': parse_iso8601(e.get('datePublished')),
  1536. 'title': unescapeHTML(e.get('headline')),
  1537. 'description': unescapeHTML(e.get('articleBody') or e.get('description')),
  1538. })
  1539. if is_type(traverse_obj(e, ('video', 0)), 'VideoObject'):
  1540. extract_video_object(e['video'][0])
  1541. elif is_type(traverse_obj(e, ('subjectOf', 0)), 'VideoObject'):
  1542. extract_video_object(e['subjectOf'][0])
  1543. elif is_type(e, 'VideoObject', 'AudioObject'):
  1544. extract_video_object(e)
  1545. if expected_type is None:
  1546. continue
  1547. else:
  1548. break
  1549. video = e.get('video')
  1550. if is_type(video, 'VideoObject'):
  1551. extract_video_object(video)
  1552. if expected_type is None:
  1553. continue
  1554. else:
  1555. break
  1556. traverse_json_ld(json_ld)
  1557. return filter_dict(info)
  1558. def _search_nextjs_data(self, webpage, video_id, *, fatal=True, default=NO_DEFAULT, **kw):
  1559. if default == '{}':
  1560. self._downloader.deprecation_warning('using `default=\'{}\'` is deprecated, use `default={}` instead')
  1561. default = {}
  1562. if default is not NO_DEFAULT:
  1563. fatal = False
  1564. return self._search_json(
  1565. r'<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>', webpage, 'next.js data',
  1566. video_id, end_pattern='</script>', fatal=fatal, default=default, **kw)
  1567. def _search_nuxt_data(self, webpage, video_id, context_name='__NUXT__', *, fatal=True, traverse=('data', 0)):
  1568. """Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure function"""
  1569. rectx = re.escape(context_name)
  1570. FUNCTION_RE = r'\(function\((?P<arg_keys>.*?)\){.*?\breturn\s+(?P<js>{.*?})\s*;?\s*}\((?P<arg_vals>.*?)\)'
  1571. js, arg_keys, arg_vals = self._search_regex(
  1572. (rf'<script>\s*window\.{rectx}={FUNCTION_RE}\s*\)\s*;?\s*</script>', rf'{rectx}\(.*?{FUNCTION_RE}'),
  1573. webpage, context_name, group=('js', 'arg_keys', 'arg_vals'),
  1574. default=NO_DEFAULT if fatal else (None, None, None))
  1575. if js is None:
  1576. return {}
  1577. args = dict(zip(arg_keys.split(','), map(json.dumps, self._parse_json(
  1578. f'[{arg_vals}]', video_id, transform_source=js_to_json, fatal=fatal) or ())))
  1579. ret = self._parse_json(js, video_id, transform_source=functools.partial(js_to_json, vars=args), fatal=fatal)
  1580. return traverse_obj(ret, traverse) or {}
  1581. @staticmethod
  1582. def _hidden_inputs(html):
  1583. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  1584. hidden_inputs = {}
  1585. for input_el in re.findall(r'(?i)(<input[^>]+>)', html):
  1586. attrs = extract_attributes(input_el)
  1587. if not input_el:
  1588. continue
  1589. if attrs.get('type') not in ('hidden', 'submit'):
  1590. continue
  1591. name = attrs.get('name') or attrs.get('id')
  1592. value = attrs.get('value')
  1593. if name and value is not None:
  1594. hidden_inputs[name] = value
  1595. return hidden_inputs
  1596. def _form_hidden_inputs(self, form_id, html):
  1597. form = self._search_regex(
  1598. rf'(?is)<form[^>]+?id=(["\']){form_id}\1[^>]*>(?P<form>.+?)</form>',
  1599. html, f'{form_id} form', group='form')
  1600. return self._hidden_inputs(form)
  1601. @classproperty(cache=True)
  1602. def FormatSort(cls):
  1603. class FormatSort(FormatSorter):
  1604. def __init__(ie, *args, **kwargs):
  1605. super().__init__(ie._downloader, *args, **kwargs)
  1606. deprecation_warning(
  1607. 'yt_dlp.InfoExtractor.FormatSort is deprecated and may be removed in the future. '
  1608. 'Use yt_dlp.utils.FormatSorter instead')
  1609. return FormatSort
  1610. def _sort_formats(self, formats, field_preference=[]):
  1611. if not field_preference:
  1612. self._downloader.deprecation_warning(
  1613. 'yt_dlp.InfoExtractor._sort_formats is deprecated and is no longer required')
  1614. return
  1615. self._downloader.deprecation_warning(
  1616. 'yt_dlp.InfoExtractor._sort_formats is deprecated and no longer works as expected. '
  1617. 'Return _format_sort_fields in the info_dict instead')
  1618. if formats:
  1619. formats[0]['__sort_fields'] = field_preference
  1620. def _check_formats(self, formats, video_id):
  1621. if formats:
  1622. formats[:] = filter(
  1623. lambda f: self._is_valid_url(
  1624. f['url'], video_id,
  1625. item='{} video format'.format(f.get('format_id')) if f.get('format_id') else 'video'),
  1626. formats)
  1627. @staticmethod
  1628. def _remove_duplicate_formats(formats):
  1629. format_urls = set()
  1630. unique_formats = []
  1631. for f in formats:
  1632. if f['url'] not in format_urls:
  1633. format_urls.add(f['url'])
  1634. unique_formats.append(f)
  1635. formats[:] = unique_formats
  1636. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1637. url = self._proto_relative_url(url, scheme='http:')
  1638. # For now assume non HTTP(S) URLs always valid
  1639. if not url.startswith(('http://', 'https://')):
  1640. return True
  1641. try:
  1642. self._request_webpage(url, video_id, f'Checking {item} URL', headers=headers)
  1643. return True
  1644. except ExtractorError as e:
  1645. self.to_screen(
  1646. f'{video_id}: {item} URL is invalid, skipping: {e.cause!s}')
  1647. return False
  1648. def http_scheme(self):
  1649. """ Either "http:" or "https:", depending on the user's preferences """
  1650. return (
  1651. 'http:'
  1652. if self.get_param('prefer_insecure', False)
  1653. else 'https:')
  1654. def _proto_relative_url(self, url, scheme=None):
  1655. scheme = scheme or self.http_scheme()
  1656. assert scheme.endswith(':')
  1657. return sanitize_url(url, scheme=scheme[:-1])
  1658. def _sleep(self, timeout, video_id, msg_template=None):
  1659. if msg_template is None:
  1660. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1661. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1662. self.to_screen(msg)
  1663. time.sleep(timeout)
  1664. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1665. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1666. fatal=True, m3u8_id=None, data=None, headers={}, query={}):
  1667. if self.get_param('ignore_no_formats_error'):
  1668. fatal = False
  1669. res = self._download_xml_handle(
  1670. manifest_url, video_id, 'Downloading f4m manifest',
  1671. 'Unable to download f4m manifest',
  1672. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1673. # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244)
  1674. transform_source=transform_source,
  1675. fatal=fatal, data=data, headers=headers, query=query)
  1676. if res is False:
  1677. return []
  1678. manifest, urlh = res
  1679. manifest_url = urlh.url
  1680. return self._parse_f4m_formats(
  1681. manifest, manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1682. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1683. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1684. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1685. fatal=True, m3u8_id=None):
  1686. if not isinstance(manifest, xml.etree.ElementTree.Element) and not fatal:
  1687. return []
  1688. # currently yt-dlp cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1689. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1690. if akamai_pv is not None and ';' in akamai_pv.text:
  1691. player_verification_challenge = akamai_pv.text.split(';')[0]
  1692. if player_verification_challenge.strip() != '':
  1693. return []
  1694. formats = []
  1695. manifest_version = '1.0'
  1696. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1697. if not media_nodes:
  1698. manifest_version = '2.0'
  1699. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1700. # Remove unsupported DRM protected media from final formats
  1701. # rendition (see https://github.com/ytdl-org/youtube-dl/issues/8573).
  1702. media_nodes = remove_encrypted_media(media_nodes)
  1703. if not media_nodes:
  1704. return formats
  1705. manifest_base_url = get_base_url(manifest)
  1706. bootstrap_info = xpath_element(
  1707. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1708. 'bootstrap info', default=None)
  1709. vcodec = None
  1710. mime_type = xpath_text(
  1711. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1712. 'base URL', default=None)
  1713. if mime_type and mime_type.startswith('audio/'):
  1714. vcodec = 'none'
  1715. for i, media_el in enumerate(media_nodes):
  1716. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1717. width = int_or_none(media_el.attrib.get('width'))
  1718. height = int_or_none(media_el.attrib.get('height'))
  1719. format_id = join_nonempty(f4m_id, tbr or i)
  1720. # If <bootstrapInfo> is present, the specified f4m is a
  1721. # stream-level manifest, and only set-level manifests may refer to
  1722. # external resources. See section 11.4 and section 4 of F4M spec
  1723. if bootstrap_info is None:
  1724. media_url = None
  1725. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1726. if manifest_version == '2.0':
  1727. media_url = media_el.attrib.get('href')
  1728. if media_url is None:
  1729. media_url = media_el.attrib.get('url')
  1730. if not media_url:
  1731. continue
  1732. manifest_url = (
  1733. media_url if media_url.startswith(('http://', 'https://'))
  1734. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1735. # If media_url is itself a f4m manifest do the recursive extraction
  1736. # since bitrates in parent manifest (this one) and media_url manifest
  1737. # may differ leading to inability to resolve the format by requested
  1738. # bitrate in f4m downloader
  1739. ext = determine_ext(manifest_url)
  1740. if ext == 'f4m':
  1741. f4m_formats = self._extract_f4m_formats(
  1742. manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1743. transform_source=transform_source, fatal=fatal)
  1744. # Sometimes stream-level manifest contains single media entry that
  1745. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1746. # At the same time parent's media entry in set-level manifest may
  1747. # contain it. We will copy it from parent in such cases.
  1748. if len(f4m_formats) == 1:
  1749. f = f4m_formats[0]
  1750. f.update({
  1751. 'tbr': f.get('tbr') or tbr,
  1752. 'width': f.get('width') or width,
  1753. 'height': f.get('height') or height,
  1754. 'format_id': f.get('format_id') if not tbr else format_id,
  1755. 'vcodec': vcodec,
  1756. })
  1757. formats.extend(f4m_formats)
  1758. continue
  1759. elif ext == 'm3u8':
  1760. formats.extend(self._extract_m3u8_formats(
  1761. manifest_url, video_id, 'mp4', preference=preference,
  1762. quality=quality, m3u8_id=m3u8_id, fatal=fatal))
  1763. continue
  1764. formats.append({
  1765. 'format_id': format_id,
  1766. 'url': manifest_url,
  1767. 'manifest_url': manifest_url,
  1768. 'ext': 'flv' if bootstrap_info is not None else None,
  1769. 'protocol': 'f4m',
  1770. 'tbr': tbr,
  1771. 'width': width,
  1772. 'height': height,
  1773. 'vcodec': vcodec,
  1774. 'preference': preference,
  1775. 'quality': quality,
  1776. })
  1777. return formats
  1778. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, quality=None, m3u8_id=None):
  1779. return {
  1780. 'format_id': join_nonempty(m3u8_id, 'meta'),
  1781. 'url': m3u8_url,
  1782. 'ext': ext,
  1783. 'protocol': 'm3u8',
  1784. 'preference': preference - 100 if preference else -100,
  1785. 'quality': quality,
  1786. 'resolution': 'multiple',
  1787. 'format_note': 'Quality selection URL',
  1788. }
  1789. def _report_ignoring_subs(self, name):
  1790. self.report_warning(bug_reports_message(
  1791. f'Ignoring subtitle tracks found in the {name} manifest; '
  1792. 'if any subtitle tracks are missing,',
  1793. ), only_once=True)
  1794. def _extract_m3u8_formats(self, *args, **kwargs):
  1795. fmts, subs = self._extract_m3u8_formats_and_subtitles(*args, **kwargs)
  1796. if subs:
  1797. self._report_ignoring_subs('HLS')
  1798. return fmts
  1799. def _extract_m3u8_formats_and_subtitles(
  1800. self, m3u8_url, video_id, ext=None, entry_protocol='m3u8_native',
  1801. preference=None, quality=None, m3u8_id=None, note=None,
  1802. errnote=None, fatal=True, live=False, data=None, headers={},
  1803. query={}):
  1804. if self.get_param('ignore_no_formats_error'):
  1805. fatal = False
  1806. if not m3u8_url:
  1807. if errnote is not False:
  1808. errnote = errnote or 'Failed to obtain m3u8 URL'
  1809. if fatal:
  1810. raise ExtractorError(errnote, video_id=video_id)
  1811. self.report_warning(f'{errnote}{bug_reports_message()}')
  1812. return [], {}
  1813. res = self._download_webpage_handle(
  1814. m3u8_url, video_id,
  1815. note='Downloading m3u8 information' if note is None else note,
  1816. errnote='Failed to download m3u8 information' if errnote is None else errnote,
  1817. fatal=fatal, data=data, headers=headers, query=query)
  1818. if res is False:
  1819. return [], {}
  1820. m3u8_doc, urlh = res
  1821. m3u8_url = urlh.url
  1822. return self._parse_m3u8_formats_and_subtitles(
  1823. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1824. preference=preference, quality=quality, m3u8_id=m3u8_id,
  1825. note=note, errnote=errnote, fatal=fatal, live=live, data=data,
  1826. headers=headers, query=query, video_id=video_id)
  1827. def _parse_m3u8_formats_and_subtitles(
  1828. self, m3u8_doc, m3u8_url=None, ext=None, entry_protocol='m3u8_native',
  1829. preference=None, quality=None, m3u8_id=None, live=False, note=None,
  1830. errnote=None, fatal=True, data=None, headers={}, query={},
  1831. video_id=None):
  1832. formats, subtitles = [], {}
  1833. has_drm = HlsFD._has_drm(m3u8_doc)
  1834. def format_url(url):
  1835. return url if re.match(r'^https?://', url) else urllib.parse.urljoin(m3u8_url, url)
  1836. if self.get_param('hls_split_discontinuity', False):
  1837. def _extract_m3u8_playlist_indices(manifest_url=None, m3u8_doc=None):
  1838. if not m3u8_doc:
  1839. if not manifest_url:
  1840. return []
  1841. m3u8_doc = self._download_webpage(
  1842. manifest_url, video_id, fatal=fatal, data=data, headers=headers,
  1843. note=False, errnote='Failed to download m3u8 playlist information')
  1844. if m3u8_doc is False:
  1845. return []
  1846. return range(1 + sum(line.startswith('#EXT-X-DISCONTINUITY') for line in m3u8_doc.splitlines()))
  1847. else:
  1848. def _extract_m3u8_playlist_indices(*args, **kwargs):
  1849. return [None]
  1850. # References:
  1851. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1852. # 2. https://github.com/ytdl-org/youtube-dl/issues/12211
  1853. # 3. https://github.com/ytdl-org/youtube-dl/issues/18923
  1854. # We should try extracting formats only from master playlists [1, 4.3.4],
  1855. # i.e. playlists that describe available qualities. On the other hand
  1856. # media playlists [1, 4.3.3] should be returned as is since they contain
  1857. # just the media without qualities renditions.
  1858. # Fortunately, master playlist can be easily distinguished from media
  1859. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1860. # master playlist tags MUST NOT appear in a media playlist and vice versa.
  1861. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1862. # media playlist and MUST NOT appear in master playlist thus we can
  1863. # clearly detect media playlist with this criterion.
  1864. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1865. formats = [{
  1866. 'format_id': join_nonempty(m3u8_id, idx),
  1867. 'format_index': idx,
  1868. 'url': m3u8_url or encode_data_uri(m3u8_doc.encode(), 'application/x-mpegurl'),
  1869. 'ext': ext,
  1870. 'protocol': entry_protocol,
  1871. 'preference': preference,
  1872. 'quality': quality,
  1873. 'has_drm': has_drm,
  1874. } for idx in _extract_m3u8_playlist_indices(m3u8_doc=m3u8_doc)]
  1875. return formats, subtitles
  1876. groups = {}
  1877. last_stream_inf = {}
  1878. def extract_media(x_media_line):
  1879. media = parse_m3u8_attributes(x_media_line)
  1880. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1881. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1882. if not (media_type and group_id and name):
  1883. return
  1884. groups.setdefault(group_id, []).append(media)
  1885. # <https://tools.ietf.org/html/rfc8216#section-4.3.4.1>
  1886. if media_type == 'SUBTITLES':
  1887. # According to RFC 8216 §4.3.4.2.1, URI is REQUIRED in the
  1888. # EXT-X-MEDIA tag if the media type is SUBTITLES.
  1889. # However, lack of URI has been spotted in the wild.
  1890. # e.g. NebulaIE; see https://github.com/yt-dlp/yt-dlp/issues/339
  1891. if not media.get('URI'):
  1892. return
  1893. url = format_url(media['URI'])
  1894. sub_info = {
  1895. 'url': url,
  1896. 'ext': determine_ext(url),
  1897. }
  1898. if sub_info['ext'] == 'm3u8':
  1899. # Per RFC 8216 §3.1, the only possible subtitle format m3u8
  1900. # files may contain is WebVTT:
  1901. # <https://tools.ietf.org/html/rfc8216#section-3.1>
  1902. sub_info['ext'] = 'vtt'
  1903. sub_info['protocol'] = 'm3u8_native'
  1904. lang = media.get('LANGUAGE') or 'und'
  1905. subtitles.setdefault(lang, []).append(sub_info)
  1906. if media_type not in ('VIDEO', 'AUDIO'):
  1907. return
  1908. media_url = media.get('URI')
  1909. if media_url:
  1910. manifest_url = format_url(media_url)
  1911. formats.extend({
  1912. 'format_id': join_nonempty(m3u8_id, group_id, name, idx),
  1913. 'format_note': name,
  1914. 'format_index': idx,
  1915. 'url': manifest_url,
  1916. 'manifest_url': m3u8_url,
  1917. 'language': media.get('LANGUAGE'),
  1918. 'ext': ext,
  1919. 'protocol': entry_protocol,
  1920. 'preference': preference,
  1921. 'quality': quality,
  1922. 'has_drm': has_drm,
  1923. 'vcodec': 'none' if media_type == 'AUDIO' else None,
  1924. } for idx in _extract_m3u8_playlist_indices(manifest_url))
  1925. def build_stream_name():
  1926. # Despite specification does not mention NAME attribute for
  1927. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1928. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1929. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1930. stream_name = last_stream_inf.get('NAME')
  1931. if stream_name:
  1932. return stream_name
  1933. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1934. # from corresponding rendition group
  1935. stream_group_id = last_stream_inf.get('VIDEO')
  1936. if not stream_group_id:
  1937. return
  1938. stream_group = groups.get(stream_group_id)
  1939. if not stream_group:
  1940. return stream_group_id
  1941. rendition = stream_group[0]
  1942. return rendition.get('NAME') or stream_group_id
  1943. # parse EXT-X-MEDIA tags before EXT-X-STREAM-INF in order to have the
  1944. # chance to detect video only formats when EXT-X-STREAM-INF tags
  1945. # precede EXT-X-MEDIA tags in HLS manifest such as [3].
  1946. for line in m3u8_doc.splitlines():
  1947. if line.startswith('#EXT-X-MEDIA:'):
  1948. extract_media(line)
  1949. for line in m3u8_doc.splitlines():
  1950. if line.startswith('#EXT-X-STREAM-INF:'):
  1951. last_stream_inf = parse_m3u8_attributes(line)
  1952. elif line.startswith('#') or not line.strip():
  1953. continue
  1954. else:
  1955. tbr = float_or_none(
  1956. last_stream_inf.get('AVERAGE-BANDWIDTH')
  1957. or last_stream_inf.get('BANDWIDTH'), scale=1000)
  1958. manifest_url = format_url(line.strip())
  1959. for idx in _extract_m3u8_playlist_indices(manifest_url):
  1960. format_id = [m3u8_id, None, idx]
  1961. # Bandwidth of live streams may differ over time thus making
  1962. # format_id unpredictable. So it's better to keep provided
  1963. # format_id intact.
  1964. if not live:
  1965. stream_name = build_stream_name()
  1966. format_id[1] = stream_name or '%d' % (tbr or len(formats))
  1967. f = {
  1968. 'format_id': join_nonempty(*format_id),
  1969. 'format_index': idx,
  1970. 'url': manifest_url,
  1971. 'manifest_url': m3u8_url,
  1972. 'tbr': tbr,
  1973. 'ext': ext,
  1974. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  1975. 'protocol': entry_protocol,
  1976. 'preference': preference,
  1977. 'quality': quality,
  1978. 'has_drm': has_drm,
  1979. }
  1980. # YouTube-specific
  1981. if yt_audio_content_id := last_stream_inf.get('YT-EXT-AUDIO-CONTENT-ID'):
  1982. f['language'] = yt_audio_content_id.split('.')[0]
  1983. resolution = last_stream_inf.get('RESOLUTION')
  1984. if resolution:
  1985. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1986. if mobj:
  1987. f['width'] = int(mobj.group('width'))
  1988. f['height'] = int(mobj.group('height'))
  1989. # Unified Streaming Platform
  1990. mobj = re.search(
  1991. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1992. if mobj:
  1993. abr, vbr = mobj.groups()
  1994. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1995. f.update({
  1996. 'vbr': vbr,
  1997. 'abr': abr,
  1998. })
  1999. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  2000. f.update(codecs)
  2001. audio_group_id = last_stream_inf.get('AUDIO')
  2002. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  2003. # references a rendition group MUST have a CODECS attribute.
  2004. # However, this is not always respected. E.g. [2]
  2005. # contains EXT-X-STREAM-INF tag which references AUDIO
  2006. # rendition group but does not have CODECS and despite
  2007. # referencing an audio group it represents a complete
  2008. # (with audio and video) format. So, for such cases we will
  2009. # ignore references to rendition groups and treat them
  2010. # as complete formats.
  2011. if audio_group_id and codecs and f.get('vcodec') != 'none':
  2012. audio_group = groups.get(audio_group_id)
  2013. if audio_group and audio_group[0].get('URI'):
  2014. # TODO: update acodec for audio only formats with
  2015. # the same GROUP-ID
  2016. f['acodec'] = 'none'
  2017. if not f.get('ext'):
  2018. f['ext'] = 'm4a' if f.get('vcodec') == 'none' else 'mp4'
  2019. formats.append(f)
  2020. # for DailyMotion
  2021. progressive_uri = last_stream_inf.get('PROGRESSIVE-URI')
  2022. if progressive_uri:
  2023. http_f = f.copy()
  2024. del http_f['manifest_url']
  2025. http_f.update({
  2026. 'format_id': f['format_id'].replace('hls-', 'http-'),
  2027. 'protocol': 'http',
  2028. 'url': progressive_uri,
  2029. })
  2030. formats.append(http_f)
  2031. last_stream_inf = {}
  2032. return formats, subtitles
  2033. def _extract_m3u8_vod_duration(
  2034. self, m3u8_vod_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2035. m3u8_vod = self._download_webpage(
  2036. m3u8_vod_url, video_id,
  2037. note='Downloading m3u8 VOD manifest' if note is None else note,
  2038. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2039. fatal=False, data=data, headers=headers, query=query)
  2040. return self._parse_m3u8_vod_duration(m3u8_vod or '', video_id)
  2041. def _parse_m3u8_vod_duration(self, m3u8_vod, video_id):
  2042. if '#EXT-X-ENDLIST' not in m3u8_vod:
  2043. return None
  2044. return int(sum(
  2045. float(line[len('#EXTINF:'):].split(',')[0])
  2046. for line in m3u8_vod.splitlines() if line.startswith('#EXTINF:'))) or None
  2047. def _extract_mpd_vod_duration(
  2048. self, mpd_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2049. mpd_doc = self._download_xml(
  2050. mpd_url, video_id,
  2051. note='Downloading MPD VOD manifest' if note is None else note,
  2052. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2053. fatal=False, data=data, headers=headers, query=query)
  2054. if not isinstance(mpd_doc, xml.etree.ElementTree.Element):
  2055. return None
  2056. return int_or_none(parse_duration(mpd_doc.get('mediaPresentationDuration')))
  2057. @staticmethod
  2058. def _xpath_ns(path, namespace=None):
  2059. if not namespace:
  2060. return path
  2061. out = []
  2062. for c in path.split('/'):
  2063. if not c or c == '.':
  2064. out.append(c)
  2065. else:
  2066. out.append(f'{{{namespace}}}{c}')
  2067. return '/'.join(out)
  2068. def _extract_smil_formats_and_subtitles(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  2069. if self.get_param('ignore_no_formats_error'):
  2070. fatal = False
  2071. res = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  2072. if res is False:
  2073. assert not fatal
  2074. return [], {}
  2075. smil, urlh = res
  2076. return self._parse_smil_formats_and_subtitles(smil, urlh.url, video_id, f4m_params=f4m_params,
  2077. namespace=self._parse_smil_namespace(smil))
  2078. def _extract_smil_formats(self, *args, **kwargs):
  2079. fmts, subs = self._extract_smil_formats_and_subtitles(*args, **kwargs)
  2080. if subs:
  2081. self._report_ignoring_subs('SMIL')
  2082. return fmts
  2083. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  2084. res = self._download_smil(smil_url, video_id, fatal=fatal)
  2085. if res is False:
  2086. return {}
  2087. smil, urlh = res
  2088. smil_url = urlh.url
  2089. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  2090. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  2091. return self._download_xml_handle(
  2092. smil_url, video_id, 'Downloading SMIL file',
  2093. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  2094. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  2095. namespace = self._parse_smil_namespace(smil)
  2096. formats, subtitles = self._parse_smil_formats_and_subtitles(
  2097. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  2098. video_id = os.path.splitext(url_basename(smil_url))[0]
  2099. title = None
  2100. description = None
  2101. upload_date = None
  2102. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2103. name = meta.attrib.get('name')
  2104. content = meta.attrib.get('content')
  2105. if not name or not content:
  2106. continue
  2107. if not title and name == 'title':
  2108. title = content
  2109. elif not description and name in ('description', 'abstract'):
  2110. description = content
  2111. elif not upload_date and name == 'date':
  2112. upload_date = unified_strdate(content)
  2113. thumbnails = [{
  2114. 'id': image.get('type'),
  2115. 'url': image.get('src'),
  2116. 'width': int_or_none(image.get('width')),
  2117. 'height': int_or_none(image.get('height')),
  2118. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  2119. return {
  2120. 'id': video_id,
  2121. 'title': title or video_id,
  2122. 'description': description,
  2123. 'upload_date': upload_date,
  2124. 'thumbnails': thumbnails,
  2125. 'formats': formats,
  2126. 'subtitles': subtitles,
  2127. }
  2128. def _parse_smil_namespace(self, smil):
  2129. return self._search_regex(
  2130. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  2131. def _parse_smil_formats(self, *args, **kwargs):
  2132. fmts, subs = self._parse_smil_formats_and_subtitles(*args, **kwargs)
  2133. if subs:
  2134. self._report_ignoring_subs('SMIL')
  2135. return fmts
  2136. def _parse_smil_formats_and_subtitles(
  2137. self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  2138. base = smil_url
  2139. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2140. b = meta.get('base') or meta.get('httpBase')
  2141. if b:
  2142. base = b
  2143. break
  2144. formats, subtitles = [], {}
  2145. rtmp_count = 0
  2146. http_count = 0
  2147. m3u8_count = 0
  2148. imgs_count = 0
  2149. srcs = set()
  2150. media = itertools.chain.from_iterable(
  2151. smil.findall(self._xpath_ns(arg, namespace))
  2152. for arg in ['.//video', './/audio', './/media'])
  2153. for medium in media:
  2154. src = medium.get('src')
  2155. if not src or src in srcs:
  2156. continue
  2157. srcs.add(src)
  2158. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  2159. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  2160. width = int_or_none(medium.get('width'))
  2161. height = int_or_none(medium.get('height'))
  2162. proto = medium.get('proto')
  2163. ext = medium.get('ext')
  2164. src_ext = determine_ext(src, default_ext=None) or ext or urlhandle_detect_ext(
  2165. self._request_webpage(HEADRequest(src), video_id, note='Requesting extension info', fatal=False))
  2166. streamer = medium.get('streamer') or base
  2167. if proto == 'rtmp' or streamer.startswith('rtmp'):
  2168. rtmp_count += 1
  2169. formats.append({
  2170. 'url': streamer,
  2171. 'play_path': src,
  2172. 'ext': 'flv',
  2173. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  2174. 'tbr': bitrate,
  2175. 'filesize': filesize,
  2176. 'width': width,
  2177. 'height': height,
  2178. })
  2179. if transform_rtmp_url:
  2180. streamer, src = transform_rtmp_url(streamer, src)
  2181. formats[-1].update({
  2182. 'url': streamer,
  2183. 'play_path': src,
  2184. })
  2185. continue
  2186. src_url = src if src.startswith('http') else urllib.parse.urljoin(f'{base}/', src)
  2187. src_url = src_url.strip()
  2188. if proto == 'm3u8' or src_ext == 'm3u8':
  2189. m3u8_formats, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
  2190. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  2191. self._merge_subtitles(m3u8_subs, target=subtitles)
  2192. if len(m3u8_formats) == 1:
  2193. m3u8_count += 1
  2194. m3u8_formats[0].update({
  2195. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  2196. 'tbr': bitrate,
  2197. 'width': width,
  2198. 'height': height,
  2199. })
  2200. formats.extend(m3u8_formats)
  2201. elif src_ext == 'f4m':
  2202. f4m_url = src_url
  2203. if not f4m_params:
  2204. f4m_params = {
  2205. 'hdcore': '3.2.0',
  2206. 'plugin': 'flowplayer-3.2.0.1',
  2207. }
  2208. f4m_url += '&' if '?' in f4m_url else '?'
  2209. f4m_url += urllib.parse.urlencode(f4m_params)
  2210. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  2211. elif src_ext == 'mpd':
  2212. mpd_formats, mpd_subs = self._extract_mpd_formats_and_subtitles(
  2213. src_url, video_id, mpd_id='dash', fatal=False)
  2214. formats.extend(mpd_formats)
  2215. self._merge_subtitles(mpd_subs, target=subtitles)
  2216. elif re.search(r'\.ism/[Mm]anifest', src_url):
  2217. ism_formats, ism_subs = self._extract_ism_formats_and_subtitles(
  2218. src_url, video_id, ism_id='mss', fatal=False)
  2219. formats.extend(ism_formats)
  2220. self._merge_subtitles(ism_subs, target=subtitles)
  2221. elif src_url.startswith('http') and self._is_valid_url(src, video_id):
  2222. http_count += 1
  2223. formats.append({
  2224. 'url': src_url,
  2225. 'ext': ext or src_ext or 'flv',
  2226. 'format_id': 'http-%d' % (bitrate or http_count),
  2227. 'tbr': bitrate,
  2228. 'filesize': filesize,
  2229. 'width': width,
  2230. 'height': height,
  2231. })
  2232. for medium in smil.findall(self._xpath_ns('.//imagestream', namespace)):
  2233. src = medium.get('src')
  2234. if not src or src in srcs:
  2235. continue
  2236. srcs.add(src)
  2237. imgs_count += 1
  2238. formats.append({
  2239. 'format_id': f'imagestream-{imgs_count}',
  2240. 'url': src,
  2241. 'ext': mimetype2ext(medium.get('type')),
  2242. 'acodec': 'none',
  2243. 'vcodec': 'none',
  2244. 'width': int_or_none(medium.get('width')),
  2245. 'height': int_or_none(medium.get('height')),
  2246. 'format_note': 'SMIL storyboards',
  2247. })
  2248. smil_subs = self._parse_smil_subtitles(smil, namespace=namespace)
  2249. self._merge_subtitles(smil_subs, target=subtitles)
  2250. return formats, subtitles
  2251. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  2252. urls = []
  2253. subtitles = {}
  2254. for textstream in smil.findall(self._xpath_ns('.//textstream', namespace)):
  2255. src = textstream.get('src')
  2256. if not src or src in urls:
  2257. continue
  2258. urls.append(src)
  2259. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  2260. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  2261. subtitles.setdefault(lang, []).append({
  2262. 'url': src,
  2263. 'ext': ext,
  2264. })
  2265. return subtitles
  2266. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  2267. res = self._download_xml_handle(
  2268. xspf_url, playlist_id, 'Downloading xpsf playlist',
  2269. 'Unable to download xspf manifest', fatal=fatal)
  2270. if res is False:
  2271. return []
  2272. xspf, urlh = res
  2273. xspf_url = urlh.url
  2274. return self._parse_xspf(
  2275. xspf, playlist_id, xspf_url=xspf_url,
  2276. xspf_base_url=base_url(xspf_url))
  2277. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  2278. NS_MAP = {
  2279. 'xspf': 'http://xspf.org/ns/0/',
  2280. 's1': 'http://static.streamone.nl/player/ns/0',
  2281. }
  2282. entries = []
  2283. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  2284. title = xpath_text(
  2285. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  2286. description = xpath_text(
  2287. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  2288. thumbnail = xpath_text(
  2289. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  2290. duration = float_or_none(
  2291. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  2292. formats = []
  2293. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  2294. format_url = urljoin(xspf_base_url, location.text)
  2295. if not format_url:
  2296. continue
  2297. formats.append({
  2298. 'url': format_url,
  2299. 'manifest_url': xspf_url,
  2300. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  2301. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  2302. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  2303. })
  2304. entries.append({
  2305. 'id': playlist_id,
  2306. 'title': title,
  2307. 'description': description,
  2308. 'thumbnail': thumbnail,
  2309. 'duration': duration,
  2310. 'formats': formats,
  2311. })
  2312. return entries
  2313. def _extract_mpd_formats(self, *args, **kwargs):
  2314. fmts, subs = self._extract_mpd_formats_and_subtitles(*args, **kwargs)
  2315. if subs:
  2316. self._report_ignoring_subs('DASH')
  2317. return fmts
  2318. def _extract_mpd_formats_and_subtitles(self, *args, **kwargs):
  2319. periods = self._extract_mpd_periods(*args, **kwargs)
  2320. return self._merge_mpd_periods(periods)
  2321. def _extract_mpd_periods(
  2322. self, mpd_url, video_id, mpd_id=None, note=None, errnote=None,
  2323. fatal=True, data=None, headers={}, query={}):
  2324. if self.get_param('ignore_no_formats_error'):
  2325. fatal = False
  2326. res = self._download_xml_handle(
  2327. mpd_url, video_id,
  2328. note='Downloading MPD manifest' if note is None else note,
  2329. errnote='Failed to download MPD manifest' if errnote is None else errnote,
  2330. fatal=fatal, data=data, headers=headers, query=query)
  2331. if res is False:
  2332. return []
  2333. mpd_doc, urlh = res
  2334. if mpd_doc is None:
  2335. return []
  2336. # We could have been redirected to a new url when we retrieved our mpd file.
  2337. mpd_url = urlh.url
  2338. mpd_base_url = base_url(mpd_url)
  2339. return self._parse_mpd_periods(mpd_doc, mpd_id, mpd_base_url, mpd_url)
  2340. def _parse_mpd_formats(self, *args, **kwargs):
  2341. fmts, subs = self._parse_mpd_formats_and_subtitles(*args, **kwargs)
  2342. if subs:
  2343. self._report_ignoring_subs('DASH')
  2344. return fmts
  2345. def _parse_mpd_formats_and_subtitles(self, *args, **kwargs):
  2346. periods = self._parse_mpd_periods(*args, **kwargs)
  2347. return self._merge_mpd_periods(periods)
  2348. def _merge_mpd_periods(self, periods):
  2349. """
  2350. Combine all formats and subtitles from an MPD manifest into a single list,
  2351. by concatenate streams with similar formats.
  2352. """
  2353. formats, subtitles = {}, {}
  2354. for period in periods:
  2355. for f in period['formats']:
  2356. assert 'is_dash_periods' not in f, 'format already processed'
  2357. f['is_dash_periods'] = True
  2358. format_key = tuple(v for k, v in f.items() if k not in (
  2359. ('format_id', 'fragments', 'manifest_stream_number')))
  2360. if format_key not in formats:
  2361. formats[format_key] = f
  2362. elif 'fragments' in f:
  2363. formats[format_key].setdefault('fragments', []).extend(f['fragments'])
  2364. if subtitles and period['subtitles']:
  2365. self.report_warning(bug_reports_message(
  2366. 'Found subtitles in multiple periods in the DASH manifest; '
  2367. 'if part of the subtitles are missing,',
  2368. ), only_once=True)
  2369. for sub_lang, sub_info in period['subtitles'].items():
  2370. subtitles.setdefault(sub_lang, []).extend(sub_info)
  2371. return list(formats.values()), subtitles
  2372. def _parse_mpd_periods(self, mpd_doc, mpd_id=None, mpd_base_url='', mpd_url=None):
  2373. """
  2374. Parse formats from MPD manifest.
  2375. References:
  2376. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  2377. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  2378. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  2379. """
  2380. if not self.get_param('dynamic_mpd', True):
  2381. if mpd_doc.get('type') == 'dynamic':
  2382. return [], {}
  2383. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  2384. def _add_ns(path):
  2385. return self._xpath_ns(path, namespace)
  2386. def is_drm_protected(element):
  2387. return element.find(_add_ns('ContentProtection')) is not None
  2388. def extract_multisegment_info(element, ms_parent_info):
  2389. ms_info = ms_parent_info.copy()
  2390. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  2391. # common attributes and elements. We will only extract relevant
  2392. # for us.
  2393. def extract_common(source):
  2394. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  2395. if segment_timeline is not None:
  2396. s_e = segment_timeline.findall(_add_ns('S'))
  2397. if s_e:
  2398. ms_info['total_number'] = 0
  2399. ms_info['s'] = []
  2400. for s in s_e:
  2401. r = int(s.get('r', 0))
  2402. ms_info['total_number'] += 1 + r
  2403. ms_info['s'].append({
  2404. 't': int(s.get('t', 0)),
  2405. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  2406. 'd': int(s.attrib['d']),
  2407. 'r': r,
  2408. })
  2409. start_number = source.get('startNumber')
  2410. if start_number:
  2411. ms_info['start_number'] = int(start_number)
  2412. timescale = source.get('timescale')
  2413. if timescale:
  2414. ms_info['timescale'] = int(timescale)
  2415. segment_duration = source.get('duration')
  2416. if segment_duration:
  2417. ms_info['segment_duration'] = float(segment_duration)
  2418. def extract_Initialization(source):
  2419. initialization = source.find(_add_ns('Initialization'))
  2420. if initialization is not None:
  2421. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  2422. segment_list = element.find(_add_ns('SegmentList'))
  2423. if segment_list is not None:
  2424. extract_common(segment_list)
  2425. extract_Initialization(segment_list)
  2426. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  2427. if segment_urls_e:
  2428. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  2429. else:
  2430. segment_template = element.find(_add_ns('SegmentTemplate'))
  2431. if segment_template is not None:
  2432. extract_common(segment_template)
  2433. media = segment_template.get('media')
  2434. if media:
  2435. ms_info['media'] = media
  2436. initialization = segment_template.get('initialization')
  2437. if initialization:
  2438. ms_info['initialization'] = initialization
  2439. else:
  2440. extract_Initialization(segment_template)
  2441. return ms_info
  2442. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  2443. stream_numbers = collections.defaultdict(int)
  2444. for period_idx, period in enumerate(mpd_doc.findall(_add_ns('Period'))):
  2445. period_entry = {
  2446. 'id': period.get('id', f'period-{period_idx}'),
  2447. 'formats': [],
  2448. 'subtitles': collections.defaultdict(list),
  2449. }
  2450. period_duration = parse_duration(period.get('duration')) or mpd_duration
  2451. period_ms_info = extract_multisegment_info(period, {
  2452. 'start_number': 1,
  2453. 'timescale': 1,
  2454. })
  2455. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  2456. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  2457. for representation in adaptation_set.findall(_add_ns('Representation')):
  2458. representation_attrib = adaptation_set.attrib.copy()
  2459. representation_attrib.update(representation.attrib)
  2460. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  2461. mime_type = representation_attrib['mimeType']
  2462. content_type = representation_attrib.get('contentType', mime_type.split('/')[0])
  2463. codec_str = representation_attrib.get('codecs', '')
  2464. # Some kind of binary subtitle found in some youtube livestreams
  2465. if mime_type == 'application/x-rawcc':
  2466. codecs = {'scodec': codec_str}
  2467. else:
  2468. codecs = parse_codecs(codec_str)
  2469. if content_type not in ('video', 'audio', 'text'):
  2470. if mime_type == 'image/jpeg':
  2471. content_type = mime_type
  2472. elif codecs.get('vcodec', 'none') != 'none':
  2473. content_type = 'video'
  2474. elif codecs.get('acodec', 'none') != 'none':
  2475. content_type = 'audio'
  2476. elif codecs.get('scodec', 'none') != 'none':
  2477. content_type = 'text'
  2478. elif mimetype2ext(mime_type) in ('tt', 'dfxp', 'ttml', 'xml', 'json'):
  2479. content_type = 'text'
  2480. else:
  2481. self.report_warning(f'Unknown MIME type {mime_type} in DASH manifest')
  2482. continue
  2483. base_url = ''
  2484. for element in (representation, adaptation_set, period, mpd_doc):
  2485. base_url_e = element.find(_add_ns('BaseURL'))
  2486. if try_call(lambda: base_url_e.text) is not None:
  2487. base_url = base_url_e.text + base_url
  2488. if re.match(r'^https?://', base_url):
  2489. break
  2490. if mpd_base_url and base_url.startswith('/'):
  2491. base_url = urllib.parse.urljoin(mpd_base_url, base_url)
  2492. elif mpd_base_url and not re.match(r'^https?://', base_url):
  2493. if not mpd_base_url.endswith('/'):
  2494. mpd_base_url += '/'
  2495. base_url = mpd_base_url + base_url
  2496. representation_id = representation_attrib.get('id')
  2497. lang = representation_attrib.get('lang')
  2498. url_el = representation.find(_add_ns('BaseURL'))
  2499. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  2500. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  2501. if representation_id is not None:
  2502. format_id = representation_id
  2503. else:
  2504. format_id = content_type
  2505. if mpd_id:
  2506. format_id = mpd_id + '-' + format_id
  2507. if content_type in ('video', 'audio'):
  2508. f = {
  2509. 'format_id': format_id,
  2510. 'manifest_url': mpd_url,
  2511. 'ext': mimetype2ext(mime_type),
  2512. 'width': int_or_none(representation_attrib.get('width')),
  2513. 'height': int_or_none(representation_attrib.get('height')),
  2514. 'tbr': float_or_none(bandwidth, 1000),
  2515. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  2516. 'fps': int_or_none(representation_attrib.get('frameRate')),
  2517. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  2518. 'format_note': f'DASH {content_type}',
  2519. 'filesize': filesize,
  2520. 'container': mimetype2ext(mime_type) + '_dash',
  2521. **codecs,
  2522. }
  2523. elif content_type == 'text':
  2524. f = {
  2525. 'ext': mimetype2ext(mime_type),
  2526. 'manifest_url': mpd_url,
  2527. 'filesize': filesize,
  2528. }
  2529. elif content_type == 'image/jpeg':
  2530. # See test case in VikiIE
  2531. # https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1
  2532. f = {
  2533. 'format_id': format_id,
  2534. 'ext': 'mhtml',
  2535. 'manifest_url': mpd_url,
  2536. 'format_note': 'DASH storyboards (jpeg)',
  2537. 'acodec': 'none',
  2538. 'vcodec': 'none',
  2539. }
  2540. if is_drm_protected(adaptation_set) or is_drm_protected(representation):
  2541. f['has_drm'] = True
  2542. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  2543. def prepare_template(template_name, identifiers):
  2544. tmpl = representation_ms_info[template_name]
  2545. if representation_id is not None:
  2546. tmpl = tmpl.replace('$RepresentationID$', representation_id)
  2547. # First of, % characters outside $...$ templates
  2548. # must be escaped by doubling for proper processing
  2549. # by % operator string formatting used further (see
  2550. # https://github.com/ytdl-org/youtube-dl/issues/16867).
  2551. t = ''
  2552. in_template = False
  2553. for c in tmpl:
  2554. t += c
  2555. if c == '$':
  2556. in_template = not in_template
  2557. elif c == '%' and not in_template:
  2558. t += c
  2559. # Next, $...$ templates are translated to their
  2560. # %(...) counterparts to be used with % operator
  2561. t = re.sub(r'\$({})\$'.format('|'.join(identifiers)), r'%(\1)d', t)
  2562. t = re.sub(r'\$({})%([^$]+)\$'.format('|'.join(identifiers)), r'%(\1)\2', t)
  2563. t.replace('$$', '$')
  2564. return t
  2565. # @initialization is a regular template like @media one
  2566. # so it should be handled just the same way (see
  2567. # https://github.com/ytdl-org/youtube-dl/issues/11605)
  2568. if 'initialization' in representation_ms_info:
  2569. initialization_template = prepare_template(
  2570. 'initialization',
  2571. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  2572. # $Time$ shall not be included for @initialization thus
  2573. # only $Bandwidth$ remains
  2574. ('Bandwidth', ))
  2575. representation_ms_info['initialization_url'] = initialization_template % {
  2576. 'Bandwidth': bandwidth,
  2577. }
  2578. def location_key(location):
  2579. return 'url' if re.match(r'^https?://', location) else 'path'
  2580. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  2581. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  2582. media_location_key = location_key(media_template)
  2583. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  2584. # can't be used at the same time
  2585. if '%(Number' in media_template and 's' not in representation_ms_info:
  2586. segment_duration = None
  2587. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  2588. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  2589. representation_ms_info['total_number'] = int(math.ceil(
  2590. float_or_none(period_duration, segment_duration, default=0)))
  2591. representation_ms_info['fragments'] = [{
  2592. media_location_key: media_template % {
  2593. 'Number': segment_number,
  2594. 'Bandwidth': bandwidth,
  2595. },
  2596. 'duration': segment_duration,
  2597. } for segment_number in range(
  2598. representation_ms_info['start_number'],
  2599. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  2600. else:
  2601. # $Number*$ or $Time$ in media template with S list available
  2602. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  2603. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  2604. representation_ms_info['fragments'] = []
  2605. segment_time = 0
  2606. segment_d = None
  2607. segment_number = representation_ms_info['start_number']
  2608. def add_segment_url():
  2609. segment_url = media_template % {
  2610. 'Time': segment_time,
  2611. 'Bandwidth': bandwidth,
  2612. 'Number': segment_number,
  2613. }
  2614. representation_ms_info['fragments'].append({
  2615. media_location_key: segment_url,
  2616. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  2617. })
  2618. for s in representation_ms_info['s']:
  2619. segment_time = s.get('t') or segment_time
  2620. segment_d = s['d']
  2621. add_segment_url()
  2622. segment_number += 1
  2623. for _ in range(s.get('r', 0)):
  2624. segment_time += segment_d
  2625. add_segment_url()
  2626. segment_number += 1
  2627. segment_time += segment_d
  2628. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  2629. # No media template,
  2630. # e.g. https://www.youtube.com/watch?v=iXZV5uAYMJI
  2631. # or any YouTube dashsegments video
  2632. fragments = []
  2633. segment_index = 0
  2634. timescale = representation_ms_info['timescale']
  2635. for s in representation_ms_info['s']:
  2636. duration = float_or_none(s['d'], timescale)
  2637. for _ in range(s.get('r', 0) + 1):
  2638. segment_uri = representation_ms_info['segment_urls'][segment_index]
  2639. fragments.append({
  2640. location_key(segment_uri): segment_uri,
  2641. 'duration': duration,
  2642. })
  2643. segment_index += 1
  2644. representation_ms_info['fragments'] = fragments
  2645. elif 'segment_urls' in representation_ms_info:
  2646. # Segment URLs with no SegmentTimeline
  2647. # E.g. https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  2648. # https://github.com/ytdl-org/youtube-dl/pull/14844
  2649. fragments = []
  2650. segment_duration = float_or_none(
  2651. representation_ms_info['segment_duration'],
  2652. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  2653. for segment_url in representation_ms_info['segment_urls']:
  2654. fragment = {
  2655. location_key(segment_url): segment_url,
  2656. }
  2657. if segment_duration:
  2658. fragment['duration'] = segment_duration
  2659. fragments.append(fragment)
  2660. representation_ms_info['fragments'] = fragments
  2661. # If there is a fragments key available then we correctly recognized fragmented media.
  2662. # Otherwise we will assume unfragmented media with direct access. Technically, such
  2663. # assumption is not necessarily correct since we may simply have no support for
  2664. # some forms of fragmented media renditions yet, but for now we'll use this fallback.
  2665. if 'fragments' in representation_ms_info:
  2666. f.update({
  2667. # NB: mpd_url may be empty when MPD manifest is parsed from a string
  2668. 'url': mpd_url or base_url,
  2669. 'fragment_base_url': base_url,
  2670. 'fragments': [],
  2671. 'protocol': 'http_dash_segments' if mime_type != 'image/jpeg' else 'mhtml',
  2672. })
  2673. if 'initialization_url' in representation_ms_info:
  2674. initialization_url = representation_ms_info['initialization_url']
  2675. if not f.get('url'):
  2676. f['url'] = initialization_url
  2677. f['fragments'].append({location_key(initialization_url): initialization_url})
  2678. f['fragments'].extend(representation_ms_info['fragments'])
  2679. if not period_duration:
  2680. period_duration = try_get(
  2681. representation_ms_info,
  2682. lambda r: sum(frag['duration'] for frag in r['fragments']), float)
  2683. else:
  2684. # Assuming direct URL to unfragmented media.
  2685. f['url'] = base_url
  2686. if content_type in ('video', 'audio', 'image/jpeg'):
  2687. f['manifest_stream_number'] = stream_numbers[f['url']]
  2688. stream_numbers[f['url']] += 1
  2689. period_entry['formats'].append(f)
  2690. elif content_type == 'text':
  2691. period_entry['subtitles'][lang or 'und'].append(f)
  2692. yield period_entry
  2693. def _extract_ism_formats(self, *args, **kwargs):
  2694. fmts, subs = self._extract_ism_formats_and_subtitles(*args, **kwargs)
  2695. if subs:
  2696. self._report_ignoring_subs('ISM')
  2697. return fmts
  2698. def _extract_ism_formats_and_subtitles(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  2699. if self.get_param('ignore_no_formats_error'):
  2700. fatal = False
  2701. res = self._download_xml_handle(
  2702. ism_url, video_id,
  2703. note='Downloading ISM manifest' if note is None else note,
  2704. errnote='Failed to download ISM manifest' if errnote is None else errnote,
  2705. fatal=fatal, data=data, headers=headers, query=query)
  2706. if res is False:
  2707. return [], {}
  2708. ism_doc, urlh = res
  2709. if ism_doc is None:
  2710. return [], {}
  2711. return self._parse_ism_formats_and_subtitles(ism_doc, urlh.url, ism_id)
  2712. def _parse_ism_formats_and_subtitles(self, ism_doc, ism_url, ism_id=None):
  2713. """
  2714. Parse formats from ISM manifest.
  2715. References:
  2716. 1. [MS-SSTR]: Smooth Streaming Protocol,
  2717. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  2718. """
  2719. if ism_doc.get('IsLive') == 'TRUE':
  2720. return [], {}
  2721. duration = int(ism_doc.attrib['Duration'])
  2722. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  2723. formats = []
  2724. subtitles = {}
  2725. for stream in ism_doc.findall('StreamIndex'):
  2726. stream_type = stream.get('Type')
  2727. if stream_type not in ('video', 'audio', 'text'):
  2728. continue
  2729. url_pattern = stream.attrib['Url']
  2730. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  2731. stream_name = stream.get('Name')
  2732. stream_language = stream.get('Language', 'und')
  2733. for track in stream.findall('QualityLevel'):
  2734. KNOWN_TAGS = {'255': 'AACL', '65534': 'EC-3'}
  2735. fourcc = track.get('FourCC') or KNOWN_TAGS.get(track.get('AudioTag'))
  2736. # TODO: add support for WVC1 and WMAP
  2737. if fourcc not in ('H264', 'AVC1', 'AACL', 'TTML', 'EC-3'):
  2738. self.report_warning(f'{fourcc} is not a supported codec')
  2739. continue
  2740. tbr = int(track.attrib['Bitrate']) // 1000
  2741. # [1] does not mention Width and Height attributes. However,
  2742. # they're often present while MaxWidth and MaxHeight are
  2743. # missing, so should be used as fallbacks
  2744. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  2745. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  2746. sampling_rate = int_or_none(track.get('SamplingRate'))
  2747. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  2748. track_url_pattern = urllib.parse.urljoin(ism_url, track_url_pattern)
  2749. fragments = []
  2750. fragment_ctx = {
  2751. 'time': 0,
  2752. }
  2753. stream_fragments = stream.findall('c')
  2754. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  2755. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  2756. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  2757. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  2758. if not fragment_ctx['duration']:
  2759. try:
  2760. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  2761. except IndexError:
  2762. next_fragment_time = duration
  2763. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  2764. for _ in range(fragment_repeat):
  2765. fragments.append({
  2766. 'url': re.sub(r'{start[ _]time}', str(fragment_ctx['time']), track_url_pattern),
  2767. 'duration': fragment_ctx['duration'] / stream_timescale,
  2768. })
  2769. fragment_ctx['time'] += fragment_ctx['duration']
  2770. if stream_type == 'text':
  2771. subtitles.setdefault(stream_language, []).append({
  2772. 'ext': 'ismt',
  2773. 'protocol': 'ism',
  2774. 'url': ism_url,
  2775. 'manifest_url': ism_url,
  2776. 'fragments': fragments,
  2777. '_download_params': {
  2778. 'stream_type': stream_type,
  2779. 'duration': duration,
  2780. 'timescale': stream_timescale,
  2781. 'fourcc': fourcc,
  2782. 'language': stream_language,
  2783. 'codec_private_data': track.get('CodecPrivateData'),
  2784. },
  2785. })
  2786. elif stream_type in ('video', 'audio'):
  2787. formats.append({
  2788. 'format_id': join_nonempty(ism_id, stream_name, tbr),
  2789. 'url': ism_url,
  2790. 'manifest_url': ism_url,
  2791. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  2792. 'width': width,
  2793. 'height': height,
  2794. 'tbr': tbr,
  2795. 'asr': sampling_rate,
  2796. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  2797. 'acodec': 'none' if stream_type == 'video' else fourcc,
  2798. 'protocol': 'ism',
  2799. 'fragments': fragments,
  2800. 'has_drm': ism_doc.find('Protection') is not None,
  2801. 'language': stream_language,
  2802. 'audio_channels': int_or_none(track.get('Channels')),
  2803. '_download_params': {
  2804. 'stream_type': stream_type,
  2805. 'duration': duration,
  2806. 'timescale': stream_timescale,
  2807. 'width': width or 0,
  2808. 'height': height or 0,
  2809. 'fourcc': fourcc,
  2810. 'language': stream_language,
  2811. 'codec_private_data': track.get('CodecPrivateData'),
  2812. 'sampling_rate': sampling_rate,
  2813. 'channels': int_or_none(track.get('Channels', 2)),
  2814. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  2815. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  2816. },
  2817. })
  2818. return formats, subtitles
  2819. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8_native', mpd_id=None, preference=None, quality=None):
  2820. def absolute_url(item_url):
  2821. return urljoin(base_url, item_url)
  2822. def parse_content_type(content_type):
  2823. if not content_type:
  2824. return {}
  2825. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  2826. if ctr:
  2827. mimetype, codecs = ctr.groups()
  2828. f = parse_codecs(codecs)
  2829. f['ext'] = mimetype2ext(mimetype)
  2830. return f
  2831. return {}
  2832. def _media_formats(src, cur_media_type, type_info=None):
  2833. type_info = type_info or {}
  2834. full_url = absolute_url(src)
  2835. ext = type_info.get('ext') or determine_ext(full_url)
  2836. if ext == 'm3u8':
  2837. is_plain_url = False
  2838. formats = self._extract_m3u8_formats(
  2839. full_url, video_id, ext='mp4',
  2840. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  2841. preference=preference, quality=quality, fatal=False)
  2842. elif ext == 'mpd':
  2843. is_plain_url = False
  2844. formats = self._extract_mpd_formats(
  2845. full_url, video_id, mpd_id=mpd_id, fatal=False)
  2846. else:
  2847. is_plain_url = True
  2848. formats = [{
  2849. 'url': full_url,
  2850. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  2851. 'ext': ext,
  2852. }]
  2853. return is_plain_url, formats
  2854. entries = []
  2855. # amp-video and amp-audio are very similar to their HTML5 counterparts
  2856. # so we will include them right here (see
  2857. # https://www.ampproject.org/docs/reference/components/amp-video)
  2858. # For dl8-* tags see https://delight-vr.com/documentation/dl8-video/
  2859. _MEDIA_TAG_NAME_RE = r'(?:(?:amp|dl8(?:-live)?)-)?(video|audio)'
  2860. media_tags = [(media_tag, media_tag_name, media_type, '')
  2861. for media_tag, media_tag_name, media_type
  2862. in re.findall(rf'(?s)(<({_MEDIA_TAG_NAME_RE})[^>]*/>)', webpage)]
  2863. media_tags.extend(re.findall(
  2864. # We only allow video|audio followed by a whitespace or '>'.
  2865. # Allowing more characters may end up in significant slow down (see
  2866. # https://github.com/ytdl-org/youtube-dl/issues/11979,
  2867. # e.g. http://www.porntrex.com/maps/videositemap.xml).
  2868. rf'(?s)(<(?P<tag>{_MEDIA_TAG_NAME_RE})(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  2869. for media_tag, _, media_type, media_content in media_tags:
  2870. media_info = {
  2871. 'formats': [],
  2872. 'subtitles': {},
  2873. }
  2874. media_attributes = extract_attributes(media_tag)
  2875. src = strip_or_none(dict_get(media_attributes, ('src', 'data-video-src', 'data-src', 'data-source')))
  2876. if src:
  2877. f = parse_content_type(media_attributes.get('type'))
  2878. _, formats = _media_formats(src, media_type, f)
  2879. media_info['formats'].extend(formats)
  2880. media_info['thumbnail'] = absolute_url(media_attributes.get('poster'))
  2881. if media_content:
  2882. for source_tag in re.findall(r'<source[^>]+>', media_content):
  2883. s_attr = extract_attributes(source_tag)
  2884. # data-video-src and data-src are non standard but seen
  2885. # several times in the wild
  2886. src = strip_or_none(dict_get(s_attr, ('src', 'data-video-src', 'data-src', 'data-source')))
  2887. if not src:
  2888. continue
  2889. f = parse_content_type(s_attr.get('type'))
  2890. is_plain_url, formats = _media_formats(src, media_type, f)
  2891. if is_plain_url:
  2892. # width, height, res, label and title attributes are
  2893. # all not standard but seen several times in the wild
  2894. labels = [
  2895. s_attr.get(lbl)
  2896. for lbl in ('label', 'title')
  2897. if str_or_none(s_attr.get(lbl))
  2898. ]
  2899. width = int_or_none(s_attr.get('width'))
  2900. height = (int_or_none(s_attr.get('height'))
  2901. or int_or_none(s_attr.get('res')))
  2902. if not width or not height:
  2903. for lbl in labels:
  2904. resolution = parse_resolution(lbl)
  2905. if not resolution:
  2906. continue
  2907. width = width or resolution.get('width')
  2908. height = height or resolution.get('height')
  2909. for lbl in labels:
  2910. tbr = parse_bitrate(lbl)
  2911. if tbr:
  2912. break
  2913. else:
  2914. tbr = None
  2915. f.update({
  2916. 'width': width,
  2917. 'height': height,
  2918. 'tbr': tbr,
  2919. 'format_id': s_attr.get('label') or s_attr.get('title'),
  2920. })
  2921. f.update(formats[0])
  2922. media_info['formats'].append(f)
  2923. else:
  2924. media_info['formats'].extend(formats)
  2925. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2926. track_attributes = extract_attributes(track_tag)
  2927. kind = track_attributes.get('kind')
  2928. if not kind or kind in ('subtitles', 'captions'):
  2929. src = strip_or_none(track_attributes.get('src'))
  2930. if not src:
  2931. continue
  2932. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2933. media_info['subtitles'].setdefault(lang, []).append({
  2934. 'url': absolute_url(src),
  2935. })
  2936. for f in media_info['formats']:
  2937. f.setdefault('http_headers', {})['Referer'] = base_url
  2938. if media_info['formats'] or media_info['subtitles']:
  2939. entries.append(media_info)
  2940. return entries
  2941. def _extract_akamai_formats(self, *args, **kwargs):
  2942. fmts, subs = self._extract_akamai_formats_and_subtitles(*args, **kwargs)
  2943. if subs:
  2944. self._report_ignoring_subs('akamai')
  2945. return fmts
  2946. def _extract_akamai_formats_and_subtitles(self, manifest_url, video_id, hosts={}):
  2947. signed = 'hdnea=' in manifest_url
  2948. if not signed:
  2949. # https://learn.akamai.com/en-us/webhelp/media-services-on-demand/stream-packaging-user-guide/GUID-BE6C0F73-1E06-483B-B0EA-57984B91B7F9.html
  2950. manifest_url = re.sub(
  2951. r'(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?',
  2952. '', manifest_url).strip('?')
  2953. formats = []
  2954. subtitles = {}
  2955. hdcore_sign = 'hdcore=3.7.0'
  2956. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  2957. hds_host = hosts.get('hds')
  2958. if hds_host:
  2959. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  2960. if 'hdcore=' not in f4m_url:
  2961. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  2962. f4m_formats = self._extract_f4m_formats(
  2963. f4m_url, video_id, f4m_id='hds', fatal=False)
  2964. for entry in f4m_formats:
  2965. entry.update({'extra_param_to_segment_url': hdcore_sign})
  2966. formats.extend(f4m_formats)
  2967. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  2968. hls_host = hosts.get('hls')
  2969. if hls_host:
  2970. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  2971. m3u8_formats, m3u8_subtitles = self._extract_m3u8_formats_and_subtitles(
  2972. m3u8_url, video_id, 'mp4', 'm3u8_native',
  2973. m3u8_id='hls', fatal=False)
  2974. formats.extend(m3u8_formats)
  2975. subtitles = self._merge_subtitles(subtitles, m3u8_subtitles)
  2976. http_host = hosts.get('http')
  2977. if http_host and m3u8_formats and not signed:
  2978. REPL_REGEX = r'https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+'
  2979. qualities = re.match(REPL_REGEX, m3u8_url).group(2).split(',')
  2980. qualities_length = len(qualities)
  2981. if len(m3u8_formats) in (qualities_length, qualities_length + 1):
  2982. i = 0
  2983. for f in m3u8_formats:
  2984. if f['vcodec'] != 'none':
  2985. for protocol in ('http', 'https'):
  2986. http_f = f.copy()
  2987. del http_f['manifest_url']
  2988. http_url = re.sub(
  2989. REPL_REGEX, protocol + fr'://{http_host}/\g<1>{qualities[i]}\3', f['url'])
  2990. http_f.update({
  2991. 'format_id': http_f['format_id'].replace('hls-', protocol + '-'),
  2992. 'url': http_url,
  2993. 'protocol': protocol,
  2994. })
  2995. formats.append(http_f)
  2996. i += 1
  2997. return formats, subtitles
  2998. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  2999. query = urllib.parse.urlparse(url).query
  3000. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  3001. mobj = re.search(
  3002. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  3003. url_base = mobj.group('url')
  3004. http_base_url = '{}{}:{}'.format('http', mobj.group('s') or '', url_base)
  3005. formats = []
  3006. def manifest_url(manifest):
  3007. m_url = f'{http_base_url}/{manifest}'
  3008. if query:
  3009. m_url += f'?{query}'
  3010. return m_url
  3011. if 'm3u8' not in skip_protocols:
  3012. formats.extend(self._extract_m3u8_formats(
  3013. manifest_url('playlist.m3u8'), video_id, 'mp4',
  3014. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  3015. if 'f4m' not in skip_protocols:
  3016. formats.extend(self._extract_f4m_formats(
  3017. manifest_url('manifest.f4m'),
  3018. video_id, f4m_id='hds', fatal=False))
  3019. if 'dash' not in skip_protocols:
  3020. formats.extend(self._extract_mpd_formats(
  3021. manifest_url('manifest.mpd'),
  3022. video_id, mpd_id='dash', fatal=False))
  3023. if re.search(r'(?:/smil:|\.smil)', url_base):
  3024. if 'smil' not in skip_protocols:
  3025. rtmp_formats = self._extract_smil_formats(
  3026. manifest_url('jwplayer.smil'),
  3027. video_id, fatal=False)
  3028. for rtmp_format in rtmp_formats:
  3029. rtsp_format = rtmp_format.copy()
  3030. rtsp_format['url'] = '{}/{}'.format(rtmp_format['url'], rtmp_format['play_path'])
  3031. del rtsp_format['play_path']
  3032. del rtsp_format['ext']
  3033. rtsp_format.update({
  3034. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  3035. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  3036. 'protocol': 'rtsp',
  3037. })
  3038. formats.extend([rtmp_format, rtsp_format])
  3039. else:
  3040. for protocol in ('rtmp', 'rtsp'):
  3041. if protocol not in skip_protocols:
  3042. formats.append({
  3043. 'url': f'{protocol}:{url_base}',
  3044. 'format_id': protocol,
  3045. 'protocol': protocol,
  3046. })
  3047. return formats
  3048. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  3049. return self._search_json(
  3050. r'''(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)''',
  3051. webpage, 'JWPlayer data', video_id,
  3052. # must be a {...} or sequence, ending
  3053. contains_pattern=r'\{(?s:.*)}(?(load)(?:\s*,\s*\{(?s:.*)})*)', end_pattern=r'(?(load)\]|\))',
  3054. transform_source=transform_source, default=None)
  3055. def _extract_jwplayer_data(self, webpage, video_id, *args, transform_source=js_to_json, **kwargs):
  3056. jwplayer_data = self._find_jwplayer_data(
  3057. webpage, video_id, transform_source=transform_source)
  3058. return self._parse_jwplayer_data(
  3059. jwplayer_data, video_id, *args, **kwargs)
  3060. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  3061. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3062. entries = []
  3063. if not isinstance(jwplayer_data, dict):
  3064. return entries
  3065. playlist_items = jwplayer_data.get('playlist')
  3066. # JWPlayer backward compatibility: single playlist item/flattened playlists
  3067. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  3068. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  3069. if not isinstance(playlist_items, list):
  3070. playlist_items = (playlist_items or jwplayer_data, )
  3071. for video_data in playlist_items:
  3072. if not isinstance(video_data, dict):
  3073. continue
  3074. # JWPlayer backward compatibility: flattened sources
  3075. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  3076. if 'sources' not in video_data:
  3077. video_data['sources'] = [video_data]
  3078. this_video_id = video_id or video_data['mediaid']
  3079. formats = self._parse_jwplayer_formats(
  3080. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  3081. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  3082. subtitles = {}
  3083. for track in traverse_obj(video_data, (
  3084. 'tracks', lambda _, v: v['kind'].lower() in ('captions', 'subtitles'))):
  3085. track_url = urljoin(base_url, track.get('file'))
  3086. if not track_url:
  3087. continue
  3088. subtitles.setdefault(track.get('label') or 'en', []).append({
  3089. 'url': self._proto_relative_url(track_url),
  3090. })
  3091. entry = {
  3092. 'id': this_video_id,
  3093. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  3094. 'description': clean_html(video_data.get('description')),
  3095. 'thumbnail': urljoin(base_url, self._proto_relative_url(video_data.get('image'))),
  3096. 'timestamp': int_or_none(video_data.get('pubdate')),
  3097. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  3098. 'subtitles': subtitles,
  3099. 'alt_title': clean_html(video_data.get('subtitle')), # attributes used e.g. by Tele5 ...
  3100. 'genre': clean_html(video_data.get('genre')),
  3101. 'channel': clean_html(dict_get(video_data, ('category', 'channel'))),
  3102. 'season_number': int_or_none(video_data.get('season')),
  3103. 'episode_number': int_or_none(video_data.get('episode')),
  3104. 'release_year': int_or_none(video_data.get('releasedate')),
  3105. 'age_limit': int_or_none(video_data.get('age_restriction')),
  3106. }
  3107. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  3108. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  3109. entry.update({
  3110. '_type': 'url_transparent',
  3111. 'url': formats[0]['url'],
  3112. })
  3113. else:
  3114. entry['formats'] = formats
  3115. entries.append(entry)
  3116. if len(entries) == 1:
  3117. return entries[0]
  3118. else:
  3119. return self.playlist_result(entries)
  3120. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  3121. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3122. urls = set()
  3123. formats = []
  3124. for source in jwplayer_sources_data:
  3125. if not isinstance(source, dict):
  3126. continue
  3127. source_url = urljoin(
  3128. base_url, self._proto_relative_url(source.get('file')))
  3129. if not source_url or source_url in urls:
  3130. continue
  3131. urls.add(source_url)
  3132. source_type = source.get('type') or ''
  3133. ext = mimetype2ext(source_type) or determine_ext(source_url)
  3134. if source_type == 'hls' or ext == 'm3u8' or 'format=m3u8-aapl' in source_url:
  3135. formats.extend(self._extract_m3u8_formats(
  3136. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  3137. m3u8_id=m3u8_id, fatal=False))
  3138. elif source_type == 'dash' or ext == 'mpd' or 'format=mpd-time-csf' in source_url:
  3139. formats.extend(self._extract_mpd_formats(
  3140. source_url, video_id, mpd_id=mpd_id, fatal=False))
  3141. elif ext == 'smil':
  3142. formats.extend(self._extract_smil_formats(
  3143. source_url, video_id, fatal=False))
  3144. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  3145. elif source_type.startswith('audio') or ext in (
  3146. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  3147. formats.append({
  3148. 'url': source_url,
  3149. 'vcodec': 'none',
  3150. 'ext': ext,
  3151. })
  3152. else:
  3153. format_id = str_or_none(source.get('label'))
  3154. height = int_or_none(source.get('height'))
  3155. if height is None and format_id:
  3156. # Often no height is provided but there is a label in
  3157. # format like "1080p", "720p SD", or 1080.
  3158. height = parse_resolution(format_id).get('height')
  3159. a_format = {
  3160. 'url': source_url,
  3161. 'width': int_or_none(source.get('width')),
  3162. 'height': height,
  3163. 'tbr': int_or_none(source.get('bitrate'), scale=1000),
  3164. 'filesize': int_or_none(source.get('filesize')),
  3165. 'ext': ext,
  3166. 'format_id': format_id,
  3167. }
  3168. if source_url.startswith('rtmp'):
  3169. a_format['ext'] = 'flv'
  3170. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  3171. # of jwplayer.flash.swf
  3172. rtmp_url_parts = re.split(
  3173. r'((?:mp4|mp3|flv):)', source_url, maxsplit=1)
  3174. if len(rtmp_url_parts) == 3:
  3175. rtmp_url, prefix, play_path = rtmp_url_parts
  3176. a_format.update({
  3177. 'url': rtmp_url,
  3178. 'play_path': prefix + play_path,
  3179. })
  3180. if rtmp_params:
  3181. a_format.update(rtmp_params)
  3182. formats.append(a_format)
  3183. return formats
  3184. def _live_title(self, name):
  3185. self._downloader.deprecation_warning('yt_dlp.InfoExtractor._live_title is deprecated and does not work as expected')
  3186. return name
  3187. def _int(self, v, name, fatal=False, **kwargs):
  3188. res = int_or_none(v, **kwargs)
  3189. if res is None:
  3190. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3191. if fatal:
  3192. raise ExtractorError(msg)
  3193. else:
  3194. self.report_warning(msg)
  3195. return res
  3196. def _float(self, v, name, fatal=False, **kwargs):
  3197. res = float_or_none(v, **kwargs)
  3198. if res is None:
  3199. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3200. if fatal:
  3201. raise ExtractorError(msg)
  3202. else:
  3203. self.report_warning(msg)
  3204. return res
  3205. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  3206. path='/', secure=False, discard=False, rest={}, **kwargs):
  3207. cookie = http.cookiejar.Cookie(
  3208. 0, name, value, port, port is not None, domain, True,
  3209. domain.startswith('.'), path, True, secure, expire_time,
  3210. discard, None, None, rest)
  3211. self.cookiejar.set_cookie(cookie)
  3212. def _get_cookies(self, url):
  3213. """ Return a http.cookies.SimpleCookie with the cookies for the url """
  3214. return LenientSimpleCookie(self._downloader.cookiejar.get_cookie_header(url))
  3215. def _apply_first_set_cookie_header(self, url_handle, cookie):
  3216. """
  3217. Apply first Set-Cookie header instead of the last. Experimental.
  3218. Some sites (e.g. [1-3]) may serve two cookies under the same name
  3219. in Set-Cookie header and expect the first (old) one to be set rather
  3220. than second (new). However, as of RFC6265 the newer one cookie
  3221. should be set into cookie store what actually happens.
  3222. We will workaround this issue by resetting the cookie to
  3223. the first one manually.
  3224. 1. https://new.vk.com/
  3225. 2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
  3226. 3. https://learning.oreilly.com/
  3227. """
  3228. for header, cookies in url_handle.headers.items():
  3229. if header.lower() != 'set-cookie':
  3230. continue
  3231. cookies = cookies.encode('iso-8859-1').decode('utf-8')
  3232. cookie_value = re.search(
  3233. rf'{cookie}=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)', cookies)
  3234. if cookie_value:
  3235. value, domain = cookie_value.groups()
  3236. self._set_cookie(domain, cookie, value)
  3237. break
  3238. @classmethod
  3239. def get_testcases(cls, include_onlymatching=False):
  3240. # Do not look in super classes
  3241. t = vars(cls).get('_TEST')
  3242. if t:
  3243. assert not hasattr(cls, '_TESTS'), f'{cls.ie_key()}IE has _TEST and _TESTS'
  3244. tests = [t]
  3245. else:
  3246. tests = vars(cls).get('_TESTS', [])
  3247. for t in tests:
  3248. if not include_onlymatching and t.get('only_matching', False):
  3249. continue
  3250. t['name'] = cls.ie_key()
  3251. yield t
  3252. if getattr(cls, '__wrapped__', None):
  3253. yield from cls.__wrapped__.get_testcases(include_onlymatching)
  3254. @classmethod
  3255. def get_webpage_testcases(cls):
  3256. tests = vars(cls).get('_WEBPAGE_TESTS', [])
  3257. for t in tests:
  3258. t['name'] = cls.ie_key()
  3259. yield t
  3260. if getattr(cls, '__wrapped__', None):
  3261. yield from cls.__wrapped__.get_webpage_testcases()
  3262. @classproperty(cache=True)
  3263. def age_limit(cls):
  3264. """Get age limit from the testcases"""
  3265. return max(traverse_obj(
  3266. (*cls.get_testcases(include_onlymatching=False), *cls.get_webpage_testcases()),
  3267. (..., (('playlist', 0), None), 'info_dict', 'age_limit')) or [0])
  3268. @classproperty(cache=True)
  3269. def _RETURN_TYPE(cls):
  3270. """What the extractor returns: "video", "playlist", "any", or None (Unknown)"""
  3271. tests = tuple(cls.get_testcases(include_onlymatching=False))
  3272. if not tests:
  3273. return None
  3274. elif not any(k.startswith('playlist') for test in tests for k in test):
  3275. return 'video'
  3276. elif all(any(k.startswith('playlist') for k in test) for test in tests):
  3277. return 'playlist'
  3278. return 'any'
  3279. @classmethod
  3280. def is_single_video(cls, url):
  3281. """Returns whether the URL is of a single video, None if unknown"""
  3282. if cls.suitable(url):
  3283. return {'video': True, 'playlist': False}.get(cls._RETURN_TYPE)
  3284. @classmethod
  3285. def is_suitable(cls, age_limit):
  3286. """Test whether the extractor is generally suitable for the given age limit"""
  3287. return not age_restricted(cls.age_limit, age_limit)
  3288. @classmethod
  3289. def description(cls, *, markdown=True, search_examples=None):
  3290. """Description of the extractor"""
  3291. desc = ''
  3292. if cls._NETRC_MACHINE:
  3293. if markdown:
  3294. desc += f' [*{cls._NETRC_MACHINE}*](## "netrc machine")'
  3295. else:
  3296. desc += f' [{cls._NETRC_MACHINE}]'
  3297. if cls.IE_DESC is False:
  3298. desc += ' [HIDDEN]'
  3299. elif cls.IE_DESC:
  3300. desc += f' {cls.IE_DESC}'
  3301. if cls.SEARCH_KEY:
  3302. desc += f'{";" if cls.IE_DESC else ""} "{cls.SEARCH_KEY}:" prefix'
  3303. if search_examples:
  3304. _COUNTS = ('', '5', '10', 'all')
  3305. desc += f' (e.g. "{cls.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(search_examples)}")'
  3306. if not cls.working():
  3307. desc += ' (**Currently broken**)' if markdown else ' (Currently broken)'
  3308. # Escape emojis. Ref: https://github.com/github/markup/issues/1153
  3309. name = (' - **{}**'.format(re.sub(r':(\w+:)', ':\u200B\\g<1>', cls.IE_NAME))) if markdown else cls.IE_NAME
  3310. return f'{name}:{desc}' if desc else name
  3311. def extract_subtitles(self, *args, **kwargs):
  3312. if (self.get_param('writesubtitles', False)
  3313. or self.get_param('listsubtitles')):
  3314. return self._get_subtitles(*args, **kwargs)
  3315. return {}
  3316. def _get_subtitles(self, *args, **kwargs):
  3317. raise NotImplementedError('This method must be implemented by subclasses')
  3318. class CommentsDisabled(Exception):
  3319. """Raise in _get_comments if comments are disabled for the video"""
  3320. def extract_comments(self, *args, **kwargs):
  3321. if not self.get_param('getcomments'):
  3322. return None
  3323. generator = self._get_comments(*args, **kwargs)
  3324. def extractor():
  3325. comments = []
  3326. interrupted = True
  3327. try:
  3328. while True:
  3329. comments.append(next(generator))
  3330. except StopIteration:
  3331. interrupted = False
  3332. except KeyboardInterrupt:
  3333. self.to_screen('Interrupted by user')
  3334. except self.CommentsDisabled:
  3335. return {'comments': None, 'comment_count': None}
  3336. except Exception as e:
  3337. if self.get_param('ignoreerrors') is not True:
  3338. raise
  3339. self._downloader.report_error(e)
  3340. comment_count = len(comments)
  3341. self.to_screen(f'Extracted {comment_count} comments')
  3342. return {
  3343. 'comments': comments,
  3344. 'comment_count': None if interrupted else comment_count,
  3345. }
  3346. return extractor
  3347. def _get_comments(self, *args, **kwargs):
  3348. raise NotImplementedError('This method must be implemented by subclasses')
  3349. @staticmethod
  3350. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  3351. """ Merge subtitle items for one language. Items with duplicated URLs/data
  3352. will be dropped. """
  3353. list1_data = {(item.get('url'), item.get('data')) for item in subtitle_list1}
  3354. ret = list(subtitle_list1)
  3355. ret.extend(item for item in subtitle_list2 if (item.get('url'), item.get('data')) not in list1_data)
  3356. return ret
  3357. @classmethod
  3358. def _merge_subtitles(cls, *dicts, target=None):
  3359. """ Merge subtitle dictionaries, language by language. """
  3360. if target is None:
  3361. target = {}
  3362. for d in dicts:
  3363. for lang, subs in d.items():
  3364. target[lang] = cls._merge_subtitle_items(target.get(lang, []), subs)
  3365. return target
  3366. def extract_automatic_captions(self, *args, **kwargs):
  3367. if (self.get_param('writeautomaticsub', False)
  3368. or self.get_param('listsubtitles')):
  3369. return self._get_automatic_captions(*args, **kwargs)
  3370. return {}
  3371. def _get_automatic_captions(self, *args, **kwargs):
  3372. raise NotImplementedError('This method must be implemented by subclasses')
  3373. @functools.cached_property
  3374. def _cookies_passed(self):
  3375. """Whether cookies have been passed to YoutubeDL"""
  3376. return self.get_param('cookiefile') is not None or self.get_param('cookiesfrombrowser') is not None
  3377. def mark_watched(self, *args, **kwargs):
  3378. if not self.get_param('mark_watched', False):
  3379. return
  3380. if self.supports_login() and self._get_login_info()[0] is not None or self._cookies_passed:
  3381. self._mark_watched(*args, **kwargs)
  3382. def _mark_watched(self, *args, **kwargs):
  3383. raise NotImplementedError('This method must be implemented by subclasses')
  3384. def geo_verification_headers(self):
  3385. headers = {}
  3386. geo_verification_proxy = self.get_param('geo_verification_proxy')
  3387. if geo_verification_proxy:
  3388. headers['Ytdl-request-proxy'] = geo_verification_proxy
  3389. return headers
  3390. @staticmethod
  3391. def _generic_id(url):
  3392. return urllib.parse.unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  3393. def _generic_title(self, url='', webpage='', *, default=None):
  3394. return (self._og_search_title(webpage, default=None)
  3395. or self._html_extract_title(webpage, default=None)
  3396. or urllib.parse.unquote(os.path.splitext(url_basename(url))[0])
  3397. or default)
  3398. def _extract_chapters_helper(self, chapter_list, start_function, title_function, duration, strict=True):
  3399. if not duration:
  3400. return
  3401. chapter_list = [{
  3402. 'start_time': start_function(chapter),
  3403. 'title': title_function(chapter),
  3404. } for chapter in chapter_list or []]
  3405. if strict:
  3406. warn = self.report_warning
  3407. else:
  3408. warn = self.write_debug
  3409. chapter_list.sort(key=lambda c: c['start_time'] or 0)
  3410. chapters = [{'start_time': 0}]
  3411. for idx, chapter in enumerate(chapter_list):
  3412. if chapter['start_time'] is None:
  3413. warn(f'Incomplete chapter {idx}')
  3414. elif chapters[-1]['start_time'] <= chapter['start_time'] <= duration:
  3415. chapters.append(chapter)
  3416. elif chapter not in chapters:
  3417. issue = (f'{chapter["start_time"]} > {duration}' if chapter['start_time'] > duration
  3418. else f'{chapter["start_time"]} < {chapters[-1]["start_time"]}')
  3419. warn(f'Invalid start time ({issue}) for chapter "{chapter["title"]}"')
  3420. return chapters[1:]
  3421. def _extract_chapters_from_description(self, description, duration):
  3422. duration_re = r'(?:\d+:)?\d{1,2}:\d{2}'
  3423. sep_re = r'(?m)^\s*(%s)\b\W*\s(%s)\s*$'
  3424. return self._extract_chapters_helper(
  3425. re.findall(sep_re % (duration_re, r'.+?'), description or ''),
  3426. start_function=lambda x: parse_duration(x[0]), title_function=lambda x: x[1],
  3427. duration=duration, strict=False) or self._extract_chapters_helper(
  3428. re.findall(sep_re % (r'.+?', duration_re), description or ''),
  3429. start_function=lambda x: parse_duration(x[1]), title_function=lambda x: x[0],
  3430. duration=duration, strict=False)
  3431. @staticmethod
  3432. def _availability(is_private=None, needs_premium=None, needs_subscription=None, needs_auth=None, is_unlisted=None):
  3433. all_known = all(
  3434. x is not None for x in
  3435. (is_private, needs_premium, needs_subscription, needs_auth, is_unlisted))
  3436. return (
  3437. 'private' if is_private
  3438. else 'premium_only' if needs_premium
  3439. else 'subscriber_only' if needs_subscription
  3440. else 'needs_auth' if needs_auth
  3441. else 'unlisted' if is_unlisted
  3442. else 'public' if all_known
  3443. else None)
  3444. def _configuration_arg(self, key, default=NO_DEFAULT, *, ie_key=None, casesense=False):
  3445. '''
  3446. @returns A list of values for the extractor argument given by "key"
  3447. or "default" if no such key is present
  3448. @param default The default value to return when the key is not present (default: [])
  3449. @param casesense When false, the values are converted to lower case
  3450. '''
  3451. ie_key = ie_key if isinstance(ie_key, str) else (ie_key or self).ie_key()
  3452. val = traverse_obj(self._downloader.params, ('extractor_args', ie_key.lower(), key))
  3453. if val is None:
  3454. return [] if default is NO_DEFAULT else default
  3455. return list(val) if casesense else [x.lower() for x in val]
  3456. def _yes_playlist(self, playlist_id, video_id, smuggled_data=None, *, playlist_label='playlist', video_label='video'):
  3457. if not playlist_id or not video_id:
  3458. return not video_id
  3459. no_playlist = (smuggled_data or {}).get('force_noplaylist')
  3460. if no_playlist is not None:
  3461. return not no_playlist
  3462. video_id = '' if video_id is True else f' {video_id}'
  3463. playlist_id = '' if playlist_id is True else f' {playlist_id}'
  3464. if self.get_param('noplaylist'):
  3465. self.to_screen(f'Downloading just the {video_label}{video_id} because of --no-playlist')
  3466. return False
  3467. self.to_screen(f'Downloading {playlist_label}{playlist_id} - add --no-playlist to download just the {video_label}{video_id}')
  3468. return True
  3469. def _error_or_warning(self, err, _count=None, _retries=0, *, fatal=True):
  3470. RetryManager.report_retry(
  3471. err, _count or int(fatal), _retries,
  3472. info=self.to_screen, warn=self.report_warning, error=None if fatal else self.report_warning,
  3473. sleep_func=self.get_param('retry_sleep_functions', {}).get('extractor'))
  3474. def RetryManager(self, **kwargs):
  3475. return RetryManager(self.get_param('extractor_retries', 3), self._error_or_warning, **kwargs)
  3476. def _extract_generic_embeds(self, url, *args, info_dict={}, note='Extracting generic embeds', **kwargs):
  3477. display_id = traverse_obj(info_dict, 'display_id', 'id')
  3478. self.to_screen(f'{format_field(display_id, None, "%s: ")}{note}')
  3479. return self._downloader.get_info_extractor('Generic')._extract_embeds(
  3480. smuggle_url(url, {'block_ies': [self.ie_key()]}), *args, **kwargs)
  3481. @classmethod
  3482. def extract_from_webpage(cls, ydl, url, webpage):
  3483. ie = (cls if isinstance(cls._extract_from_webpage, types.MethodType)
  3484. else ydl.get_info_extractor(cls.ie_key()))
  3485. for info in ie._extract_from_webpage(url, webpage) or []:
  3486. # url = None since we do not want to set (webpage/original)_url
  3487. ydl.add_default_extra_info(info, ie, None)
  3488. yield info
  3489. @classmethod
  3490. def _extract_from_webpage(cls, url, webpage):
  3491. for embed_url in orderedSet(
  3492. cls._extract_embed_urls(url, webpage) or [], lazy=True):
  3493. yield cls.url_result(embed_url, None if cls._VALID_URL is False else cls)
  3494. @classmethod
  3495. def _extract_embed_urls(cls, url, webpage):
  3496. """@returns all the embed urls on the webpage"""
  3497. if '_EMBED_URL_RE' not in cls.__dict__:
  3498. assert isinstance(cls._EMBED_REGEX, (list, tuple))
  3499. for idx, regex in enumerate(cls._EMBED_REGEX):
  3500. assert regex.count('(?P<url>') == 1, \
  3501. f'{cls.__name__}._EMBED_REGEX[{idx}] must have exactly 1 url group\n\t{regex}'
  3502. cls._EMBED_URL_RE = tuple(map(re.compile, cls._EMBED_REGEX))
  3503. for regex in cls._EMBED_URL_RE:
  3504. for mobj in regex.finditer(webpage):
  3505. embed_url = urllib.parse.urljoin(url, unescapeHTML(mobj.group('url')))
  3506. if cls._VALID_URL is False or cls.suitable(embed_url):
  3507. yield embed_url
  3508. class StopExtraction(Exception):
  3509. pass
  3510. @classmethod
  3511. def _extract_url(cls, webpage): # TODO: Remove
  3512. """Only for compatibility with some older extractors"""
  3513. return next(iter(cls._extract_embed_urls(None, webpage) or []), None)
  3514. @classmethod
  3515. def __init_subclass__(cls, *, plugin_name=None, **kwargs):
  3516. if plugin_name:
  3517. mro = inspect.getmro(cls)
  3518. super_class = cls.__wrapped__ = mro[mro.index(cls) + 1]
  3519. cls.PLUGIN_NAME, cls.ie_key = plugin_name, super_class.ie_key
  3520. cls.IE_NAME = f'{super_class.IE_NAME}+{plugin_name}'
  3521. while getattr(super_class, '__wrapped__', None):
  3522. super_class = super_class.__wrapped__
  3523. setattr(sys.modules[super_class.__module__], super_class.__name__, cls)
  3524. _PLUGIN_OVERRIDES[super_class].append(cls)
  3525. return super().__init_subclass__(**kwargs)
  3526. class SearchInfoExtractor(InfoExtractor):
  3527. """
  3528. Base class for paged search queries extractors.
  3529. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  3530. Instances should define _SEARCH_KEY and optionally _MAX_RESULTS
  3531. """
  3532. _MAX_RESULTS = float('inf')
  3533. _RETURN_TYPE = 'playlist'
  3534. @classproperty
  3535. def _VALID_URL(cls):
  3536. return rf'{cls._SEARCH_KEY}(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)'
  3537. def _real_extract(self, query):
  3538. prefix, query = self._match_valid_url(query).group('prefix', 'query')
  3539. if prefix == '':
  3540. return self._get_n_results(query, 1)
  3541. elif prefix == 'all':
  3542. return self._get_n_results(query, self._MAX_RESULTS)
  3543. else:
  3544. n = int(prefix)
  3545. if n <= 0:
  3546. raise ExtractorError(f'invalid download number {n} for query "{query}"')
  3547. elif n > self._MAX_RESULTS:
  3548. self.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  3549. n = self._MAX_RESULTS
  3550. return self._get_n_results(query, n)
  3551. def _get_n_results(self, query, n):
  3552. """Get a specified number of results for a query.
  3553. Either this function or _search_results must be overridden by subclasses """
  3554. return self.playlist_result(
  3555. itertools.islice(self._search_results(query), 0, None if n == float('inf') else n),
  3556. query, query)
  3557. def _search_results(self, query):
  3558. """Returns an iterator of search results"""
  3559. raise NotImplementedError('This method must be implemented by subclasses')
  3560. @classproperty
  3561. def SEARCH_KEY(cls):
  3562. return cls._SEARCH_KEY
  3563. class UnsupportedURLIE(InfoExtractor):
  3564. _VALID_URL = '.*'
  3565. _ENABLED = False
  3566. IE_DESC = False
  3567. def _real_extract(self, url):
  3568. raise UnsupportedError(url)
  3569. _PLUGIN_OVERRIDES = collections.defaultdict(list)